Merge main into feat/tangent-circle-preview-prefs
No files matched your search
@@ -143,12 +143,14 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
|
||||
| `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-artboard.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-artboard-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-artboards.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-blend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-blend-align-page.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-blend-align-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-bloat.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-blob-brush.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cap-butt.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cap-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
@@ -227,6 +229,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-live-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-mask-none.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-measure.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-measure-inspect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-mesh.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-mirror-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
@@ -245,6 +248,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-para-numbers.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: the digits 1, 2 and 3, each before a line | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-para-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-parametric-shape.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 | |
|
||||
@@ -262,32 +266,38 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-place-symbol.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-polar-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-print-tiling.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `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.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | 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 | |
|
||||
| `assets/icons/dc-remove-brush.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-reshape.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-reverse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rotate.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rotate-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rounded-rect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rule-evenodd.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-rule-nonzero.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-scale.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-scallop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `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-shaper.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-spiral.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 | |
|
||||
@@ -305,6 +315,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `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-tangent-circle.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 | |
|
||||
@@ -315,6 +326,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-type-vertical.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-vertical-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-vertical-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-warp.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-width-profile.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-width.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-wrinkle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
@@ -1134,7 +1134,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
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=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
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=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
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=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1204,7 +1204,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1229,7 +1229,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1247,7 +1247,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1265,7 +1265,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1274,7 +1274,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1282,7 +1282,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1291,12 +1291,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1316,7 +1316,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
@@ -1326,7 +1326,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1334,7 +1334,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-atomic",
|
||||
@@ -1359,7 +1359,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1367,7 +1367,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1386,7 +1386,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1398,12 +1398,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1418,7 +1418,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1437,7 +1437,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1459,12 +1459,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1472,7 +1472,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1480,7 +1480,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1493,7 +1493,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
@@ -1521,7 +1521,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1548,7 +1548,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1566,7 +1566,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1574,7 +1574,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1585,7 +1585,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1600,7 +1600,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1614,7 +1614,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1632,7 +1632,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1644,7 +1644,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1655,7 +1655,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1665,7 +1665,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1681,7 +1681,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1693,7 +1693,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1724,7 +1724,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1733,7 +1733,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1757,7 +1757,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1768,7 +1768,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -1782,7 +1782,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1793,7 +1793,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1806,7 +1806,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1825,7 +1825,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -1842,7 +1842,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -1853,7 +1853,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -1874,7 +1874,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1886,7 +1886,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -1911,7 +1911,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -1926,7 +1926,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -1941,7 +1941,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1951,7 +1951,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1960,7 +1960,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1975,12 +1975,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -1994,7 +1994,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -2010,7 +2010,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2048,7 +2048,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2059,7 +2059,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2077,7 +2077,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2098,7 +2098,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2119,7 +2119,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2138,7 +2138,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-host",
|
||||
@@ -2167,7 +2167,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2178,7 +2178,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2188,7 +2188,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2199,7 +2199,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2207,7 +2207,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2239,7 +2239,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -3507,7 +3507,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -3516,7 +3516,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3534,7 +3534,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3552,12 +3552,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4488,7 +4488,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4645,7 +4645,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
@@ -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 = "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" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# 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 = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
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" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# 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 = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# 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 = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -191,13 +191,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
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" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
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" }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, and the Essentials row names Shape Builder's remaining depth, #8314; previously: G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -35,7 +35,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|---|---:|---:|---:|---|
|
||||
| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem |
|
||||
| **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas |
|
||||
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder regions (4–8 h), UI polish |
|
||||
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish |
|
||||
|
||||
Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per
|
||||
Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration).
|
||||
@@ -119,7 +119,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h.
|
||||
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
|
||||
3. **Launch and stability on real machines** (G10): 20–35 h.
|
||||
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
|
||||
4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h.
|
||||
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
|
||||
|
||||
## Progress log
|
||||
@@ -251,6 +251,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
|
||||
@@ -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 = "4bed21baaa41d2b47bef90879c04df521f6f6043", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -104,6 +104,9 @@ impl eframe::App for App {
|
||||
// screen first (`quit_windows`).
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
super::quit_windows::before_teardown(self.winit_window.as_deref());
|
||||
// Plug-ins still loading end before the launch marker does (the macOS exit below skips
|
||||
// dropping the app).
|
||||
self.app.session.cancel_plugin_loads();
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
@@ -164,8 +167,9 @@ impl App {
|
||||
// dialog is open: what asked for it runs again on its document when it answers. They also
|
||||
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
|
||||
// do the command line's files held back for it. Files later launches handed over before the
|
||||
// choice ended in Safe Mode open in a new app with plug-ins.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
|
||||
// choice ended in Safe Mode open in a new app with plug-ins. They wait while plug-ins load
|
||||
// as well, since a plug-in may be what reads them.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) && !self.app.session.plugins_loading() {
|
||||
let held = std::mem::take(&mut self.held_files);
|
||||
#[cfg(target_os = "macos")]
|
||||
let files = open_documents::take();
|
||||
@@ -215,9 +219,10 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
|
||||
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
|
||||
/// ([`safe_mode::choosing`]) or plug-ins are still loading (a plug-in may be what reads one),
|
||||
/// return them to open once it is made and they have loaded.
|
||||
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
|
||||
if safe_mode::choosing(app) {
|
||||
if safe_mode::choosing(app) || app.session.plugins_loading() {
|
||||
return files;
|
||||
}
|
||||
open_files(app, files);
|
||||
|
||||
@@ -398,6 +398,31 @@ pub fn adapter_order(
|
||||
order.into_iter().map(|(i, _)| i).collect()
|
||||
}
|
||||
|
||||
/// [`adapter_order`] without the adapters a restart left out after they failed (`skip`) and those
|
||||
/// that crashed an earlier start (`crashed`), and `true` when that left none and the ones that
|
||||
/// crashed are tried again. A crash record can't stop a start that has no other adapter to try:
|
||||
/// the record may be from a start ended from outside before its first frame (#9183), which looks
|
||||
/// the same as a crash in the driver. An adapter in `skip` failed in this run of the app and
|
||||
/// stays left out.
|
||||
pub fn order_leaving_out(
|
||||
candidates: &[Candidate],
|
||||
power: PowerPreference,
|
||||
displays: &[DisplayGpu],
|
||||
compositor: Option<(u32, u32)>,
|
||||
named: Option<&str>,
|
||||
skip: &[String],
|
||||
crashed: &[String],
|
||||
) -> (Vec<usize>, bool) {
|
||||
let left_out: Vec<String> = skip.iter().chain(crashed).cloned().collect();
|
||||
let order = adapter_order(candidates, power, displays, compositor, named, &left_out);
|
||||
if !order.is_empty() || crashed.is_empty() {
|
||||
return (order, false);
|
||||
}
|
||||
let again = adapter_order(candidates, power, displays, compositor, named, skip);
|
||||
let retried = !again.is_empty();
|
||||
(again, retried)
|
||||
}
|
||||
|
||||
/// wgpu's own ranking for a power preference: the preferred kind of GPU, the other kind, unknown,
|
||||
/// virtual, software.
|
||||
fn power_rank(t: DeviceType, power: PowerPreference) -> u8 {
|
||||
@@ -845,10 +870,9 @@ pub fn selector(
|
||||
) -> NativeAdapterSelectorMethod {
|
||||
let named = std::env::var(NAME_ENV).ok();
|
||||
let skip = skipped();
|
||||
let left_out: Vec<String> = skip.iter().chain(&crashed).cloned().collect();
|
||||
Arc::new(move |adapters, surface| {
|
||||
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::new(a, surface)).collect();
|
||||
let order = adapter_order(&candidates, power, &displays, compositor, named.as_deref(), &left_out);
|
||||
let (order, retried) = order_leaving_out(&candidates, power, &displays, compositor, named.as_deref(), &skip, &crashed);
|
||||
let listed: Vec<String> = candidates
|
||||
.iter()
|
||||
.map(|c| {
|
||||
@@ -872,6 +896,9 @@ pub fn selector(
|
||||
})
|
||||
.collect();
|
||||
log::info!("graphics adapters: {}", listed.join("; "));
|
||||
if retried {
|
||||
log::warn!("every graphics adapter that can show the window crashed an earlier start: trying them again");
|
||||
}
|
||||
let first = order.first().and_then(|&i| adapters.get(i).zip(candidates.get(i)));
|
||||
let Some((adapter, chosen)) = first else {
|
||||
startup.none_left();
|
||||
|
||||
@@ -827,3 +827,17 @@ fn pci_ids_reject_a_sign_in_the_hex_digits() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_+10DE&DEV_2204"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_+2204"), None);
|
||||
}
|
||||
|
||||
/// #9183: a Mac lists one adapter. A start ended from outside before its first frame left it
|
||||
/// recorded as crashed, and the next start left it out and had nothing to draw on. It is tried
|
||||
/// again when nothing else is left; an adapter a restart left out after it failed stays out, and
|
||||
/// with another adapter to try, the one that crashed is still left out.
|
||||
#[test]
|
||||
fn an_adapter_that_crashed_an_earlier_start_is_tried_again_when_no_other_is_left() {
|
||||
let mac = [gpu("Apple M6", Backend::Metal, DeviceType::IntegratedGpu)];
|
||||
let crashed = vec![mac[0].key.clone()];
|
||||
assert_eq!(order_leaving_out(&mac, PowerPreference::LowPower, &[], None, None, &[], &crashed), (vec![0], true));
|
||||
assert_eq!(order_leaving_out(&mac, PowerPreference::LowPower, &[], None, None, &crashed, &crashed), (vec![], false));
|
||||
let two = [gpu("Apple M6", Backend::Metal, DeviceType::IntegratedGpu), gpu("llvmpipe", Backend::Gl, DeviceType::Cpu)];
|
||||
assert_eq!(order_leaving_out(&two, PowerPreference::LowPower, &[], None, None, &[], &crashed), (vec![1], false));
|
||||
}
|
||||
@@ -811,6 +811,9 @@ fn main() -> std::process::ExitCode {
|
||||
let launch_dir = prefs_dir::prefs_dir().filter(|_| prefs_enabled()).map(|d| d.join("Launch"));
|
||||
let folder = |name: &str| prefs_dir::prefs_dir().map(|d| d.join(name).to_string_lossy().to_string());
|
||||
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
|
||||
// The launch's loads of the stored plug-ins and the plug-ins folder go on on worker
|
||||
// threads while the window shows; the frames install them as they finish.
|
||||
session.load_plugins_in_background(true);
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
@@ -826,6 +829,9 @@ fn main() -> std::process::ExitCode {
|
||||
app.set_startup_update_check(!nightly);
|
||||
load_prefs(&mut app, &settings);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// Loads started later (a preference change, the end of Safe Mode) are waited for,
|
||||
// after the launch's own.
|
||||
app.session.load_plugins_in_background(false);
|
||||
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
|
||||
// which takes over from the copy the preferences file used to hold.
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
|
||||
@@ -50,7 +50,8 @@ fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
|
||||
let held = serde_json::json!({"id": "test.held", "name": "Held"});
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"item": held, "items": [held]}));
|
||||
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
|
||||
assert!(read.borrow().is_empty(), "nothing opened before the choice");
|
||||
app.ui.stopped_plugin = None;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12"/><path d="M6 2v2M2 6h2M18 22v-2M22 18h-2"/></svg>
|
||||
|
After Width: | Height: | Size: 274 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.5 3.5 14.75 9.25"/><path d="M13 7.5l3.5 3.5-3 3c-1 1-2.75 1-3.75 0s-1-2.75 0-3.75z"/><path d="M10.2 14.2C8.5 15.5 6 15 4.5 16.5S3.5 20.5 6 20.5 8.5 19 10 19.5s3.5-1 2.5-3-1.5-1.7-2.3-2.3z" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 413 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="8.5" r="5"/><path d="M13.5 12 17 15.5"/><path d="M3 20h18M4 20v-3.5M8 20v-2M12 20v-3.5M16 20v-2M20 20v-3.5"/></svg>
|
||||
|
After Width: | Height: | Size: 319 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3.5 L19.5 8 L19.5 16 L12 20.5 L4.5 16 L4.5 8 Z"/><path d="M8 12h8"/><circle cx="13.5" cy="12" r="1.8" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 326 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12"/><path d="M6 2v2M2 6h2M18 22v-2M22 18h-2"/><rect x="11" y="2.5" width="9" height="11.5" stroke-dasharray="2 2"/></svg>
|
||||
|
After Width: | Height: | Size: 343 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="5" width="16" height="14"/></svg>
|
||||
|
After Width: | Height: | Size: 232 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="10" width="11" height="8" transform="rotate(-30 6 18)"/><circle cx="6" cy="18" r="1.5"/><path d="M19 10.5A15 15 0 0 0 13.5 5"/><path d="M14.56 7.27 13.5 5l2.49-.22"/></svg>
|
||||
|
After Width: | Height: | Size: 371 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="13" width="7" height="7" stroke-dasharray="2 2"/><rect x="4" y="4" width="16" height="16"/><path d="M12 12l5-5M13.5 7H17v3.5"/></svg>
|
||||
|
After Width: | Height: | Size: 332 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 13 5 9.5 6 10 7.5 5 9 9l-.5.5 2 3-2.5-.5-1.5 1.5-1.5-1"/><path d="M15 10 21 20H9Z"/></svg>
|
||||
|
After Width: | Height: | Size: 288 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13.8 10.8a1.2 1.2 0 0 1 1.2 1.2a2.4 2.4 0 0 1-2.4 2.4a3.6 3.6 0 0 1-3.6-3.6a4.8 4.8 0 0 1 4.8-4.8a6 6 0 0 1 6 6a7.2 7.2 0 0 1-7.2 7.2a8.4 8.4 0 0 1-8.4-8.4V5.6"/><circle cx="4.2" cy="4.4" r="1.6" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 417 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8l10 10 10-10"/><circle cx="12" cy="11.64" r="4.5"/></svg>
|
||||
|
After Width: | Height: | Size: 254 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 18h4c3 0 4-9 7-9s3 9 5.5 9h2.5"/><circle cx="13.5" cy="9.5" r="4"/></svg>
|
||||
|
After Width: | Height: | Size: 271 B |
@@ -2192,6 +2192,13 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
|
||||
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
|
||||
}
|
||||
|
||||
/// Most steps the blends in `n` and its subtree make in all when drawn: a step that copies a
|
||||
/// blend counts that blend's steps again, and each instance of a repeat counts its source's
|
||||
/// steps again. Objects that are not blend steps count 0.
|
||||
pub fn blend_steps_made(n: &Node) -> usize {
|
||||
StepCount::default().node(n, false)
|
||||
}
|
||||
|
||||
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
|
||||
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
|
||||
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
|
||||
|
||||
@@ -96,6 +96,18 @@ impl Unit {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The SVG length unit an export writes this unit's sizes in: the unit itself when SVG has it,
|
||||
/// else an SVG unit of the same kind (inches for feet and yards, centimeters for meters,
|
||||
/// millimeters for Q and Ha). `None` for points and pixels.
|
||||
pub fn svg_unit(self) -> Option<Unit> {
|
||||
match self {
|
||||
Unit::Millimeters | Unit::Centimeters | Unit::Inches | Unit::Picas => Some(self),
|
||||
Unit::FeetInches | Unit::Feet | Unit::Yards => Some(Unit::Inches),
|
||||
Unit::Meters => Some(Unit::Centimeters),
|
||||
Unit::Q | Unit::Ha => Some(Unit::Millimeters),
|
||||
Unit::Points | Unit::Pixels => None,
|
||||
}
|
||||
}
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Points => "Points",
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export EPS",
|
||||
[],
|
||||
None,
|
||||
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
|
||||
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default; paper white fills and strokes knock out with document.setup discardWhiteOverprint; white linked to a spot swatch that has a color, at a tint above 0%, still overprints)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
|
||||
has_doc,
|
||||
export_eps
|
||||
)]
|
||||
|
||||
@@ -849,6 +849,13 @@ impl ReadFile {
|
||||
r
|
||||
}
|
||||
|
||||
/// Is part of the read still to do ([`Self::finish_read`]): the policies and the color mode of a
|
||||
/// file that stopped for its profile question, or the linked files and the type of an answered
|
||||
/// one?
|
||||
pub fn read_left(&self) -> bool {
|
||||
self.rest.is_some() || self.links_left.is_some()
|
||||
}
|
||||
|
||||
/// The rest of [`read_for_open_asking`], once: the color management policies with the profile
|
||||
/// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked
|
||||
/// files and the type. The app runs it off the UI thread once the question is answered.
|
||||
|
||||
@@ -212,11 +212,29 @@ fn flattening_cropped_art_keeps_the_art_under_its_hidden_part() {
|
||||
fn overprints_are_kept_or_discarded() {
|
||||
let mut s = session(100.0, 100.0, 1);
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [id], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
|
||||
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": true})).unwrap();
|
||||
let kept = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
|
||||
assert!(kept.contains("true op\n"), "{kept}");
|
||||
let dropped = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none", "overprints": "discard"})).unwrap()));
|
||||
assert!(!dropped.contains("true op"));
|
||||
|
||||
// A white fill or stroke that overprints knocks out with Discard White Overprint (on by
|
||||
// default), and overprints without it, as in PDF export.
|
||||
let white = json!({"c": 0, "m": 0, "y": 0, "k": 0});
|
||||
let filled = [json!({"ids": [id], "color": white}), json!({"ids": [id], "none": true})];
|
||||
let stroked = [json!({"ids": [id], "none": true}), json!({"ids": [id], "color": white})];
|
||||
for (i, [fill, stroke]) in [filled, stroked].iter().enumerate() {
|
||||
s.execute("paint.setFill", fill).unwrap();
|
||||
s.execute("paint.setStroke", stroke).unwrap();
|
||||
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": i == 0, "overprintStroke": i == 1})).unwrap();
|
||||
s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap();
|
||||
let knocked_out = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
|
||||
assert!(!knocked_out.contains("true op"), "{i}: {knocked_out}");
|
||||
s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap();
|
||||
let overprinted = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
|
||||
assert!(overprinted.contains("true op\n"), "{i}: {overprinted}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Artboard Options…",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
has_doc,
|
||||
artboard_set
|
||||
),
|
||||
|
||||
@@ -43,6 +43,11 @@
|
||||
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
|
||||
//! images or symbol instances of those kinds, to read only: its output must return each of them
|
||||
//! unchanged ([`objects::decode_output_with`]).
|
||||
//!
|
||||
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
|
||||
//! also given the parts of the active document it names in `_context.document`, whether or not
|
||||
//! anything is selected: the settings, artboards, layers and swatches, as plain values
|
||||
//! ([`context`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
@@ -52,10 +57,13 @@ 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};
|
||||
use crate::store::StoreTurn;
|
||||
use crate::store::{PluginLoad, StoreTurn};
|
||||
|
||||
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
|
||||
|
||||
mod context;
|
||||
pub use context::{CONTEXT_FUEL_PER_ITEM, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
|
||||
|
||||
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
|
||||
fn err(e: vectorcraft_plugins::Error) -> EngineError {
|
||||
match e {
|
||||
@@ -102,6 +110,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.context.is_empty() {
|
||||
v["context"] = json!(m.context);
|
||||
}
|
||||
if m.paint_output {
|
||||
v["paintOutput"] = json!(true);
|
||||
}
|
||||
@@ -254,15 +265,25 @@ impl FilterRun {
|
||||
params["_context"]["mode"] = json!("command");
|
||||
params["_context"]["command"] = json!(cmd.id);
|
||||
}
|
||||
// The parts of the document its manifest asks for (`context`), selection or not. Each row
|
||||
// costs the run [`context::CONTEXT_FUEL_PER_ITEM`] instructions.
|
||||
let sections = m.context_sections();
|
||||
let mut charged = 0;
|
||||
if !sections.is_empty() && may.contains(&Permission::DocRead) {
|
||||
let given = context::document_context(st, §ions, c)?;
|
||||
params["_context"]["document"] = given.value;
|
||||
charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM);
|
||||
}
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| bad(c, e.to_string()))?;
|
||||
// The input and the parameters may use half the plug-in's memory together.
|
||||
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
|
||||
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
|
||||
let document = (st.uid, st.revision);
|
||||
let limits = match s.prefs.plugin_instruction_budget {
|
||||
let mut limits = match s.prefs.plugin_instruction_budget {
|
||||
crate::PluginBudget::Normal => plugin.limits().clone(),
|
||||
crate::PluginBudget::Large => plugin.large_limits(),
|
||||
};
|
||||
limits.fuel_base = limits.fuel_base.saturating_sub(charged);
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
|
||||
}
|
||||
|
||||
@@ -296,11 +317,17 @@ impl FilterRun {
|
||||
}
|
||||
|
||||
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
|
||||
/// it was made.
|
||||
/// it was made, less what its document context costs.
|
||||
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// The parameters it hands the plug-in, `_context` included.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn params_json(&self) -> Value {
|
||||
serde_json::from_slice(&self.params).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
|
||||
/// session ([`FilterRun::run_with_calls`]).
|
||||
pub fn calls(&self) -> bool {
|
||||
@@ -1010,12 +1037,16 @@ thread_local! {
|
||||
pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.reload` on this thread after its load started and before
|
||||
/// it installs, as another session loading a folder in between would.
|
||||
pub(crate) static BEFORE_RELOAD_INSTALLS: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Held by `plugin.install` from its first read of the grant until the store holds what it
|
||||
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
|
||||
/// other across sessions.
|
||||
/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run
|
||||
/// one after the other across sessions. It is not held while the modules load, so a session's
|
||||
/// plug-in commands don't wait for another session's loads.
|
||||
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
|
||||
@@ -1033,6 +1064,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting.
|
||||
pub(crate) fn try_hold_plugin_changes() -> Option<std::sync::MutexGuard<'static, ()>> {
|
||||
match PLUGIN_CHANGES.try_lock() {
|
||||
Ok(held) => Some(held),
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()),
|
||||
Err(std::sync::TryLockError::WouldBlock) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests: whether [`PLUGIN_CHANGES`] could be taken now.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn plugin_changes_free() -> bool {
|
||||
!matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock))
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
@@ -1282,31 +1328,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
|
||||
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
|
||||
}
|
||||
|
||||
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
|
||||
/// happened.
|
||||
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
|
||||
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what
|
||||
/// happened, the load whose report it is ([`FOLDER_LOADS`]), and whether a file failed because no
|
||||
/// loader thread was left to load it ([`vectorcraft_plugins::loader::NO_THREAD`]), so that the next
|
||||
/// [`sync_prefs`] loads the folder again.
|
||||
type FolderRecord = (String, Option<std::path::PathBuf>, Value, u64, bool);
|
||||
|
||||
/// The [`FolderRecord`] of the plug-in folder last loaded.
|
||||
static FOLDER: Mutex<Option<FolderRecord>> = Mutex::new(None);
|
||||
|
||||
/// The number of the last folder load [`sync_prefs`] or `plugin.reload` started. [`sync_prefs`]
|
||||
/// keeps it in [`FOLDER`] while its load runs, so only that load replaces or clears the record, and
|
||||
/// a `plugin.reload` keeps its report only when no load started after it.
|
||||
static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
|
||||
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
|
||||
/// (startup, `prefs.set`). Native only.
|
||||
pub(crate) fn sync_prefs(s: &Session) {
|
||||
let folder = s.prefs.plugins_folder.trim();
|
||||
/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the
|
||||
/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it
|
||||
/// returns once the folder's plug-ins are installed, also while another session is still loading
|
||||
/// the same folder. Native only.
|
||||
pub(crate) fn sync_prefs(s: &mut Session) {
|
||||
let folder = s.prefs.plugins_folder.trim().to_string();
|
||||
// In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]).
|
||||
if folder.is_empty() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
|
||||
// This session's own load of the folder, still running, is waited for unless loads go on in the
|
||||
// background.
|
||||
if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) {
|
||||
if !s.plugin_loads_in_background {
|
||||
s.finish_plugin_loads();
|
||||
}
|
||||
return;
|
||||
}
|
||||
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
|
||||
let token = {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A folder another session is still loading is loaded here too: that load may end with its
|
||||
// session, and this one returns once its own plug-ins are installed.
|
||||
// A load in which a file found no thread to load it is tried again.
|
||||
if last.as_ref().is_some_and(|(f, store, r, _, retry)| *f == folder && *store == s.plugin_dir && r["loading"] != true && !retry) {
|
||||
return;
|
||||
}
|
||||
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
*last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false));
|
||||
token
|
||||
};
|
||||
let load = start_folder(s, &folder, Some(token));
|
||||
s.queue_plugin_load(PluginLoad::Folder(load));
|
||||
}
|
||||
|
||||
/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last
|
||||
/// loaded, it is forgotten, so setting the preference to it again loads it again.
|
||||
pub(crate) fn forget_prefs_folder(old: &str) {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) {
|
||||
if last.as_ref().is_some_and(|(f, _, _, _, _)| f == old.trim()) {
|
||||
*last = None;
|
||||
}
|
||||
}
|
||||
@@ -1326,42 +1402,232 @@ pub fn load_prefs_folder(s: &mut Session) {
|
||||
sync_prefs(s);
|
||||
}
|
||||
|
||||
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
|
||||
/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the
|
||||
/// disabled list when loading changed it.
|
||||
/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
if let Err(e) = crate::file_access::check_read(folder) {
|
||||
return json!({"folder": folder, "error": e});
|
||||
}
|
||||
// A file in it may be a link to one elsewhere.
|
||||
let allow = |f: &std::path::Path| match f.to_str() {
|
||||
Some(f) => crate::file_access::check_read(f),
|
||||
// A lossy name would check another file than the one loaded.
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session or process finishes writing the store first. When the
|
||||
// store can't be locked, the folder still loads, and the store isn't written.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
}
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
|
||||
type FolderModules = registry::FolderLoad;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
type FolderModules = std::convert::Infallible;
|
||||
|
||||
/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the
|
||||
/// modules load and [`end_folder`] ends.
|
||||
pub(crate) struct FolderPending {
|
||||
folder: String,
|
||||
/// The plug-in store whose grants it loads with.
|
||||
store: Option<std::path::PathBuf>,
|
||||
/// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last
|
||||
/// loaded ([`sync_prefs`]).
|
||||
record: Option<u64>,
|
||||
/// A `plugin.reload`'s load: [`end_folder`] keeps its report as the folder last loaded unless a
|
||||
/// load started after it.
|
||||
reload: bool,
|
||||
/// The modules loading, or the report of a folder that can't be loaded; `None` once ended.
|
||||
load: Option<std::result::Result<FolderModules, Value>>,
|
||||
/// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]).
|
||||
canceled: bool,
|
||||
}
|
||||
|
||||
impl FolderPending {
|
||||
/// Whether every module has been installed or reported.
|
||||
pub(crate) fn done(&self) -> bool {
|
||||
match &self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => load.done(),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => true,
|
||||
}
|
||||
Err(e) => json!({"folder": folder, "error": e.to_string()}),
|
||||
}
|
||||
|
||||
/// Starts the modules loading, unless they started already.
|
||||
pub(crate) fn start(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut self.load {
|
||||
load.start();
|
||||
}
|
||||
}
|
||||
|
||||
/// The installs and removals its modules are checked against (`None`: the folder couldn't be
|
||||
/// listed, or the load ended).
|
||||
pub(crate) fn changes(&self) -> Option<®istry::LoadChanges> {
|
||||
match &self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => Some(load.changes()),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`FolderPending::changes`], to adopt an earlier load's.
|
||||
pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> {
|
||||
match &mut self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => Some(load.changes_mut()),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something can be installed or reported now, without waiting.
|
||||
pub(crate) fn ready(&mut self) -> bool {
|
||||
match &mut self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => load.ready(),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until the next module in file-name order has loaded or failed.
|
||||
pub(crate) fn wait(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut self.load {
|
||||
load.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`]
|
||||
/// then keeps no report as the folder last loaded.
|
||||
pub(crate) fn cancel(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut self.load {
|
||||
load.cancel();
|
||||
}
|
||||
self.canceled = true;
|
||||
}
|
||||
|
||||
/// Whether it is a load of `folder` with the plug-in store `store`.
|
||||
pub(crate) fn loads(&self, folder: &str, store: &Option<std::path::PathBuf>) -> bool {
|
||||
self.folder == folder && self.store == *store
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FolderPending {
|
||||
/// A load dropped before it ended (its session closed) leaves no folder reported as loading, so
|
||||
/// the next session that applies the preference loads it.
|
||||
fn drop(&mut self) {
|
||||
if let Some(token) = self.record.filter(|_| self.load.is_some()) {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) {
|
||||
*last = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`:
|
||||
/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
|
||||
let pending =
|
||||
|load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false };
|
||||
if let Err(e) = crate::file_access::check_read(folder) {
|
||||
return pending(Err(json!({"folder": folder, "error": e})));
|
||||
}
|
||||
// A file in it may be a link to one elsewhere. Each file is checked again on its worker
|
||||
// thread, in the scope in force here (the automation roots and the script gate), as the
|
||||
// folder itself was.
|
||||
let scope = crate::file_access::ScopeHandle::capture_now();
|
||||
let allow = move |f: &std::path::Path| {
|
||||
scope.clone().run(|| match f.to_str() {
|
||||
Some(f) => crate::file_access::check_read(f),
|
||||
// A lossy name would check another file than the one loaded.
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
})
|
||||
};
|
||||
// The modules start loading once the loads queued before them are done.
|
||||
pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()})))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn load_folder(_: &Session, folder: &str) -> Value {
|
||||
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
|
||||
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
|
||||
let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"}));
|
||||
FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }
|
||||
}
|
||||
|
||||
/// Installs what `load` has loaded so far, in file-name order up to the first module still
|
||||
/// loading, without waiting: those that list permissions only when `s` has them granted
|
||||
/// ([`Session::plugin_approved`], with the store's grants read once). Runs while
|
||||
/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process
|
||||
/// finishes writing the store first; when the store can't be locked, the folder still installs,
|
||||
/// and the store isn't written.
|
||||
pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut load.load
|
||||
&& !load.done()
|
||||
{
|
||||
for id in load.install_ready(s.plugin_folder_approver()) {
|
||||
s.attach_plugin_storage(turn, &id);
|
||||
}
|
||||
// A disabled plug-in's file matched by its id is saved in the same turn.
|
||||
if load.disabled_changed() && s.store_disabled_plugins_in(turn) {
|
||||
load.disabled_saved();
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (s, load, turn);
|
||||
}
|
||||
|
||||
/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so
|
||||
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
|
||||
/// record one for another module → its report; saves the disabled list when loading changed it.
|
||||
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
|
||||
let (report, retry) = match load.load.take() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(modules)) => {
|
||||
let r = modules.finish();
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins_in(turn);
|
||||
}
|
||||
let failed = r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>();
|
||||
(json!({"folder": load.folder, "loaded": r.loaded, "failed": failed, "leftOut": r.left_out}), r.no_thread)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match never {},
|
||||
Some(Err(report)) => (report, false),
|
||||
None => (Value::Null, false),
|
||||
};
|
||||
if let Some(token) = load.record {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no
|
||||
// folder reported, so the next session that applies the preference loads it. A
|
||||
// `plugin.reload`'s report replaces the record unless a load started after it, or the
|
||||
// folder couldn't be loaded.
|
||||
let current = if load.reload {
|
||||
FOLDER_LOADS.load(std::sync::atomic::Ordering::Relaxed) == token && report.get("error").is_none()
|
||||
} else {
|
||||
last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token)
|
||||
};
|
||||
if current {
|
||||
*last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token, retry)) };
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report, which is
|
||||
/// kept as the folder last loaded unless a load started after this one.
|
||||
fn load_folder_now(s: &mut Session, folder: &str) -> Value {
|
||||
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
let mut load = start_folder(s, folder, Some(token));
|
||||
load.reload = true;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_RELOAD_INSTALLS.take() {
|
||||
between();
|
||||
}
|
||||
s.finish_plugin_load(PluginLoad::Folder(load))
|
||||
}
|
||||
|
||||
/// Tests: the next [`sync_prefs`] treats the folder last loaded as one in which a file found no
|
||||
/// loader thread to load it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn folder_found_no_thread() {
|
||||
if let Some(record) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
record.4 = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1373,11 +1639,12 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if folder.is_empty() {
|
||||
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
|
||||
}
|
||||
let report = load_folder(s, &folder);
|
||||
// Loads started earlier install first, so this one's plug-ins replace theirs.
|
||||
s.finish_plugin_loads();
|
||||
let report = load_folder_now(s, &folder);
|
||||
if let Some(e) = report.get("error").and_then(Value::as_str) {
|
||||
return Err(EngineError::Other(e.to_string()));
|
||||
}
|
||||
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -1426,7 +1693,7 @@ fn shown_report(mut report: Value) -> Value {
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone()));
|
||||
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
|
||||
Ok(
|
||||
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
|
||||
@@ -1434,13 +1701,15 @@ fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
|
||||
/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet.
|
||||
/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet.
|
||||
fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let pending: Vec<Value> = safe_mode::previous().iter().map(shown_item).collect();
|
||||
Ok(json!({
|
||||
"active": safe_mode::active(),
|
||||
"source": safe_mode::source().map(safe_mode::Source::name),
|
||||
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
|
||||
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
|
||||
"pendingItem": pending.first(),
|
||||
"pendingItems": pending,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1579,7 +1848,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, 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)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1651,7 +1920,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Safe Mode",
|
||||
[],
|
||||
None,
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
always,
|
||||
safe_mode_state
|
||||
),
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! A plug-in run's document context (`_context.document`): the parts of the active document its
|
||||
//! manifest's `context` asks for ([`ContextSection`]), read when the run is prepared, with or
|
||||
//! without a selection. It holds plain values only: names, flags, rectangles and colors, never an
|
||||
//! object, a file path or a link target.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{ColorMode, LayerColor, Node, NodeKind};
|
||||
use vectorcraft_plugins::ContextSection;
|
||||
|
||||
use super::super::{Result, bad};
|
||||
use crate::DocState;
|
||||
|
||||
/// Most rows (artboards, layers and sublayers, and swatches together) a document context holds.
|
||||
pub const MAX_CONTEXT_ITEMS: usize = 10_000;
|
||||
|
||||
/// Most bytes the rows of a document context take as JSON.
|
||||
pub const MAX_CONTEXT_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// Instructions each row costs: they come off the run's instruction budget.
|
||||
pub const CONTEXT_FUEL_PER_ITEM: u64 = 1_000;
|
||||
|
||||
/// A document context, and the rows it holds.
|
||||
pub(super) struct DocumentContext {
|
||||
pub value: Value,
|
||||
pub items: usize,
|
||||
}
|
||||
|
||||
/// The document context of `sections` for a run of command `c` on `st`: `{revision}` and a key
|
||||
/// for each section asked for. A document with more than [`MAX_CONTEXT_ITEMS`] rows in them, or
|
||||
/// rows of more than [`MAX_CONTEXT_BYTES`], is an error, before any row is made in the first case.
|
||||
pub(super) fn document_context(st: &DocState, sections: &[ContextSection], c: &str) -> Result<DocumentContext> {
|
||||
let d = &st.doc;
|
||||
let layers = if sections.contains(&ContextSection::Layers) { layer_rows(d) } else { Vec::new() };
|
||||
let swatches = || super::super::swatch::listed_swatches(d, true, d.swatch_groups.iter().collect());
|
||||
let mut items = 0;
|
||||
for s in sections {
|
||||
items += match s {
|
||||
ContextSection::Settings => 0,
|
||||
ContextSection::Artboards => d.artboards.len(),
|
||||
ContextSection::Layers => layers.len(),
|
||||
ContextSection::Swatches => swatches().count(),
|
||||
};
|
||||
}
|
||||
let too_large = || {
|
||||
bad(
|
||||
c,
|
||||
format!(
|
||||
"the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes"
|
||||
),
|
||||
)
|
||||
};
|
||||
if items > MAX_CONTEXT_ITEMS {
|
||||
return Err(too_large());
|
||||
}
|
||||
let mut bytes = 0usize;
|
||||
let mut row = |v: Value| -> Result<Value> {
|
||||
bytes = bytes.saturating_add(serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len() + 1));
|
||||
if bytes > MAX_CONTEXT_BYTES { Err(too_large()) } else { Ok(v) }
|
||||
};
|
||||
let active = active_artboard(st);
|
||||
let mut out = json!({"revision": st.revision});
|
||||
for s in sections {
|
||||
let value = match s {
|
||||
ContextSection::Settings => {
|
||||
let board = active.and_then(|i| d.artboards.get(i));
|
||||
row(json!({
|
||||
"name": st.title(),
|
||||
"colorMode": match d.color_mode {
|
||||
ColorMode::Rgb => "rgb",
|
||||
ColorMode::Cmyk => "cmyk",
|
||||
},
|
||||
"units": d.units.label(),
|
||||
"width": board.map(|a| a.rect.width()),
|
||||
"height": board.map(|a| a.rect.height()),
|
||||
"bleed": d.setup.bleed,
|
||||
"rasterEffectsPpi": d.raster_ppi(),
|
||||
"activeArtboard": board.map(|a| a.id),
|
||||
}))?
|
||||
}
|
||||
ContextSection::Artboards => {
|
||||
let rows = d.artboards.iter().enumerate().map(|(i, a)| {
|
||||
let r = a.rect;
|
||||
row(json!({"id": a.id, "index": i, "name": a.name, "rect": [r.x0, r.y0, r.x1, r.y1], "active": active == Some(i)}))
|
||||
});
|
||||
Value::Array(rows.collect::<Result<_>>()?)
|
||||
}
|
||||
ContextSection::Layers => {
|
||||
let rows = layers.iter().map(|l| {
|
||||
let n = l.node;
|
||||
row(json!({
|
||||
"id": n.id.0, "parentId": l.parent, "depth": l.depth, "name": n.display_name(),
|
||||
"visible": n.visible, "locked": n.locked, "template": l.template, "color": l.color.label_text(),
|
||||
"sublayers": l.sublayers, "current": st.active_layer == Some(n.id),
|
||||
}))
|
||||
});
|
||||
Value::Array(rows.collect::<Result<_>>()?)
|
||||
}
|
||||
ContextSection::Swatches => {
|
||||
let rows = swatches().map(|(w, g)| row(super::super::swatch::swatch_json(w, g)));
|
||||
Value::Array(rows.collect::<Result<_>>()?)
|
||||
}
|
||||
};
|
||||
out[s.name()] = value;
|
||||
}
|
||||
Ok(DocumentContext { value: out, items })
|
||||
}
|
||||
|
||||
/// Is `n` a layer or sublayer?
|
||||
fn is_layer(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// A layer or sublayer, where it is in the layer tree, and what its row reports besides the
|
||||
/// node's own name and flags.
|
||||
struct LayerRow<'a> {
|
||||
node: &'a Node,
|
||||
/// Its parent layer's id; `None` for a top-level layer.
|
||||
parent: Option<u64>,
|
||||
/// 0 for a top-level layer, 1 for its sublayers, and so on.
|
||||
depth: usize,
|
||||
color: LayerColor,
|
||||
template: bool,
|
||||
/// The sublayers it holds directly.
|
||||
sublayers: usize,
|
||||
}
|
||||
|
||||
/// Every layer and sublayer of `d`, depth first in document order (bottom first within each
|
||||
/// parent). The walk keeps its own stack, so deep nesting can't overflow the thread's.
|
||||
fn layer_rows(d: &vectorcraft_doc::Document) -> Vec<LayerRow<'_>> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack: Vec<(&Node, Option<u64>, usize)> = d.layers.iter().rev().map(|l| (l.as_ref(), None, 0)).collect();
|
||||
while let Some((node, parent, depth)) = stack.pop() {
|
||||
let NodeKind::Layer { color, template, children, .. } = &node.kind else { continue };
|
||||
let sublayers = children.iter().filter(|c| is_layer(c)).count();
|
||||
stack.extend(children.iter().rev().filter(|c| is_layer(c)).map(|c| (c.as_ref(), Some(node.id.0), depth + 1)));
|
||||
out.push(LayerRow { node, parent, depth, color: *color, template: *template, sublayers });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
|
||||
/// longer has it, the artboard the document opened on, else the first; `None` with no artboards.
|
||||
fn active_artboard(st: &DocState) -> Option<usize> {
|
||||
let d = &st.doc;
|
||||
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
|
||||
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
|
||||
}
|
||||
@@ -1012,18 +1012,28 @@ fn swatch_list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(g) => vec![d.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| bad("swatch.list", format!("no colour group `{g}`")))?],
|
||||
None => d.swatch_groups.iter().collect(),
|
||||
};
|
||||
// The built-in Registration swatch lists after None, as the panel shows it.
|
||||
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
|
||||
let (specials, rest) = d.swatches.split_at(none);
|
||||
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
|
||||
let ungrouped = all.filter(|_| only.is_none()).map(|w| swatch_json(w, None));
|
||||
let grouped = groups.iter().flat_map(|g| g.swatches.iter().map(|w| swatch_json(w, Some(&g.name))));
|
||||
let swatches: Vec<Value> = ungrouped.chain(grouped).collect();
|
||||
let swatches: Vec<Value> = listed_swatches(d, only.is_none(), groups.clone()).map(|(w, g)| swatch_json(w, g)).collect();
|
||||
let groups: Vec<Value> =
|
||||
groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect();
|
||||
Ok(json!({"swatches": swatches, "groups": groups}))
|
||||
}
|
||||
|
||||
/// The swatches `swatch.list` lists, in its order, each with the name of the colour group it is
|
||||
/// in: with `ungrouped`, the swatches outside groups (the built-in Registration swatch after None,
|
||||
/// as the panel shows it), then those of `groups`.
|
||||
pub(super) fn listed_swatches<'a>(
|
||||
d: &'a Document,
|
||||
ungrouped: bool,
|
||||
groups: Vec<&'a SwatchGroup>,
|
||||
) -> impl Iterator<Item = (&'a Swatch, Option<&'a str>)> + 'a {
|
||||
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
|
||||
let (specials, rest) = d.swatches.split_at(none);
|
||||
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
|
||||
let ungrouped = all.filter(move |_| ungrouped).map(|w| (w, None));
|
||||
let grouped = groups.into_iter().flat_map(|g| g.swatches.iter().map(move |w| (w, Some(g.name.as_str()))));
|
||||
ungrouped.chain(grouped)
|
||||
}
|
||||
|
||||
fn swatch_sort(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.edit("Sort Swatches", |d, _| {
|
||||
// [None] and other bracketed specials stay first, like the reference app.
|
||||
|
||||
@@ -125,6 +125,14 @@ pub fn waits_for_tool_edit(id: &str) -> bool {
|
||||
find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id))
|
||||
}
|
||||
|
||||
/// Does command `id` first install the plug-ins still loading on other threads
|
||||
/// ([`crate::Session::finish_plugin_loads`])? Plug-in commands do, a plug-in's own commands
|
||||
/// included, and so does every command that waits for a tool edit ([`waits_for_tool_edit`]);
|
||||
/// queries that only read, and view commands, go ahead while the plug-ins load.
|
||||
pub fn waits_for_plugin_loads(id: &str) -> bool {
|
||||
id.starts_with(vectorcraft_plugins::PREFIX) || waits_for_tool_edit(id)
|
||||
}
|
||||
|
||||
/// Journaled commands that write a file and change nothing in the document: with an object of a
|
||||
/// dynamic symbol instance's art selected, they read the instance as queries do
|
||||
/// ([`crate::Session::execute`]).
|
||||
|
||||
@@ -227,6 +227,14 @@ fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
|
||||
f()
|
||||
}
|
||||
|
||||
/// `scope`, or for a thread without one, the `process` roots in force now (none: unconfined).
|
||||
fn resolved(scope: Option<Scope>, process: Option<&Arc<AutomationRoots>>) -> Scope {
|
||||
scope.unwrap_or_else(|| match process {
|
||||
Some(r) => Scope::Confined(r.clone()),
|
||||
None => Scope::Unconfined,
|
||||
})
|
||||
}
|
||||
|
||||
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
|
||||
/// another thread ([`ScopeHandle::run`]).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -238,6 +246,15 @@ impl ScopeHandle {
|
||||
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// [`ScopeHandle::capture`], except that a thread with no scope of its own takes the process's
|
||||
/// roots as they are now ([`confine_process`]): work captured before the process is confined
|
||||
/// stays unconfined on the thread that runs it, as it would have been had it run on the calling
|
||||
/// thread at once.
|
||||
pub fn capture_now() -> Self {
|
||||
let scope = resolved(SCOPE.with(|s| s.borrow().clone()), PROCESS.get());
|
||||
Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
let Self(scope, gate, exempt) = self;
|
||||
@@ -1327,6 +1344,24 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Work captured with [`ScopeHandle::capture_now`] before the process is confined stays
|
||||
/// unconfined when it runs after; work captured with [`ScopeHandle::capture`] is confined then.
|
||||
#[test]
|
||||
fn a_scope_captured_now_stays_unconfined_after_the_process_is_confined() {
|
||||
if !crate::tests::in_own_process("file_access::tests::a_scope_captured_now_stays_unconfined_after_the_process_is_confined") {
|
||||
return;
|
||||
}
|
||||
let (base, roots) = folders("captured-process");
|
||||
let outside = s(base.join("outside/secret.svg"));
|
||||
let (now, plain) = std::thread::spawn(|| (ScopeHandle::capture_now(), ScopeHandle::capture())).join().unwrap();
|
||||
assert!(confine_process(roots));
|
||||
assert_eq!(now.run(|| check_read(&outside)), Ok(()), "captured now, before the process was confined");
|
||||
assert!(plain.run(|| check_read(&outside)).is_err(), "captured plainly, run after the process was confined");
|
||||
let later = std::thread::spawn(ScopeHandle::capture_now).join().unwrap();
|
||||
assert!(later.run(|| check_read(&outside)).is_err(), "captured now, after the process was confined");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] {
|
||||
|
||||
@@ -203,6 +203,11 @@ pub struct Session {
|
||||
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
|
||||
/// ([`Session::attach_plugin_store`]).
|
||||
plugin_dir: Option<std::path::PathBuf>,
|
||||
/// Plug-in loads running on worker threads, oldest first ([`Session::poll_plugin_loads`]).
|
||||
plugin_loads: std::collections::VecDeque<store::PluginLoad>,
|
||||
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
|
||||
/// that starts them ([`Session::load_plugins_in_background`]).
|
||||
plugin_loads_in_background: bool,
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
@@ -453,7 +458,7 @@ mod session;
|
||||
pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -326,7 +326,7 @@ impl Files {
|
||||
|
||||
/// 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() }
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
}
|
||||
|
||||
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
|
||||
|
||||
@@ -2009,7 +2009,7 @@ impl Session {
|
||||
// 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 options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..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 {
|
||||
|
||||
@@ -106,6 +106,8 @@ impl Session {
|
||||
profile_dir: None,
|
||||
color_settings_file: None,
|
||||
plugin_dir: None,
|
||||
plugin_loads: Default::default(),
|
||||
plugin_loads_in_background: false,
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
|
||||
@@ -59,6 +59,13 @@ impl Session {
|
||||
|
||||
/// Execute a command by id. This is THE entry point for every frontend.
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
// Plug-ins still loading on other threads ([`Session::load_plugins_in_background`]) are
|
||||
// installed before a plug-in command, its own commands included, and before a command that
|
||||
// may edit, as they would have been before the window showed; a step of a batch waits for
|
||||
// the plug-ins an earlier step started loading.
|
||||
if self.plugins_loading() && crate::waits_for_plugin_loads(id) {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
self.revealing(|s| s.execute_unwatched(id, params))
|
||||
}
|
||||
|
||||
|
||||
@@ -35,14 +35,16 @@
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
|
||||
use vectorcraft_plugins::loader::{Job, Loads};
|
||||
use vectorcraft_plugins::permissions::GrantToken;
|
||||
use vectorcraft_plugins::safe_mode;
|
||||
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
|
||||
@@ -170,6 +172,29 @@ fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
files
|
||||
}
|
||||
|
||||
/// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it.
|
||||
fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return vec![] };
|
||||
let mut files: Vec<_> = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)))
|
||||
.filter_map(|p| {
|
||||
let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?;
|
||||
match m.modified() {
|
||||
Ok(t) => Some((p, (m.len(), t))),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", p.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase()));
|
||||
files.truncate(MAX_STORE_FILES);
|
||||
files
|
||||
}
|
||||
|
||||
/// The content of `path` when it is at most `max` bytes; the file is never read past `max`.
|
||||
pub(crate) fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?;
|
||||
@@ -187,11 +212,243 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
|
||||
/// [`Session::finish_plugin_loads`] install.
|
||||
pub(crate) enum PluginLoad {
|
||||
/// The plug-in store's ([`Session::load_stored_plugins`]).
|
||||
Stored(StoredLoad),
|
||||
/// The Additional Plug-ins Folder's ([`crate::cmd::plugin::sync_prefs`]).
|
||||
Folder(crate::cmd::plugin::FolderPending),
|
||||
}
|
||||
|
||||
impl PluginLoad {
|
||||
/// Starts the modules loading, unless they started already.
|
||||
fn start(&mut self) {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.loads.begin(),
|
||||
PluginLoad::Folder(load) => load.start(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The installs and removals it checks its modules against (`None`: a folder that couldn't be
|
||||
/// listed, or one ended already).
|
||||
fn changes(&self) -> Option<&vectorcraft_plugins::registry::LoadChanges> {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => Some(&load.changes),
|
||||
PluginLoad::Folder(load) => load.changes(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`PluginLoad::changes`], to adopt an earlier load's.
|
||||
fn changes_mut(&mut self) -> Option<&mut vectorcraft_plugins::registry::LoadChanges> {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => Some(&mut load.changes),
|
||||
PluginLoad::Folder(load) => load.changes_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every module has been installed or skipped.
|
||||
fn done(&self) -> bool {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.next == load.files.len() && load.rest.is_empty(),
|
||||
PluginLoad::Folder(load) => load.done(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something can be installed or ended now, without waiting.
|
||||
pub(crate) fn ready(&mut self) -> bool {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.next == load.files.len() || !load.loaded.is_empty() || load.loads.next_ready(),
|
||||
PluginLoad::Folder(load) => load.ready(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until [`PluginLoad::ready`], starting the modules loading first ([`PluginLoad::start`]).
|
||||
fn wait(&mut self) {
|
||||
self.start();
|
||||
match self {
|
||||
PluginLoad::Stored(load) if load.loaded.is_empty() && load.next < load.files.len() => load.loads.wait_next(),
|
||||
PluginLoad::Stored(_) => {}
|
||||
PluginLoad::Folder(load) => load.wait(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the modules not installed yet ([`Session::cancel_plugin_loads`]), leaving it
|
||||
/// [`PluginLoad::done`] with what it installed.
|
||||
fn cancel(&mut self) {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => {
|
||||
load.loads = Loads::deferred(Vec::new());
|
||||
load.loaded.clear();
|
||||
load.next = load.files.len();
|
||||
load.rest.clear();
|
||||
}
|
||||
PluginLoad::Folder(load) => load.cancel(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether installing it takes the plug-in store's own turn, making the store folder (a
|
||||
/// folder's plug-ins keep their settings and cache there), rather than one that goes ahead
|
||||
/// without a store folder.
|
||||
fn creates_store(&self) -> bool {
|
||||
matches!(self, PluginLoad::Folder(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// A stored plug-in file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be
|
||||
/// read).
|
||||
type StoredFile = (PathBuf, Option<FileStamp>);
|
||||
|
||||
/// The stored plug-ins loading from the plug-in store `dir`.
|
||||
pub(crate) struct StoredLoad {
|
||||
dir: PathBuf,
|
||||
/// The files listed, in file-name order.
|
||||
files: Vec<StoredFile>,
|
||||
loads: Loads<StoredRead>,
|
||||
/// Outcomes taken from `loads` and not installed yet, in order.
|
||||
loaded: VecDeque<vectorcraft_plugins::Result<StoredRead>>,
|
||||
/// The next file to install.
|
||||
next: usize,
|
||||
/// The store's grants this load removed, by id, because the module stored for the id lists no
|
||||
/// permissions: a later file holding a module with that id that the grant covers still loads,
|
||||
/// and the grant goes back to the store.
|
||||
retired: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
/// Installs and removals elsewhere since the store was listed, which a module loaded before
|
||||
/// them doesn't undo.
|
||||
changes: vectorcraft_plugins::registry::LoadChanges,
|
||||
/// The files listed after `files`, in file-name order, with their stamps from when the store was
|
||||
/// listed, that wait for `files` to load because what is left of [`MAX_PLUGIN_STORE`] may not
|
||||
/// cover them until the reads that fail give back what they didn't read
|
||||
/// ([`list_stored_plugins`]).
|
||||
rest: VecDeque<StoredFile>,
|
||||
/// What is left of [`MAX_PLUGIN_STORE`]: the listed length of each file in `files` is taken
|
||||
/// from it, and what a failed read didn't read of it is given back.
|
||||
left: u64,
|
||||
}
|
||||
|
||||
/// What a stored plug-in's load read of its file, at most its listed length, and the module.
|
||||
pub(crate) struct StoredRead {
|
||||
read: u64,
|
||||
plugin: vectorcraft_plugins::Result<vectorcraft_plugins::Plugin>,
|
||||
}
|
||||
|
||||
/// Tests: what runs before a stored module is read, given its path.
|
||||
#[cfg(test)]
|
||||
type StoredHook = Arc<dyn Fn(&Path) + Send + Sync>;
|
||||
|
||||
/// Tests: runs on the worker thread before the stored module at the path it is given is read.
|
||||
#[cfg(test)]
|
||||
pub(crate) static BEFORE_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
|
||||
|
||||
#[cfg(test)]
|
||||
fn before_stored_load(path: &Path) {
|
||||
let hook = BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests: runs on the worker thread once the stored module at the path it is given has loaded, and
|
||||
/// before its file is read again to check that it still holds the module.
|
||||
#[cfg(test)]
|
||||
pub(crate) static AFTER_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
|
||||
|
||||
#[cfg(test)]
|
||||
fn after_stored_load(path: &Path) {
|
||||
let hook = AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a stored plug-in whose file changed between its listing and its install is skipped.
|
||||
const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]).
|
||||
pub(crate) static PLUGIN_STORE_BUDGET: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_PLUGIN_STORE) };
|
||||
}
|
||||
|
||||
/// The stored plug-in bytes one store's load reads, all files together ([`MAX_PLUGIN_STORE`]).
|
||||
#[cfg(not(test))]
|
||||
fn plugin_store_budget() -> u64 {
|
||||
MAX_PLUGIN_STORE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn plugin_store_budget() -> u64 {
|
||||
PLUGIN_STORE_BUDGET.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// What a file over its cap is told (a detail after the file's name, in the log or an error).
|
||||
fn too_large(max: u64) -> String {
|
||||
format!("larger than {max} bytes")
|
||||
}
|
||||
|
||||
/// Takes the stored plug-in files at the front of `rest`, in order, each one's listed length taken
|
||||
/// from `left` → those files, and the jobs that load them, each reading no more than that length.
|
||||
/// It stops at the first file that `left` doesn't cover but would if files taken before it failed to
|
||||
/// read and gave back what they took; that file and the ones after it stay in `rest`. A file that
|
||||
/// `left` wouldn't cover even then is skipped with a log record, and once nothing can be given back
|
||||
/// to a used-up `left` the rest are, as when the files were read one after the other.
|
||||
fn list_stored_plugins(rest: &mut VecDeque<StoredFile>, left: &mut u64) -> (Vec<StoredFile>, Vec<Job<StoredRead>>) {
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut files = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
// What the files taken so far took of `left`.
|
||||
let mut taken = 0;
|
||||
while let Some((path, stamp)) = rest.pop_front() {
|
||||
let len = stamp.flatten().map_or(0, |(len, _)| len);
|
||||
let most = *left + taken;
|
||||
if most == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
rest.clear();
|
||||
break;
|
||||
}
|
||||
if len > most {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most));
|
||||
continue;
|
||||
}
|
||||
// An empty file too waits once `left` is used up.
|
||||
if len > *left || *left == 0 {
|
||||
rest.push_front((path, stamp));
|
||||
break;
|
||||
}
|
||||
*left -= len;
|
||||
taken += len;
|
||||
let item = safe_mode::Item::file(path.display().to_string());
|
||||
let (read, limits) = (path.clone(), limits.clone());
|
||||
jobs.push(Job::new(Some(item), move || {
|
||||
#[cfg(test)]
|
||||
before_stored_load(&read);
|
||||
let mut bytes = vec![];
|
||||
let got = std::fs::File::open(&read).and_then(|f| f.take(len + 1).read_to_end(&mut bytes));
|
||||
let plugin = match got {
|
||||
Err(e) => Err(vectorcraft_plugins::Error::Io(e.to_string())),
|
||||
Ok(_) if bytes.len() as u64 > len => Err(vectorcraft_plugins::Error::Io(too_large(len))),
|
||||
Ok(_) => vectorcraft_plugins::Plugin::load(&bytes, limits),
|
||||
};
|
||||
#[cfg(test)]
|
||||
after_stored_load(&read);
|
||||
// A file replaced while its module loaded, by one that kept its length and modified time,
|
||||
// is told apart by its content: it is read again here, within the load's deadline. The
|
||||
// install then skips a file whose stamp changed since.
|
||||
let plugin = plugin.and_then(|p| {
|
||||
if std::fs::File::open(&read).is_ok_and(|f| holds(f, &bytes)) {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(vectorcraft_plugins::Error::Io(CHANGED_WHILE_LOADING.into()))
|
||||
}
|
||||
});
|
||||
// A read that failed part way read what `bytes` holds.
|
||||
Ok(StoredRead { read: (bytes.len() as u64).min(len), plugin })
|
||||
}));
|
||||
files.push((path, stamp));
|
||||
}
|
||||
(files, jobs)
|
||||
}
|
||||
|
||||
/// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a
|
||||
/// large file is not read into memory.
|
||||
pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool {
|
||||
@@ -230,8 +487,7 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
|
||||
/// replaced or removed, so that every window locks the same file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?;
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
@@ -245,6 +501,30 @@ fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_store_lock(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))
|
||||
}
|
||||
|
||||
/// [`lock_store`] without waiting: `None` while another window or process holds the lock.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Some(file)),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn try_lock_store(_: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
@@ -445,78 +725,188 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]).
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). Loads
|
||||
/// still running from an earlier call are finished first.
|
||||
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
self.finish_plugin_loads();
|
||||
self.plugin_dir = Some(dir);
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
self.load_stored_plugins_in(&turn);
|
||||
self.start_stored_plugins(true);
|
||||
}
|
||||
|
||||
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
|
||||
/// disabled (matched by file name, which is made from the id). The launch marker names each
|
||||
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// any session in the process attached to the folder until the file can be written for the id
|
||||
/// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]).
|
||||
/// disabled (matched by file name, which is made from the id). The modules load on worker
|
||||
/// threads ([`vectorcraft_plugins::loader`]) and install in file-name order, whatever order
|
||||
/// their loads finish in; the launch marker names each file while it loads. A module that
|
||||
/// doesn't load (its load panicked or didn't finish in time included), one that changed or
|
||||
/// went away while it loaded, and one that lists permissions the grants there don't grant that
|
||||
/// very module ([`grant_covers`]), is skipped with a log record, and stays in the folder with
|
||||
/// its grant. A grant for an id whose stored module lists no permissions is forgotten; one that
|
||||
/// can't be removed from the grants file doesn't count for any session in the process attached
|
||||
/// to the folder until the file can be written for the id ([`Session::ignore_stored_grant`]).
|
||||
/// The folder is listed, and what loaded is installed and the folder changed, in turns on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With
|
||||
/// [`Session::load_plugins_in_background`] on, this returns while the modules load.
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
if self.plugin_dir.is_none() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
self.load_stored_plugins_in(&turn);
|
||||
self.start_stored_plugins(false);
|
||||
}
|
||||
|
||||
/// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`]
|
||||
/// is held.
|
||||
fn load_stored_plugins_in(&mut self, turn: &StoreTurn) {
|
||||
/// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the
|
||||
/// folder ([`DISABLED_FILE`]).
|
||||
fn start_stored_plugins(&mut self, disabled: bool) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
// A `plugin.install` in another session or process writes the store before this lists it.
|
||||
let held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
if disabled {
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(saved);
|
||||
}
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
let mut asks_nothing = BTreeSet::new();
|
||||
for path in list_files(&dir, PLUGIN_EXT) {
|
||||
if left == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
break;
|
||||
}
|
||||
let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
let mut rest = VecDeque::new();
|
||||
let disabled: BTreeSet<String> = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect();
|
||||
for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) {
|
||||
let item = safe_mode::Item::file(path.display().to_string());
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string());
|
||||
let by_id = safe_mode::skipped_ids().iter().any(|id| stem.as_deref() == Some(file_stem(id).as_str()));
|
||||
let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref()));
|
||||
if safe_mode::skipped(&item) || by_id {
|
||||
log::info!("skipping the stored plug-in {}: disabled", path.display());
|
||||
} else if stamp.0 > module {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module));
|
||||
} else {
|
||||
rest.push_back((path, Some(Some(stamp))));
|
||||
}
|
||||
}
|
||||
let mut left = plugin_store_budget();
|
||||
let (files, jobs) = list_stored_plugins(&mut rest, &mut left);
|
||||
// A change made after the listing, while `held` no longer stops one, is made elsewhere.
|
||||
let mut changes = vectorcraft_plugins::registry::LoadChanges::default();
|
||||
changes.start();
|
||||
// The modules load after the turn, once the loads queued before them are done.
|
||||
drop((turn, held));
|
||||
let load =
|
||||
StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left };
|
||||
self.queue_plugin_load(PluginLoad::Stored(load));
|
||||
}
|
||||
|
||||
/// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the
|
||||
/// first module still loading, without waiting ([`Session::load_stored_plugins`]), while
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] and `turn` are held.
|
||||
fn install_stored_plugins(&mut self, load: &mut StoredLoad, turn: &StoreTurn) {
|
||||
if load.next == load.files.len() && !load.rest.is_empty() {
|
||||
// Every file listed so far is installed or skipped, and the reads that failed gave
|
||||
// back their length: the files waiting for them are listed now.
|
||||
let (files, jobs) = list_stored_plugins(&mut load.rest, &mut load.left);
|
||||
load.files = files;
|
||||
load.next = 0;
|
||||
load.loads = Loads::start(jobs);
|
||||
return;
|
||||
}
|
||||
load.loaded.extend(load.loads.ready());
|
||||
if load.loaded.is_empty() {
|
||||
return;
|
||||
}
|
||||
let dir = load.dir.clone();
|
||||
// The grants file is read once for this turn. `written` holds whether it names each id
|
||||
// whose grant this turn removed or put back.
|
||||
let file = read_grants(&dir);
|
||||
let mut grants = self.counted(
|
||||
&dir,
|
||||
match &file {
|
||||
Ok(file) => file.grants.clone(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut written: BTreeMap<String, bool> = BTreeMap::new();
|
||||
let named = |written: &BTreeMap<String, bool>, id: &str| {
|
||||
written.get(id).copied().unwrap_or_else(|| match &file {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
})
|
||||
};
|
||||
while let (Some(loaded), Some((path, stamp))) = (load.loaded.pop_front(), load.files.get(load.next)) {
|
||||
load.next += 1;
|
||||
load.loads.release(1);
|
||||
// What a read that failed didn't read takes nothing from the total. A load that panicked
|
||||
// or passed its deadline gives nothing back.
|
||||
let loaded = loaded.and_then(|r| {
|
||||
load.left += stamp.flatten().map_or(0, |(len, _)| len).saturating_sub(r.read);
|
||||
r.plugin
|
||||
});
|
||||
// The worker read the file again once its module loaded ([`list_stored_plugins`]); one
|
||||
// whose stamp changed since then is skipped too.
|
||||
if file_stamp(path).ok() != *stamp {
|
||||
log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display());
|
||||
continue;
|
||||
}
|
||||
let token = safe_mode::loading(&item);
|
||||
let loaded = read_capped(&path, (limits.max_module_bytes as u64).min(left)).and_then(|bytes| {
|
||||
left -= bytes.len() as u64;
|
||||
vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string())
|
||||
});
|
||||
safe_mode::loaded(token);
|
||||
match loaded {
|
||||
Ok(plugin) if load.changes.superseded(plugin.id()) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
}
|
||||
// Only this store's grants count: one given elsewhere in the process doesn't let a
|
||||
// module stored here load.
|
||||
Ok(plugin) if plugin.manifest().asks_permissions() => {
|
||||
let m = plugin.manifest();
|
||||
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
|
||||
let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned();
|
||||
// A grant given for the id since this load removed one, in another window or
|
||||
// process, is kept.
|
||||
let back = (!grants.contains_key(&m.id) && !named(&written, &m.id))
|
||||
.then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned())
|
||||
.flatten();
|
||||
match stored.or(back.clone()) {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
// A grant this load removed for an earlier file with the id goes back. When
|
||||
// it can't be written back, the module isn't installed: the store doesn't
|
||||
// grant it, so it wouldn't load at the next launch either.
|
||||
if back.is_some() {
|
||||
if !self.store_grant_in(turn, &m.id, Some(g.clone())) {
|
||||
log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display());
|
||||
continue;
|
||||
}
|
||||
load.retired.remove(&m.id);
|
||||
written.insert(m.id.clone(), true);
|
||||
grants.insert(m.id.clone(), g.clone());
|
||||
}
|
||||
let id = m.id.clone();
|
||||
let token = GrantToken::from_engine_grants_file(g.clone());
|
||||
// The storage is made before the plug-ins are held: making it reads the store.
|
||||
let storage = plugin_storage(Some(&dir), &id, turn);
|
||||
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
|
||||
// The id is checked for a change elsewhere again while the plug-ins are held.
|
||||
let installed = match vectorcraft_plugins::registry::install_for_load(
|
||||
plugin.with_source(path.display().to_string()),
|
||||
&load.changes,
|
||||
Some(token),
|
||||
attach,
|
||||
) {
|
||||
Ok(Some(p)) => {
|
||||
load.changes.installed(&p);
|
||||
true
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
false
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
false
|
||||
}
|
||||
};
|
||||
// A grant put back for a module that didn't install is removed again, so the
|
||||
// store doesn't grant those bytes at the next launch.
|
||||
if back.is_some() && !installed {
|
||||
if self.store_grant_in(turn, &id, None) {
|
||||
written.insert(id.clone(), false);
|
||||
grants.remove(&id);
|
||||
load.retired.insert(id, g);
|
||||
} else {
|
||||
log::warn!("couldn't remove the grant put back for the stored plug-in {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -525,29 +915,213 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
let id = plugin.id().to_string();
|
||||
// The storage is made before the plug-ins are held: making it reads the store.
|
||||
let storage = plugin_storage(Some(&dir), &id, turn);
|
||||
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
|
||||
// The id is checked for a change elsewhere again while the plug-ins are held.
|
||||
let p = match vectorcraft_plugins::registry::install_for_load(
|
||||
plugin.with_source(path.display().to_string()),
|
||||
&load.changes,
|
||||
None,
|
||||
attach,
|
||||
) {
|
||||
Ok(Some(p)) => p,
|
||||
Ok(None) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
load.changes.installed(&p);
|
||||
// In the same turn: the grants for the id stop counting, the process's and the
|
||||
// store's, so no session sees the earlier module as approved. A module installed
|
||||
// in its place meanwhile keeps the process's grant recorded for it.
|
||||
vectorcraft_plugins::registry::revoke_if_installed(&id, p.serial());
|
||||
if let Some(g) = grants.remove(&id) {
|
||||
load.retired.insert(id.clone(), g);
|
||||
}
|
||||
if named(&written, &id) {
|
||||
let writes = self.grant_writes();
|
||||
if self.store_grant_in(turn, &id, None) {
|
||||
written.insert(id.clone(), false);
|
||||
} else if self.holds_plugin_grant(&id) {
|
||||
self.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let kept = read_grants(&dir);
|
||||
for id in &asks_nothing {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
let named = match &kept {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
}
|
||||
|
||||
/// Whether the loads of the stored plug-ins and of the Additional Plug-ins Folder go on after
|
||||
/// the call that starts them ([`Session::attach_plugin_store`], [`Session::load_stored_plugins`],
|
||||
/// preferences that set the folder): the app turns it on for its launch so that its window
|
||||
/// shows while they load, installs what loaded with [`Session::poll_plugin_loads`] as its
|
||||
/// frames go by, and turns it off once the launch's loads have started. Off (the default),
|
||||
/// those calls return once what loaded is installed, the loads still running from before
|
||||
/// included.
|
||||
pub fn load_plugins_in_background(&mut self, on: bool) {
|
||||
self.plugin_loads_in_background = on;
|
||||
}
|
||||
|
||||
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
|
||||
/// load's file-name order, up to the first module still loading, without waiting → whether
|
||||
/// some are still loading. A load starts once the loads before it are done. When another
|
||||
/// session or process is changing the plug-ins or the store, nothing installs until a later
|
||||
/// call.
|
||||
pub fn poll_plugin_loads(&mut self) -> bool {
|
||||
while let Some(mut next) = self.plugin_loads.pop_front() {
|
||||
next.start();
|
||||
if !next.ready() {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
}
|
||||
let Some((held, turn)) = self.plugin_install_turn_now(next.creates_store()) else {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
};
|
||||
if named {
|
||||
let writes = self.grant_writes();
|
||||
if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id, writes);
|
||||
self.install_plugin_load(&mut next, &turn);
|
||||
if !next.done() {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
}
|
||||
self.end_plugin_load(next, &turn);
|
||||
drop((turn, held));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Waits for every plug-in load still running and installs what they loaded, in the order the
|
||||
/// loads started. Plug-in commands, and commands that may edit, call it first
|
||||
/// ([`Session::execute`]).
|
||||
pub fn finish_plugin_loads(&mut self) {
|
||||
while let Some(next) = self.plugin_loads.pop_front() {
|
||||
self.finish_plugin_load(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the plug-in loads still running without installing more of what they load: the app
|
||||
/// calls it as it quits. Modules not started are dropped, and the ones running are given until
|
||||
/// their deadline, so the launch marker is not left naming a plug-in that was loading. Each load
|
||||
/// then ends as one that finished does for what it installed; a folder's end saves the disabled
|
||||
/// list only when the store's turn can be taken without waiting.
|
||||
pub fn cancel_plugin_loads(&mut self) {
|
||||
while let Some(mut load) = self.plugin_loads.pop_front() {
|
||||
load.cancel();
|
||||
// A stored load's grants were settled as each module installed: its end writes nothing.
|
||||
if !load.creates_store() {
|
||||
self.end_plugin_load(load, &StoreTurn::unheld());
|
||||
continue;
|
||||
}
|
||||
// Another session changing the plug-ins isn't waited for either: the folder's load then
|
||||
// ends without the store's turn, so the grants of what it installed are still forgotten
|
||||
// and the store isn't written.
|
||||
let Some(held) = crate::cmd::plugin::try_hold_plugin_changes() else {
|
||||
self.end_plugin_load(load, &StoreTurn::unheld());
|
||||
continue;
|
||||
};
|
||||
// A store another window or process is using isn't waited for: the turn then isn't
|
||||
// held, and the folder's end writes nothing to the store.
|
||||
let turn = match self.plugin_dir.as_deref().map(try_lock_store) {
|
||||
Some(Ok(Some(file))) => StoreTurn { lock: Some(file) },
|
||||
_ => StoreTurn::unheld(),
|
||||
};
|
||||
self.end_plugin_load(load, &turn);
|
||||
drop((turn, held));
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for `load`'s modules and installs them as they load, in turns on the store, then
|
||||
/// ends it → its report (a folder's; `null` for the stored plug-ins).
|
||||
pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value {
|
||||
load.start();
|
||||
loop {
|
||||
load.wait();
|
||||
let held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_install_turn(load.creates_store());
|
||||
self.install_plugin_load(&mut load, &turn);
|
||||
if load.done() {
|
||||
let report = self.end_plugin_load(load, &turn);
|
||||
drop((turn, held));
|
||||
return report;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A turn on the store for installing what a load loaded, taken after
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`]: the folder's own turn
|
||||
/// ([`Session::plugin_store_turn`]) when `create`, else one that goes ahead without a store
|
||||
/// folder ([`Session::plugin_store_turn_for_load`]). One that can't be locked goes ahead
|
||||
/// unheld.
|
||||
fn plugin_install_turn(&self, create: bool) -> StoreTurn {
|
||||
if create { self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()) } else { self.plugin_store_turn_for_load() }
|
||||
}
|
||||
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] and [`Session::plugin_install_turn`] without
|
||||
/// waiting: `None` while another session holds the one or another window or process the other.
|
||||
fn plugin_install_turn_now(&self, create: bool) -> Option<(MutexGuard<'static, ()>, StoreTurn)> {
|
||||
let held = crate::cmd::plugin::try_hold_plugin_changes()?;
|
||||
let turn = match self.plugin_dir.as_deref() {
|
||||
Some(dir) if create || dir.is_dir() => match try_lock_store(dir) {
|
||||
Ok(Some(file)) => StoreTurn { lock: Some(file) },
|
||||
Ok(None) => return None,
|
||||
Err(e) => {
|
||||
log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display());
|
||||
StoreTurn::unheld()
|
||||
}
|
||||
},
|
||||
_ => StoreTurn::unheld(),
|
||||
};
|
||||
Some((held, turn))
|
||||
}
|
||||
|
||||
/// Whether plug-ins are still loading on worker threads ([`Session::load_plugins_in_background`]).
|
||||
pub fn plugins_loading(&self) -> bool {
|
||||
!self.plugin_loads.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps `load` to install after the loads started before it; without
|
||||
/// [`Session::load_plugins_in_background`], waits for them all and installs what they loaded.
|
||||
pub(crate) fn queue_plugin_load(&mut self, load: PluginLoad) {
|
||||
self.plugin_loads.push_back(load);
|
||||
// The first load starts now; one queued after it starts once those before it are done.
|
||||
if let [only] = self.plugin_loads.make_contiguous() {
|
||||
only.start();
|
||||
}
|
||||
if !self.plugin_loads_in_background {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs what `load` has loaded so far, without waiting, in `turn`.
|
||||
fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) {
|
||||
match load {
|
||||
PluginLoad::Stored(load) => self.install_stored_plugins(load, turn),
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's).
|
||||
fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value {
|
||||
// The loads queued after it count what it installed as their own: one of theirs replaces
|
||||
// it, as it would have with the loads run one after the other.
|
||||
if let Some(ended) = load.changes() {
|
||||
for later in &mut self.plugin_loads {
|
||||
if let Some(changes) = later.changes_mut() {
|
||||
changes.adopt(ended);
|
||||
}
|
||||
}
|
||||
}
|
||||
match load {
|
||||
// A stored load's grants were settled as each module installed.
|
||||
PluginLoad::Stored(_) => Value::Null,
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or
|
||||
@@ -659,8 +1233,17 @@ impl Session {
|
||||
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
|
||||
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
|
||||
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
self.counted(dir, stored_grants(dir))
|
||||
}
|
||||
|
||||
/// `grants`, read from the plug-in store `dir`, without those the process doesn't count for
|
||||
/// that folder ([`Session::counted_grants`]).
|
||||
fn counted(
|
||||
&self,
|
||||
dir: &Path,
|
||||
mut grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
let key = plugin_store_key(dir);
|
||||
let mut grants = stored_grants(dir);
|
||||
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
|
||||
grants.remove(id);
|
||||
|
||||
@@ -2196,6 +2196,550 @@ fn installed_plugins_are_kept_in_the_store() {
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
}
|
||||
|
||||
/// Held by the tests that set [`crate::store::BEFORE_STORED_LOAD`].
|
||||
static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// A stored module's load waits on its worker thread until the test lets it go
|
||||
/// ([`crate::store::BEFORE_STORED_LOAD`]). The hook is cleared when this is dropped.
|
||||
struct HeldLoad {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl HeldLoad {
|
||||
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
|
||||
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
|
||||
fn new(path: std::path::PathBuf) -> HeldLoad {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
|
||||
if p != path {
|
||||
return;
|
||||
}
|
||||
e.store(true, Ordering::SeqCst);
|
||||
if !(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
g.load(Ordering::SeqCst)
|
||||
}) {
|
||||
q.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
HeldLoad { _lock: lock, entered, go, gave_up }
|
||||
}
|
||||
|
||||
fn entered(&self) -> bool {
|
||||
self.entered.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn gave_up(&self) -> bool {
|
||||
self.gave_up.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HeldLoad {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A store holding the module of a filter `id` in `<id>.wasm`.
|
||||
fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::PathBuf) {
|
||||
let folder = crate::tests_links::Folder::new(name);
|
||||
let path = folder.0.join(format!("{id}.wasm"));
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
std::fs::write(&path, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
(folder, path)
|
||||
}
|
||||
|
||||
/// With loads in the background, attaching a plug-in store returns while a stored module is
|
||||
/// still loading: the plug-in installs once its load is done, at the next plug-in command.
|
||||
#[test]
|
||||
fn a_store_attached_with_background_loads_returns_before_its_plugins_load() {
|
||||
let id = "test.engine.background";
|
||||
let (folder, path) = store_with("plugin-background", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let returned_while_loading = !held.gave_up();
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(returned_while_loading, "attaching the store waited for the module to load");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing installs before its load is done");
|
||||
assert!(s.poll_plugin_loads(), "still loading");
|
||||
held.release();
|
||||
let listed = run(&mut s, "plugin.list", json!({}));
|
||||
assert!(listed.to_string().contains(id), "plugin.list waits for the load and lists it: {listed}");
|
||||
assert!(!s.poll_plugin_loads());
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// Stored files that can't be opened take nothing from the bytes the stored plug-ins may read
|
||||
/// together: a module after 512 MiB of them still installs.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn unreadable_stored_files_leave_the_store_budget_to_the_others() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let id = "test.engine.budget.after";
|
||||
let (folder, _) = store_with("plugin-budget-unreadable", id);
|
||||
let per_file = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
let locked: Vec<_> = (0..crate::store::MAX_PLUGIN_STORE.div_ceil(per_file))
|
||||
.map(|n| {
|
||||
// Sparse files sorted before the module, each as long as a module may be.
|
||||
let path = folder.0.join(format!("a{n:03}.wasm"));
|
||||
std::fs::File::create(&path).unwrap().set_len(per_file).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
path
|
||||
})
|
||||
.collect();
|
||||
// A process that may read any file (root) opens them all: nothing to check.
|
||||
if std::fs::File::open(&locked[0]).is_ok() {
|
||||
return;
|
||||
}
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::get(id).is_some();
|
||||
for path in &locked {
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
assert!(installed, "the files that couldn't be opened used up the store's bytes");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// A stored file whose read fails on the worker thread gives back what it took of the bytes the
|
||||
/// stored plug-ins may read together, so a module after files that use them all up still installs.
|
||||
#[test]
|
||||
fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() {
|
||||
struct Unhook {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
impl Drop for Unhook {
|
||||
fn drop(&mut self) {
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
let id = "test.engine.budget.failed";
|
||||
let (folder, module) = store_with("plugin-budget-failed", id);
|
||||
let len = std::fs::metadata(&module).unwrap().len();
|
||||
// Files sorted before the module, as long as it, that use up the bytes this test's store may read.
|
||||
for n in 0..4 {
|
||||
std::fs::write(folder.0.join(format!("a{n:03}.wasm")), vec![0; len as usize]).unwrap();
|
||||
}
|
||||
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(4 * len));
|
||||
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
|
||||
// Each of those files goes away as its load starts, so its read fails.
|
||||
let dir = folder.0.clone();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
|
||||
if p.parent() == Some(dir.as_path()) && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('a')) {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::get(id).is_some();
|
||||
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE));
|
||||
assert!(installed, "the files whose reads failed used up the store's bytes");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// A stored file replaced after its module loaded, by one of the same length with the same modified
|
||||
/// time, is skipped: its content no longer holds the module. That holds for a file modified moments
|
||||
/// ago and for one modified an hour ago.
|
||||
#[test]
|
||||
fn a_stored_file_replaced_with_the_same_stamp_while_it_loaded_is_skipped() {
|
||||
struct Unhook {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
impl Drop for Unhook {
|
||||
fn drop(&mut self) {
|
||||
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
|
||||
let hour = std::time::Duration::from_secs(3600);
|
||||
// A modified time ahead of the clock counts as moments ago however long the test takes.
|
||||
for (n, modified) in [std::time::SystemTime::now() + hour, std::time::SystemTime::now() - hour].into_iter().enumerate() {
|
||||
let id = format!("test.engine.background.replaced{n}");
|
||||
let (folder, path) = store_with(&format!("plugin-background-replaced{n}"), &id);
|
||||
std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap();
|
||||
let replaced = path.clone();
|
||||
// Set once the file holds other bytes with the old stamp, so the case reaches the check.
|
||||
let rewritten = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let done = rewritten.clone();
|
||||
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
|
||||
if p == replaced {
|
||||
let mut bytes = std::fs::read(p).unwrap();
|
||||
bytes.reverse();
|
||||
std::fs::write(p, &bytes).unwrap();
|
||||
std::fs::File::options().write(true).open(p).unwrap().set_modified(modified).unwrap();
|
||||
done.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::remove(&id);
|
||||
assert!(rewritten.load(std::sync::atomic::Ordering::SeqCst), "the file was not replaced while it loaded ({n})");
|
||||
assert!(!installed, "the module installed from a file that no longer holds it ({n})");
|
||||
}
|
||||
}
|
||||
|
||||
/// While a session loads the plug-ins folder in the background, another session's `plugin.list`
|
||||
/// reports the folder as loading; once the load installs, it reports what loaded.
|
||||
#[test]
|
||||
fn another_session_lists_a_folder_still_loading_as_loading() {
|
||||
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
|
||||
if !in_own_process("another_session_lists_a_folder_still_loading_as_loading") {
|
||||
return;
|
||||
}
|
||||
let id = "test.engine.listedloading";
|
||||
let (folder, _) = store_with("plugin-listed-loading", id);
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
|
||||
let mut other = session();
|
||||
let listed = run(&mut other, "plugin.list", json!({}));
|
||||
assert_eq!(listed["folder"]["loading"], true, "{listed}");
|
||||
background.finish_plugin_loads();
|
||||
let listed = run(&mut other, "plugin.list", json!({}));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(listed["folder"]["loaded"], json!([id]), "{listed}");
|
||||
assert!(listed["folder"].get("loading").is_none(), "{listed}");
|
||||
}
|
||||
|
||||
/// A `plugin.reload` doesn't replace the record of a folder load that started after it: once that
|
||||
/// load installs, `plugin.list` reports its folder.
|
||||
#[test]
|
||||
fn a_reload_keeps_the_record_of_a_folder_load_started_after_it() {
|
||||
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
|
||||
if !in_own_process("a_reload_keeps_the_record_of_a_folder_load_started_after_it") {
|
||||
return;
|
||||
}
|
||||
let (reloaded, later) = ("test.engine.reloadorder.reloaded", "test.engine.reloadorder.later");
|
||||
let (reload_folder, _) = store_with("plugin-reload-order-reloaded", reloaded);
|
||||
let (later_folder, _) = store_with("plugin-reload-order-later", later);
|
||||
let other = std::rc::Rc::new(std::cell::RefCell::new(None));
|
||||
let started = other.clone();
|
||||
let path = later_folder.0.display().to_string();
|
||||
// Another session sets the plug-ins folder while the reload loads.
|
||||
crate::cmd::plugin::BEFORE_RELOAD_INSTALLS.set(Some(Box::new(move || {
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
*started.borrow_mut() = Some(background);
|
||||
})));
|
||||
let mut s = session();
|
||||
run(&mut s, "plugin.reload", json!({"path": reload_folder.0.display().to_string()}));
|
||||
let mut background = other.borrow_mut().take().expect("the other session's load started while the reload loaded");
|
||||
background.finish_plugin_loads();
|
||||
let listed = run(&mut s, "plugin.list", json!({}));
|
||||
assert!(vectorcraft_plugins::registry::remove(reloaded) && vectorcraft_plugins::registry::remove(later));
|
||||
assert_eq!(listed["folder"]["loaded"], json!([later]), "{listed}");
|
||||
}
|
||||
|
||||
/// The plug-ins folder already loaded isn't loaded again when the preferences are applied, unless
|
||||
/// a file in it found no loader thread to load it: then it is.
|
||||
#[test]
|
||||
fn a_folder_in_which_a_file_found_no_thread_is_loaded_again() {
|
||||
if !in_own_process("a_folder_in_which_a_file_found_no_thread_is_loaded_again") {
|
||||
return;
|
||||
}
|
||||
let id = "test.engine.nothread";
|
||||
let (folder, _) = store_with("plugin-no-thread", id);
|
||||
let mut s = session();
|
||||
run(&mut s, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "installed from the folder");
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a folder already loaded was loaded again");
|
||||
crate::cmd::plugin::folder_found_no_thread();
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "the folder wasn't loaded again");
|
||||
}
|
||||
|
||||
/// A folder listed while the stored plug-ins still load, in the same session, replaces a stored
|
||||
/// plug-in with a module of the same id once it loads, as it does when the loads run one after the
|
||||
/// other: what an earlier load of the session installed doesn't count as a change made elsewhere.
|
||||
#[test]
|
||||
fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.engine.queued.same";
|
||||
let (store, stored) = store_with("plugin-queued-store", id);
|
||||
let (folder, from_folder) = store_with("plugin-queued-folder", id);
|
||||
let held = HeldLoad::new(stored);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(store.0.clone());
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
s.prefs.plugins_folder = folder.0.display().to_string();
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(source.as_deref(), Some(from_folder.display().to_string().as_str()), "the folder's module replaces the stored one");
|
||||
}
|
||||
|
||||
/// A query that only reads runs while the stored plug-ins load in the background, and doesn't
|
||||
/// wait for them; a plug-in command does.
|
||||
#[test]
|
||||
fn a_query_runs_while_the_plugins_load() {
|
||||
let id = "test.engine.background.query";
|
||||
let (folder, path) = store_with("plugin-background-query", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
run(&mut s, "file.new", json!({}));
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
run(&mut s, "document.info", json!({}));
|
||||
let waited = held.gave_up() || !s.plugins_loading();
|
||||
held.release();
|
||||
assert!(!waited, "document.info waited for the plug-ins to load");
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// The stored plug-ins load without holding the lock that `plugin.install` and `plugin.remove`
|
||||
/// take, so another session's plug-in changes don't wait for them.
|
||||
#[test]
|
||||
fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
let id = "test.engine.unlocked";
|
||||
let (folder, path) = store_with("plugin-unlocked", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while !held.entered() && !held.gave_up() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
|
||||
// tenth of the yields the held load waits before it gives up).
|
||||
let free = (0..100_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
crate::cmd::plugin::plugin_changes_free()
|
||||
});
|
||||
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
|
||||
let gave_up = held.gave_up();
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
assert!(!gave_up, "the held load gave up before the lock was looked at");
|
||||
assert!(free, "the lock was held while the module loaded");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// Loads canceled as the app quits still end for what they installed: a stored module listing no
|
||||
/// permissions that installed before a later one finished loading has its id's grant forgotten,
|
||||
/// in the process and in `grants.json`, and the module still loading doesn't install.
|
||||
#[test]
|
||||
fn canceled_loads_forget_the_grants_of_what_they_installed() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let (first, later) = ("test.engine.cancel.a", "test.engine.cancel.b");
|
||||
let (folder, _) = store_with("plugin-cancel", first);
|
||||
let held_path = folder.0.join(format!("{later}.wasm"));
|
||||
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(first, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
|
||||
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
let held = HeldLoad::new(held_path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
s.cancel_plugin_loads();
|
||||
// The file goes once it holds no grant.
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
|
||||
assert!(vectorcraft_plugins::registry::granted(first).is_none());
|
||||
assert!(vectorcraft_plugins::registry::get(later).is_none(), "the module still loading doesn't install");
|
||||
assert!(!s.plugins_loading());
|
||||
drop(held);
|
||||
assert!(vectorcraft_plugins::registry::remove(first));
|
||||
}
|
||||
|
||||
/// The grants for a stored module that lists no permissions stop counting when it installs, in the
|
||||
/// same turn, while a later module of the load is still loading.
|
||||
#[test]
|
||||
fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let (first, later) = ("test.engine.retire.a", "test.engine.retire.b");
|
||||
let (folder, _) = store_with("plugin-retire", first);
|
||||
let held_path = folder.0.join(format!("{later}.wasm"));
|
||||
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(first, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
|
||||
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
let held = HeldLoad::new(held_path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
assert!(s.plugins_loading(), "the second module is still loading");
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
|
||||
assert!(vectorcraft_plugins::registry::granted(first).is_none());
|
||||
drop(held);
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(first));
|
||||
assert!(vectorcraft_plugins::registry::remove(later));
|
||||
}
|
||||
|
||||
/// A grant the load removed for a stored module without permissions doesn't go back for a later
|
||||
/// file with the same id when another window or process granted the id since: that grant stays, and
|
||||
/// the later module, which it doesn't cover, is skipped.
|
||||
#[test]
|
||||
fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.kept";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-kept");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap();
|
||||
std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap();
|
||||
let held = HeldLoad::new(later.clone());
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(id).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Another process grants the id for another module while the later file loads.
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"path": triangle()}]}));
|
||||
std::fs::write(&grants, entry(sha256_hex(&other))).unwrap();
|
||||
drop(held);
|
||||
s.finish_plugin_loads();
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
let listed: Vec<Value> = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap();
|
||||
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed");
|
||||
assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::<Vec<_>>(), [json!(sha256_hex(&other))], "{listed:?}");
|
||||
}
|
||||
|
||||
/// A grant the load removed for a stored module without permissions that can't be written back for
|
||||
/// a later file with the same id leaves that file's module uninstalled: the store doesn't grant it.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.unwritten";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-unwritten");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
|
||||
// The first write removes the grant; the second, which puts it back, finds a folder where the
|
||||
// file goes and fails.
|
||||
let blocked = grants.clone();
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
let _ = std::fs::remove_file(&blocked);
|
||||
std::fs::create_dir_all(&blocked).unwrap();
|
||||
})));
|
||||
})));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(None);
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
let _ = std::fs::remove_dir(&grants);
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed without its grant in the store");
|
||||
}
|
||||
|
||||
/// A grant the load put back for a later stored file with the same id is removed again when that
|
||||
/// file's module doesn't install because the id was installed elsewhere meanwhile: the store doesn't
|
||||
/// grant bytes that weren't installed.
|
||||
#[test]
|
||||
fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.superseded";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-superseded");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
let plain = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
std::fs::write(&first, &plain).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
|
||||
// The first write removes the grant; while the second puts it back, the id is installed
|
||||
// elsewhere.
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
vectorcraft_plugins::registry::install_bytes(&plain).unwrap();
|
||||
})));
|
||||
})));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(None);
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
// A grants file that went away holds no grant; one still there must read as a list.
|
||||
let listed: Vec<Value> = match std::fs::read(&grants) {
|
||||
Ok(b) => serde_json::from_slice(&b).unwrap(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![],
|
||||
Err(e) => panic!("the grants file could not be read: {e}"),
|
||||
};
|
||||
assert_eq!(source, None, "the later module replaced the one installed elsewhere");
|
||||
assert!(listed.iter().all(|e| e["id"] != id), "the grant put back stayed in the store: {listed:?}");
|
||||
}
|
||||
|
||||
/// A session that waits for its loads and sets the plug-ins folder another session is still
|
||||
/// loading in the background loads the folder itself: its plug-in is installed when `prefs.set`
|
||||
/// returns, and the other session's load, when it installs, counts the same module as loaded.
|
||||
#[test]
|
||||
fn a_folder_another_session_is_loading_is_loaded_by_a_session_that_waits() {
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.engine.sharedfolder";
|
||||
let (folder, _) = store_with("plugin-shared-folder", id);
|
||||
let path = folder.0.display().to_string();
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
assert!(background.plugins_loading(), "the folder loads in the background");
|
||||
let mut waits = session();
|
||||
run(&mut waits, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "prefs.set returned before the folder's plug-in installed");
|
||||
let report = run(&mut background, "plugin.list", json!({}));
|
||||
assert!(!background.plugins_loading());
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "{report}");
|
||||
}
|
||||
|
||||
/// A heavy test filter `id` that counts `steps` down, then adds a triangle named "Plug-in".
|
||||
fn heavy(id: &str, steps: u64) -> Vec<u8> {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#);
|
||||
@@ -4085,6 +4629,168 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
|
||||
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
|
||||
}
|
||||
|
||||
/// The manifest of a filter at `api` 3 with id `id` that asks for the document information
|
||||
/// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or
|
||||
/// nothing).
|
||||
fn context_manifest(id: &str, context: &str, rest: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"context":{context}{rest}}}"#)
|
||||
}
|
||||
|
||||
/// Installs `src` granted `doc.read` and `doc.write`, in place of any module with its id.
|
||||
fn install_reading(s: &mut Session, src: &str) -> Value {
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
|
||||
run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true}))
|
||||
}
|
||||
|
||||
/// A filter at `api` 3 whose manifest lists `context` is given the document's settings, artboards,
|
||||
/// layers and swatches in `_context.document` with nothing selected: plain values, hidden and
|
||||
/// locked layers with their flags, the active artboard and the current layer marked, and the
|
||||
/// document's name without its folder. A filter that doesn't list `context` is given none, and one
|
||||
/// that lists it without `doc.read` or below `api` 3 doesn't install.
|
||||
#[test]
|
||||
fn an_unselected_filter_reads_the_document_context_it_asks_for() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let mut s = session();
|
||||
run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 100, "height": 50}));
|
||||
let hidden = run(&mut s, "layer.new", json!({"name": "Hidden", "visible": false}))["id"].as_u64().unwrap();
|
||||
let locked = run(&mut s, "layer.newSublayer", json!({"parent": hidden, "name": "Locked", "locked": true}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "layer.setCurrent", json!({"id": locked}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.doc_mut().unwrap().path = Some("/private/folder/Poster.vectorcraft".into());
|
||||
let second = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(second);
|
||||
let id = "test.engine.context";
|
||||
let all = r#"["settings","artboards","layers","swatches"]"#;
|
||||
let installed = install_reading(&mut s, &tpl::returning(&context_manifest(id, all, ""), r#"{"objects":[]}"#));
|
||||
assert_eq!(installed["context"], json!(["settings", "artboards", "layers", "swatches"]));
|
||||
let swatches = run(&mut s, "swatch.list", json!({}))["swatches"].clone();
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
let given = FilterRun::prepare(&s, &json!({"id": id})).unwrap().params_json()["_context"]["document"].clone();
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
assert_eq!(given["revision"], json!(st.revision));
|
||||
let board = &d.artboards[1];
|
||||
let settings = json!({
|
||||
"name": "Poster.vectorcraft", "colorMode": "rgb", "units": d.units.label(), "width": board.rect.width(),
|
||||
"height": board.rect.height(), "bleed": d.setup.bleed, "rasterEffectsPpi": d.raster_ppi(), "activeArtboard": second,
|
||||
});
|
||||
assert_eq!(given["settings"], settings);
|
||||
let boards: Vec<Value> = d
|
||||
.artboards
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, a)| json!({"id": a.id, "index": i, "name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1], "active": i == 1}))
|
||||
.collect();
|
||||
assert_eq!((boards.len(), &given["artboards"]), (2, &json!(boards)));
|
||||
let layers = given["layers"].as_array().unwrap();
|
||||
let rows: Vec<(String, u64, bool, bool, bool)> = layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
(l["name"].as_str().unwrap().to_string(), l["depth"].as_u64().unwrap(), l["visible"] == true, l["locked"] == true, l["current"] == true)
|
||||
})
|
||||
.collect();
|
||||
let bottom = d.layers[0].display_name();
|
||||
assert_eq!(rows, [(bottom, 0, true, false, false), ("Hidden".into(), 0, false, false, false), ("Locked".into(), 1, true, true, true)]);
|
||||
assert_eq!((&layers[0]["parentId"], &layers[1]["sublayers"], &layers[2]["parentId"]), (&Value::Null, &json!(1), &json!(hidden)));
|
||||
assert_eq!((&layers[1]["id"], &layers[2]["id"]), (&json!(hidden), &json!(locked)));
|
||||
assert_eq!(given["swatches"], swatches, "as swatch.list lists them");
|
||||
assert!(given["swatches"].as_array().unwrap().iter().any(|w| w["name"] == "Tone" && w["global"] == true));
|
||||
assert!(!given.to_string().contains("/private/folder"), "no path: {given}");
|
||||
// Only the sections asked for.
|
||||
let some = "test.engine.context.some";
|
||||
install_reading(&mut s, &tpl::returning(&context_manifest(some, r#"["layers"]"#, ""), r#"{"objects":[]}"#));
|
||||
let given = FilterRun::prepare(&s, &json!({"id": some})).unwrap().params_json()["_context"]["document"].clone();
|
||||
let keys: Vec<&String> = given.as_object().unwrap().keys().collect();
|
||||
assert_eq!(keys.len(), 2, "{keys:?}");
|
||||
assert!(given.get("layers").is_some() && given.get("revision").is_some());
|
||||
// A filter without `context` is given none.
|
||||
let legacy = "test.engine.context.legacy";
|
||||
install_reading(&mut s, &tpl::returning(&tpl::manifest(legacy, "filter", "{}"), r#"{"objects":[]}"#));
|
||||
assert!(FilterRun::prepare(&s, &json!({"id": legacy})).unwrap().params_json()["_context"].get("document").is_none());
|
||||
// Without `doc.read`, or below `api` 3, it doesn't install.
|
||||
let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`";
|
||||
for manifest in [
|
||||
format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}}"#),
|
||||
format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}}"#),
|
||||
] {
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap());
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})).unwrap_err();
|
||||
assert!(e.to_string().contains(needs), "{manifest}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in command, of a filter or of a live effect, whose manifest lists `context` is given it
|
||||
/// too, with nothing selected.
|
||||
#[test]
|
||||
fn a_plugin_command_reads_the_document_context_without_a_selection() {
|
||||
let mut s = session();
|
||||
let made = json!({"objects": [{"path": triangle(), "name": "Saw layers"}]}).to_string();
|
||||
for (id, kind, permissions) in [
|
||||
("test.engine.context.command", "filter", r#"["doc.read","doc.write"]"#),
|
||||
("test.engine.context.effectcommand", "effect", r#"["doc.read","doc.write","effect.render"]"#),
|
||||
] {
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","kind":"{kind}","api":3,"permissions":{permissions},"context":["layers"],"commands":[{{"id":"look","label":"Look"}}]}}"#
|
||||
);
|
||||
let src = tpl::when_given_else(&manifest, tpl::Given::Params, r#""layers":["#, &made, r#"{"objects":[]}"#);
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
|
||||
let grant: Vec<Value> = serde_json::from_str(permissions).unwrap();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let ids = run(&mut s, &format!("plugin.{id}.look"), json!({}))["ids"].clone();
|
||||
assert_eq!(ids.as_array().map(Vec::len), Some(1), "{kind}: {ids}");
|
||||
assert_eq!(node(&s, NodeId(ids[0].as_u64().unwrap())).name.as_deref(), Some("Saw layers"), "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A document context holds at most [`cmd::plugin::MAX_CONTEXT_ITEMS`] rows in
|
||||
/// [`cmd::plugin::MAX_CONTEXT_BYTES`] bytes: past either, the run fails before the plug-in starts,
|
||||
/// with the document and undo history as they were. Each row comes off the run's instruction
|
||||
/// budget.
|
||||
#[test]
|
||||
fn the_document_context_is_capped_and_its_rows_cost_instructions() {
|
||||
use cmd::plugin::{CONTEXT_FUEL_PER_ITEM, FilterRun, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
|
||||
let mut s = session();
|
||||
let id = "test.engine.context.cap";
|
||||
install_reading(&mut s, &tpl::returning(&context_manifest(id, r#"["swatches"]"#, ""), r#"{"objects":[]}"#));
|
||||
let p = json!({"id": id});
|
||||
let listed = run(&mut s, "swatch.list", json!({}))["swatches"].as_array().unwrap().len();
|
||||
let add = |s: &mut Session, n: usize| {
|
||||
s.edit("Set up", |d, _| {
|
||||
let base = d.swatches.last().unwrap().clone();
|
||||
let at = d.swatches.len();
|
||||
d.swatches.extend((at..at + n).map(|i| vectorcraft_color::Swatch { name: format!("Many {i}"), ..base.clone() }));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
add(&mut s, MAX_CONTEXT_ITEMS - listed);
|
||||
let full = FilterRun::prepare(&s, &p).unwrap();
|
||||
assert_eq!(full.params_json()["_context"]["document"]["swatches"].as_array().map(Vec::len), Some(MAX_CONTEXT_ITEMS));
|
||||
assert_eq!(full.limits().fuel_base, full.plugin().limits().fuel_base - MAX_CONTEXT_ITEMS as u64 * CONTEXT_FUEL_PER_ITEM);
|
||||
let too_large = "the document information the plug-in asks for is too large to hand over";
|
||||
add(&mut s, 1);
|
||||
let refused = |s: &mut Session| {
|
||||
let Err(e) = FilterRun::prepare(s, &p) else { panic!("prepared past the cap") };
|
||||
assert!(e.to_string().contains(too_large), "{e}");
|
||||
let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(too_large), "{e}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo));
|
||||
};
|
||||
refused(&mut s);
|
||||
// A few rows past the byte cap are refused as well.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
s.edit("Set up", |d, _| {
|
||||
d.swatches.last_mut().unwrap().name = "n".repeat(MAX_CONTEXT_BYTES);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
refused(&mut s);
|
||||
}
|
||||
|
||||
/// A run past its memory budget fails before the plug-in starts, with the document and undo
|
||||
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
|
||||
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
|
||||
|
||||
@@ -391,6 +391,40 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not()
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_script_reads_e4x_and_has_the_xml_objects() {
|
||||
let dir = fresh_folder("e4x");
|
||||
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});
|
||||
// Script text: literals, selectors, for each and the four constructors.
|
||||
let text = "var x = <list><item id=\"a\">1</item><item id=\"b\">2</item></list>;\n\
|
||||
vc.log(x.item.length() + ' ' + x.item.(@id == 'b').toString() + ' ' + x..item[0].@id);\n\
|
||||
var sum = 0; for each (var i in x.item) sum += Number(i); vc.log(sum);\n\
|
||||
vc.log(new XML('<a><b/></a>').b.length() + new XMLList('<c/><c/>').length());\n\
|
||||
vc.log(new Namespace('p', 'urn:p').prefix + ' ' + new QName('urn:q', 'n').localName + ' ' + isXMLName('ok'));\n\
|
||||
vc.log(typeof setDefaultXMLNamespace + ' ' + (1 < 2));\n";
|
||||
let r = run(&mut s, text).unwrap();
|
||||
assert_eq!(r["log"], json!(["2 2 a", 3, 3, "p n true", "function true"]), "{r}");
|
||||
// A .js file, a file it includes, eval, Function and $.evalFile read XML as well.
|
||||
write("lib.jsxinc", "var fromLib = <lib n=\"7\"/>.@n.toString();\n");
|
||||
write("more.jsx", "<m>{fromLib}</m>.toString();\n");
|
||||
let modern = "#include \"lib.jsxinc\"\nlet tag = <t>{fromLib}</t>;\nvc.log(tag.toString());\n\
|
||||
vc.log(eval('<e>5</e>').toString());\nvc.log(new Function('return <f>6</f>.toString()')());\n\
|
||||
vc.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!(["7", "5", "6", "7"]), "{r}");
|
||||
// A named engine first made by a .js run gives a later .jsx run the XML objects too.
|
||||
s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap();
|
||||
let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('<k>2</k>').toString());"))).unwrap();
|
||||
assert_eq!(later["log"], json!(["2"]), "{later}");
|
||||
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()));
|
||||
|
||||
@@ -1463,6 +1463,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The object a click of the active tool at `p` with `mods` would act on
|
||||
/// ([`vectorcraft_tools::Tool::hover_object`]), for Smart Guides › Object Highlighting. None
|
||||
/// while Cmd lends a selection tool to the press ([`Self::lent_tool_at`]).
|
||||
pub fn hover_object(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Option<NodeId> {
|
||||
if mods.cmd && self.lender.is_none() && !self.tool_editing() && self.lent_tool_at(p, &mods, view).is_some() {
|
||||
return None;
|
||||
}
|
||||
self.with_tool_cx(view, |t, cx| t.hover_object(cx, p, mods))
|
||||
}
|
||||
|
||||
pub fn tool_options(&self) -> Value {
|
||||
self.tool.options()
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! the tables below, and each name that reaches outside the document has the `outside` id
|
||||
//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own
|
||||
//! properties of the global object, of each object or function it holds and of each function's
|
||||
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` also
|
||||
//! has are the language's, which reach files and other apps only through the host; `eval` and
|
||||
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` with
|
||||
//! E4X also has are the language's, which reach files and other apps only through the host; `eval` and
|
||||
//! `Function` still have rows, since they run code the checker can't read. A name the host adds
|
||||
//! without a row fails the test.
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_js::{DirectiveName, JsValue, Realm};
|
||||
use vectorcraft_js::{DirectiveName, JsValue, Options, Realm};
|
||||
use vectorcraft_scriptcheck::{Limits, check};
|
||||
|
||||
/// The names that reach outside the document: each with a script that uses it and the `outside` id
|
||||
@@ -110,9 +110,9 @@ fn host_names() -> BTreeSet<String> {
|
||||
text.lines().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// The names a plain JavaScript engine has.
|
||||
/// The names a plain JavaScript engine with E4X has.
|
||||
fn language_names() -> BTreeSet<String> {
|
||||
match Realm::new().run(LIST) {
|
||||
match Realm::with_options(Options { e4x: true, ..Options::default() }, vectorcraft_js::Limits::default()).run(LIST) {
|
||||
Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(),
|
||||
other => panic!("no list: {other:?}"),
|
||||
}
|
||||
|
||||
@@ -906,6 +906,77 @@ proptest! {
|
||||
vectorcraft_plugins::registry::revoke("fuzz.inputs");
|
||||
}
|
||||
|
||||
/// Manifests with a hostile `context` (unknown, repeated and oddly cased sections, long lists,
|
||||
/// junk of every type) with any `api`, kind and permissions parse to an error or to a filter, or
|
||||
/// a live effect with commands, at `api` 3 or later asking for each section once, whose
|
||||
/// `permissions` list `doc.read` so that installing it asks for approval. One that installs and
|
||||
/// echoes its input, with or without a selection, leaves the document as it was, and it still
|
||||
/// renders.
|
||||
#[test]
|
||||
fn hostile_manifest_context_never_crash(
|
||||
kind in prop::sample::select(vec!["filter", "effect", "exporter"]),
|
||||
commands in any::<bool>(),
|
||||
names in prop::collection::vec(prop::sample::select(vec!["settings", "artboards", "layers", "swatches", "Layers", "document", ""]), 0..6),
|
||||
long in prop::option::weighted(0.1, 5usize..300),
|
||||
context in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]),
|
||||
api in prop_oneof![2 => Just(json!(3)), 1 => Just(json!(2)), 1 => Just(json!(4)), 1 => arb_junk()],
|
||||
permissions in prop_oneof![Just(Value::Null), Just(json!([])), Just(json!(["doc.read", "doc.write"])), Just(json!(["doc.read", "effect.render"])), Just(json!(["doc.write"]))],
|
||||
select in any::<bool>(),
|
||||
) {
|
||||
let mut m = json!({"id": "fuzz.context", "name": "Context", "kind": kind, "api": api});
|
||||
if kind == "exporter" {
|
||||
m["extensions"] = json!(["fz"]);
|
||||
}
|
||||
if commands {
|
||||
m["commands"] = json!([{"id": "c", "label": "C"}]);
|
||||
}
|
||||
if !permissions.is_null() {
|
||||
m["permissions"] = permissions;
|
||||
}
|
||||
m["context"] = match (context, long) {
|
||||
(_, Some(n)) => json!(vec!["layers"; n]),
|
||||
(Some(Value::Null) | None, None) => json!(names),
|
||||
(Some(junk), None) => junk,
|
||||
};
|
||||
let text = m.to_string();
|
||||
let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes()));
|
||||
let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?;
|
||||
if let Ok(man) = &parsed {
|
||||
let sections = man.context_sections();
|
||||
prop_assert_eq!(sections.len(), man.context.len(), "{}", text);
|
||||
prop_assert!(sections.iter().enumerate().all(|(i, k)| !sections[..i].contains(k)), "{}", text);
|
||||
let kind_ok = man.kind == Kind::Filter || (man.kind == Kind::Effect && !man.commands.is_empty());
|
||||
prop_assert!(sections.is_empty() || (kind_ok && man.api >= 3), "{}", text);
|
||||
let reads = man.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == "doc.read"));
|
||||
prop_assert!(sections.is_empty() || (man.asks_permissions() && reads), "{}", text);
|
||||
}
|
||||
let mut s = rich_session();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
let module = wat::parse_str(tpl::module(&text, tpl::ECHO, "", 1)).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&module);
|
||||
let grant = json!(["doc.read", "doc.write", "state", "effect.render", "export.write"]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = catch_quiet(|| {
|
||||
let installed = s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant})).is_ok();
|
||||
let _ = s.execute(if select { "select.all" } else { "select.none" }, &json!({}));
|
||||
let ran = installed && s.execute("plugin.run", &json!({"id": "fuzz.context"})).is_ok();
|
||||
if installed {
|
||||
for c in s.commands().into_iter().filter(|c| c.id.starts_with("plugin.fuzz.context.")) {
|
||||
let _ = s.execute(c.id, &json!({}));
|
||||
}
|
||||
}
|
||||
(installed, ran)
|
||||
});
|
||||
let (installed, ran) = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?;
|
||||
prop_assert!(!installed || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text);
|
||||
if ran {
|
||||
prop_assert!(s.doc().unwrap().doc.layers == before.layers, "an echo changed the document: {}", text);
|
||||
}
|
||||
renders(&s, &text)?;
|
||||
vectorcraft_plugins::registry::remove("fuzz.context");
|
||||
vectorcraft_plugins::registry::revoke("fuzz.context");
|
||||
}
|
||||
|
||||
/// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names,
|
||||
/// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of
|
||||
/// its memory runs to an output, or on a small budget to its instruction budget, never a panic;
|
||||
|
||||
@@ -90,7 +90,7 @@ fn a_disabled_plug_in_stays_installed_and_loads_again_once_enabled_at_the_next_l
|
||||
let list = s.execute("plugin.list", &json!({})).unwrap();
|
||||
assert_eq!((list["safeMode"].clone(), list["disabled"][0]["id"].clone()), (json!(false), json!("test.sm.x")));
|
||||
let state = s.execute("plugin.safeMode", &json!({})).unwrap();
|
||||
assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "disabled": state["disabled"].clone()}));
|
||||
assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "pendingItems": [], "disabled": state["disabled"].clone()}));
|
||||
assert_eq!(state["disabled"].as_array().map(Vec::len), Some(1));
|
||||
|
||||
s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": true})).unwrap();
|
||||
|
||||
@@ -132,6 +132,15 @@ fn over(under: Option<Paint>, art: &[Node]) -> Document {
|
||||
/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and as a PostScript
|
||||
/// separation at `level` read back, both drawn at 1 px a point.
|
||||
fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) {
|
||||
let area = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let (plate, out) = separation(d, ink, level);
|
||||
let back = crate::import(&out.bytes).unwrap().document;
|
||||
(render_region(&plate, area, 1.0), render_region(&back, area, 1.0))
|
||||
}
|
||||
|
||||
/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and that plate written
|
||||
/// as a PostScript separation at `level`.
|
||||
fn separation(d: &Document, ink: &str, level: Level) -> (Document, EpsOutput) {
|
||||
let area = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let settings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap();
|
||||
let plan = vectorcraft_pdf::plan(d, &vectorcraft_pdf::PrintOptions { settings, postscript: true, ..Default::default() }).unwrap();
|
||||
@@ -151,8 +160,7 @@ fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) {
|
||||
};
|
||||
let out = print(&[page], &[0], &PrintJob { level, ..PrintJob::default() }).unwrap();
|
||||
assert!(level == Level::Three || !text(&out).contains("shfill"), "Level 2 has no smooth shadings");
|
||||
let back = crate::import(&out.bytes).unwrap().document;
|
||||
(render_region(plate, area, 1.0), render_region(&back, area, 1.0))
|
||||
(plate.clone(), out)
|
||||
}
|
||||
|
||||
/// Ink `ink`'s PostScript plate of `art` over a page of 100% `ink` (`under`), checked against the
|
||||
@@ -234,6 +242,44 @@ fn an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscri
|
||||
assert_keeps_the_ink_below(&cases);
|
||||
}
|
||||
|
||||
/// With Discard White Overprint, a process white fill or stroke marked to overprint knocks out the
|
||||
/// cyan below it on the Cyan plate and is written without overprinting, as in composite output.
|
||||
/// Without the setting, and for a white linked to a spot swatch with a color at a tint above 0%,
|
||||
/// the cyan below it prints.
|
||||
#[test]
|
||||
fn white_overprints_knock_out_on_postscript_plates_with_discard_white_overprint() {
|
||||
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
|
||||
let white = Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0));
|
||||
let spot_white = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 0.0), swatch: Some("White Ink".into()), tint: 1.0 };
|
||||
// The fill is sampled in the rectangle's middle, the stroke on its top edge.
|
||||
let (fill_at, stroke_at) = ((100, 50), (100, 10));
|
||||
let cases = [
|
||||
("process white fill", overprinting(white.clone(), Paint::None), fill_at, true, true),
|
||||
("process white stroke", overprinting(Paint::None, white.clone()), stroke_at, true, true),
|
||||
("process white fill without the setting", overprinting(white.clone(), Paint::None), fill_at, false, false),
|
||||
("process white stroke without the setting", overprinting(Paint::None, white), stroke_at, false, false),
|
||||
("spot white fill", overprinting(spot_white.clone(), Paint::None), fill_at, true, false),
|
||||
("spot white stroke", overprinting(Paint::None, spot_white), stroke_at, true, false),
|
||||
];
|
||||
let mut failed = vec![];
|
||||
for (name, art, (x, y), discard, knocks_out) in cases {
|
||||
let mut d = over(Some(cyan.clone()), &[art]);
|
||||
d.swatches.push(Swatch { name: "White Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0)), global: true, spot: true });
|
||||
d.setup.discard_white_overprint = discard;
|
||||
for level in [Level::Three, Level::Two] {
|
||||
let (_, printed) = plate_of(&d, "Cyan", level);
|
||||
let paper = printed.over_white(x, y)[0] >= 254;
|
||||
if paper != knocks_out {
|
||||
failed.push(format!("{name} at level {level:?}: knocked out {paper}, expected {knocks_out}"));
|
||||
}
|
||||
if text(&separation(&d, "Cyan", level).1).contains("true op") {
|
||||
failed.push(format!("{name} at level {level:?}: overprints on the plate"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failed.is_empty(), "{failed:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate() {
|
||||
// Two stops at an end, one with cyan and one without: Level 2's bands pad with the end stop,
|
||||
|
||||
@@ -298,6 +298,8 @@ 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,
|
||||
/// Overprinting is on in the page's graphics state ([`Self::overprint_on`]).
|
||||
overprinting: bool,
|
||||
/// The print job's fonts: type in a solid fill is shown through them (`None`: drawn as
|
||||
/// outlines).
|
||||
fonts: Option<&'a RefCell<FontJob>>,
|
||||
@@ -336,6 +338,7 @@ impl<'a> Scene<'a> {
|
||||
nest: 0,
|
||||
plate: false,
|
||||
keep_below: false,
|
||||
overprinting: false,
|
||||
fonts: None,
|
||||
used: UsedGlyphs::new(),
|
||||
used_order: vec![],
|
||||
@@ -535,11 +538,30 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn overprinting on for one paint (when overprints are preserved); `false` when it stays off.
|
||||
/// Whether a fill or stroke of `paint` marked to overprint (`overprint`) does: not when it is
|
||||
/// paper white with Discard White Overprint in Output (Document Setup); a spot white still
|
||||
/// overprints ([`Self::spot_ink`]). On a plate the colors are already the plate's coverage, and
|
||||
/// the plate's document has already turned overprinting off for each white the setting knocks
|
||||
/// out, so white is not checked there.
|
||||
fn overprints(&self, overprint: bool, paint: &Paint) -> bool {
|
||||
let discarded = !self.plate && self.doc.setup.discard_white_overprint && vectorcraft_doc::overprint::is_white(paint) && !self.spot_ink(paint);
|
||||
overprint && !discarded
|
||||
}
|
||||
|
||||
/// Whether `paint` is a tint above 0% of a spot swatch with a solid color, which the page writes
|
||||
/// as a Separation ink of its own ([`Self::spot_space`]); a link is judged by the first swatch of
|
||||
/// its name.
|
||||
fn spot_ink(&self, paint: &Paint) -> bool {
|
||||
matches!(paint, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some()))
|
||||
}
|
||||
|
||||
/// Turn overprinting on for one paint (when overprints are preserved); `false` when it stays off
|
||||
/// or is already on (a pattern's tiles inside an overprinting pattern fill).
|
||||
fn overprint_on(&mut self, overprint: bool) -> bool {
|
||||
let on = overprint && self.o.overprint == Overprint::Preserve;
|
||||
let on = overprint && self.o.overprint == Overprint::Preserve && !self.overprinting;
|
||||
if on {
|
||||
self.line("true op");
|
||||
self.overprinting = true;
|
||||
}
|
||||
on
|
||||
}
|
||||
@@ -547,6 +569,7 @@ impl<'a> Scene<'a> {
|
||||
fn overprint_off(&mut self, on: bool) {
|
||||
if on {
|
||||
self.line("false op");
|
||||
self.overprinting = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -611,7 +634,9 @@ impl<'a> Scene<'a> {
|
||||
&& 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);
|
||||
// Inside an overprinting pattern fill the image overprints with its tiles.
|
||||
let overprinting = self.overprinting;
|
||||
self.colorized_image(im, blob, p, overprinting);
|
||||
self.overprint_off(on);
|
||||
}
|
||||
_ => self.image(&im.key, blob, im.width, im.height, im.xf),
|
||||
@@ -729,7 +754,8 @@ impl<'a> Scene<'a> {
|
||||
match item {
|
||||
AppearanceItem::Fill(fl) if fl.visible && !fl.paint.is_none() => {
|
||||
self.note_item(fl.opacity, fl.blend);
|
||||
self.fill(bp, rule, &fl.paint, bounds, fl.overprint);
|
||||
let overprint = self.overprints(fl.overprint, &fl.paint);
|
||||
self.fill(bp, rule, &fl.paint, bounds, overprint);
|
||||
}
|
||||
AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0 && st.width.is_finite() => {
|
||||
self.stroke(bp, rule, st, bounds);
|
||||
@@ -812,6 +838,7 @@ impl<'a> Scene<'a> {
|
||||
return;
|
||||
}
|
||||
self.note_item(st.opacity, st.blend);
|
||||
let overprint = self.overprints(st.overprint, &st.paint);
|
||||
let paint_bounds = st.paint_bounds(bounds);
|
||||
let area_paint = match &st.paint {
|
||||
Paint::Pattern { .. } => true,
|
||||
@@ -822,7 +849,7 @@ impl<'a> Scene<'a> {
|
||||
// The area the stroke paints, as Outline Stroke makes it, painted with the pattern's
|
||||
// tiles or the freeform's image.
|
||||
let region = stroke::outline_region(&PathData::from_bezpath(bp), rule, st).to_bezpath();
|
||||
self.fill(®ion, FillRule::NonZero, &st.paint, paint_bounds, st.overprint);
|
||||
self.fill(®ion, FillRule::NonZero, &st.paint, paint_bounds, overprint);
|
||||
return;
|
||||
}
|
||||
let w = stroke::for_writer(bp, st);
|
||||
@@ -847,7 +874,7 @@ impl<'a> Scene<'a> {
|
||||
};
|
||||
match &w.shape {
|
||||
WrittenShape::Stroke { width } => {
|
||||
let on = self.overprint_on(st.overprint);
|
||||
let on = self.overprint_on(overprint);
|
||||
self.line_style(st, *width);
|
||||
match &st.paint {
|
||||
Paint::Solid { color, swatch, tint } => {
|
||||
@@ -861,7 +888,7 @@ impl<'a> Scene<'a> {
|
||||
self.line("q");
|
||||
push_path(&mut self.body, bp);
|
||||
self.line("strokepath W");
|
||||
self.paint_overprinting(st.overprint, p, paint_bounds, w.reach(st, bounds));
|
||||
self.paint_overprinting(overprint, p, paint_bounds, w.reach(st, bounds));
|
||||
self.line("Q");
|
||||
}
|
||||
}
|
||||
@@ -874,14 +901,14 @@ impl<'a> Scene<'a> {
|
||||
push_path(&mut self.body, &ws.clip);
|
||||
self.body.push_str(clip_op(FillRule::NonZero));
|
||||
for (shape, paint) in &ws.slices {
|
||||
self.fill(shape, FillRule::NonZero, paint, shape.bounding_box(), st.overprint);
|
||||
self.fill(shape, FillRule::NonZero, paint, shape.bounding_box(), overprint);
|
||||
}
|
||||
self.line("Q");
|
||||
}
|
||||
}
|
||||
WrittenShape::Fill(outlines) => {
|
||||
for o in outlines {
|
||||
self.fill(o, FillRule::NonZero, &st.paint, paint_bounds, st.overprint);
|
||||
self.fill(o, FillRule::NonZero, &st.paint, paint_bounds, overprint);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -989,12 +1016,13 @@ impl<'a> Scene<'a> {
|
||||
if bp.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let overprint = self.overprints(run.style.overprint_fill, &run.style.fill);
|
||||
if fonts.is_none() {
|
||||
self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
|
||||
self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, overprint);
|
||||
} else {
|
||||
self.show(&shown, &run.style.fill, run.style.overprint_fill);
|
||||
self.show(&shown, &run.style.fill, overprint);
|
||||
if !art.elements().is_empty() {
|
||||
self.fill(&art, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
|
||||
self.fill(&art, FillRule::NonZero, &run.style.fill, layout.bounds, overprint);
|
||||
}
|
||||
}
|
||||
if run.style.has_stroke() {
|
||||
@@ -1014,7 +1042,8 @@ impl<'a> Scene<'a> {
|
||||
match item {
|
||||
AppearanceItem::Fill(fl) if fl.visible && !fl.paint.is_none() => {
|
||||
self.note_item(fl.opacity, fl.blend);
|
||||
self.fill(bp, FillRule::NonZero, &fl.paint, tb, fl.overprint);
|
||||
let overprint = self.overprints(fl.overprint, &fl.paint);
|
||||
self.fill(bp, FillRule::NonZero, &fl.paint, tb, overprint);
|
||||
}
|
||||
AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0 && st.width.is_finite() => {
|
||||
self.stroke(bp, FillRule::NonZero, st, tb);
|
||||
|
||||
@@ -448,6 +448,106 @@ fn spot_colours_are_separations_and_overprints_are_kept_or_dropped() {
|
||||
assert!(!page_of(&d, &EpsOptions { overprint: Overprint::Discard, ..opts(&d) }).contains("true op"));
|
||||
}
|
||||
|
||||
/// Whether overprinting is on at each fill a page paints, by its `true op` and `false op` lines.
|
||||
fn overprint_at_fills(page: &str) -> Vec<bool> {
|
||||
let mut on = false;
|
||||
let mut fills = vec![];
|
||||
for line in page.lines() {
|
||||
match line {
|
||||
"true op" => on = true,
|
||||
"false op" => on = false,
|
||||
l if l == "f" || l.ends_with(" f") || l.ends_with(" f*") || l == "f*" => fills.push(on),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fills
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_overprint_with_their_overprinting_pattern() {
|
||||
// A rectangle filled with an overprinting pattern whose tile is a white square marked to
|
||||
// overprint and then a cyan one that is not.
|
||||
let mut d = doc_with(|_| vec![]);
|
||||
let square = |d: &mut Document, paint: Paint, overprint: bool| {
|
||||
let mut n = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), paint, Paint::None, 0.0);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.overprint = overprint;
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let tile = vec![square(&mut d, Paint::solid(Color::WHITE), true), square(&mut d, Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), false)];
|
||||
d.patterns.push(vectorcraft_doc::PatternDef::new("tile", tile));
|
||||
let mut n = red_rect(&mut d);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY };
|
||||
f.overprint = true;
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
// The whole pattern overprints, as in PDF export: the white square's own mark does not turn
|
||||
// overprinting off for the cyan square after it, and Discard White Overprint applies to the
|
||||
// pattern fill, not to its tiles.
|
||||
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
|
||||
assert!(!fills.is_empty() && fills.iter().all(|&on| on), "{fills:?}");
|
||||
// On a plate too.
|
||||
let plate = crate::scene::Scene::new(&d, &opts(&d)).on_plate(true).run();
|
||||
let fills = overprint_at_fills(&plate.body);
|
||||
assert!(!fills.is_empty() && fills.iter().all(|&on| on), "{fills:?}");
|
||||
}
|
||||
|
||||
/// A white character fill, and a white fill of the type object itself, marked to overprint knock
|
||||
/// out with Discard White Overprint and overprint without it.
|
||||
#[test]
|
||||
fn white_type_fills_knock_out_with_discard_white_overprint() {
|
||||
use vectorcraft_doc::{CharStyle, FillLayer, TextObject};
|
||||
let white = Paint::solid(Color::WHITE);
|
||||
let char_fill = CharStyle { size: 30.0, fill: white.clone(), overprint_fill: true, ..CharStyle::default() };
|
||||
let object_fill = CharStyle { size: 30.0, fill: Paint::None, ..CharStyle::default() };
|
||||
for (i, style) in [char_fill, object_fill].into_iter().enumerate() {
|
||||
let mut d = doc_with(|d| {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 100.0), "AB", style))));
|
||||
if i == 1 {
|
||||
n.appearance.items = vec![AppearanceItem::Fill(FillLayer { overprint: true, ..FillLayer::new(white.clone()) })];
|
||||
}
|
||||
vec![n]
|
||||
});
|
||||
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
|
||||
assert!(!fills.is_empty() && fills.iter().all(|&on| !on), "{i}: {fills:?}");
|
||||
d.setup.discard_white_overprint = false;
|
||||
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
|
||||
assert!(!fills.is_empty() && fills.iter().all(|&on| on), "{i}: {fills:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Discard White Overprint applies to paper white only: a white fill linked to a spot swatch
|
||||
/// still overprints, at 100% and 50%; one linked to a global process swatch, at a 0% tint of a
|
||||
/// spot swatch, or to a spot swatch without a color (written as process) knocks out.
|
||||
#[test]
|
||||
fn spot_white_fills_overprint_with_discard_white_overprint() {
|
||||
let white = Paint::solid(Color::WHITE);
|
||||
let cases = [
|
||||
(true, white.clone(), 1.0, true),
|
||||
(true, white.clone(), 0.5, true),
|
||||
(false, white.clone(), 1.0, false),
|
||||
(true, white.clone(), 0.0, false),
|
||||
(true, Paint::None, 1.0, false),
|
||||
];
|
||||
for (spot, swatch, tint, overprints) in cases {
|
||||
let mut d = doc_with(|_| vec![]);
|
||||
d.swatches.push(Swatch { name: "White Ink".into(), paint: swatch, global: true, spot });
|
||||
let mut n = red_rect(&mut d);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Solid { color: Color::WHITE, swatch: Some("White Ink".into()), tint };
|
||||
f.overprint = true;
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
assert!(d.setup.discard_white_overprint);
|
||||
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
|
||||
assert_eq!(fills, vec![overprints], "spot: {spot}, tint: {tint}, expected to overprint: {overprints}");
|
||||
}
|
||||
}
|
||||
|
||||
const GOLD: Color = Color::Cmyk { c: 0.0, m: 0.2, y: 0.8, k: 0.1 };
|
||||
const LEAF: Color = Color::Cmyk { c: 1.0, m: 0.0, y: 1.0, k: 0.0 };
|
||||
|
||||
@@ -1253,6 +1353,27 @@ fn an_overprinting_colorized_image_writes_only_its_process_inks() {
|
||||
assert!(ps.contains("VCdn0 setcolorspace") && ps.contains("/DeviceCMYK setcolorspace"), "{ps}");
|
||||
}
|
||||
|
||||
/// An overprinting colorized image in the tile of an overprinting pattern fill is written in only
|
||||
/// the process inks it puts down, as it is outside a pattern, so the inks below it stay.
|
||||
#[test]
|
||||
fn an_overprinting_colorized_image_in_an_overprinting_pattern_writes_only_its_process_inks() {
|
||||
let mut d = overprinting_colorized_doc(vec![0, 128, 255], Color::cmyk(1.0, 0.0, 0.0, 0.0), true);
|
||||
let id = d.layers[0].children().unwrap()[0].id;
|
||||
let image = d.remove(id).unwrap();
|
||||
d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![image]));
|
||||
let mut n = red_rect(&mut d);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY };
|
||||
f.overprint = true;
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
for level in Level::ALL {
|
||||
let ps = page_of(&d, &EpsOptions { level, ..opts(&d) });
|
||||
assert!(ps.contains("true op") && ps.contains("VCdn0 setcolorspace") && !ps.contains("/DeviceCMYK setcolorspace"), "{level:?}: {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
|
||||
|
||||
@@ -613,26 +613,32 @@ fn an_array_s_spread_is_checked_against_the_elements_it_reads() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_setter_without_a_getter_does_not_delay_the_spread_s_check() {
|
||||
// A setter does not run when the elements are read, so the array is still checked when
|
||||
// spread begins, on its own and on its prototype.
|
||||
fn an_index_setter_without_a_getter_does_not_run_when_the_array_is_spread() {
|
||||
// The iterator reads the element and the new array defines its own, so a setter on the array
|
||||
// or on its prototype does not run, and the long array ends at the fuel limit.
|
||||
for setter in ["a", "Array.prototype"] {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
|
||||
let src = format!("var a = []; a.length = 4294967295; Object.defineProperty({setter}, 0, {{ set: function () {{}} }}); [...a]");
|
||||
let src = format!(
|
||||
"var ran = false; var a = []; a.length = 4294967295; Object.defineProperty({setter}, 0, {{ set: function () {{ ran = true; }} }}); [...a]"
|
||||
);
|
||||
let long = realm.run(&src);
|
||||
assert!(is_thrown(&long, "RangeError"), "{setter}: {long:?}");
|
||||
assert!(matches!(&long, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Fuel)), "{setter}: {long:?}");
|
||||
realm.set_limits(Limits::default());
|
||||
assert_eq!(realm.run("ran"), Ok(JsValue::Bool(false)), "{setter}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prototype_getter_behind_an_own_element_does_not_delay_the_spread_s_check() {
|
||||
// The array's own element 0 is read instead of the getter on its prototype, so no getter can
|
||||
// shrink it, and it is checked when spread begins.
|
||||
fn a_prototype_getter_behind_an_own_element_is_not_read_by_the_spread() {
|
||||
// The array's own element 0 is read instead of the getter on its prototype, so the getter does
|
||||
// not shrink it, and the long array ends at the fuel limit.
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
|
||||
let src = "var a = [7]; Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 0; } }); \
|
||||
a.length = 4294967295; [...a]";
|
||||
let long = realm.run(src);
|
||||
assert!(is_thrown(&long, "RangeError"), "{long:?}");
|
||||
assert!(matches!(&long, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Fuel)), "{long:?}");
|
||||
realm.set_limits(Limits::default());
|
||||
assert_eq!(realm.run("a.length"), Ok(JsValue::Number(4294967295.0)));
|
||||
// A getter on the prototype with no own element in front of it is read, and shrinks the array.
|
||||
let shrink = "var a = []; a.length = 4294967295; \
|
||||
Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 7; } }); \
|
||||
@@ -640,20 +646,6 @@ fn a_prototype_getter_behind_an_own_element_does_not_delay_the_spread_s_check()
|
||||
truth(shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn looking_for_index_getters_takes_fuel_for_each_property() {
|
||||
// Each attempt to spread the long array looks at every one of its 10,000 elements, so each
|
||||
// takes at least that much fuel.
|
||||
let fuel = 10_000_000;
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel, ..Limits::default() });
|
||||
let setup = "var a = []; for (var i = 0; i < 10000; i++) a[i] = i; a.length = 4294967295; 0";
|
||||
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
|
||||
let attempt = "var ok = false; try { [...a]; } catch (e) { ok = e instanceof RangeError; } ok";
|
||||
assert_eq!(realm.run(attempt), Ok(JsValue::Bool(true)));
|
||||
let used = fuel - realm.interp().fuel;
|
||||
assert!(used >= 10_000, "{used}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_counts_each_index_name_against_the_heap() {
|
||||
// The elements' properties, with their index names and a string's characters, fit in the
|
||||
|
||||
@@ -238,8 +238,9 @@ impl<'a> Separator<'a> {
|
||||
|
||||
/// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and
|
||||
/// overprinting character fills and strokes, that put none of ink `plate` down leave its plate
|
||||
/// as it is: they are drawn as nothing on it (paper white ones that `discard_white` knocks out
|
||||
/// aside, [`DiscardWhite::discards`]). A writer without blending modes (PostScript) then keeps the ink below them,
|
||||
/// as it is: they are drawn as nothing on it. Paper white ones that `discard_white` knocks out
|
||||
/// ([`DiscardWhite::discards`]) stop overprinting instead, and knock out the ink below them on
|
||||
/// the plate as in composite output. A writer without blending modes (PostScript) then keeps the ink below them,
|
||||
/// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on
|
||||
/// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting
|
||||
/// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a
|
||||
@@ -259,6 +260,9 @@ impl<'a> Separator<'a> {
|
||||
}
|
||||
let image = whole && n.extras().colorize.as_deref().is_some_and(|p| self.no_ink(plate, p));
|
||||
for it in &mut n.appearance.items {
|
||||
if it.overprint() && discard_white.discards(it.paint()) {
|
||||
*it.overprint_mut() = false;
|
||||
}
|
||||
let normal = match it {
|
||||
AppearanceItem::Fill(l) => l.blend == BlendMode::Normal,
|
||||
AppearanceItem::Stroke(l) => l.blend == BlendMode::Normal,
|
||||
@@ -274,6 +278,8 @@ impl<'a> Separator<'a> {
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
r.style.overprint_fill &= !discard_white.discards(&r.style.fill);
|
||||
r.style.overprint_stroke &= !discard_white.discards(&r.style.stroke);
|
||||
if inkless(r.style.overprint_fill, &r.style.fill) {
|
||||
r.style.fill = Paint::None;
|
||||
} else if r.style.overprint_fill {
|
||||
|
||||
@@ -807,7 +807,7 @@ mod tests {
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = std::env::temp_dir().join(format!("vc-effect-overlap-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(crate::safe_mode::begin_launch(&dir), None);
|
||||
assert_eq!(crate::safe_mode::begin_launch(&dir), []);
|
||||
let marker = || {
|
||||
let files = std::fs::read_dir(&dir).unwrap().filter_map(|e| Some(e.ok()?.path()));
|
||||
let json = files.filter(|p| p.extension().is_some_and(|x| x == "json")).collect::<Vec<_>>();
|
||||
@@ -816,8 +816,8 @@ mod tests {
|
||||
};
|
||||
let src = crate::wat::returning(&crate::wat::manifest("test.effect.overlap", "effect", "{}"), r#"{"objects":[]}"#);
|
||||
let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap();
|
||||
let named = Some(crate::safe_mode::Item::of(&plugin));
|
||||
assert_eq!(marker(), None);
|
||||
let named = vec![crate::safe_mode::Item::of(&plugin)];
|
||||
assert_eq!(marker(), []);
|
||||
|
||||
assert!(begin_run(&plugin), "the first run is guarded");
|
||||
assert!(begin_run(&plugin), "a run that starts while the first is running is guarded");
|
||||
@@ -829,9 +829,9 @@ mod tests {
|
||||
end_run(plugin.serial(), true);
|
||||
assert_eq!(marker(), named, "the third run is still running");
|
||||
end_run(plugin.serial(), false);
|
||||
assert_eq!(marker(), None, "no run is running");
|
||||
assert_eq!(marker(), [], "no run is running");
|
||||
assert!(!begin_run(&plugin), "later runs aren't guarded");
|
||||
assert_eq!(marker(), None);
|
||||
assert_eq!(marker(), []);
|
||||
|
||||
crate::safe_mode::end_launch();
|
||||
crate::safe_mode::forget_previous();
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod effect;
|
||||
pub mod export;
|
||||
pub mod host;
|
||||
pub mod import;
|
||||
pub mod loader;
|
||||
pub mod manifest;
|
||||
pub mod objects;
|
||||
pub mod painted;
|
||||
@@ -52,7 +53,7 @@ pub mod wat;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec};
|
||||
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
@@ -0,0 +1,753 @@
|
||||
//! Loads plug-ins on worker threads.
|
||||
//!
|
||||
//! [`Loads::start`] hands its jobs to a pool of at most [`MAX_WORKERS`] threads and returns at
|
||||
//! once. The web build has no threads, so there it runs the jobs one after the other before it
|
||||
//! returns. Each job runs inside a panic boundary: a job that panics fails with [`Error::Failed`],
|
||||
//! and the launch marker stops naming its item ([`crate::safe_mode::loading`]), as when it loads.
|
||||
//! A job that takes [`LOAD_DEADLINE`] or longer fails too, and the marker names its item until its
|
||||
//! thread returns; while it is still running, its thread is left to finish on its own, and another worker
|
||||
//! takes the jobs after it, up to twice as many threads as were started. While
|
||||
//! [`MAX_STUCK_THREADS`] threads in the process still run jobs past their deadline, no load starts
|
||||
//! a thread. When no thread is left to take them, the jobs not started fail.
|
||||
//!
|
||||
//! The caller takes the outcomes in the order of the jobs, whatever order they finish in
|
||||
//! ([`Loads::ready`]), so it installs them in the same order on every launch. A job starts only
|
||||
//! while fewer than twice the workers' count of outcomes before it are waiting to be taken or are
|
||||
//! still held by the caller ([`Loads::release`]), so the loaded modules held at once stay bounded
|
||||
//! however many jobs there are.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use web_time::Instant;
|
||||
|
||||
use crate::safe_mode::{self, Item};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The most worker threads one [`Loads`] starts, besides those that replace a worker whose job
|
||||
/// passed [`LOAD_DEADLINE`].
|
||||
pub const MAX_WORKERS: usize = 4;
|
||||
|
||||
/// How long one job may take; one that takes longer fails as not finished.
|
||||
pub const LOAD_DEADLINE: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How often a wait looks at the deadlines while no job finishes.
|
||||
const TICK: Duration = Duration::from_millis(50);
|
||||
|
||||
/// The most loader threads in the process still running a job past its deadline. While that many
|
||||
/// are, no [`Loads`] starts another thread, so loads started again and again on files whose reads
|
||||
/// never return don't pile up threads.
|
||||
pub const MAX_STUCK_THREADS: usize = 2 * MAX_WORKERS;
|
||||
|
||||
/// Loader threads in the process running a job past its deadline, across every [`Loads`].
|
||||
static STUCK_THREADS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The [`Error::Failed`] message of a job that failed because no thread was left to run it.
|
||||
pub const NO_THREAD: &str = "no thread was left to load it";
|
||||
|
||||
/// One plug-in to load: the item the launch marker names while it loads, and the work, which runs
|
||||
/// on a worker thread.
|
||||
pub struct Job<T> {
|
||||
pub item: Option<Item>,
|
||||
pub work: Box<dyn FnOnce() -> Result<T> + Send>,
|
||||
}
|
||||
|
||||
impl<T> Job<T> {
|
||||
pub fn new(item: Option<Item>, work: impl FnOnce() -> Result<T> + Send + 'static) -> Self {
|
||||
Job { item, work: Box::new(work) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The time since a fixed start, for the deadlines.
|
||||
type Clock = Arc<dyn Fn() -> Duration + Send + Sync>;
|
||||
|
||||
/// A job's outcome as its worker sends it: the job, its result and how long it took.
|
||||
type Done<T> = (usize, Result<T>, Duration);
|
||||
|
||||
/// What the workers and [`Loads`] share.
|
||||
struct State<T> {
|
||||
/// The jobs not started yet, in order.
|
||||
queue: VecDeque<(usize, Job<T>)>,
|
||||
/// When each job started, and whether it has finished or passed its deadline.
|
||||
started: Vec<Option<Duration>>,
|
||||
finished: Vec<bool>,
|
||||
expired: Vec<bool>,
|
||||
/// Jobs whose index is below this may start.
|
||||
limit: usize,
|
||||
/// Worker threads alive, and how many of them run a job past its deadline.
|
||||
workers: usize,
|
||||
stuck: usize,
|
||||
}
|
||||
|
||||
struct Pool<T> {
|
||||
state: Mutex<State<T>>,
|
||||
/// Told when a job may start, or when the queue is emptied.
|
||||
wake: Condvar,
|
||||
}
|
||||
|
||||
impl<T> Pool<T> {
|
||||
fn lock(&self) -> MutexGuard<'_, State<T>> {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts a worker as alive until its thread ends, however it ends.
|
||||
struct Alive<T>(Arc<Pool<T>>);
|
||||
|
||||
impl<T> Drop for Alive<T> {
|
||||
fn drop(&mut self) {
|
||||
self.0.lock().workers -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Jobs loading on worker threads ([`Loads::start`]).
|
||||
pub struct Loads<T: Send + 'static> {
|
||||
pool: Arc<Pool<T>>,
|
||||
results: Mutex<Receiver<Done<T>>>,
|
||||
send: Sender<Done<T>>,
|
||||
outcomes: Vec<Option<Result<T>>>,
|
||||
/// The outcomes before this one were taken ([`Loads::ready`]).
|
||||
next: usize,
|
||||
/// Of those, the ones the caller is done with ([`Loads::release`]).
|
||||
released: usize,
|
||||
/// How many jobs past `next` may start.
|
||||
window: usize,
|
||||
clock: Clock,
|
||||
deadline: Duration,
|
||||
/// The workers [`Loads::begin`] starts, and whether it has.
|
||||
workers: usize,
|
||||
begun: bool,
|
||||
/// The process's count of stuck loader threads ([`STUCK_THREADS`]), and its most.
|
||||
stuck_threads: &'static AtomicUsize,
|
||||
max_stuck: usize,
|
||||
/// Tests: no thread can be started from now on.
|
||||
#[cfg(test)]
|
||||
pub(crate) refuse_threads: bool,
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Loads<T> {
|
||||
/// Starts `jobs` on `min(available parallelism, MAX_WORKERS)` threads.
|
||||
pub fn start(jobs: Vec<Job<T>>) -> Self {
|
||||
let mut loads = Self::deferred(jobs);
|
||||
loads.begin();
|
||||
loads
|
||||
}
|
||||
|
||||
/// `jobs` to start on `min(available parallelism, MAX_WORKERS)` threads once [`Loads::begin`]
|
||||
/// is called (or something waits for them).
|
||||
pub fn deferred(jobs: Vec<Job<T>>) -> Self {
|
||||
Self::deferred_on(jobs, std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_WORKERS))
|
||||
}
|
||||
|
||||
/// [`Loads::deferred`] on `workers` threads (at least one).
|
||||
pub(crate) fn deferred_on(jobs: Vec<Job<T>>, workers: usize) -> Self {
|
||||
let origin = Instant::now();
|
||||
Self::with(jobs, workers, LOAD_DEADLINE, Arc::new(move || origin.elapsed()))
|
||||
}
|
||||
|
||||
/// Starts the jobs, unless they started already.
|
||||
pub fn begin(&mut self) {
|
||||
if self.begun {
|
||||
return;
|
||||
}
|
||||
self.begun = true;
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
// The web build has no threads: each job runs here, in order.
|
||||
let jobs: Vec<_> = self.pool.lock().queue.drain(..).collect();
|
||||
for (i, job) in jobs {
|
||||
// A job can't be stopped here, but one that took past its deadline fails as on
|
||||
// the desktop.
|
||||
let at = (self.clock)();
|
||||
let r = run_job(job);
|
||||
let took = (self.clock)().saturating_sub(at);
|
||||
self.record((i, r, took));
|
||||
}
|
||||
} else {
|
||||
for _ in 0..self.workers.min(self.outcomes.len()) {
|
||||
self.spawn_worker();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn start_with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
|
||||
let mut loads = Self::with(jobs, workers, deadline, clock);
|
||||
loads.begin();
|
||||
loads
|
||||
}
|
||||
|
||||
fn with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
|
||||
let n = jobs.len();
|
||||
let workers = workers.max(1);
|
||||
let window = workers * 2;
|
||||
let state = State {
|
||||
queue: jobs.into_iter().enumerate().collect(),
|
||||
started: vec![None; n],
|
||||
finished: vec![false; n],
|
||||
expired: vec![false; n],
|
||||
limit: window,
|
||||
workers: 0,
|
||||
stuck: 0,
|
||||
};
|
||||
let (send, results) = mpsc::channel();
|
||||
Loads {
|
||||
pool: Arc::new(Pool { state: Mutex::new(state), wake: Condvar::new() }),
|
||||
results: Mutex::new(results),
|
||||
send,
|
||||
outcomes: (0..n).map(|_| None).collect(),
|
||||
next: 0,
|
||||
released: 0,
|
||||
window,
|
||||
clock,
|
||||
deadline,
|
||||
workers,
|
||||
begun: false,
|
||||
stuck_threads: &STUCK_THREADS,
|
||||
max_stuck: MAX_STUCK_THREADS,
|
||||
#[cfg(test)]
|
||||
refuse_threads: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a thread that takes jobs until none are left → whether it started.
|
||||
fn spawn_worker(&self) -> bool {
|
||||
#[cfg(test)]
|
||||
if self.refuse_threads {
|
||||
return false;
|
||||
}
|
||||
if self.stuck_threads.load(Ordering::SeqCst) >= self.max_stuck {
|
||||
log::warn!("not starting a thread to load plug-ins: {} loader threads are still running loads past their deadline", self.max_stuck);
|
||||
return false;
|
||||
}
|
||||
let pool = self.pool.clone();
|
||||
let send = self.send.clone();
|
||||
let clock = self.clock.clone();
|
||||
let target = self.workers;
|
||||
let stuck_threads = self.stuck_threads;
|
||||
self.pool.lock().workers += 1;
|
||||
let spawned = std::thread::Builder::new().name("plug-in loader".into()).spawn(move || {
|
||||
let alive = Alive(pool);
|
||||
loop {
|
||||
let (i, job, at) = {
|
||||
let mut s = alive.0.lock();
|
||||
loop {
|
||||
match s.queue.front() {
|
||||
None => return,
|
||||
Some((i, _)) if *i < s.limit => break,
|
||||
Some(_) => s = alive.0.wake.wait(s).unwrap_or_else(|e| e.into_inner()),
|
||||
}
|
||||
}
|
||||
let Some((i, job)) = s.queue.pop_front() else { return };
|
||||
let at = clock();
|
||||
s.started[i] = Some(at);
|
||||
(i, job, at)
|
||||
};
|
||||
let r = run_job(job);
|
||||
// A worker whose job passed its deadline and was replaced ends once the job
|
||||
// returns, unless the workers able to take jobs are fewer than started. The time
|
||||
// the job took is read while the job is marked finished, so a deadline check that
|
||||
// finds it unfinished counts a time that its own outcome reaches too.
|
||||
let (took, retire) = {
|
||||
let mut s = alive.0.lock();
|
||||
let took = clock().saturating_sub(at);
|
||||
s.finished[i] = true;
|
||||
let retire = s.expired[i] && {
|
||||
s.stuck -= 1;
|
||||
stuck_threads.fetch_sub(1, Ordering::SeqCst);
|
||||
s.workers - s.stuck > target
|
||||
};
|
||||
(took, retire)
|
||||
};
|
||||
let _ = send.send((i, r, took));
|
||||
if retire {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
self.pool.lock().workers -= 1;
|
||||
log::warn!("can't start a thread to load plug-ins: {e}");
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes the outcomes that came in and fails the jobs past their deadline → whether every job
|
||||
/// has its outcome.
|
||||
pub fn poll(&mut self) -> bool {
|
||||
loop {
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).try_recv();
|
||||
let Ok(done) = next else { break };
|
||||
self.record(done);
|
||||
}
|
||||
self.expire();
|
||||
self.outcomes.iter().all(Option::is_some)
|
||||
}
|
||||
|
||||
/// The outcomes not taken yet that come in order from the last one taken, without waiting
|
||||
/// ([`Loads::poll`] first). The jobs after them start as the caller releases them
|
||||
/// ([`Loads::release`]).
|
||||
pub fn ready(&mut self) -> Vec<Result<T>> {
|
||||
self.poll();
|
||||
let mut out = Vec::new();
|
||||
while let Some(o) = self.outcomes.get_mut(self.next).and_then(Option::take) {
|
||||
out.push(o);
|
||||
self.next += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The caller is done with `n` more of the outcomes it took (installed or dropped them): as
|
||||
/// many more jobs may start, so the outcomes held, here and by the caller, stay at most twice
|
||||
/// the workers' count.
|
||||
pub fn release(&mut self, n: usize) {
|
||||
let released = (self.released + n).min(self.next);
|
||||
if released != self.released {
|
||||
self.released = released;
|
||||
self.pool.lock().limit = released + self.window;
|
||||
self.pool.wake.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every outcome has been taken.
|
||||
pub fn taken(&self) -> bool {
|
||||
self.next == self.outcomes.len()
|
||||
}
|
||||
|
||||
/// Whether the next outcome in order can be taken ([`Loads::ready`]).
|
||||
pub fn next_ready(&mut self) -> bool {
|
||||
self.poll();
|
||||
self.outcomes.get(self.next).is_some_and(Option::is_some)
|
||||
}
|
||||
|
||||
/// Waits until the next outcome in order can be taken, or every one has been. Jobs that have
|
||||
/// not been started are started first ([`Loads::begin`]).
|
||||
pub fn wait_next(&mut self) {
|
||||
self.begin();
|
||||
while !self.taken() && !self.next_ready() {
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
|
||||
match next {
|
||||
Ok(done) => self.record(done),
|
||||
Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for every outcome → those not taken yet, in the order of the jobs. The outcomes taken
|
||||
/// before ([`Loads::ready`]) count as released, so the jobs after them start.
|
||||
pub fn wait(mut self) -> Vec<Result<T>> {
|
||||
self.release(self.next - self.released);
|
||||
let mut out = Vec::new();
|
||||
while !self.taken() {
|
||||
self.wait_next();
|
||||
let ready = self.ready();
|
||||
self.release(ready.len());
|
||||
out.extend(ready);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn record(&mut self, (i, r, took): Done<T>) {
|
||||
let r = if took >= self.deadline { Err(self.too_long()) } else { r };
|
||||
// An outcome that comes after the job failed past its deadline is dropped.
|
||||
if let Some(slot @ None) = self.outcomes.get_mut(i) {
|
||||
*slot = Some(r);
|
||||
}
|
||||
}
|
||||
|
||||
fn too_long(&self) -> Error {
|
||||
let secs = self.deadline.as_secs();
|
||||
Error::Failed(format!("did not finish loading within {secs} s"))
|
||||
}
|
||||
|
||||
/// Fails the jobs still running past their deadline, starting a worker in place of each one's
|
||||
/// while the threads alive are fewer than twice the workers started. When no worker is left to
|
||||
/// take the jobs not started (none could be made, or every one is stuck), those fail too.
|
||||
fn expire(&mut self) {
|
||||
if !self.begun {
|
||||
return;
|
||||
}
|
||||
let mut expired = Vec::new();
|
||||
{
|
||||
let mut s = self.pool.lock();
|
||||
// Read while the workers can't mark a job finished ([`Loads::spawn_worker`]).
|
||||
let now = (self.clock)();
|
||||
for i in 0..self.outcomes.len() {
|
||||
let late = s.started[i].is_some_and(|at| now.saturating_sub(at) >= self.deadline);
|
||||
if late && !s.finished[i] && !s.expired[i] && self.outcomes[i].is_none() {
|
||||
s.expired[i] = true;
|
||||
s.stuck += 1;
|
||||
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
|
||||
expired.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in &expired {
|
||||
self.outcomes[*i] = Some(Err(self.too_long()));
|
||||
}
|
||||
for _ in &expired {
|
||||
let room = {
|
||||
let s = self.pool.lock();
|
||||
!s.queue.is_empty() && s.workers < 2 * self.workers
|
||||
};
|
||||
if !room || !self.spawn_worker() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The jobs not started are taken from the queue under the lock that finds no worker able to
|
||||
// take them, so a stuck worker that returns can't start one of them in between. Only those
|
||||
// fail: a job already started reports its own outcome.
|
||||
let stranded: Vec<usize> = {
|
||||
let mut s = self.pool.lock();
|
||||
if s.workers <= s.stuck { s.queue.drain(..).map(|(i, _)| i).collect() } else { Vec::new() }
|
||||
};
|
||||
for i in stranded {
|
||||
if let Some(o @ None) = self.outcomes.get_mut(i) {
|
||||
*o = Some(Err(Error::Failed(NO_THREAD.into())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Drop for Loads<T> {
|
||||
/// Jobs not started yet are dropped; the running ones are given until their deadline, so the
|
||||
/// launch marker is not left naming a plug-in that was still loading when the app quit.
|
||||
fn drop(&mut self) {
|
||||
self.pool.lock().queue.clear();
|
||||
self.pool.wake.notify_all();
|
||||
loop {
|
||||
let running = {
|
||||
let s = self.pool.lock();
|
||||
let now = (self.clock)();
|
||||
(0..self.outcomes.len())
|
||||
.any(|i| !s.finished[i] && !s.expired[i] && s.started[i].is_some_and(|at| now.saturating_sub(at) < self.deadline))
|
||||
};
|
||||
if !running {
|
||||
break;
|
||||
}
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
|
||||
if let Ok(done) = next {
|
||||
self.record(done);
|
||||
}
|
||||
}
|
||||
// A job still running past its deadline leaves its thread stuck, and the thread counts
|
||||
// against the process's stuck threads until the job returns.
|
||||
let mut s = self.pool.lock();
|
||||
for i in 0..self.outcomes.len() {
|
||||
if s.started[i].is_some() && !s.finished[i] && !s.expired[i] {
|
||||
s.expired[i] = true;
|
||||
s.stuck += 1;
|
||||
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `job` inside a panic boundary, with the launch marker naming its item while it runs.
|
||||
fn run_job<T>(job: Job<T>) -> Result<T> {
|
||||
let token = job.item.as_ref().map(safe_mode::loading);
|
||||
let result = catch_unwind(AssertUnwindSafe(job.work));
|
||||
if let Some(t) = token {
|
||||
safe_mode::loaded(t);
|
||||
}
|
||||
match result {
|
||||
Ok(r) => r,
|
||||
Err(panic) => {
|
||||
let what = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());
|
||||
Err(match what {
|
||||
Some(what) => Error::Failed(format!("panicked while loading: {what}")),
|
||||
None => Error::Failed("panicked while loading".into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::mpsc::sync_channel;
|
||||
|
||||
/// A clock the test moves.
|
||||
fn manual() -> (Arc<AtomicU64>, Clock) {
|
||||
let ms = Arc::new(AtomicU64::new(0));
|
||||
let read = ms.clone();
|
||||
(ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst))))
|
||||
}
|
||||
|
||||
/// A job that says it started on `started`, then waits for `go` and returns `v`.
|
||||
fn held(v: u32, started: mpsc::SyncSender<u32>, go: Receiver<()>) -> Job<u32> {
|
||||
Job::new(None, move || {
|
||||
let _ = started.send(v);
|
||||
let _ = go.recv();
|
||||
Ok(v)
|
||||
})
|
||||
}
|
||||
|
||||
/// Polls `loads` until `done` says so, at most a million times.
|
||||
fn poll_until(loads: &mut Loads<u32>, mut done: impl FnMut(&mut Loads<u32>) -> bool) -> bool {
|
||||
(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
loads.poll();
|
||||
done(loads)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the
|
||||
/// test instead of holding it. The test fails at once when every sender is gone.
|
||||
fn recv_soon<V>(rx: &Receiver<V>) -> V {
|
||||
for _ in 0..100_000_000 {
|
||||
match rx.try_recv() {
|
||||
Ok(v) => return v,
|
||||
Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"),
|
||||
Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(),
|
||||
}
|
||||
}
|
||||
panic!("nothing was received");
|
||||
}
|
||||
|
||||
/// The outcomes come back in the order of the jobs when they finish in the reverse order.
|
||||
#[test]
|
||||
fn outcomes_keep_the_order_of_the_jobs() {
|
||||
let (started, starts) = sync_channel(3);
|
||||
let mut go = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
for v in 0..3 {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
go.push(tx);
|
||||
jobs.push(held(v, started.clone(), rx));
|
||||
}
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 3, LOAD_DEADLINE, clock);
|
||||
// Bound after `loads`, so a failing assertion drops the senders first: the held jobs then
|
||||
// return, and dropping `loads` does not wait on them while the test clock stands still.
|
||||
let release = go;
|
||||
for _ in 0..3 {
|
||||
recv_soon(&starts);
|
||||
}
|
||||
// Each job is let go only once the one after it has finished.
|
||||
let mut finished = Vec::new();
|
||||
for v in (0..3).rev() {
|
||||
release[v].send(()).unwrap();
|
||||
let done = recv_soon(&loads.results.lock().unwrap());
|
||||
finished.push(done.0);
|
||||
loads.record(done);
|
||||
}
|
||||
assert_eq!(finished, vec![2, 1, 0], "they finished in reverse");
|
||||
assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
/// A job that panics fails with the panic's message, and the others load.
|
||||
#[test]
|
||||
fn a_job_that_panics_fails_alone() {
|
||||
let jobs: Vec<Job<u32>> = vec![Job::new(None, || Ok(1)), Job::new(None, || panic!("broken module")), Job::new(None, || Ok(3))];
|
||||
let (_, clock) = manual();
|
||||
let out = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
|
||||
assert_eq!(out[0], Ok(1));
|
||||
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("panicked") && m.contains("broken module")), "{:?}", out[1]);
|
||||
assert_eq!(out[2], Ok(3));
|
||||
}
|
||||
|
||||
/// With one worker, a job that never finishes fails at its deadline, and the job after it
|
||||
/// still loads, on the worker that takes its place.
|
||||
#[test]
|
||||
fn a_job_that_hangs_fails_at_its_deadline_and_the_rest_load() {
|
||||
let (started, starts) = sync_channel(2);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
assert_eq!(recv_soon(&starts), 0);
|
||||
assert!(!loads.poll(), "the first job is still running and the second waits for a worker");
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some));
|
||||
go.send(()).unwrap();
|
||||
assert!(done, "the job after the one that hangs never got its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
assert_eq!(out[1], Ok(1));
|
||||
}
|
||||
|
||||
/// Workers that replace stuck ones stop at twice the workers started: with one worker and two
|
||||
/// jobs that never finish, the third job fails instead of a third thread taking it.
|
||||
#[test]
|
||||
fn replacements_stop_at_twice_the_workers() {
|
||||
let (started, starts) = sync_channel(3);
|
||||
let (go0, held0) = mpsc::channel();
|
||||
let (go1, held1) = mpsc::channel();
|
||||
let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
assert_eq!(recv_soon(&starts), 0);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
loads.poll();
|
||||
assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one");
|
||||
ms.store(20_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
go0.send(()).unwrap();
|
||||
go1.send(()).unwrap();
|
||||
assert!(done, "every job has its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[2], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[2]);
|
||||
}
|
||||
|
||||
/// A job that finished but took longer than the deadline fails, however soon it is looked at.
|
||||
#[test]
|
||||
fn a_job_that_took_too_long_fails_when_it_is_taken() {
|
||||
let (ms, clock) = manual();
|
||||
let moved = ms.clone();
|
||||
let jobs = vec![Job::new(None, move || {
|
||||
moved.store(10_000, Ordering::SeqCst);
|
||||
Ok(1u32)
|
||||
})];
|
||||
let out = Loads::start_with(jobs, 1, Duration::from_secs(10), clock).wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
}
|
||||
|
||||
/// Only twice the workers' count of jobs past the last outcome taken start: the next one waits
|
||||
/// until an outcome is taken.
|
||||
#[test]
|
||||
fn jobs_past_the_window_wait_until_outcomes_are_taken() {
|
||||
let ran = Arc::new(AtomicUsize::new(0));
|
||||
let jobs: Vec<Job<u32>> = (0..5)
|
||||
.map(|v| {
|
||||
let ran = ran.clone();
|
||||
Job::new(None, move || {
|
||||
ran.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(v)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
|
||||
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
|
||||
let early = ran.load(Ordering::SeqCst);
|
||||
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
|
||||
assert_eq!(early, 2, "the third job waited for the first outcomes to be taken");
|
||||
assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released");
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes");
|
||||
loads.release(2);
|
||||
assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]);
|
||||
}
|
||||
|
||||
/// `wait` after outcomes were taken and not released still gets the rest: it counts the outcomes
|
||||
/// taken as released, so the job past the window starts.
|
||||
#[test]
|
||||
fn wait_after_outcomes_were_taken_gets_the_jobs_past_the_window() {
|
||||
let jobs: Vec<Job<u32>> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect();
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
|
||||
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
|
||||
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
|
||||
let (done, rest) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = done.send(loads.wait());
|
||||
});
|
||||
assert_eq!(recv_soon(&rest), vec![Ok(2)]);
|
||||
}
|
||||
|
||||
/// When no worker can take the jobs left, because the only one is stuck past its deadline and
|
||||
/// no thread takes its place, those jobs fail instead of being waited for.
|
||||
#[test]
|
||||
fn jobs_no_worker_can_take_fail() {
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
recv_soon(&starts);
|
||||
loads.refuse_threads = true;
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
go.send(()).unwrap();
|
||||
assert!(done, "every job has its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[1]);
|
||||
}
|
||||
|
||||
/// A thread stuck past its deadline counts against later loads until its job returns: with
|
||||
/// room for one stuck thread in the process, the load after one that left a thread stuck
|
||||
/// starts no thread and fails its job, and once the stuck job returns a load runs again.
|
||||
#[test]
|
||||
fn stuck_threads_count_across_loads_until_they_end() {
|
||||
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
|
||||
let make = |jobs: Vec<Job<u32>>, clock: Clock| {
|
||||
let mut loads = Loads::with(jobs, 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.max_stuck = 1;
|
||||
loads.begin();
|
||||
loads
|
||||
};
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut first = make(vec![held(0, started, held_until)], clock);
|
||||
recv_soon(&starts);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
assert!(first.poll(), "the stuck job failed at its deadline");
|
||||
drop(first);
|
||||
let (_, clock) = manual();
|
||||
let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]);
|
||||
go.send(()).unwrap();
|
||||
assert!((0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
stuck.load(Ordering::SeqCst) == 0
|
||||
}));
|
||||
assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]);
|
||||
}
|
||||
|
||||
/// A load dropped while a job runs past its deadline, before anything looked at the job, still
|
||||
/// counts the job's thread as stuck until the job returns.
|
||||
#[test]
|
||||
fn a_dropped_load_counts_a_job_past_its_deadline_as_stuck() {
|
||||
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.begin();
|
||||
recv_soon(&starts);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
drop(loads);
|
||||
assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts");
|
||||
go.send(()).unwrap();
|
||||
assert!((0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
stuck.load(Ordering::SeqCst) == 0
|
||||
}));
|
||||
}
|
||||
|
||||
/// The launch marker names an item while its job runs, and stops naming it when the job
|
||||
/// returns, a job that panicked included.
|
||||
#[test]
|
||||
fn a_job_names_its_item_until_it_returns_even_when_it_panics() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let ok = Item::file("test-loader-ok.wasm");
|
||||
let bad = Item::file("test-loader-panics.wasm");
|
||||
let named = |item: &Item| crate::safe_mode::still_loading().iter().any(|i| i.same(item));
|
||||
let (ok2, bad2) = (ok.clone(), bad.clone());
|
||||
let bad_named = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = bad_named.clone();
|
||||
let jobs: Vec<Job<bool>> = vec![
|
||||
Job::new(Some(ok.clone()), move || Ok(named(&ok2))),
|
||||
Job::new(Some(bad.clone()), move || {
|
||||
seen.store(named(&bad2), Ordering::SeqCst);
|
||||
panic!("x")
|
||||
}),
|
||||
];
|
||||
let (_, clock) = manual();
|
||||
let outcomes = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
|
||||
assert!(matches!(outcomes.first(), Some(Ok(true))), "named while it runs");
|
||||
assert!(bad_named.load(Ordering::SeqCst), "named while it runs, before it panics");
|
||||
assert!(matches!(outcomes.get(1), Some(Err(Error::Failed(m))) if m.contains("panicked while loading")), "the panic is the job's failure");
|
||||
let running = crate::safe_mode::still_loading();
|
||||
assert!(!running.iter().any(|i| i.same(&bad) || i.same(&ok)), "{running:?}");
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission};
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -164,6 +164,45 @@ impl InputKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// A part of the active document a filter or a plug-in command asks to be given in
|
||||
/// `_context.document`, with or without a selection (its manifest's `context`, plug-in API level 3):
|
||||
/// plain values to read, never objects.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ContextSection {
|
||||
/// The document's name (never its path), color mode, units, the active artboard's size, the
|
||||
/// bleed and the raster effects resolution.
|
||||
Settings,
|
||||
/// Every artboard's id, name and rectangle, and which one is active.
|
||||
Artboards,
|
||||
/// Every layer and sublayer: name, visibility, lock, nesting, and which one is current.
|
||||
Layers,
|
||||
/// Every swatch, as `swatch.list` lists it.
|
||||
Swatches,
|
||||
}
|
||||
|
||||
impl ContextSection {
|
||||
/// Every section, in the order the docs list them.
|
||||
pub const ALL: [ContextSection; 4] = [ContextSection::Settings, ContextSection::Artboards, ContextSection::Layers, ContextSection::Swatches];
|
||||
|
||||
/// Its name in `context`, which is also its key in `_context.document`.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ContextSection::Settings => "settings",
|
||||
ContextSection::Artboards => "artboards",
|
||||
ContextSection::Layers => "layers",
|
||||
ContextSection::Swatches => "swatches",
|
||||
}
|
||||
}
|
||||
|
||||
/// The section named `name`.
|
||||
pub fn parse(name: &str) -> Option<ContextSection> {
|
||||
ContextSection::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of a `context` that is not a list of distinct section names.
|
||||
const CONTEXT_LIST: &str = "`context` must list distinct sections: settings, artboards, layers or swatches";
|
||||
|
||||
/// How much one run of a plug-in may compute.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -417,6 +456,12 @@ pub struct Manifest {
|
||||
/// lists them. Left out or empty, it is given paths and compound paths alone.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
|
||||
pub inputs: Vec<String>,
|
||||
/// The parts of the document a run is given in `_context.document`, by
|
||||
/// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command
|
||||
/// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty,
|
||||
/// a run is given none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "context_names")]
|
||||
pub context: Vec<String>,
|
||||
/// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest.
|
||||
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
|
||||
pub params: Vec<(String, Param)>,
|
||||
@@ -469,6 +514,7 @@ impl Manifest {
|
||||
api: 1,
|
||||
permissions: None,
|
||||
inputs: Vec::new(),
|
||||
context: Vec::new(),
|
||||
params: Vec::new(),
|
||||
extensions: Vec::new(),
|
||||
budget: Budget::Light,
|
||||
@@ -539,6 +585,7 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
|
||||
}
|
||||
self.validate_inputs()?;
|
||||
self.validate_context()?;
|
||||
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
|
||||
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
|
||||
}
|
||||
@@ -635,6 +682,33 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect
|
||||
/// with commands, at `api` 3 or later lists any, with a `permissions` list that holds
|
||||
/// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]).
|
||||
fn validate_context(&self) -> Result<()> {
|
||||
if self.context.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for (i, name) in self.context.iter().enumerate() {
|
||||
if ContextSection::parse(name).is_none() || self.context.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(CONTEXT_LIST.into()));
|
||||
}
|
||||
}
|
||||
let runs = self.kind == Kind::Filter || (self.kind == Kind::Effect && !self.commands.is_empty());
|
||||
let reads = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::DocRead.name()));
|
||||
if !runs || self.api < CONTEXT_API || !reads {
|
||||
return Err(Error::Manifest(
|
||||
"`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The parts of the document it asks to be given (`context`).
|
||||
pub fn context_sections(&self) -> Vec<ContextSection> {
|
||||
self.context.iter().filter_map(|n| ContextSection::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct
|
||||
/// id, a printable label and parameters declared as the manifest's own are. A heavy filter
|
||||
/// lists none. The error names the command: its id, or its place in the list.
|
||||
@@ -850,6 +924,18 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `context`: a list of names (`null`: none). Anything else is the error
|
||||
/// [`Manifest::validate_context`] gives a wrong entry.
|
||||
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => {
|
||||
names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(serde::de::Error::custom(CONTEXT_LIST)) }).collect()
|
||||
}
|
||||
_ => Err(serde::de::Error::custom(CONTEXT_LIST)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the `commands` list one entry at a time from the manifest itself, so each command's
|
||||
/// `params` keep their declaration order and a repeated parameter is refused. A malformed entry
|
||||
/// is an error that names it (its id when the id comes before the fault, otherwise its place in
|
||||
@@ -1241,7 +1327,7 @@ mod tests {
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4; this host implements plug-in API levels 1 to 3"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"),
|
||||
] {
|
||||
@@ -1297,6 +1383,51 @@ mod tests {
|
||||
assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice"));
|
||||
}
|
||||
|
||||
/// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document
|
||||
/// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks
|
||||
/// for approval. Left out or empty, it asks for none and isn't written back. Anything else is
|
||||
/// refused naming `context`.
|
||||
#[test]
|
||||
fn a_level_3_plugin_lists_the_document_context_it_reads() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["settings","artboards","layers","swatches"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.context_sections(), ContextSection::ALL);
|
||||
assert!(m.asks_permissions());
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["context"], json!(["settings", "artboards", "layers", "swatches"]));
|
||||
let effect = br#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"],"commands":[{"id":"c","label":"C"}]}"#;
|
||||
assert_eq!(Manifest::parse(effect).unwrap().context_sections(), [ContextSection::Layers]);
|
||||
for none in [r#"{"id":"a","name":"x","kind":"filter","context":[]}"#, r#"{"id":"a","name":"x","kind":"filter","api":3,"context":null}"#] {
|
||||
let m = Manifest::parse(none.as_bytes()).unwrap();
|
||||
assert!(m.context_sections().is_empty(), "{none}");
|
||||
assert!(serde_json::to_value(&m).unwrap().get("context").is_none(), "{none}");
|
||||
}
|
||||
let list = "`context` must list distinct sections";
|
||||
let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`";
|
||||
for (bad, says) in [
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["paths"]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["Layers"]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["layers","layers"]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":"layers"}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":[1]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":{"layers":true}}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["doc.read"],"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"]}"#, needs),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"api":3,"permissions":["doc.read","export.write"],"context":["layers"]}"#,
|
||||
needs,
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"api":3,"permissions":["import.read"],"context":["layers"]}"#, needs),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A live effect at `api` 2 may declare `"paintOutput": true`, and only that value; any other
|
||||
/// kind or level, and `false`, `null` or another type, is refused naming the key. Without the
|
||||
/// key, at any level, the effect returns geometry only.
|
||||
|
||||
@@ -15,8 +15,8 @@ use crate::{Error, Kind, Result};
|
||||
|
||||
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
|
||||
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
|
||||
/// ([`crate::painted`]).
|
||||
pub const API_LEVEL: u32 = 2;
|
||||
/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]).
|
||||
pub const API_LEVEL: u32 = 3;
|
||||
|
||||
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
|
||||
/// `settings`, `cache` and `commands` permissions they need.
|
||||
@@ -29,6 +29,10 @@ pub const INPUTS_API: u32 = 2;
|
||||
/// is ignored.
|
||||
pub const MENU_API: u32 = 2;
|
||||
|
||||
/// The API level that adds a manifest's `context` ([`crate::ContextSection`]): the document's
|
||||
/// settings, artboards, layers and swatches, given to a run with or without a selection.
|
||||
pub const CONTEXT_API: u32 = 3;
|
||||
|
||||
/// Most permissions a manifest may list.
|
||||
pub const MAX_PERMISSIONS: usize = 16;
|
||||
|
||||
@@ -46,7 +50,8 @@ pub const RESERVED: &[&str] = &["ui.panel", "ui.tool"];
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Permission {
|
||||
/// Read the objects the host hands it: a filter's selected paths, the object a live effect is
|
||||
/// on, the document an exporter writes.
|
||||
/// on, the document an exporter writes; and the document information a manifest's `context`
|
||||
/// asks for ([`crate::ContextSection`]).
|
||||
#[serde(rename = "doc.read")]
|
||||
DocRead,
|
||||
/// Change, add and delete objects (a filter's output), as one undo step.
|
||||
|
||||
@@ -68,7 +68,7 @@ pub fn approved(plugin: &Plugin) -> bool {
|
||||
/// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists
|
||||
/// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and
|
||||
/// the plug-in installed under its id, the grants and the revision stay as they were.
|
||||
pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
pub fn install(plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
// The revision moves while the write lock is held, so a cache that reads the new revision and
|
||||
// then the plug-ins finds the new plug-in among them. The approval is checked while it is held
|
||||
// too.
|
||||
@@ -76,12 +76,112 @@ pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
if !approved(&plugin) {
|
||||
return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", ")));
|
||||
}
|
||||
Ok(insert(&mut plugins, plugin))
|
||||
}
|
||||
|
||||
/// Installs `plugin` in `plugins`, which the plug-ins' write lock holds, with the next revision.
|
||||
fn insert(plugins: &mut BTreeMap<String, Arc<Plugin>>, mut plugin: Plugin) -> Arc<Plugin> {
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
note_change(plugin.id(), plugin.serial());
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(p.id().to_string(), p.clone());
|
||||
Ok(p)
|
||||
p
|
||||
}
|
||||
|
||||
/// [`install`] for a load that installs plug-ins one by one, recording `grant` first when it is
|
||||
/// given: while the plug-ins' write lock is held, a plug-in whose id was installed or removed
|
||||
/// elsewhere since the load started ([`LoadChanges::superseded`]) is not installed (`Ok(None)`), and
|
||||
/// neither the plug-ins nor the grants change. A grant that doesn't give this very module every
|
||||
/// permission it lists is refused ([`Error::NeedsApproval`]) and not recorded. Otherwise `attach`
|
||||
/// runs, then the grant is recorded and the plug-in installed. `attach` runs while the plug-ins are
|
||||
/// held, so it may call [`set_storage`] but no function that reads or changes the plug-ins or grants.
|
||||
pub fn install_for_load(plugin: Plugin, changes: &LoadChanges, grant: Option<GrantToken>, attach: impl FnOnce()) -> Result<Option<Arc<Plugin>>> {
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
if changes.superseded(plugin.id()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let m = plugin.manifest();
|
||||
let approved = match &grant {
|
||||
Some(token) => !m.asks_permissions() || token.grant().covers(&m.id, plugin.hash(), &m.permissions()),
|
||||
None => approved(&plugin),
|
||||
};
|
||||
if !approved {
|
||||
return Err(Error::NeedsApproval(crate::permissions::names(&m.permissions()).join(", ")));
|
||||
}
|
||||
attach();
|
||||
if let Some(token) = grant {
|
||||
let g = token.grant().clone();
|
||||
GRANTS.write().unwrap_or_else(|e| e.into_inner()).insert(g.id.clone(), g);
|
||||
}
|
||||
Ok(Some(insert(&mut plugins, plugin)))
|
||||
}
|
||||
|
||||
/// Forgets the grant for `id` when the plug-in installed under it is the one that took the revision
|
||||
/// `serial` ([`Plugin::serial`]), checked while the plug-ins are held, so a plug-in installed in its
|
||||
/// place meanwhile keeps the grant recorded for it → whether a grant was forgotten.
|
||||
pub fn revoke_if_installed(id: &str, serial: u64) -> bool {
|
||||
// The same order as `install`, which reads the grants while it holds the plug-ins.
|
||||
let plugins = PLUGINS.read().unwrap_or_else(|e| e.into_inner());
|
||||
plugins.get(id).is_some_and(|p| p.serial() == serial) && GRANTS.write().unwrap_or_else(|e| e.into_inner()).remove(id).is_some()
|
||||
}
|
||||
|
||||
/// The [`revision`] of each id's last install or removal ([`changed_since`]).
|
||||
static CHANGED: RwLock<BTreeMap<String, u64>> = RwLock::new(BTreeMap::new());
|
||||
|
||||
/// Records that `id` was installed or removed at revision `rev`; called while the plug-ins' write
|
||||
/// lock is held.
|
||||
fn note_change(id: &str, rev: u64) {
|
||||
CHANGED.write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), rev);
|
||||
}
|
||||
|
||||
/// Whether plug-in `id` was installed or removed after [`revision`] gave `rev`.
|
||||
pub fn changed_since(id: &str, rev: u64) -> bool {
|
||||
CHANGED.read().unwrap_or_else(|e| e.into_inner()).get(id).is_some_and(|&r| r > rev)
|
||||
}
|
||||
|
||||
/// What a load that installs plug-ins one by one has to check, so that a module it loaded before
|
||||
/// another session installed or removed the same id doesn't undo that change: the [`revision`] when
|
||||
/// the load listed its files, and the revision of each id it, or a load of the same session that
|
||||
/// ended before it, installed.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LoadChanges {
|
||||
since: Option<u64>,
|
||||
own: BTreeMap<String, u64>,
|
||||
}
|
||||
|
||||
impl LoadChanges {
|
||||
/// Marks the load as started now, unless it started already. A load calls it as it lists its
|
||||
/// files, so a change made between the listing and the loads counts as one made elsewhere.
|
||||
pub fn start(&mut self) {
|
||||
self.since.get_or_insert_with(revision);
|
||||
}
|
||||
|
||||
/// Whether `id` was installed or removed since the load started, other than by the load itself
|
||||
/// or a load it [adopted](LoadChanges::adopt).
|
||||
pub fn superseded(&self, id: &str) -> bool {
|
||||
self.since.is_some_and(|since| changed_since(id, since.max(self.own.get(id).copied().unwrap_or(0))))
|
||||
}
|
||||
|
||||
/// Records that the load installed `plugin`.
|
||||
pub fn installed(&mut self, plugin: &Plugin) {
|
||||
self.own.insert(plugin.id().to_string(), plugin.serial());
|
||||
}
|
||||
|
||||
/// Counts what `earlier`, a load of the same session queued before this one that has ended,
|
||||
/// installed as this load's own: a module this load installs after it then replaces it, as it
|
||||
/// would have with the loads run one after the other.
|
||||
pub fn adopt(&mut self, earlier: &LoadChanges) {
|
||||
for (id, &serial) in &earlier.own {
|
||||
let own = self.own.entry(id.clone()).or_default();
|
||||
*own = (*own).max(serial);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a load reports for a module it skips because the plug-in under its id was installed or
|
||||
/// removed elsewhere while it loaded ([`LoadChanges`]).
|
||||
pub const SUPERSEDED: &str = "skipped: the plug-in with its id was installed or removed elsewhere while it loaded";
|
||||
|
||||
/// What [`install_checked`] does to the grant recorded for the plug-in's id.
|
||||
pub enum GrantUpdate {
|
||||
/// Records this grant, replacing an earlier one for the id ([`grant`]).
|
||||
@@ -128,6 +228,7 @@ pub fn install_checked<E>(
|
||||
}
|
||||
}
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
note_change(&id, plugin.serial());
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(id, p.clone());
|
||||
Ok(p)
|
||||
@@ -154,7 +255,7 @@ pub fn remove(id: &str) -> bool {
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
let gone = plugins.remove(id).is_some();
|
||||
if gone {
|
||||
REVISION.fetch_add(1, Ordering::Relaxed);
|
||||
note_change(id, REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
}
|
||||
gone
|
||||
}
|
||||
@@ -267,14 +368,19 @@ pub struct FolderReport {
|
||||
/// found in a file, which is now disabled too ([`crate::safe_mode::disable_file_of`]). The app
|
||||
/// saves the list again.
|
||||
pub disabled_changed: bool,
|
||||
/// A file failed because no loader thread was left to load it ([`crate::loader::NO_THREAD`]):
|
||||
/// loading the folder again may load it.
|
||||
pub no_thread: bool,
|
||||
}
|
||||
|
||||
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first
|
||||
/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything
|
||||
/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it
|
||||
/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one
|
||||
/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists
|
||||
/// permissions the user has not granted this very module ([`approved`]).
|
||||
/// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name
|
||||
/// order. A bad module is reported and skipped, the others still load; so is one whose load panics
|
||||
/// or doesn't finish in time ([`crate::loader`]), a heavy one ([`crate::Budget::Heavy`]), which
|
||||
/// installs only once the user agrees, and one that lists permissions the user has not granted this
|
||||
/// very module ([`approved`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
load_folder_where(dir, |_| Ok(()), approved)
|
||||
@@ -291,54 +397,255 @@ pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder_where(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String>,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
approve: impl Fn(&Plugin) -> bool,
|
||||
) -> Result<FolderReport> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
let (files, left_out) = folder_files(dir)?;
|
||||
let mut report = FolderReport { left_out, ..FolderReport::default() };
|
||||
for f in files {
|
||||
if let Err(why) = allow(&f) {
|
||||
report.failed.push((f.display().to_string(), why));
|
||||
continue;
|
||||
let mut load = FolderLoad::begin(dir, allow)?;
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(&approve);
|
||||
}
|
||||
Ok(load.finish())
|
||||
}
|
||||
|
||||
/// Tests: what runs before a folder module loads, given its path.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
type FileHook = std::sync::Arc<dyn Fn(&std::path::Path) + Send + Sync>;
|
||||
|
||||
/// Tests: runs on the worker thread before the module at the path it is given loads.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) static BEFORE_FOLDER_FILE: Mutex<Option<FileHook>> = Mutex::new(None);
|
||||
|
||||
/// A [`load_folder_where`] whose modules load on worker threads ([`crate::loader`]) while the
|
||||
/// caller goes on: [`FolderLoad::begin`] lists the folder and starts the loads,
|
||||
/// [`FolderLoad::install_ready`] installs what loaded so far in file-name order, whatever order the
|
||||
/// loads finish in, and [`FolderLoad::finish`] ends the load once [`FolderLoad::done`]. A module
|
||||
/// whose load panics or doesn't finish in time is reported as failed, and the others still install.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub struct FolderLoad {
|
||||
/// Each file in file-name order, with why it was refused before loading, if it was.
|
||||
files: Vec<(std::path::PathBuf, Option<String>)>,
|
||||
loads: crate::loader::Loads<Plugin>,
|
||||
/// Outcomes taken from `loads` and not installed yet, in order.
|
||||
loaded: std::collections::VecDeque<Result<Plugin>>,
|
||||
/// The next file to install or report.
|
||||
next: usize,
|
||||
report: FolderReport,
|
||||
/// Installs and removals elsewhere since the folder was listed, which a module loaded before
|
||||
/// them doesn't undo.
|
||||
changes: LoadChanges,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl FolderLoad {
|
||||
/// Lists `dir` and starts loading the files `allow` accepts and the user didn't disable. Each
|
||||
/// file is checked with `allow` again on its worker thread, right before it is read. In Safe
|
||||
/// Mode nothing loads ([`Error::SafeMode`]); an error listing the folder is returned.
|
||||
pub fn begin(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Result<FolderLoad> {
|
||||
let mut load = Self::list_on(dir, allow, None)?;
|
||||
load.start();
|
||||
Ok(load)
|
||||
}
|
||||
|
||||
/// [`FolderLoad::begin`] without starting the loads: [`FolderLoad::start`] starts them, and
|
||||
/// so does waiting for them.
|
||||
pub fn list(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Result<FolderLoad> {
|
||||
Self::list_on(dir, allow, None)
|
||||
}
|
||||
|
||||
/// Starts the loads, unless they started already.
|
||||
pub fn start(&mut self) {
|
||||
self.changes.start();
|
||||
self.loads.begin();
|
||||
}
|
||||
|
||||
/// [`FolderLoad::list`] for `workers` threads (`None`: as many as [`crate::loader::Loads::start`]
|
||||
/// starts).
|
||||
fn list_on(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
workers: Option<usize>,
|
||||
) -> Result<FolderLoad> {
|
||||
use crate::loader::{Job, Loads};
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
// A change made elsewhere once the folder starts being listed is one the load doesn't undo.
|
||||
let mut changes = LoadChanges::default();
|
||||
changes.start();
|
||||
let (found, left_out) = folder_files(dir)?;
|
||||
let allow = std::sync::Arc::new(allow);
|
||||
let mut files = Vec::with_capacity(found.len());
|
||||
let mut jobs = Vec::new();
|
||||
for f in found {
|
||||
let item = Item::file(f.display().to_string());
|
||||
let refused = match allow(&f) {
|
||||
Err(why) => Some(why),
|
||||
Ok(()) if safe_mode::skipped(&item) => Some(DISABLED.to_string()),
|
||||
Ok(()) => None,
|
||||
};
|
||||
if refused.is_none() {
|
||||
let (path, allow) = (f.clone(), allow.clone());
|
||||
jobs.push(Job::new(Some(item), move || {
|
||||
allow(&path).map_err(Error::Io)?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
let hook = BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(&path);
|
||||
}
|
||||
}
|
||||
load_file(&path, Limits::default())
|
||||
}));
|
||||
}
|
||||
files.push((f, refused));
|
||||
}
|
||||
let item = Item::file(f.display().to_string());
|
||||
if safe_mode::skipped(&item) {
|
||||
report.failed.push((f.display().to_string(), DISABLED.into()));
|
||||
continue;
|
||||
}
|
||||
let token = safe_mode::loading(&item);
|
||||
let loaded = load_file(&f, Limits::default());
|
||||
safe_mode::loaded(token);
|
||||
match loaded {
|
||||
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
|
||||
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
|
||||
report.failed.push((f.display().to_string(), DISABLED.into()));
|
||||
}
|
||||
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
|
||||
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
|
||||
report.failed.push((f.display().to_string(), "asks for a heavy budget, which the user allows when installing it on its own".into()));
|
||||
}
|
||||
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((f.display().to_string(), Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
// `approve` only narrows what installs: `install` still refuses a module that no
|
||||
// recorded grant covers.
|
||||
Ok(p) => match install(p) {
|
||||
Ok(p) => report.loaded.push(p.id().to_string()),
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
},
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
let loads = match workers {
|
||||
Some(n) => Loads::deferred_on(jobs, n),
|
||||
None => Loads::deferred(jobs),
|
||||
};
|
||||
let report = FolderReport { left_out, ..FolderReport::default() };
|
||||
Ok(FolderLoad { files, loads, loaded: Default::default(), next: 0, report, changes })
|
||||
}
|
||||
|
||||
/// The installs and removals the load checks its modules against ([`LoadChanges`]).
|
||||
pub fn changes(&self) -> &LoadChanges {
|
||||
&self.changes
|
||||
}
|
||||
|
||||
/// [`FolderLoad::changes`], to [adopt](LoadChanges::adopt) an earlier load's.
|
||||
pub fn changes_mut(&mut self) -> &mut LoadChanges {
|
||||
&mut self.changes
|
||||
}
|
||||
|
||||
/// Whether every file has been installed or reported.
|
||||
pub fn done(&self) -> bool {
|
||||
self.next == self.files.len()
|
||||
}
|
||||
|
||||
/// Whether [`FolderLoad::install_ready`] has something to install or report now, without
|
||||
/// waiting (or nothing is left).
|
||||
pub fn ready(&mut self) -> bool {
|
||||
match self.files.get(self.next) {
|
||||
None => true,
|
||||
Some((_, Some(_))) => true,
|
||||
Some((_, None)) => !self.loaded.is_empty() || self.loads.next_ready(),
|
||||
}
|
||||
}
|
||||
for id in &report.loaded {
|
||||
if get(id).is_some_and(|p| !p.manifest().asks_permissions()) {
|
||||
revoke(id);
|
||||
|
||||
/// Waits until [`FolderLoad::ready`], starting the loads first ([`FolderLoad::start`]).
|
||||
pub fn wait(&mut self) {
|
||||
self.start();
|
||||
while !self.ready() && !self.loads.taken() {
|
||||
self.loads.wait_next();
|
||||
}
|
||||
}
|
||||
Ok(report)
|
||||
|
||||
/// Installs the plug-ins that loaded, and reports the files that failed, in file-name order up
|
||||
/// to the first file still loading, as [`load_folder_where`] does: those that list permissions
|
||||
/// only when `approve` accepts them and a recorded grant covers them → the ids it installed.
|
||||
pub fn install_ready(&mut self, approve: impl Fn(&Plugin) -> bool) -> Vec<String> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
self.loaded.extend(self.loads.ready());
|
||||
let mut installed = Vec::new();
|
||||
while let Some((f, refused)) = self.files.get(self.next) {
|
||||
let name = f.display().to_string();
|
||||
if let Some(why) = refused {
|
||||
self.report.failed.push((name, why.clone()));
|
||||
self.next += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(loaded) = self.loaded.pop_front() else { break };
|
||||
self.loads.release(1);
|
||||
self.next += 1;
|
||||
let report = &mut self.report;
|
||||
match loaded {
|
||||
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
|
||||
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
|
||||
report.failed.push((name, DISABLED.into()));
|
||||
}
|
||||
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
|
||||
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
|
||||
report.failed.push((name, "asks for a heavy budget, which the user allows when installing it on its own".into()));
|
||||
}
|
||||
// The very module installed elsewhere meanwhile (another session loading the same
|
||||
// folder) counts as loaded. `approve` may record a grant, so it is asked only for
|
||||
// that module: a module another session replaced or removed changes no grant.
|
||||
Ok(p) if self.changes.superseded(p.id()) => match get(p.id()) {
|
||||
Some(q) if q.hash() == p.hash() && (!p.manifest().asks_permissions() || approve(&p)) => report.loaded.push(p.id().to_string()),
|
||||
Some(q) if q.hash() == p.hash() => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
_ => report.failed.push((name, SUPERSEDED.into())),
|
||||
},
|
||||
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
// `approve` only narrows what installs: `install_for_load` still refuses a module that
|
||||
// no recorded grant covers, and one whose id changed elsewhere since the check above.
|
||||
Ok(p) => match install_for_load(p, &self.changes, None, || {}) {
|
||||
Ok(Some(p)) => {
|
||||
self.changes.installed(&p);
|
||||
report.loaded.push(p.id().to_string());
|
||||
installed.push(p.id().to_string());
|
||||
}
|
||||
Ok(None) => report.failed.push((name, SUPERSEDED.into())),
|
||||
Err(e) => report.failed.push((name, e.to_string())),
|
||||
},
|
||||
Err(e) => {
|
||||
report.no_thread |= matches!(&e, Error::Failed(m) if m == crate::loader::NO_THREAD);
|
||||
report.failed.push((name, e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
installed
|
||||
}
|
||||
|
||||
/// Whether [`FolderLoad::install_ready`] turned off the file of a disabled plug-in it matched by
|
||||
/// id ([`crate::safe_mode::disable_file_of`]) since the list of disabled plug-ins was last saved
|
||||
/// ([`FolderLoad::disabled_saved`]).
|
||||
pub fn disabled_changed(&self) -> bool {
|
||||
self.report.disabled_changed
|
||||
}
|
||||
|
||||
/// The list of disabled plug-ins was saved: [`FolderLoad::disabled_changed`] is false until the
|
||||
/// load changes it again.
|
||||
pub fn disabled_saved(&mut self) {
|
||||
self.report.disabled_changed = false;
|
||||
}
|
||||
|
||||
/// Drops the loads not taken yet: jobs not started don't start, and running ones are given
|
||||
/// until their deadline ([`crate::loader::Loads`]). What was installed stays, and the load is
|
||||
/// [`FolderLoad::done`].
|
||||
pub fn cancel(&mut self) {
|
||||
self.loads = crate::loader::Loads::deferred(Vec::new());
|
||||
self.loaded.clear();
|
||||
self.next = self.files.len();
|
||||
}
|
||||
|
||||
/// Ends the load → its report. When the module the load installed under an id lists no
|
||||
/// permissions and is still installed, the process's grant for that id is forgotten. Files not
|
||||
/// installed or reported yet ([`FolderLoad::done`] false) are left out.
|
||||
pub fn finish(self) -> FolderReport {
|
||||
let FolderLoad { report, changes, .. } = self;
|
||||
for id in &report.loaded {
|
||||
// The serial is checked again while the grant is removed, so a module installed in its
|
||||
// place meanwhile keeps its grant.
|
||||
if let Some(&serial) = changes.own.get(id)
|
||||
&& get(id).is_some_and(|p| p.serial() == serial && !p.manifest().asks_permissions())
|
||||
{
|
||||
revoke_if_installed(id, serial);
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -618,4 +925,282 @@ mod tests {
|
||||
let first: Vec<String> = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect();
|
||||
assert_eq!(tried, first, "the first files by name, in that order");
|
||||
}
|
||||
|
||||
/// Clears [`BEFORE_FOLDER_FILE`] when a test ends, failed or not.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Hooked;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Hooked {
|
||||
fn set(hook: impl Fn(&std::path::Path) + Send + Sync + 'static) -> Hooked {
|
||||
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(hook));
|
||||
Hooked
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for Hooked {
|
||||
fn drop(&mut self) {
|
||||
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The plug-ins of a folder install in file-name order, and take their revisions in that order,
|
||||
/// when the first file's load finishes after the others.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_installs_in_file_name_order_whatever_order_the_loads_finish_in() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("order");
|
||||
let ids = ["test.registry.order.a", "test.registry.order.b", "test.registry.order.c"];
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 11)).unwrap();
|
||||
}
|
||||
let first = dir.join("a.wasm");
|
||||
let (go, a_waits) = std::sync::mpsc::channel::<()>();
|
||||
let a_waits = Mutex::new(a_waits);
|
||||
let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
|
||||
let held = first.clone();
|
||||
let saw = seen.clone();
|
||||
let _hook = Hooked::set(move |p| {
|
||||
saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf());
|
||||
if p == held {
|
||||
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
}
|
||||
});
|
||||
// Two workers, so the other files load while the first one waits.
|
||||
let loading = std::thread::spawn({
|
||||
let dir = dir.clone();
|
||||
move || {
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?;
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
Ok::<_, Error>(load.finish())
|
||||
}
|
||||
});
|
||||
// The other two files load on the other worker while the first one waits: their loads have
|
||||
// started (the hook saw them) and ended (the launch marker list no longer has them).
|
||||
let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm")));
|
||||
let finished = |p: &std::path::Path| {
|
||||
let item = crate::safe_mode::Item::file(p.display().to_string());
|
||||
seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item))
|
||||
};
|
||||
// Looked at a bounded number of times, and given up when the load ends first.
|
||||
let reached = (0..10_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2]))
|
||||
});
|
||||
assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited");
|
||||
assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded");
|
||||
go.send(()).unwrap();
|
||||
let r = loading.join().unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r.loaded, ids.to_vec(), "{r:?}");
|
||||
let serials: Vec<u64> = ids.iter().map(|id| get(id).unwrap().serial()).collect();
|
||||
assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}");
|
||||
for id in ids {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder module that loaded before something else installed or removed the same id, while
|
||||
/// an earlier file still loaded, doesn't undo that change: it is reported as skipped, and the
|
||||
/// plug-in installed meanwhile stays, as does the removal.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_undo_a_change_made_while_it_waited() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("superseded");
|
||||
let ids = ["test.registry.superseded.a", "test.registry.superseded.b", "test.registry.superseded.c"];
|
||||
// b's file asks for a permission: asking whether it may install could record a grant.
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
let asks = (*n == "b").then_some(r#"["doc.read"]"#);
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, asks, 13)).unwrap();
|
||||
}
|
||||
install_bytes(&module(ids[2], None, 14)).unwrap();
|
||||
let first = dir.join("a.wasm");
|
||||
let (go, a_waits) = std::sync::mpsc::channel::<()>();
|
||||
let a_waits = Mutex::new(a_waits);
|
||||
let (reached, a_reached) = std::sync::mpsc::channel::<()>();
|
||||
let held = first.clone();
|
||||
let _hook = Hooked::set(move |p| {
|
||||
if p == held {
|
||||
let _ = reached.send(());
|
||||
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
}
|
||||
});
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
load.start();
|
||||
a_reached.recv().unwrap();
|
||||
// Elsewhere, while the first file still loads: `b` is installed and `c` removed.
|
||||
let theirs = install_bytes(&module(ids[1], None, 15)).unwrap().serial();
|
||||
assert!(remove(ids[2]));
|
||||
go.send(()).unwrap();
|
||||
let asked = Mutex::new(Vec::new());
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|p| {
|
||||
asked.lock().unwrap_or_else(|e| e.into_inner()).push(p.id().to_string());
|
||||
false
|
||||
});
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[0]], "{r:?}");
|
||||
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 2, "{r:?}");
|
||||
assert!(asked.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "no grant is asked for a superseded module");
|
||||
assert_eq!(get(ids[1]).map(|p| p.serial()), Some(theirs), "the plug-in installed meanwhile stays");
|
||||
assert!(get(ids[2]).is_none(), "the removal stays");
|
||||
for id in &ids[..2] {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in installed elsewhere after the folder was listed and before its loads started
|
||||
/// stays: the folder's module with its id is skipped. One a load of the same session installed
|
||||
/// before it ([`LoadChanges::adopt`]) is replaced.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_undo_a_change_made_before_its_loads_started() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("superseded-listed");
|
||||
let ids = ["test.registry.listed.a", "test.registry.listed.b"];
|
||||
for (n, id) in ["a", "b"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 13)).unwrap();
|
||||
}
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
// Before the loads start: another session installs `a`, and an earlier load of this
|
||||
// session installs `b`.
|
||||
let theirs = install_bytes(&module(ids[0], None, 14)).unwrap().serial();
|
||||
let mut earlier = LoadChanges::default();
|
||||
earlier.start();
|
||||
earlier.installed(&install_bytes(&module(ids[1], None, 15)).unwrap());
|
||||
load.changes_mut().adopt(&earlier);
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[1]], "{r:?}");
|
||||
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 1, "{r:?}");
|
||||
assert_eq!(get(ids[0]).map(|p| p.serial()), Some(theirs), "the plug-in installed elsewhere stays");
|
||||
for id in ids {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder whose second module panics while it loads reports it as failed and installs the
|
||||
/// others.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_that_panics_while_loading_fails_alone() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("panics");
|
||||
let ids = ["test.registry.panics.a", "test.registry.panics.b", "test.registry.panics.c"];
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 12)).unwrap();
|
||||
}
|
||||
let broken = dir.join("b.wasm");
|
||||
let hooked = broken.clone();
|
||||
let hook = Hooked::set(move |p| {
|
||||
if p == hooked {
|
||||
panic!("a defect while loading");
|
||||
}
|
||||
});
|
||||
let r = load_folder_where(&dir, |_| Ok(()), |_| false);
|
||||
drop(hook);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let item = crate::safe_mode::Item::file(broken.display().to_string());
|
||||
let marked = crate::safe_mode::still_loading().iter().any(|i| i.same(&item));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[0], ids[2]], "{r:?}");
|
||||
assert_eq!(r.failed.len(), 1, "{r:?}");
|
||||
assert!(r.failed[0].0 == broken.display().to_string() && r.failed[0].1.contains("panicked"), "{r:?}");
|
||||
assert!(!marked, "the launch marker stops naming the module whose load failed");
|
||||
for id in [ids[0], ids[2]] {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder module isn't installed over a plug-in installed elsewhere with its id while the load
|
||||
/// asked whether it may install: that plug-in stays, and the module is reported as skipped.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_replace_one_installed_while_it_was_approved() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("approving");
|
||||
let id = "test.registry.approving";
|
||||
let asking = module(id, Some(r#"["doc.read"]"#), 17);
|
||||
std::fs::write(dir.join("a.wasm"), &asking).unwrap();
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
|
||||
let theirs = std::cell::Cell::new(None);
|
||||
let r = load_folder_where(
|
||||
&dir,
|
||||
|_| Ok(()),
|
||||
|_| {
|
||||
theirs.set(Some(install_bytes(&module(id, None, 18)).unwrap().serial()));
|
||||
true
|
||||
},
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let now = get(id).map(|p| p.serial());
|
||||
assert!(remove(id));
|
||||
revoke(id);
|
||||
let r = r.unwrap();
|
||||
assert_eq!(now, theirs.get(), "the plug-in installed meanwhile was replaced: {r:?}");
|
||||
assert!(r.loaded.is_empty() && r.failed.len() == 1 && r.failed[0].1 == SUPERSEDED, "{r:?}");
|
||||
}
|
||||
|
||||
/// A grant is forgotten only while the plug-in that took the given revision is installed under
|
||||
/// its id: a plug-in installed in its place keeps the grant recorded for it.
|
||||
#[test]
|
||||
fn a_grant_is_revoked_only_for_the_plugin_still_installed() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.registry.revokeinstalled";
|
||||
let first = install_bytes(&module(id, None, 19)).unwrap().serial();
|
||||
let asking = module(id, Some(r#"["doc.read"]"#), 20);
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
|
||||
let second = install_bytes(&asking).unwrap().serial();
|
||||
assert!(!revoke_if_installed(id, first), "the grant of the plug-in installed in its place was forgotten");
|
||||
assert!(granted(id).is_some());
|
||||
assert!(revoke_if_installed(id, second));
|
||||
assert!(granted(id).is_none() && remove(id));
|
||||
}
|
||||
|
||||
/// A folder file that no loader thread was left to load fails with that reason, and the report
|
||||
/// says a file found no thread ([`FolderReport::no_thread`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_file_no_thread_was_left_to_load_is_reported() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("nothread");
|
||||
let id = "test.registry.nothread";
|
||||
std::fs::write(dir.join("a.wasm"), module(id, None, 16)).unwrap();
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(1)).unwrap();
|
||||
load.loads.refuse_threads = true;
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(get(id).is_none(), "{r:?}");
|
||||
assert_eq!(r.failed.len(), 1, "{r:?}");
|
||||
assert!(r.no_thread && r.failed[0].1.contains(crate::loader::NO_THREAD), "{r:?}");
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,16 @@
|
||||
//!
|
||||
//! **Launch marker** (native builds): a small file in a folder the app picks, written before the
|
||||
//! stored plug-ins load, updated before and after each module load and each live effect's first
|
||||
//! evaluation (and each evaluation that starts while one of those is running) to name the oldest
|
||||
//! item still loading (several threads can load at once), and removed
|
||||
//! when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A launch that
|
||||
//! ends while an item is still loading (a panic the app caught while a plug-in loaded) keeps its
|
||||
//! marker naming that item. A marker left behind by a
|
||||
//! launch that is no longer running names the item that was loading when it stopped, which may or
|
||||
//! may not be what stopped it. Until the user
|
||||
//! chooses what to do about that item ([`forget_previous`]), the next launch's marker names it too
|
||||
//! and stays when that launch quits, so a launch that asks nothing (`--safe-mode`) or one closed in
|
||||
//! Safe Mode leaves the choice to the launch after it. Each launch has
|
||||
//! evaluation (and each evaluation that starts while one of those is running) to name every item
|
||||
//! still loading, oldest first (several threads can load at once; at most [`MAX_MARKER_ITEMS`]),
|
||||
//! and removed when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A
|
||||
//! launch that ends while an item is still loading (a panic the app caught outside a load job
|
||||
//! while a plug-in loaded) keeps its marker naming that item. A marker left behind by a launch
|
||||
//! that is no longer running names the items that were loading when it stopped; any one of them,
|
||||
//! or none, may be what stopped it. Until the user chooses what to do about those items
|
||||
//! ([`forget_previous`]), the next launch's marker names them too and stays when that launch
|
||||
//! quits, so a launch that asks nothing (`--safe-mode`) or one closed in Safe Mode leaves the
|
||||
//! choice to the launch after it. Each launch has
|
||||
//! its own marker and holds a lock on a file beside it, so a launch that is still running (a second
|
||||
//! window) is never taken for one that stopped. A marker that is missing, empty, unreadable,
|
||||
//! malformed, larger than [`MAX_MARKER_BYTES`] or of another version names nothing.
|
||||
@@ -41,8 +41,11 @@ const MAX_FIELD_CHARS: usize = 1024;
|
||||
/// The most bytes one stored item takes in JSON: three fields of [`MAX_FIELD_CHARS`] characters,
|
||||
/// each written in at most 6 bytes (`\u001f`), plus keys, quotes and indentation.
|
||||
const MAX_ITEM_JSON_BYTES: usize = 3 * MAX_FIELD_CHARS * 6 + 256;
|
||||
/// The largest launch marker read, in bytes: room for one stored item.
|
||||
pub const MAX_MARKER_BYTES: u64 = (MAX_ITEM_JSON_BYTES + 256) as u64;
|
||||
/// The most items a launch marker names.
|
||||
pub const MAX_MARKER_ITEMS: usize = 16;
|
||||
/// The largest launch marker read, in bytes: room for [`MAX_MARKER_ITEMS`] stored items, and the
|
||||
/// first of them again as `item`.
|
||||
pub const MAX_MARKER_BYTES: u64 = ((MAX_MARKER_ITEMS + 1) * MAX_ITEM_JSON_BYTES + 256) as u64;
|
||||
/// The longest name an item is shown with, in characters (longer ones end with "…").
|
||||
pub const MAX_NAME_CHARS: usize = 64;
|
||||
/// The most disabled items kept.
|
||||
@@ -413,18 +416,19 @@ pub fn read_disabled_file(bytes: &[u8]) -> Option<Vec<Item>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// The item the launch before this one was loading when it stopped, once [`begin_launch`] read it.
|
||||
static PREVIOUS: Mutex<Option<Item>> = Mutex::new(None);
|
||||
/// The items the launch before this one was loading when it stopped, once [`begin_launch`] read
|
||||
/// them.
|
||||
static PREVIOUS: Mutex<Vec<Item>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The item the launch before this one was loading when it stopped ([`begin_launch`]); `None` once
|
||||
/// the user chose what to do about it ([`forget_previous`]).
|
||||
pub fn previous() -> Option<Item> {
|
||||
/// The items the launch before this one was loading when it stopped, oldest first
|
||||
/// ([`begin_launch`]); none once the user chose what to do about them ([`forget_previous`]).
|
||||
pub fn previous() -> Vec<Item> {
|
||||
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
/// The user chose what to do about [`previous`]: this launch's marker stops naming it.
|
||||
/// The user chose what to do about [`previous`]: this launch's marker stops naming them.
|
||||
pub fn forget_previous() {
|
||||
*PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
refresh();
|
||||
}
|
||||
|
||||
@@ -437,9 +441,19 @@ struct Running {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Running {
|
||||
/// The item this launch's marker names: the oldest item still loading, else [`previous`].
|
||||
fn pending(&self) -> Option<Item> {
|
||||
self.items.first().map(|(_, i)| i.clone()).or_else(previous)
|
||||
/// The items this launch's marker names: the items still loading, oldest first, each plug-in
|
||||
/// once, at most [`MAX_MARKER_ITEMS`]; with none loading, [`previous`].
|
||||
fn pending(&self) -> Vec<Item> {
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
for (_, item) in &self.items {
|
||||
if items.len() == MAX_MARKER_ITEMS {
|
||||
break;
|
||||
}
|
||||
if !items.iter().any(|i| i.same(item)) {
|
||||
items.push(item.clone());
|
||||
}
|
||||
}
|
||||
if items.is_empty() { previous() } else { items }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,22 +464,33 @@ static LOADING: Mutex<Running> = Mutex::new(Running { next: 0, items: Vec::new()
|
||||
#[derive(Debug)]
|
||||
pub struct Loading(u64);
|
||||
|
||||
/// Writes this launch's marker naming the item [`Running::pending`] gives, while holding the lock
|
||||
/// Writes this launch's marker naming the items [`Running::pending`] gives, while holding the lock
|
||||
/// on the items still loading, so two threads' writes land in the order of their changes.
|
||||
fn refresh() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending().as_ref());
|
||||
marker::write(&LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending());
|
||||
}
|
||||
|
||||
/// The marker's content naming `item`, cut as a stored item is (none: nothing is loading).
|
||||
/// The marker's content naming `items` (none: nothing is loading), each cut as a stored item is,
|
||||
/// at most [`MAX_MARKER_ITEMS`]: the first as `item`, and all of them as `items` when there are
|
||||
/// several.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn marker_bytes(item: Option<&Item>) -> Vec<u8> {
|
||||
let item = item.cloned().and_then(Item::bounded);
|
||||
serde_json::to_vec(&json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": item})).unwrap_or_default()
|
||||
fn marker_bytes(items: &[Item]) -> Vec<u8> {
|
||||
let items: Vec<Item> = items.iter().cloned().filter_map(Item::bounded).take(MAX_MARKER_ITEMS).collect();
|
||||
let mut v = json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": items.first()});
|
||||
if items.len() > 1 {
|
||||
v["items"] = json!(items);
|
||||
}
|
||||
serde_json::to_vec(&v).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The item a marker's content names; `None` when it names none or isn't a marker of this version.
|
||||
pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
|
||||
/// The items a marker's content names, oldest first: its `items` when it has them, else its
|
||||
/// `item`; none when it names none or isn't a marker of this version.
|
||||
pub fn parse_marker(bytes: &[u8]) -> Vec<Item> {
|
||||
read_marker(bytes).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn read_marker(bytes: &[u8]) -> Option<Vec<Item>> {
|
||||
if bytes.len() as u64 > MAX_MARKER_BYTES {
|
||||
return None;
|
||||
}
|
||||
@@ -473,31 +498,44 @@ pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
|
||||
if v["format"] != MARKER_FORMAT || v["version"] != MARKER_VERSION {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_value::<Item>(v.get("item").filter(|i| i.is_object())?.clone()).ok()?.bounded()
|
||||
let item = |i: &Value| serde_json::from_value::<Item>(i.clone()).ok()?.bounded();
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
for i in v["items"].as_array().into_iter().flatten().filter(|i| i.is_object()) {
|
||||
if items.len() == MAX_MARKER_ITEMS {
|
||||
break;
|
||||
}
|
||||
if let Some(i) = item(i).filter(|i| !items.iter().any(|e| e.same(i))) {
|
||||
items.push(i);
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
items.extend(v.get("item").filter(|i| i.is_object()).and_then(item));
|
||||
}
|
||||
Some(items)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use marker::{begin_launch, end_launch};
|
||||
|
||||
/// Adds `item` to the items still loading and writes this launch's marker naming the oldest of
|
||||
/// them (no marker: only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
|
||||
/// Adds `item` to the items still loading and writes this launch's marker naming them (no marker:
|
||||
/// only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
|
||||
pub fn loading(item: &Item) -> Loading {
|
||||
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let token = running.next;
|
||||
running.next = running.next.wrapping_add(1);
|
||||
running.items.push((token, item.clone()));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(running.pending().as_ref());
|
||||
marker::write(&running.pending());
|
||||
Loading(token)
|
||||
}
|
||||
|
||||
/// Removes the item `token` names from the items still loading and writes this launch's marker
|
||||
/// naming the oldest one left; with none left, the item of [`previous`] or nothing.
|
||||
/// naming the ones left; with none left, the items of [`previous`] or nothing.
|
||||
pub fn loaded(token: Loading) {
|
||||
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
running.items.retain(|(t, _)| *t != token.0);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(running.pending().as_ref());
|
||||
marker::write(&running.pending());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -551,12 +589,12 @@ mod marker {
|
||||
(bytes.len() as u64 <= MAX_MARKER_BYTES).then_some(bytes)
|
||||
}
|
||||
|
||||
/// Starts this launch's marker in `dir` → the item a launch that is no longer running was
|
||||
/// loading when it stopped, if one was (its marker is then removed, and this launch's marker
|
||||
/// names the item until [`super::forget_previous`]). A folder that can't be written leaves this
|
||||
/// launch without a marker; it still starts.
|
||||
pub fn begin_launch(dir: &Path) -> Option<Item> {
|
||||
let mut previous = None;
|
||||
/// Starts this launch's marker in `dir` → the items a launch that is no longer running was
|
||||
/// loading when it stopped, if it was loading any (its marker is then removed, and this
|
||||
/// launch's marker names the items until [`super::forget_previous`]). A folder that can't be
|
||||
/// written leaves this launch without a marker; it still starts.
|
||||
pub fn begin_launch(dir: &Path) -> Vec<Item> {
|
||||
let mut previous = Vec::new();
|
||||
let mut tokens: Vec<String> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -569,8 +607,8 @@ mod marker {
|
||||
if running(dir, &token) {
|
||||
continue;
|
||||
}
|
||||
if previous.is_none() {
|
||||
previous = read(&json_path(dir, &token)).as_deref().and_then(parse_marker);
|
||||
if previous.is_empty() {
|
||||
previous = read(&json_path(dir, &token)).as_deref().map(parse_marker).unwrap_or_default();
|
||||
}
|
||||
for path in [json_path(dir, &token), tmp_path(dir, &token), lock_path(dir, &token)] {
|
||||
let _ = std::fs::remove_file(path);
|
||||
@@ -588,32 +626,32 @@ mod marker {
|
||||
previous
|
||||
}
|
||||
|
||||
/// Replaces this launch's marker with one naming `item`: written to a temporary file first,
|
||||
/// Replaces this launch's marker with one naming `items`: written to a temporary file first,
|
||||
/// then renamed over the marker, so a reader finds the old marker or the new one. A write that
|
||||
/// fails leaves the marker as it was.
|
||||
pub(super) fn write(item: Option<&Item>) {
|
||||
pub(super) fn write(items: &[Item]) {
|
||||
let current = CURRENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(c) = current.as_ref() else { return };
|
||||
let tmp = tmp_path(&c.dir, &c.token);
|
||||
let _ = File::create(&tmp)
|
||||
.and_then(|mut f| f.write_all(&marker_bytes(item)).and_then(|()| f.sync_all()))
|
||||
.and_then(|mut f| f.write_all(&marker_bytes(items)).and_then(|()| f.sync_all()))
|
||||
.and_then(|()| std::fs::rename(&tmp, json_path(&c.dir, &c.token)));
|
||||
}
|
||||
|
||||
/// Removes this launch's marker: the app is quitting normally. While an item is still loading
|
||||
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the oldest one;
|
||||
/// otherwise, while the user has not chosen what to do about [`super::previous`], the marker
|
||||
/// stays, naming that, so the next launch asks.
|
||||
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the items still
|
||||
/// loading; otherwise, while the user has not chosen what to do about [`super::previous`], the
|
||||
/// marker stays, naming those, so the next launch asks.
|
||||
pub fn end_launch() {
|
||||
let running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let pending = running.pending();
|
||||
if pending.is_some() {
|
||||
write(pending.as_ref());
|
||||
if !pending.is_empty() {
|
||||
write(&pending);
|
||||
}
|
||||
let Some(c) = CURRENT.lock().unwrap_or_else(|e| e.into_inner()).take() else { return };
|
||||
let Current { dir, token, _lock } = c;
|
||||
drop(_lock);
|
||||
let marker = pending.is_none().then(|| json_path(&dir, &token));
|
||||
let marker = pending.is_empty().then(|| json_path(&dir, &token));
|
||||
for path in marker.into_iter().chain([tmp_path(&dir, &token), lock_path(&dir, &token)]) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
@@ -629,6 +667,12 @@ mod marker {
|
||||
#[cfg(test)]
|
||||
pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Tests: the items still loading, oldest first.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn still_loading() -> Vec<Item> {
|
||||
LOADING.lock().unwrap_or_else(|e| e.into_inner()).items.iter().map(|(_, i)| i.clone()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -683,11 +727,18 @@ mod tests {
|
||||
assert_eq!(Item::file("C:\\Plug-ins\\x.wasm").label(), "x.wasm");
|
||||
}
|
||||
|
||||
/// The items the marker at `path` names.
|
||||
fn marker_at(path: &std::path::Path) -> Vec<Item> {
|
||||
std::fs::read(path).ok().as_deref().map(parse_marker).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_marker_of_this_version_names_an_item() {
|
||||
let item = Item { id: Some("org.example.x".into()), file: Some("/p/x.wasm".into()), name: None };
|
||||
assert_eq!(parse_marker(&marker_bytes(Some(&item))), Some(item));
|
||||
assert_eq!(parse_marker(&marker_bytes(None)), None, "nothing was loading");
|
||||
assert_eq!(parse_marker(&marker_bytes(std::slice::from_ref(&item))), std::slice::from_ref(&item));
|
||||
assert_eq!(parse_marker(&marker_bytes(&[])), [], "nothing was loading");
|
||||
// A marker naming one item has no `items`, as before markers named several.
|
||||
assert!(!String::from_utf8(marker_bytes(std::slice::from_ref(&item))).unwrap().contains("\"items\""));
|
||||
for bad in [
|
||||
&b""[..],
|
||||
b"{",
|
||||
@@ -698,13 +749,28 @@ mod tests {
|
||||
br#"{"format":"vectorcraft-launch","version":1,"item":{}}"#,
|
||||
br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x""#,
|
||||
] {
|
||||
assert_eq!(parse_marker(bad), None, "{}", String::from_utf8_lossy(bad));
|
||||
assert_eq!(parse_marker(bad), [], "{}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
let mut big =
|
||||
format!(r#"{{"format":"vectorcraft-launch","version":1,"item":{{"id":"{}"}}}}"#, "y".repeat(MAX_MARKER_BYTES as usize)).into_bytes();
|
||||
assert_eq!(parse_marker(&big), None, "larger than the limit");
|
||||
assert_eq!(parse_marker(&big), [], "larger than the limit");
|
||||
big.truncate(10);
|
||||
assert_eq!(parse_marker(&big), None, "cut short");
|
||||
assert_eq!(parse_marker(&big), [], "cut short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_names_every_item_up_to_its_limit() {
|
||||
let field = |i: usize, tag: &str| format!("{tag}{i:04}{}", "\u{1}".repeat(MAX_FIELD_CHARS));
|
||||
let items: Vec<Item> =
|
||||
(0..MAX_MARKER_ITEMS + 3).map(|i| Item { id: Some(field(i, "i")), file: Some(field(i, "f")), name: Some(field(i, "n")) }).collect();
|
||||
let bytes = marker_bytes(&items);
|
||||
assert!(bytes.len() as u64 <= MAX_MARKER_BYTES, "{} bytes", bytes.len());
|
||||
let read = parse_marker(&bytes);
|
||||
assert_eq!(read.len(), MAX_MARKER_ITEMS);
|
||||
assert!(read.iter().zip(&items).all(|(r, i)| r.same(i)), "oldest first");
|
||||
// A marker whose `items` names nothing readable falls back to its `item`.
|
||||
let x = br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x"},"items":[{},"y"]}"#;
|
||||
assert_eq!(parse_marker(x), [Item { id: Some("x".into()), ..Item::default() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -714,23 +780,23 @@ mod tests {
|
||||
// A launch that stopped while loading x: its marker without a held lock, and a stray
|
||||
// temporary file from a write it didn't finish.
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-1-a.json.tmp"), b"{\"format\":\"vectorcr").unwrap();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()));
|
||||
assert_eq!(previous(), Some(x.clone()));
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
|
||||
assert_eq!(previous(), std::slice::from_ref(&x));
|
||||
assert!(!dir.join("launch-1-a.json").exists() && !dir.join("launch-1-a.json.tmp").exists(), "read once");
|
||||
let mine = marker::path_of_current().unwrap();
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()), "named until the user chooses");
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&x), "named until the user chooses");
|
||||
forget_previous();
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
|
||||
assert_eq!(marker_at(&mine), []);
|
||||
let token = loading(&x);
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()));
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&x));
|
||||
assert!(!mine.with_extension("json.tmp").exists(), "the temporary file is renamed over the marker");
|
||||
loaded(token);
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
|
||||
assert_eq!(marker_at(&mine), []);
|
||||
end_launch();
|
||||
assert!(!mine.exists(), "a normal quit removes the marker");
|
||||
assert_eq!(begin_launch(&dir), None, "nothing left behind");
|
||||
assert_eq!(begin_launch(&dir), [], "nothing left behind");
|
||||
end_launch();
|
||||
forget_previous();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -741,13 +807,13 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("pending");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()));
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()), "asked again");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "asked again");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None, "once the user chose");
|
||||
assert_eq!(begin_launch(&dir), [], "once the user chose");
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -757,15 +823,15 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("ends-loading");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let token = loading(&x);
|
||||
// A panic the app caught while x loaded: the app quits without `loaded`.
|
||||
end_launch();
|
||||
loaded(token);
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()), "the next launch asks");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "the next launch asks");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -776,22 +842,49 @@ mod tests {
|
||||
let dir = temp_dir("two-loading");
|
||||
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
|
||||
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let mine = marker::path_of_current().unwrap();
|
||||
let marker = || std::fs::read(&mine).ok().as_deref().and_then(parse_marker);
|
||||
// Two threads run their plug-ins' first evaluations at once.
|
||||
let ta = loading(&a);
|
||||
let tb = loading(&b);
|
||||
assert_eq!(marker(), Some(a.clone()), "the oldest item still loading");
|
||||
assert_eq!(marker_at(&mine), [a.clone(), b.clone()], "both items still loading, oldest first");
|
||||
loaded(ta);
|
||||
assert_eq!(marker(), Some(b.clone()), "b is still loading");
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&b), "b is still loading");
|
||||
// The app stops while b loads.
|
||||
end_launch();
|
||||
loaded(tb);
|
||||
assert_eq!(begin_launch(&dir), Some(b.clone()), "the next launch offers b");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&b), "the next launch offers b");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A launch that stops while two plug-ins load offers both at the next launch, until the user
|
||||
/// chooses, however many launches that takes.
|
||||
#[test]
|
||||
fn a_launch_that_stops_while_two_plug_ins_load_offers_both() {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("two-stopped");
|
||||
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
|
||||
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let ta = loading(&a);
|
||||
let tb = loading(&b);
|
||||
// The same plug-in loading twice is named once.
|
||||
let ta2 = loading(&a);
|
||||
end_launch();
|
||||
for t in [ta, tb, ta2] {
|
||||
loaded(t);
|
||||
}
|
||||
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "the next launch offers both");
|
||||
assert_eq!(previous(), [a.clone(), b.clone()]);
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "asked again");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -802,11 +895,11 @@ mod tests {
|
||||
let dir = temp_dir("long-path");
|
||||
// Each character written as 6 or 2 bytes, so the item is far larger in JSON than in characters.
|
||||
let long = format!("C:\\{}\\x.wasm", "\u{1}é".repeat(700));
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let token = loading(&Item::file(long.clone()));
|
||||
end_launch();
|
||||
loaded(token);
|
||||
let stopped = begin_launch(&dir).expect("the marker names the module");
|
||||
let stopped = begin_launch(&dir).into_iter().next().expect("the marker names the module");
|
||||
assert!(stopped.same(&Item::file(long.clone())), "the stored item matches the full path");
|
||||
disable(stopped);
|
||||
assert!(skipped(&Item::file(long.clone())), "Disable and Continue skips it");
|
||||
@@ -891,14 +984,14 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("running");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: None };
|
||||
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(Some(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
let lock = std::fs::File::create(dir.join("launch-9-b.lock")).unwrap();
|
||||
lock.try_lock().unwrap();
|
||||
assert_eq!(begin_launch(&dir), None, "that launch is still running");
|
||||
assert_eq!(begin_launch(&dir), [], "that launch is still running");
|
||||
assert!(dir.join("launch-9-b.json").exists());
|
||||
end_launch();
|
||||
drop(lock);
|
||||
assert_eq!(begin_launch(&dir), Some(x), "once it stopped");
|
||||
assert_eq!(begin_launch(&dir), [x], "once it stopped");
|
||||
end_launch();
|
||||
forget_previous();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The shipped code that records a plug-in grant: only the engine's install approval and its load
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant` or
|
||||
//! `registry::install_checked`. A new call site fails this test until it is added to the list. It
|
||||
//! checks the source, not what native code can do at run time.
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`,
|
||||
//! `registry::install_checked` or `registry::install_for_load`. A new call site fails this test until
|
||||
//! it is added to the list. It checks the source, not what native code can do at run time.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
@@ -11,12 +11,19 @@ use std::path::{Path, PathBuf};
|
||||
const EXPECTED: &[(&str, &str, usize)] = &[
|
||||
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/store.rs", 1),
|
||||
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("registry::install_for_load", "crates/engine/src/store.rs", 2),
|
||||
];
|
||||
|
||||
/// The names the audit counts.
|
||||
const NAMES: [&str; 4] = ["GrantToken::after_engine_approval", "GrantToken::from_engine_grants_file", "registry::grant", "registry::install_checked"];
|
||||
const NAMES: [&str; 5] = [
|
||||
"GrantToken::after_engine_approval",
|
||||
"GrantToken::from_engine_grants_file",
|
||||
"registry::grant",
|
||||
"registry::install_checked",
|
||||
"registry::install_for_load",
|
||||
];
|
||||
|
||||
/// Every `.rs` file under `dir`, without test files and folders.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
|
||||
@@ -164,7 +164,7 @@ features! {
|
||||
DollarEnv "dollar.env" Files,
|
||||
DollarEvalFile "dollar.evalFile" Files,
|
||||
DynamicCode "dynamicCode" Language,
|
||||
E4x "e4x" HostOnly,
|
||||
E4x "e4x" Language,
|
||||
ExternalObject "externalObject" HostOnly,
|
||||
FileDialog "file.dialog" Files,
|
||||
FileExecute "file.execute" Files,
|
||||
@@ -186,6 +186,6 @@ features! {
|
||||
SelectTool "selectTool" HostOnly,
|
||||
Socket "socket" HostOnly,
|
||||
UnitValue "unitValue" Language,
|
||||
Xml "xml" HostOnly,
|
||||
Xml "xml" Language,
|
||||
Xmp "xmp" HostOnly,
|
||||
}
|
||||
@@ -109,7 +109,8 @@ impl Kind {
|
||||
/// A kind of help a script needs from the app that runs it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Need {
|
||||
/// The script language's own objects and directives (`$`, `alert`, `UnitValue`, `#target`).
|
||||
/// The script language's own objects, syntax and directives (`$`, `alert`, `UnitValue`, E4X
|
||||
/// with the `XML` object, `#target`).
|
||||
Language,
|
||||
/// The reference app's document model (`app.activeDocument…`).
|
||||
Dom,
|
||||
@@ -120,7 +121,7 @@ pub enum Need {
|
||||
/// Dialogs and windows of its own.
|
||||
Dialogs,
|
||||
/// Features only the reference app has (palettes, messages to other apps, network
|
||||
/// connections, native code, E4X, actions).
|
||||
/// connections, native code, actions).
|
||||
HostOnly,
|
||||
}
|
||||
|
||||
|
||||
@@ -1550,6 +1550,13 @@ fn application_methods_are_features_not_members() {
|
||||
assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn e4x_and_the_xml_object_need_only_the_language() {
|
||||
let r = report("var x = <a><b/></a>;\nvar y = new XML(s);\nfor each (var v in x.b) {}\n");
|
||||
assert!(feature(&r, "e4x").is_some() && feature(&r, "xml").is_some());
|
||||
assert_eq!(r.needs, [Need::Language]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_names_compared_or_created_are_listed() {
|
||||
let r = report(concat!(
|
||||
|
||||
@@ -195,9 +195,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
|
||||
root = root.attr("version", "1.2").attr("baseProfile", "tiny");
|
||||
}
|
||||
if !opts.responsive {
|
||||
if let Some(suffix) = doc.units.svg_suffix() {
|
||||
let w_val = physical_num(doc.units.from_pt(rect.width()));
|
||||
let h_val = physical_num(doc.units.from_pt(rect.height()));
|
||||
if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) {
|
||||
let w_val = physical_num(unit.from_pt(rect.width()));
|
||||
let h_val = physical_num(unit.from_pt(rect.height()));
|
||||
root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}"));
|
||||
} else {
|
||||
root = root.attr("width", &ww).attr("height", &hh);
|
||||
|
||||
@@ -192,3 +192,28 @@ fn export_physical_units_writes_unit_suffixes() {
|
||||
let back = import(&s).unwrap();
|
||||
assert_eq!(back.units, Unit::Millimeters);
|
||||
}
|
||||
|
||||
/// The `width` of `svg`'s root as a length in points, read by the SVG and CSS absolute units
|
||||
/// (96 px per inch). `None` when it has no unit an SVG reader takes as physical.
|
||||
fn root_width_in_points(svg: &str) -> Option<f64> {
|
||||
let start = svg.find("<svg")?;
|
||||
let w = svg[start..].split("width=\"").nth(1)?.split('"').next()?;
|
||||
let (points_per_unit, number) = [("mm", 72.0 / 25.4), ("cm", 72.0 / 2.54), ("in", 72.0), ("pc", 12.0), ("pt", 1.0)]
|
||||
.into_iter()
|
||||
.find_map(|(suffix, pt)| w.strip_suffix(suffix).map(|v| (pt, v)))?;
|
||||
number.parse::<f64>().ok().map(|v| v * points_per_unit)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_physical_document_unit_exports_its_printed_size() {
|
||||
// 100 inches by 50: feet, yards, meters, Q and Ha have no SVG unit of their own.
|
||||
for unit in [Unit::Feet, Unit::FeetInches, Unit::Yards, Unit::Meters, Unit::Q, Unit::Ha, Unit::Inches, Unit::Millimeters] {
|
||||
let mut d = Document::new(7200.0, 3600.0);
|
||||
d.units = unit;
|
||||
let s = export(&d, &ExportOptions::default());
|
||||
let width = root_width_in_points(&s).unwrap_or_else(|| panic!("{unit:?}: no physical width in {s}"));
|
||||
assert!((width - 7200.0).abs() < 0.01, "{unit:?}: {width} pt in {s}");
|
||||
let back = import(&s).unwrap();
|
||||
assert!(close_rect(back.artboards[0].rect, d.artboards[0].rect), "{unit:?}: {:?}", back.artboards[0].rect);
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,7 @@ pub(super) fn make_face(bytes: FontBytes, index: u32, spec: FaceStyle, path: Opt
|
||||
unencoded: std::sync::OnceLock::new(),
|
||||
char_list: std::sync::OnceLock::new(),
|
||||
named_chars: std::sync::OnceLock::new(),
|
||||
glyph_names: std::sync::OnceLock::new(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -210,6 +210,8 @@ pub struct FontFace {
|
||||
pub(super) char_list: std::sync::OnceLock<Arc<[(char, u32)]>>,
|
||||
/// [`Self::name_owner`]'s glyph names to characters, read once.
|
||||
pub(super) named_chars: std::sync::OnceLock<std::collections::HashMap<String, char>>,
|
||||
/// [`Self::glyph_name`]'s names by glyph id, read once.
|
||||
pub(super) glyph_names: std::sync::OnceLock<Vec<Option<Box<str>>>>,
|
||||
}
|
||||
|
||||
impl vectorcraft_doc::FileFontFace for FontFace {
|
||||
|
||||
@@ -589,11 +589,23 @@ impl FontFace {
|
||||
}
|
||||
|
||||
/// The name of glyph `gid` from the font's `post` or `CFF` table: `None` for a glyph past the
|
||||
/// face's glyphs, or when the font has no names (the ids are then `gid12`).
|
||||
/// face's glyphs, or when the font has no names (the ids are then `gid12`). The names are read
|
||||
/// once for the face, in one pass over the table.
|
||||
pub fn glyph_name(&self, gid: u32) -> Option<String> {
|
||||
let font = self.skrifa()?;
|
||||
let name = font.glyph_names().get(skrifa::GlyphId::new(gid))?;
|
||||
(!name.is_synthesized()).then(|| name.as_str().to_string())
|
||||
let names = self.glyph_names.get_or_init(|| {
|
||||
let Some(font) = self.skrifa() else { return Vec::new() };
|
||||
let names = font.glyph_names();
|
||||
let mut out = vec![None; names.num_glyphs() as usize];
|
||||
for (id, name) in names.iter() {
|
||||
if let Some(slot) = out.get_mut(id.to_u32() as usize)
|
||||
&& !name.is_synthesized()
|
||||
{
|
||||
*slot = Some(Box::from(name.as_str()));
|
||||
}
|
||||
}
|
||||
out
|
||||
});
|
||||
names.get(usize::try_from(gid).ok()?)?.as_deref().map(str::to_string)
|
||||
}
|
||||
|
||||
/// The kinds of glyph the face's `GSUB` table gives ([`GlyphCategoryKind`]), in the order of
|
||||
@@ -651,6 +663,28 @@ mod tests {
|
||||
assert!(face.glyph_categories().is_empty());
|
||||
}
|
||||
|
||||
/// The names read in one pass are the names the font gives each glyph id, for every bundled
|
||||
/// face, and a glyph past the face's glyphs has none.
|
||||
#[test]
|
||||
fn glyph_names_read_once_match_each_glyphs_own_name() {
|
||||
let db = super::super::FontDb::with_font_dirs(vec![]);
|
||||
let mut checked = 0;
|
||||
for family in db.families() {
|
||||
for style in db.styles(&family) {
|
||||
let Some(face) = db.face(&family, &style) else { continue };
|
||||
let Some(font) = face.skrifa() else { continue };
|
||||
let names = font.glyph_names();
|
||||
for gid in 0..face.glyph_count() {
|
||||
let own = names.get(skrifa::GlyphId::new(gid)).filter(|n| !n.is_synthesized()).map(|n| n.as_str().to_string());
|
||||
assert_eq!(face.glyph_name(gid), own, "{family} {style}: glyph {gid}");
|
||||
checked += 1;
|
||||
}
|
||||
assert_eq!(face.glyph_name(face.glyph_count()), None, "{family} {style}");
|
||||
}
|
||||
}
|
||||
assert!(checked > 0, "the bundled faces have glyphs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_round_trip_through_their_ids() {
|
||||
for kind in GlyphCategoryKind::all() {
|
||||
|
||||
@@ -27,12 +27,12 @@ use crate::{Tool, ToolInfo};
|
||||
pub const PATH_TOOLS: &[ToolInfo] = &[
|
||||
ToolInfo { id: anchor_eraser::ID, label: "Anchor Eraser Brush", shortcut: None, icon: "dc-remove-brush" },
|
||||
ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" },
|
||||
ToolInfo { id: measure_inspect::ID, label: "Measure & Inspect Tool", shortcut: None, icon: "ruler" },
|
||||
ToolInfo { id: parametric_shape::ID, label: "Parametric Shape Tool", shortcut: None, icon: "hexagon" },
|
||||
ToolInfo { id: measure_inspect::ID, label: "Measure & Inspect Tool", shortcut: None, icon: "dc-measure-inspect" },
|
||||
ToolInfo { id: parametric_shape::ID, label: "Parametric Shape Tool", shortcut: None, icon: "dc-parametric-shape" },
|
||||
ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-corner-tool" },
|
||||
ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-slide-anchor" },
|
||||
ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-shared-edge" },
|
||||
ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "circle" },
|
||||
ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "dc-tangent-circle" },
|
||||
];
|
||||
|
||||
/// Smart Pen's tool, a flyout group of its own.
|
||||
|
||||
@@ -267,6 +267,12 @@ pub trait Tool: Send {
|
||||
fn wants_rehover(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// The object a click at `p` with `mods` would act on, which Smart Guides › Object
|
||||
/// Highlighting outlines while the pointer rests there (the Eyedropper's source). None when a
|
||||
/// click there acts on no object, or the tool does not name one.
|
||||
fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option<NodeId> {
|
||||
None
|
||||
}
|
||||
/// What the Info panel shows for the tool as it is now: the drag in progress (a move of the
|
||||
/// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear
|
||||
/// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show.
|
||||
|
||||
@@ -1675,15 +1675,22 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option<NodeId> {
|
||||
/// member with only some anchors or segments selected does not count: the press selects `top`.
|
||||
/// A member with every anchor selected (as `select.anchors` and `select.key` leave a path) counts.
|
||||
fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option<NodeId> {
|
||||
if cx.selection.contains(top) {
|
||||
selected_under_in(cx.doc, cx.selection, h, top)
|
||||
}
|
||||
|
||||
/// [`selected_under`] in `doc` with `selection`: the selected object a Selection tool press on
|
||||
/// `h` lands on, where `top` is the object the press would select. The canvas's hover outline
|
||||
/// outlines nothing where this finds an object.
|
||||
pub fn selected_under_in(doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection, h: &Hit, top: NodeId) -> Option<NodeId> {
|
||||
if selection.contains(top) {
|
||||
return Some(top);
|
||||
}
|
||||
let every_anchor = |id: NodeId| {
|
||||
cx.selection
|
||||
selection
|
||||
.partial(id)
|
||||
.is_none_or(|picked| cx.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i)))))
|
||||
.is_none_or(|picked| doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i)))))
|
||||
};
|
||||
let whole = |id: NodeId| cx.selection.contains(id) && every_anchor(id) && !cx.selection.segments.contains_key(&id);
|
||||
let whole = |id: NodeId| selection.contains(id) && every_anchor(id) && !selection.segments.contains_key(&id);
|
||||
let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default());
|
||||
below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id))
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@
|
||||
//! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which
|
||||
//! samples the original image pixels and ends the pick only when a color is accepted. A miss
|
||||
//! stays armed; this tool changes neither paint nor selection.
|
||||
//!
|
||||
//! The object a click at the pointer would act on, with the keys held, is the tool's hover object
|
||||
//! ([`Tool::hover_object`]), which Smart Guides › Object Highlighting outlines.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -165,6 +168,12 @@ pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_d
|
||||
/// The visible color under `p`, including image pixels, pattern tiles, mesh colors, intermediate
|
||||
/// gradient colors, the steps a blend draws and an envelope's distorted contents.
|
||||
pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> {
|
||||
sample_at(cx, p).map(|(c, _)| c)
|
||||
}
|
||||
|
||||
/// [`sample_color_at`] with the object of the document that gives the color: the object hit, the
|
||||
/// blend or envelope whose art is sampled, or an object below them that was passed over to.
|
||||
fn sample_at(cx: &ToolContext, p: Point) -> Option<(Color, NodeId)> {
|
||||
let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample);
|
||||
vectorcraft_doc::depth::with_deep_stack(|| {
|
||||
let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum();
|
||||
@@ -175,13 +184,13 @@ pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option<Color> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke
|
||||
/// The color the front-most object of `doc` hit at `p` with `opts` shows there, and that object. Where a stroke
|
||||
/// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does;
|
||||
/// an object that gives none at all is passed over for the ones below it. A hit on a blend or an
|
||||
/// envelope, or on an object it holds, samples the art it draws ([`live_color_at`]), and where
|
||||
/// that art leaves `p` empty the whole blend or envelope is passed over. `levels` holds the
|
||||
/// scratch documents for art inside art, one for each level deeper.
|
||||
fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>], p: Point, opts: HitOptions) -> Option<Color> {
|
||||
fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>], p: Point, opts: HitOptions) -> Option<(Color, NodeId)> {
|
||||
let mut passed: HashSet<NodeId> = HashSet::new();
|
||||
let mut size = None;
|
||||
loop {
|
||||
@@ -197,7 +206,7 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>],
|
||||
let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?;
|
||||
if let Some(live) = drawn_live(doc, &h.ancestry) {
|
||||
if let Some(c) = live_color_at(s, levels, live, p) {
|
||||
return Some(c);
|
||||
return Some((c, live.id));
|
||||
}
|
||||
if !passed.insert(live.id) {
|
||||
return None;
|
||||
@@ -208,13 +217,13 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option<Document>],
|
||||
let n = doc.node(id)?;
|
||||
let on_stroke = h.kind == HitKind::Stroke;
|
||||
if let Some(c) = node_color_at(s, levels, n, on_stroke, p) {
|
||||
return Some(c);
|
||||
return Some((c, id));
|
||||
}
|
||||
if on_stroke
|
||||
&& fill_covers(n, p)
|
||||
&& let Some(c) = node_color_at(s, levels, n, false, p)
|
||||
{
|
||||
return Some(c);
|
||||
return Some((c, id));
|
||||
}
|
||||
if !passed.insert(id) {
|
||||
return None;
|
||||
@@ -240,14 +249,28 @@ fn drawn_live<'d>(doc: &'d Document, ancestry: &[NodeId]) -> Option<&'d Node> {
|
||||
/// The color the art blend or envelope `n` draws shows at `p`, sampled as [`art_color_at`] samples
|
||||
/// art: a blend's keys and steps, an envelope's distorted contents, symbol instances in them by
|
||||
/// their symbols' art. Evaluating it counts the objects it holds, and the art made counts its
|
||||
/// objects.
|
||||
/// objects. When less work is left than the steps of its blends make in all, the steps that copy
|
||||
/// a nested blend included ([`vectorcraft_doc::blend::blend_steps_made`]), it is not evaluated.
|
||||
fn live_color_at(s: &mut Sampler, levels: &mut [Option<Document>], n: &Node, p: Point) -> Option<Color> {
|
||||
let steps = vectorcraft_doc::blend::blend_steps_made(n);
|
||||
if s.work < steps {
|
||||
// Too little work is left for the steps the blends make.
|
||||
s.spend(steps)?;
|
||||
}
|
||||
s.spend(n.count())?;
|
||||
#[cfg(test)]
|
||||
EXPANSIONS.with(|e| e.set(e.get() + 1));
|
||||
let art = vectorcraft_effects::expand_live_deep(Some(s.doc), n);
|
||||
s.spend(art.count())?;
|
||||
art_color_at(s, levels, [art], p)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The blends and envelopes [`live_color_at`] has evaluated on this thread.
|
||||
static EXPANSIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol
|
||||
/// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no
|
||||
/// fill) there. Images, symbols and patterns are looked up in the sampled document.
|
||||
@@ -464,7 +487,7 @@ fn art_color_at(s: &mut Sampler, levels: &mut [Option<Document>], art: impl Into
|
||||
scratch.insert(Some(layer), usize::MAX, n).ok()?;
|
||||
}
|
||||
let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..s.opts };
|
||||
color_under(s, scratch, deeper, p, opts)
|
||||
color_under(s, scratch, deeper, p, opts).map(|(c, _)| c)
|
||||
}
|
||||
|
||||
/// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0).
|
||||
@@ -524,72 +547,50 @@ impl Tool for EyedropperTool {
|
||||
if ev.kind != PointerKind::Down {
|
||||
return vec![];
|
||||
}
|
||||
if let Some(binding) = &self.image_trace_ignore_color {
|
||||
// The panel knows whether this hits an opaque source pixel. It clears the binding
|
||||
// and restores the previous tool only after accepting a color, not on a miss.
|
||||
return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))];
|
||||
let Some(click) = self.click(cx, ev.pos, ev.mods) else { return vec![] };
|
||||
match click {
|
||||
Click::ImageTrace(binding) => {
|
||||
// The panel knows whether this hits an opaque source pixel. It clears the binding
|
||||
// and restores the previous tool only after accepting a color, not on a miss.
|
||||
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))]
|
||||
}
|
||||
Click::BrushKeyColor(c, _) => {
|
||||
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
|
||||
self.brush_key_color = false;
|
||||
vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]
|
||||
}
|
||||
Click::BackToBucket => {
|
||||
self.stop = None;
|
||||
vec![Action::SwitchTool("livePaintBucket".into())]
|
||||
}
|
||||
Click::MeshPoints(id, points, color) => {
|
||||
let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true });
|
||||
vec![Action::Exec("object.mesh.setPointColor".into(), params)]
|
||||
}
|
||||
Click::CopyFrom(src, how) => {
|
||||
let params = match how {
|
||||
Some(how) => json!({ "source": src.0, how: true }),
|
||||
None => json!({ "source": src.0 }),
|
||||
};
|
||||
vec![Action::Exec("appearance.copyFrom".into(), params)]
|
||||
}
|
||||
Click::Sample { color, meshes, stop, .. } => {
|
||||
let color = color_json(&color);
|
||||
if !meshes.is_empty() {
|
||||
let ids: Vec<u64> = meshes.iter().map(|id| id.0).collect();
|
||||
return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))];
|
||||
}
|
||||
let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] };
|
||||
self.stop = None;
|
||||
vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back)]
|
||||
}
|
||||
}
|
||||
let opts = sample_options(cx);
|
||||
if self.brush_key_color {
|
||||
let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] };
|
||||
let back = self.stop.clone().unwrap_or_else(|| "selection".to_string());
|
||||
self.brush_key_color = false;
|
||||
self.stop = None;
|
||||
return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)];
|
||||
}
|
||||
// A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without
|
||||
// sampling once that stop is no longer selected (a Cmd-click selected another object) or no
|
||||
// longer there (another paint was chosen): the click switches back.
|
||||
let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke };
|
||||
let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len()));
|
||||
if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() {
|
||||
self.stop = None;
|
||||
return vec![Action::SwitchTool("livePaintBucket".into())];
|
||||
}
|
||||
let stop = self.stop.as_ref().zip(cx.gradient_stop);
|
||||
// A plain click on a selected gradient mesh gives the fill color to the point there, else
|
||||
// to the four points of the patch there.
|
||||
if stop.is_none()
|
||||
&& !ev.mods.alt
|
||||
&& !ev.mods.shift
|
||||
&& let Paint::Solid { color, .. } = &cx.paint.fill
|
||||
&& let Some((id, points)) = selected_mesh_points(cx, ev.pos)
|
||||
{
|
||||
let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true });
|
||||
return vec![Action::Exec("object.mesh.setPointColor".into(), params)];
|
||||
}
|
||||
// Reading a source is independent of its editability. Only Alt's reverse operation
|
||||
// writes to the clicked object; Shift+Alt appends its appearance to the selection.
|
||||
let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() {
|
||||
hit_test(cx.doc, ev.pos, opts).map(|h| (paint_owner(cx.doc, h.leaf), h.kind))
|
||||
} else {
|
||||
sample_source(cx, ev.pos)
|
||||
};
|
||||
let Some((src, _)) = source else { return vec![] };
|
||||
let Some(n) = cx.doc.node(src) else { return vec![] };
|
||||
if ev.mods.alt && stop.is_none() {
|
||||
let how = if ev.mods.shift { "append" } else { "reverse" };
|
||||
return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))];
|
||||
}
|
||||
let image = matches!(n.kind, NodeKind::Image(_));
|
||||
// Picked mesh points take only a color sampled from other art or an image: the sample goes
|
||||
// to them as a fill, and to nothing else that is selected. A click on a mesh with picked
|
||||
// points is handled as before.
|
||||
let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] };
|
||||
let meshes = if meshes.contains(&src) { vec![] } else { meshes };
|
||||
if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) {
|
||||
return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))];
|
||||
}
|
||||
let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] };
|
||||
let color = color_json(&c);
|
||||
if !meshes.is_empty() {
|
||||
let ids: Vec<u64> = meshes.iter().map(|id| id.0).collect();
|
||||
return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))];
|
||||
}
|
||||
let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] };
|
||||
let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())];
|
||||
self.stop = None;
|
||||
out
|
||||
}
|
||||
|
||||
/// The object a click there samples, recolors or copies attributes to, as [`Self::click`]
|
||||
/// finds it.
|
||||
fn hover_object(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option<NodeId> {
|
||||
self.click(cx, p, mods)?.object()
|
||||
}
|
||||
|
||||
/// Expose a transient text range alongside gradient-stop and brush-key sampling state.
|
||||
@@ -684,11 +685,92 @@ impl Tool for EyedropperTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click with the Eyedropper does, which [`EyedropperTool::pointer`] carries out.
|
||||
enum Click {
|
||||
/// Image Trace's Ignore Color pick: the panel samples the image with this binding.
|
||||
ImageTrace(Value),
|
||||
/// Brush Options › Key Color: this color, sampled from this object.
|
||||
BrushKeyColor(Color, NodeId),
|
||||
/// A pick for a Live Paint Bucket stop that is no longer selected switches back unsampled.
|
||||
BackToBucket,
|
||||
/// The fill color goes to these points of this selected gradient mesh.
|
||||
MeshPoints(NodeId, Vec<usize>, Color),
|
||||
/// `appearance.copyFrom` this source, with `reverse` or `append` or neither.
|
||||
CopyFrom(NodeId, Option<&'static str>),
|
||||
/// This color, sampled from `source`, goes to the picked points of `meshes`, else to the
|
||||
/// gradient stop of `stop` (the tool to switch back to and the stop), else to the active fill
|
||||
/// or stroke.
|
||||
Sample { color: Color, source: NodeId, meshes: Vec<NodeId>, stop: Option<(String, usize)> },
|
||||
}
|
||||
|
||||
impl Click {
|
||||
/// The object of the document the click reads from or writes to.
|
||||
fn object(&self) -> Option<NodeId> {
|
||||
match self {
|
||||
Click::ImageTrace(_) | Click::BackToBucket => None,
|
||||
Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EyedropperTool {
|
||||
/// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed?
|
||||
fn picking(&self) -> bool {
|
||||
self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some()
|
||||
}
|
||||
|
||||
/// What a click at `p` with `mods` does, or None when it does nothing.
|
||||
fn click(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option<Click> {
|
||||
if let Some(binding) = &self.image_trace_ignore_color {
|
||||
return Some(Click::ImageTrace(binding.clone()));
|
||||
}
|
||||
if self.brush_key_color {
|
||||
let (c, source) = sample_at(cx, p)?;
|
||||
return Some(Click::BrushKeyColor(c, source));
|
||||
}
|
||||
// A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without
|
||||
// sampling once that stop is no longer selected (a Cmd-click selected another object) or no
|
||||
// longer there (another paint was chosen): the click switches back.
|
||||
let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke };
|
||||
let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len()));
|
||||
if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() {
|
||||
return Some(Click::BackToBucket);
|
||||
}
|
||||
let stop = self.stop.clone().zip(cx.gradient_stop);
|
||||
// A plain click on a selected gradient mesh gives the fill color to the point there, else
|
||||
// to the four points of the patch there.
|
||||
if stop.is_none()
|
||||
&& !mods.alt
|
||||
&& !mods.shift
|
||||
&& let Paint::Solid { color, .. } = &cx.paint.fill
|
||||
&& let Some((id, points)) = selected_mesh_points(cx, p)
|
||||
{
|
||||
return Some(Click::MeshPoints(id, points, *color));
|
||||
}
|
||||
// Reading a source is independent of its editability. Only Alt's reverse operation
|
||||
// writes to the clicked object; Shift+Alt appends its appearance to the selection.
|
||||
let source = if mods.alt && !mods.shift && stop.is_none() {
|
||||
hit_test(cx.doc, p, sample_options(cx)).map(|h| (paint_owner(cx.doc, h.leaf), h.kind))
|
||||
} else {
|
||||
sample_source(cx, p)
|
||||
};
|
||||
let (src, _) = source?;
|
||||
let n = cx.doc.node(src)?;
|
||||
if mods.alt && stop.is_none() {
|
||||
return Some(Click::CopyFrom(src, Some(if mods.shift { "append" } else { "reverse" })));
|
||||
}
|
||||
let image = matches!(n.kind, NodeKind::Image(_));
|
||||
// Picked mesh points take only a color sampled from other art or an image: the sample goes
|
||||
// to them as a fill, and to nothing else that is selected. A click on a mesh with picked
|
||||
// points is handled as before.
|
||||
let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] };
|
||||
let meshes = if meshes.contains(&src) { vec![] } else { meshes };
|
||||
if !(mods.shift || stop.is_some() || image || !meshes.is_empty()) {
|
||||
return Some(Click::CopyFrom(src, None));
|
||||
}
|
||||
let (color, source) = sample_at(cx, p)?;
|
||||
Some(Click::Sample { color, source, meshes, stop })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1824,7 +1906,7 @@ mod tests {
|
||||
let opts = sample_options(&cx);
|
||||
let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 };
|
||||
let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect();
|
||||
assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|c| c.to_hex()), None);
|
||||
assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|(c, _)| c.to_hex()), None);
|
||||
assert!(s.exhausted);
|
||||
}
|
||||
|
||||
@@ -1917,6 +1999,157 @@ mod tests {
|
||||
assert_eq!(sampled_hex(&below), "#00ff00");
|
||||
}
|
||||
|
||||
/// The object the hover names for a Shift-click is the one whose color the click samples: the
|
||||
/// blend where a step is drawn, and the rectangle below it in a gap between the steps. Away
|
||||
/// from all art it names none.
|
||||
#[test]
|
||||
fn shift_hover_names_the_object_the_sample_comes_from() {
|
||||
use vectorcraft_doc::live::{BlendSpacing, BlendSpec};
|
||||
use vectorcraft_geom::Rect;
|
||||
let d = doc_with_live_over_green(|d| {
|
||||
let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let spec = BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() };
|
||||
Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) })
|
||||
});
|
||||
let ids: Vec<NodeId> = d.layers[0].children().unwrap().iter().map(|n| n.id).collect();
|
||||
let [.., green, blend] = ids[..] else { panic!("two objects over the rectangle expected") };
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let t = EyedropperTool::default();
|
||||
let names = |x: f64, y: f64| t.hover_object(&cx(&d, &s, &p), Point::new(x, y), shift);
|
||||
assert_eq!(names(360.0, 310.0), Some(blend), "a blend step");
|
||||
assert_eq!(names(335.0, 310.0), Some(green), "a gap between the steps");
|
||||
assert_eq!(names(480.0, 480.0), None, "no art");
|
||||
}
|
||||
|
||||
/// A blend's steps count as work before it is evaluated: the steps of every blend it holds
|
||||
/// are counted, and with less work left than that the sample gives no color and the blend is
|
||||
/// not evaluated.
|
||||
#[test]
|
||||
fn blend_steps_count_before_the_blend_is_evaluated() {
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_doc::blend::blend_steps_made;
|
||||
use vectorcraft_doc::live::{BlendSpacing, BlendSpec};
|
||||
use vectorcraft_geom::Rect;
|
||||
let blend = |d: &mut Document, steps: u32| {
|
||||
let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() };
|
||||
Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) })
|
||||
};
|
||||
let mut scratch = Document::new(500.0, 500.0);
|
||||
let (big, small) = (blend(&mut scratch, 1000), blend(&mut scratch, 3));
|
||||
let rect = solid_rect(&mut scratch, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(0.0, 1.0, 0.0));
|
||||
assert_eq!(blend_steps_made(&big), 1000);
|
||||
assert_eq!(blend_steps_made(&rect), 0);
|
||||
let group =
|
||||
Node::new(scratch.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(big), std::sync::Arc::new(small)], clip: false });
|
||||
assert_eq!(blend_steps_made(&group), 1003, "every blend in the group");
|
||||
|
||||
let d = doc_with_live_over_green(|d| blend(d, 1000));
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let opts = sample_options(&cx);
|
||||
let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect();
|
||||
let at = Point::new(360.0, 310.0);
|
||||
let evaluated = || EXPANSIONS.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 900, exhausted: false, patterns: 0 };
|
||||
assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None);
|
||||
assert!(s.exhausted, "less work left than the blend's 1,000 steps");
|
||||
assert_eq!(evaluated(), before, "the blend is not evaluated");
|
||||
let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 };
|
||||
assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a step is drawn at the point");
|
||||
assert!(evaluated() > before, "with enough work the blend is evaluated");
|
||||
}
|
||||
|
||||
/// Each step of a blend whose keys are blends is a copy of one of them, so the steps it makes
|
||||
/// in all count before it is evaluated: an outer blend of 20 steps between two blends of 100
|
||||
/// steps makes more than 2,000, though its blends have 220 steps between their own keys.
|
||||
#[test]
|
||||
fn steps_that_copy_a_nested_blend_count_before_it_is_evaluated() {
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_doc::live::{BlendSpacing, BlendSpec};
|
||||
use vectorcraft_geom::Rect;
|
||||
let blend = |d: &mut Document, keys: Vec<Node>, steps: u32| {
|
||||
let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() };
|
||||
Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(std::sync::Arc::new).collect(), spec: Box::new(spec) })
|
||||
};
|
||||
let inner = |d: &mut Document, y: f64| {
|
||||
let red = solid_rect(d, Rect::new(300.0, y, 320.0, y + 10.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = solid_rect(d, Rect::new(400.0, y, 420.0, y + 10.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
blend(d, vec![red, blue], 100)
|
||||
};
|
||||
let d = doc_with_live_over_green(|d| {
|
||||
let (a, b) = (inner(d, 300.0), inner(d, 330.0));
|
||||
blend(d, vec![a, b], 20)
|
||||
});
|
||||
let outer = d.layers[0].children().unwrap().last().unwrap();
|
||||
assert!(vectorcraft_doc::blend::blend_steps_made(outer) > 2_000, "the copies' steps count");
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let opts = sample_options(&cx);
|
||||
let mut levels: Vec<Option<Document>> = (0..MAX_NESTING).map(|_| None).collect();
|
||||
let at = Point::new(310.0, 305.0);
|
||||
let evaluated = || EXPANSIONS.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 };
|
||||
assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None);
|
||||
assert!(s.exhausted, "less work left than the steps the outer blend makes");
|
||||
assert_eq!(evaluated(), before, "the outer blend is not evaluated");
|
||||
let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 };
|
||||
assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a key is drawn at the point");
|
||||
assert!(evaluated() > before, "with enough work the outer blend is evaluated");
|
||||
}
|
||||
|
||||
/// For a Shift-click on an envelope, the hover names the envelope where its distorted contents
|
||||
/// are drawn, and the rectangle below where they leave the point empty.
|
||||
#[test]
|
||||
fn shift_hover_names_the_envelope_where_its_art_is_drawn() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let d = doc_with_live_over_green(|d| {
|
||||
let red = solid_rect(d, Rect::new(300.0, 300.0, 420.0, 320.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
|
||||
let content = vec![std::sync::Arc::new(red)];
|
||||
let options = Default::default();
|
||||
Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope { content, kind: Box::new(kind), fidelity: 50.0, editing: false, options, frame: Box::new(Affine::IDENTITY) },
|
||||
)
|
||||
});
|
||||
let ids: Vec<NodeId> = d.layers[0].children().unwrap().iter().map(|n| n.id).collect();
|
||||
let [.., green, envelope] = ids[..] else { panic!("two objects over the rectangle expected") };
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let t = EyedropperTool::default();
|
||||
let names = |x: f64, y: f64| t.hover_object(&cx(&d, &s, &p), Point::new(x, y), shift);
|
||||
assert_eq!(names(360.0, 310.0), Some(envelope), "the distorted contents");
|
||||
assert_eq!(names(360.0, 332.0), Some(green), "a point the contents leave empty");
|
||||
}
|
||||
|
||||
/// A plain click on a selected gradient mesh recolors its points, and the hover names that
|
||||
/// mesh; Image Trace's Ignore Color pick, which the panel samples, names nothing.
|
||||
#[test]
|
||||
fn hover_names_the_selected_mesh_a_click_recolors() {
|
||||
use vectorcraft_doc::{Document, GradientMesh};
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let mesh = d.alloc_id();
|
||||
let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE);
|
||||
d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap();
|
||||
let p = paint();
|
||||
let mut s = Selection::default();
|
||||
s.set([mesh]);
|
||||
let mut t = EyedropperTool::default();
|
||||
let at = Point::new(150.0, 150.0);
|
||||
let a = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, at.x, at.y));
|
||||
assert!(matches!(a.first(), Some(Action::Exec(id, _)) if id == "object.mesh.setPointColor"), "{a:?}");
|
||||
assert_eq!(t.hover_object(&cx(&d, &s, &p), at, Mods::default()), Some(mesh));
|
||||
t.set_option("imageTraceIgnoreColor", &json!({"binding": 1}));
|
||||
assert_eq!(t.hover_object(&cx(&d, &s, &p), at, Mods::default()), None);
|
||||
}
|
||||
|
||||
/// A blend of two instances of one symbol draws its steps as instances too: Shift-click on a
|
||||
/// step samples the symbol's art there, and where that art leaves the point empty, what lies
|
||||
/// below.
|
||||
|
||||
@@ -77,7 +77,7 @@ pub(super) fn plain_selected(app: &VectorcraftApp) -> bool {
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if app.session.active().is_none() {
|
||||
empty_state(ui, "hexagon", tl!("No document"), tl!("Open a document to draw parametric shapes."));
|
||||
empty_state(ui, "dc-parametric-shape", tl!("No document"), tl!("Open a document to draw parametric shapes."));
|
||||
return;
|
||||
}
|
||||
let (id, s) = target(app);
|
||||
|
||||
@@ -50,15 +50,10 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
|
||||
divider(ui);
|
||||
if tool == "box3d" {
|
||||
const SHAPES: [Choice; 6] = [
|
||||
("box3d", "3D Box", "web_colors"),
|
||||
("rectangle", "Rectangle", "square"),
|
||||
("ellipse", "Ellipse", "dc-ellipse"),
|
||||
("polygon", "Polygon", "dc-polygon"),
|
||||
("star", "Star", "star"),
|
||||
("spiral", "Spiral", "tornado"),
|
||||
];
|
||||
if let Some(shape) = choice(ui, "Shape", &active_shape, &SHAPES) {
|
||||
let shapes: [Choice; 6] =
|
||||
[("box3d", "3D Box"), ("rectangle", "Rectangle"), ("ellipse", "Ellipse"), ("polygon", "Polygon"), ("star", "Star"), ("spiral", "Spiral")]
|
||||
.map(|(id, label)| (id, label, icon_for_shape(id)));
|
||||
if let Some(shape) = choice(ui, "Shape", &active_shape, &shapes) {
|
||||
app.run("tool.setOption", json!({ "key": "shape", "value": shape })).ok();
|
||||
}
|
||||
divider(ui);
|
||||
@@ -314,8 +309,8 @@ fn draw_polygon_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, ac
|
||||
end_deg = a1;
|
||||
mode = mode_str(arc_mode);
|
||||
}
|
||||
const KINDS: [Choice; 2] = [("polygon", "Polygon", "dc-polygon"), ("star", "Star", "star")];
|
||||
match choice(ui, "Shape", if is_star { "star" } else { "polygon" }, &KINDS) {
|
||||
let kinds: [Choice; 2] = [("polygon", "Polygon", icon_for_shape("polygon")), ("star", "Star", icon_for_shape("star"))];
|
||||
match choice(ui, "Shape", if is_star { "star" } else { "polygon" }, &kinds) {
|
||||
Some("star") => apply_shape(app, &[("polyIsStar", json!(true))], json!({ "isStar": true, "spokeRatio": spoke })),
|
||||
Some(_) => apply_shape(app, &[("polyIsStar", json!(false))], json!({ "isStar": false })),
|
||||
None => {}
|
||||
@@ -414,6 +409,11 @@ fn draw_box3d_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, sele
|
||||
}
|
||||
}
|
||||
|
||||
/// The toolbar icon of the shape tool `id`, so the Control bar's shape buttons show the same icon.
|
||||
fn icon_for_shape(id: &str) -> &'static str {
|
||||
vectorcraft_tools::tool_info(id).map_or("square-dashed", |t| crate::icons::tool_icon(t.icon))
|
||||
}
|
||||
|
||||
fn mode_str(m: EllipseMode) -> &'static str {
|
||||
match m {
|
||||
EllipseMode::Slice => "pie",
|
||||
@@ -422,3 +422,24 @@ fn mode_str(m: EllipseMode) -> &'static str {
|
||||
EllipseMode::Whole => "whole",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::behavior::IconId;
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
|
||||
use super::icon_for_shape;
|
||||
|
||||
/// The Control bar's shape buttons look their icons up by tool id; an id that names no tool
|
||||
/// would show the placeholder instead of the toolbar's icon.
|
||||
#[test]
|
||||
fn every_shape_button_shows_its_tools_icon() {
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] {
|
||||
let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool"));
|
||||
assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}");
|
||||
assert!(has_icon(&IconId::new(icon_for_shape(id))), "{id}'s icon {} isn't an icon", icon_for_shape(id));
|
||||
}
|
||||
assert_eq!(icon_for_shape("no-such-tool"), "square-dashed");
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,10 @@ use craft::platform::clock::monotonic_ms;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::{ActiveLook, PushButtonLook};
|
||||
use craft::ui::choice::ChoiceLook;
|
||||
use craft::ui::contract::{Bind, CaptionInk, GlyphColon, LinkLabelInk, LinkLabelUnderline, QuietHeader, SectionRhythm};
|
||||
use craft::ui::contract::{Bind, CaptionInk, GlyphColon, LinkLabelInk, LinkLabelUnderline, MoveBandCursor, QuietHeader, SectionRhythm};
|
||||
use craft::ui::docking::IconGroupSeparator;
|
||||
use craft::ui::list::{CommandHighlight, ThumbRows};
|
||||
use craft::ui::menu::MenuTitlePad;
|
||||
use craft::ui::menu::MenuTitleLook;
|
||||
use craft::ui::patterns::form_dialogs::PresetCardLook;
|
||||
use craft::ui::runtime::env::{RootEnv, Scale, ScrubDrags, WindowKey};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
@@ -19,7 +19,7 @@ use craft::ui::sections::{DialogButtonLook, QuietTitleRow};
|
||||
use craft::ui::shell::embed::CloseDecision;
|
||||
use craft::ui::shell::{AppShell, CanvasPanel, Slot};
|
||||
use craft::ui::style::TrackFill;
|
||||
use craft::ui::tabs::DocumentTabLook;
|
||||
use craft::ui::tabs::{DocumentTabLook, TabCloseLook};
|
||||
use craft::ui::text::{NumberLook, NumberPrecision};
|
||||
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
|
||||
use vectorcraft_engine::cmd::toast::Level;
|
||||
@@ -133,6 +133,7 @@ impl VectorcraftApp {
|
||||
find_font: None,
|
||||
hidden_chars: Default::default(),
|
||||
spelling: Default::default(),
|
||||
text_nodes: Default::default(),
|
||||
momentary: None,
|
||||
selection_box: None,
|
||||
selection_bounds: None,
|
||||
@@ -144,6 +145,7 @@ impl VectorcraftApp {
|
||||
plugin_keys: Default::default(),
|
||||
placed_keys: Default::default(),
|
||||
view_moved: None,
|
||||
hover_object: None,
|
||||
grab: None,
|
||||
carry_target: None,
|
||||
last_drag: None,
|
||||
@@ -508,6 +510,18 @@ impl VectorcraftApp {
|
||||
crate::keymap::note_os(ctx);
|
||||
prefs_dialog::apply_runtime(self, ctx);
|
||||
self.run_control(ctx);
|
||||
// Plug-ins loading on other threads since launch install as their loads finish; until then
|
||||
// the host keeps coming back to look again, and once more when the last one installs, for
|
||||
// what waits for them. They install after the control requests are drained, so the frame
|
||||
// after the last one opens the files held for them (the desktop app does that before this
|
||||
// pass) before a control request waiting for them runs.
|
||||
if self.session.plugins_loading() {
|
||||
if self.session.poll_plugin_loads() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
} else {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
// In the next frame's first pass, as production's one-pass frames did: a second pass of the frame that asked
|
||||
// for it (one a background run's result can bring) doesn't open it early.
|
||||
if ctx.current_pass_index() == 0
|
||||
@@ -727,10 +741,14 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32) -> Ro
|
||||
root.values.set(ThumbRows::Tight);
|
||||
// The Layers Objects search field fills the filter bar up to its Filter button, as production's did.
|
||||
root.values.set(ObjectsSearch::Fill);
|
||||
// The menu bar's titles stand as close as production's, which share the line with the bar's other controls.
|
||||
root.values.set(MenuTitlePad::Control);
|
||||
// The menu bar's titles are production's egui buttons: a push button high, 2 points beside the text, rounded.
|
||||
root.values.set(MenuTitleLook::Button);
|
||||
// The title bar and the panel headers keep the arrow, over the menu titles too, as production's did.
|
||||
root.values.set(MoveBandCursor::Arrow);
|
||||
// Document tabs show their title and its `*` in the label's semibold face, as production drew them.
|
||||
root.values.set(DocumentTabLook::Semibold);
|
||||
// A document tab's × is a small glyph that brightens under the pointer, with no fill, as production drew it.
|
||||
root.values.set(TabCloseLook::Glyph);
|
||||
// A collapsed panel column's icon groups stand apart by a hairline, as production drew them.
|
||||
root.values.set(IconGroupSeparator::Rule);
|
||||
// New Document's preset cards show blank paper on a flat card, as production drew them.
|
||||
|
||||
@@ -57,6 +57,15 @@ impl VectorcraftApp {
|
||||
ctx.request_repaint();
|
||||
break;
|
||||
}
|
||||
// An automation request sees every plug-in the launch loads: what it reads or writes
|
||||
// (rendered artwork, file formats, effect lists) would otherwise depend on timing. It
|
||||
// waits in the queue while the frames install them, so the window keeps drawing; one
|
||||
// held past its deadline meanwhile is answered above as expired. The frame's poll of
|
||||
// the loads asks for the next frame.
|
||||
if self.session.plugins_loading() {
|
||||
self.deferred_control = Some(req);
|
||||
break;
|
||||
}
|
||||
let roots = self.automation_roots.clone();
|
||||
self.ui.answering_control = true;
|
||||
// Guarded per request: a panic must not stop the requests behind it.
|
||||
|
||||
@@ -60,6 +60,10 @@ pub struct CanvasCache {
|
||||
/// The words Edit › Spelling › Auto Spell Check underlined on each text object in the last
|
||||
/// frame; dropped while it is off.
|
||||
pub spelling: canvas::marks::SpellingMarks,
|
||||
/// The active document's visible text objects for (document uid, revision), which Show Hidden
|
||||
/// Characters and Auto Spell Check draw over. A pass that draws neither drops them
|
||||
/// ([`canvas::marks::marks_of`]).
|
||||
pub text_nodes: canvas::marks::TextNodes,
|
||||
/// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between
|
||||
/// passes; the tool adapter takes it out for its call and puts it back.
|
||||
pub momentary: Option<craft::ui::canvas::Momentary>,
|
||||
@@ -87,6 +91,10 @@ pub struct CanvasCache {
|
||||
/// The view the canvas last drew and when it last changed (egui's input time): while it moves,
|
||||
/// the canvas doesn't hit-test the art under the pointer ([`canvas::hover_wait`], #2452).
|
||||
pub view_moved: Option<(canvas::ViewKey, f64)>,
|
||||
/// The object the Eyedropper's click at the pointer would act on, which Object Highlighting
|
||||
/// outlines, with what it was found for: finding it again, which can sample a color, waits
|
||||
/// until one of those changes.
|
||||
pub hover_object: Option<(canvas::HoverObjectKey, Option<vectorcraft_doc::NodeId>)>,
|
||||
/// Where the press of the gesture running on the canvas landed, in document points: a move carried out of the
|
||||
/// canvas drops its art there relative to the pointer (`canvas::drops`).
|
||||
pub grab: Option<Point>,
|
||||
@@ -343,6 +351,14 @@ pub struct CacheKey {
|
||||
/// The paper under the art that translucent art is blended with before the conversion
|
||||
/// ([`crate::display_profile::convert_over`]). None without a display profile, and in Outline.
|
||||
pub backdrop: Option<std::sync::Arc<crate::display_profile::Backdrop>>,
|
||||
/// The active color settings ([`vectorcraft_color::cms::active_settings`]), the working color
|
||||
/// settings ([`vectorcraft_color::cms::working_settings`]) and the loaded profiles' generation
|
||||
/// ([`vectorcraft_color::cms::profiles_generation`]) the frame's colors were converted with:
|
||||
/// Edit › Color Settings, a profile loaded again under its name or removed, and the front
|
||||
/// document's assigned profiles change them without changing the document. A proof of the
|
||||
/// working CMYK space converts through the working settings, which can change while the active
|
||||
/// settings stay the same.
|
||||
pub color: (vectorcraft_color::cms::ColorSettings, vectorcraft_color::cms::ColorSettings, u64),
|
||||
}
|
||||
|
||||
impl CacheKey {
|
||||
|
||||
@@ -50,6 +50,7 @@ pub use panes::{Layout as TileLayout, Panes};
|
||||
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
|
||||
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
|
||||
pub(crate) use rulers::{general_lengths, stroke_lengths};
|
||||
pub use selection::HoverObjectKey;
|
||||
pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions};
|
||||
pub use tool_adapter::{apply_requests, dispatch, mods};
|
||||
pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page, tool_enter};
|
||||
|
||||
@@ -76,17 +76,19 @@ pub struct CanvasDropsStyle {
|
||||
}
|
||||
|
||||
/// A drop target for one payload type `P`: `make` turns the payload into the canvas's own, or refuses it. `seen` is
|
||||
/// the operation of the last payload it accepted at the pointer.
|
||||
/// the operation of the last payload it accepted at the pointer. Where `covered` (another window lies over the canvas),
|
||||
/// it takes nothing: that window's targets take the drop.
|
||||
struct Target<'a, F> {
|
||||
rect: Rect,
|
||||
view: &'a CanvasView,
|
||||
covered: &'a dyn Fn(Pos2) -> bool,
|
||||
make: F,
|
||||
seen: Cell<Option<DropOperation>>,
|
||||
}
|
||||
|
||||
impl<'a, F> Target<'a, F> {
|
||||
fn new(rect: Rect, view: &'a CanvasView, make: F) -> Self {
|
||||
Target { rect, view, make, seen: Cell::new(None) }
|
||||
fn new(rect: Rect, view: &'a CanvasView, covered: &'a dyn Fn(Pos2) -> bool, make: F) -> Self {
|
||||
Target { rect, view, covered, make, seen: Cell::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +96,9 @@ impl<P: ?Sized, F: Fn(&P) -> Option<Payload>> DropTarget<P> for Target<'_, F> {
|
||||
type Drop = Dropped;
|
||||
|
||||
fn accept(&self, payload: &P, at: Pos2, op: DropOperation) -> Option<Dropped> {
|
||||
if (self.covered)(at) {
|
||||
return None;
|
||||
}
|
||||
let payload = (self.make)(payload)?;
|
||||
self.seen.set(Some(op));
|
||||
Some(Dropped { payload, at: self.view.to_doc(at), zoom: self.view.zoom, op })
|
||||
@@ -121,6 +126,8 @@ pub(crate) struct CanvasDrops<'a> {
|
||||
/// has the content the move started from ([`CarriedArt::before`]), and the document a tab rest showed is still the
|
||||
/// current one.
|
||||
given_up: bool,
|
||||
/// Whether another window lies over the canvas at a point of it: a floating panel's OS window.
|
||||
covered: &'a dyn Fn(Pos2) -> bool,
|
||||
out: &'a RefCell<Option<Dropped>>,
|
||||
/// The files from the OS the canvas places, and where their drop goes.
|
||||
files: (CanvasFiles<'a>, &'a RefCell<Option<CanvasDrop>>),
|
||||
@@ -150,9 +157,9 @@ impl Component for CanvasDrops<'_> {
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let rect = cx.rect;
|
||||
let (sources, given_up, view) = (&self.sources, self.given_up, &self.view);
|
||||
let (sources, given_up, view, covered) = (&self.sources, self.given_up, &self.view, self.covered);
|
||||
let unchanged = |a: &CarriedArt| given_up || sources.contains(&(a.document, a.revision));
|
||||
let art = Target::new(rect, view, |a: &CarriedArt| unchanged(a).then(|| Payload::Art(a.clone())));
|
||||
let art = Target::new(rect, view, covered, |a: &CarriedArt| unchanged(a).then(|| Payload::Art(a.clone())));
|
||||
let mut dropped = cx.drop_target::<CarriedArt, _>(&art);
|
||||
if self.kind == BodyKind::Pane
|
||||
&& let (Some(op), Some((carried, _))) = (art.seen.get(), cx.dragging::<CarriedArt>())
|
||||
@@ -163,11 +170,11 @@ impl Component for CanvasDrops<'_> {
|
||||
}
|
||||
if self.kind == BodyKind::Live {
|
||||
// The art of this canvas's own document is not accepted as a panel payload: its move resumes.
|
||||
let panel = Target::new(rect, view, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone())));
|
||||
let style = Target::new(rect, view, |d: &ListDrag<StyleKey>| Some(Payload::Style(d.grabbed.clone())));
|
||||
let symbol = Target::new(rect, view, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
|
||||
let brush = Target::new(rect, view, |d: &ListDrag<BrushKey>| Some(Payload::Brush(d.grabbed.clone())));
|
||||
let library = Target::new(rect, view, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
|
||||
let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone())));
|
||||
let style = Target::new(rect, view, covered, |d: &ListDrag<StyleKey>| Some(Payload::Style(d.grabbed.clone())));
|
||||
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
|
||||
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| Some(Payload::Brush(d.grabbed.clone())));
|
||||
let library = Target::new(rect, view, covered, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
|
||||
let panel = cx.drop_target::<PanelDrag, _>(&panel);
|
||||
let style = cx.drop_target::<ListDrag<StyleKey>, _>(&style);
|
||||
let symbol = cx.drop_target::<ListDrag<SymbolKey>, _>(&symbol);
|
||||
@@ -215,8 +222,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi
|
||||
&& app.session.documents().iter().any(|d| d.uid == a.document && d.same_content(&a.before))
|
||||
});
|
||||
let (out, files_out) = (RefCell::new(None), RefCell::new(None));
|
||||
let ctx = ui.ctx().clone();
|
||||
let covered = |at: Pos2| crate::panel_docking::os_window_at(app, &ctx, at);
|
||||
let files = (CanvasFiles::new(app, rect, &view), &files_out);
|
||||
let drops = CanvasDrops { common: Common::new(), view, kind, document, sources, given_up, out: &out, files };
|
||||
let drops = CanvasDrops { common: Common::new(), view, kind, document, sources, given_up, covered: &covered, out: &out, files };
|
||||
drops.id_salt(("canvas-drops", win)).show_at(ui, rect);
|
||||
if let Some(files) = files_out.take() {
|
||||
crate::place::canvas_drop(app, ui.ctx(), files);
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
use craft::behavior::IconId;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::behavior::{ColumnWidth, IconId};
|
||||
use craft::ui::buttons::{Link, LinkLook};
|
||||
use craft::ui::contract::{Bind, Gap, Pad, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartScreen, Template};
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Stack};
|
||||
use craft::ui::runtime::env::{Env, Overrides, with_env};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
|
||||
use craft::ui::style::{SurfaceKind, TypeRole};
|
||||
|
||||
use super::{Ui, VectorcraftApp, json};
|
||||
|
||||
@@ -13,6 +17,10 @@ const TEMPLATES: [&str; 6] = ["Letter", "A4", "Web 1920×1080", "Phone 390×844"
|
||||
/// The icons of the three `community::link_urls` links, in their order.
|
||||
const LINK_ICONS: [&str; 3] = ["globe", "external-link", "git-branch"];
|
||||
|
||||
/// The Learn cards across a full-width column, and across a narrower one.
|
||||
const FOUR: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 4];
|
||||
const TWO: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 2];
|
||||
|
||||
/// The Home screen (`app.home`; with no document open, unless its preference is off).
|
||||
pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
let recent: Vec<RecentFile> = crate::io::recent_files(app)
|
||||
@@ -35,12 +43,14 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
for ((label, url), icon) in crate::community::link_urls(app).into_iter().zip(LINK_ICONS) {
|
||||
links.push(StartLink::url(tl!(label), Some(IconId::new(icon)), url));
|
||||
}
|
||||
// The column shows no view switch or sort; the bindings hold copies so the Learn section can borrow the app.
|
||||
let (mut view, mut sort) = (app.ui.home_view, app.ui.home_sort);
|
||||
let mut pressed = None;
|
||||
let mut learn = |ui: &mut Ui| learn(app, ui, &mut pressed);
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &recent)
|
||||
// Production's community links read in the accent alone, with no underline.
|
||||
let plain_links = |overrides: &mut Overrides| {
|
||||
overrides.values.set(LinkLook::Plain);
|
||||
};
|
||||
// Learn follows the presets, which stand right under New and Open as in production 0.24.1.
|
||||
let start = StartScreen::new(Bind::bound(&mut app.ui.home_view), Bind::bound(&mut app.ui.home_sort), &recent)
|
||||
.layout(StartLayout::Column)
|
||||
.title(tl!("Welcome to VectorCraft"))
|
||||
.subtitle(tl!("Vector illustration — fast, open, scriptable."))
|
||||
@@ -51,15 +61,13 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
.templates_title(tl!("Quickly start a new file"))
|
||||
.links(&links)
|
||||
.links_title(tl!("Community"))
|
||||
.app_section(tl!("Learn"), &mut learn)
|
||||
.show(&mut child);
|
||||
app.ui.home_view = view;
|
||||
app.ui.home_sort = sort;
|
||||
.section(StartPlace::AfterSections, |ui, _| learn(ui, &mut pressed));
|
||||
let out = with_env(&mut child, plain_links, |ui| start.show(ui));
|
||||
for action in out.actions {
|
||||
run_action(app, action);
|
||||
}
|
||||
if let Some(id) = pressed
|
||||
&& let Err(e) = app.run("learn.show", json!({ "tutorial": id }))
|
||||
if let Some((command, args)) = pressed
|
||||
&& let Err(e) = app.run(command, args)
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
@@ -86,21 +94,36 @@ fn run_action(app: &mut VectorcraftApp, action: StartAction) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Home screen's Learn section: the Quick skill guide card, which shows the Learn panel's list
|
||||
/// of skills, and the Learn panel's tutorials under their skills, each a button that shows the
|
||||
/// panel at its steps (`learn.show`). The start screen may run this twice in a pass, so it only
|
||||
/// draws and records the tutorial pressed in `pressed`.
|
||||
fn learn(app: &mut VectorcraftApp, ui: &mut Ui, pressed: &mut Option<&'static str>) {
|
||||
use crate::panels::learn::{catalog, guide_card};
|
||||
guide_card(app, ui); // PLAN: assumed `guide_card(app, ui)` as document-panels-w18 leaves it, on `Button::detail`.
|
||||
for skill in catalog::SKILLS {
|
||||
let _ = Text::new(skill.title).show(ui);
|
||||
let _ = Row::new().show(ui, |ui, _| {
|
||||
for tutorial in skill.tutorials {
|
||||
if Button::new(tutorial.title).id_salt(tutorial.id).show(ui).clicked() {
|
||||
*pressed = Some(tutorial.id);
|
||||
}
|
||||
/// The Home screen's Learn section, after the new-file presets: a Column page section whose heading row ends in the
|
||||
/// Quick skill guide link, which shows the Learn panel's list of skills (`learn.skills`), over a card per skill: its
|
||||
/// title over its tutorials as links, each showing the panel at its steps (`learn.show`). The four cards stand in one
|
||||
/// row in a column at its full `size.page.column` width, and two by two in a narrower one. The start screen may run
|
||||
/// this twice in a pass, so it only draws and records the command chosen in `pressed`.
|
||||
fn learn(ui: &mut Ui, pressed: &mut Option<(&'static str, serde_json::Value)>) {
|
||||
use crate::panels::learn::catalog::SKILLS;
|
||||
let (mut guide, mut tutorial) = (false, None);
|
||||
let across = if ui.available_width() + 0.5 >= Env::of(ui).tokens.size.page.column { FOUR } else { TWO };
|
||||
let section = Section::fixed(tl!("Learn")).quiet_header().header_gap(Gap::PageHeading);
|
||||
let _ = section.controls(|ui, _| guide |= clicked(&Link::new(tl!("Quick skill guide")).show(ui))).show(ui, |ui, _| {
|
||||
let _ = Grid::new(across).gap(Gap::Section).cells(CellAlign::Top).fill_width().show(ui, |ui, _| {
|
||||
for skill in SKILLS {
|
||||
let card = Stack::new().surface(SurfaceKind::Raised).pad(Pad::Regular).gap(Gap::Stack).fill_width();
|
||||
let _ = card.show(ui, |ui, _| {
|
||||
let _ = Text::new(skill.title).role(TypeRole::BodyStrong).show(ui);
|
||||
let _ = Stack::new().gap(Gap::PageLink).show(ui, |ui, _| {
|
||||
for t in skill.tutorials {
|
||||
if clicked(&Link::new(t.title).id_salt(t.id).show(ui)) {
|
||||
tutorial = Some(t.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
if guide {
|
||||
*pressed = Some(("learn.skills", json!({})));
|
||||
} else if let Some(id) = tutorial {
|
||||
*pressed = Some(("learn.show", json!({ "tutorial": id })));
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,17 @@ pub struct SpellingMarks {
|
||||
pub(super) lines: HashMap<NodeId, (Arc<Node>, Underlines)>,
|
||||
}
|
||||
|
||||
/// The visible text objects of a document, depth first in paint order ([`TextNodes`]).
|
||||
pub(super) type TextList = Arc<Vec<Arc<Node>>>;
|
||||
|
||||
/// The visible text objects of the active document, for (document uid, revision): Show Hidden
|
||||
/// Characters and Auto Spell Check draw over them every pass ([`crate::CanvasCache::text_nodes`]).
|
||||
/// A pass that draws neither drops them ([`marks_of`]).
|
||||
#[derive(Default)]
|
||||
pub struct TextNodes {
|
||||
pub(super) list: Option<((u64, u64), TextList)>,
|
||||
}
|
||||
|
||||
/// One print tile on the screen: its paper edge and its number.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Tile {
|
||||
@@ -166,11 +177,15 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
|
||||
if !spelling_gate {
|
||||
app.canvas.spelling = SpellingMarks::default();
|
||||
}
|
||||
if !hidden_gate && !spelling_gate {
|
||||
app.canvas.text_nodes = TextNodes::default();
|
||||
}
|
||||
let fades = artboards::fades_outside_artboards(app);
|
||||
let shows_artboards = artboards::shows_artboards(app);
|
||||
let Some(st) = app.session.active() else {
|
||||
app.canvas.hidden_chars.marks.clear();
|
||||
app.canvas.spelling = SpellingMarks::default();
|
||||
app.canvas.text_nodes = TextNodes::default();
|
||||
return m;
|
||||
};
|
||||
let key = (st.uid, st.revision);
|
||||
@@ -181,11 +196,16 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
|
||||
m.bleed = artboards::bleed_paths(st);
|
||||
m.artboard_marks = artboards::mark_paths(st, view.zoom);
|
||||
}
|
||||
if hidden_gate {
|
||||
collect_hidden(st, view, &mut app.canvas.hidden_chars, &mut m.hidden);
|
||||
}
|
||||
if spelling_gate {
|
||||
collect_spelling(st, view, &mut app.canvas.spelling, &mut m.spelling);
|
||||
if hidden_gate || spelling_gate {
|
||||
// Both draw over the same text objects, found among the document's other objects once
|
||||
// for each revision.
|
||||
let texts = cached(&mut app.canvas.text_nodes.list, key, || text_nodes(&st.doc.layers));
|
||||
if hidden_gate {
|
||||
collect_hidden(&texts, view, &mut app.canvas.hidden_chars, &mut m.hidden);
|
||||
}
|
||||
if spelling_gate {
|
||||
collect_spelling(st, &texts, view, &mut app.canvas.spelling, &mut m.spelling);
|
||||
}
|
||||
}
|
||||
if inside_gate
|
||||
&& let Some(id) = app.session.draw_inside
|
||||
@@ -267,14 +287,22 @@ fn cached<T>(slot: &mut Option<((u64, u64), Arc<T>)>, key: (u64, u64), make: imp
|
||||
v
|
||||
}
|
||||
|
||||
/// Depth first in paint order, leaving out hidden objects and what is inside them.
|
||||
fn walk(nodes: &[Arc<Node>], f: &mut impl FnMut(&Arc<Node>)) {
|
||||
for n in nodes.iter().filter(|n| n.visible) {
|
||||
f(n);
|
||||
if let Some(children) = n.children() {
|
||||
walk(children, f);
|
||||
/// The text objects in `layers`, depth first in paint order, leaving out hidden objects and what
|
||||
/// is inside them.
|
||||
fn text_nodes(layers: &[Arc<Node>]) -> Vec<Arc<Node>> {
|
||||
fn walk(nodes: &[Arc<Node>], out: &mut Vec<Arc<Node>>) {
|
||||
for n in nodes.iter().filter(|n| n.visible) {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
out.push(n.clone());
|
||||
}
|
||||
if let Some(children) = n.children() {
|
||||
walk(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(layers, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `n`'s box meets the part of the document the view shows (the box round the view's
|
||||
@@ -286,7 +314,7 @@ fn in_view(n: &Node, view: &CanvasView) -> bool {
|
||||
|
||||
/// The marks of the visible text objects in view, laid out again only for the objects the memo
|
||||
/// doesn't hold as they are now. The objects not shown this pass are dropped from the memo.
|
||||
fn collect_hidden(st: &DocState, view: &CanvasView, kept: &mut HiddenChars, out: &mut Vec<PlacedMark>) {
|
||||
fn collect_hidden(texts: &[Arc<Node>], view: &CanvasView, kept: &mut HiddenChars, out: &mut Vec<PlacedMark>) {
|
||||
let mut last = std::mem::take(&mut kept.marks);
|
||||
// The inputs are read before any layout: when fonts load during this pass, the next pass lays
|
||||
// all type out again.
|
||||
@@ -295,10 +323,10 @@ fn collect_hidden(st: &DocState, view: &CanvasView, kept: &mut HiddenChars, out:
|
||||
last.clear();
|
||||
kept.inputs = inputs;
|
||||
}
|
||||
walk(&st.doc.layers, &mut |n| {
|
||||
let NodeKind::Text(tx) = &n.kind else { return };
|
||||
for n in texts {
|
||||
let NodeKind::Text(tx) = &n.kind else { continue };
|
||||
if !in_view(n, view) {
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
let marks = match last.remove(&n.id) {
|
||||
Some((was, marks)) if Arc::ptr_eq(&was, n) => marks,
|
||||
@@ -306,12 +334,12 @@ fn collect_hidden(st: &DocState, view: &CanvasView, kept: &mut HiddenChars, out:
|
||||
};
|
||||
out.extend_from_slice(&marks);
|
||||
kept.marks.insert(n.id, (n.clone(), marks));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The Auto Spell Check segments of the visible text objects in view, checked again only for the
|
||||
/// objects the memo doesn't hold as they are now.
|
||||
fn collect_spelling(st: &DocState, view: &CanvasView, kept: &mut SpellingMarks, out: &mut Vec<(Point, Point)>) {
|
||||
fn collect_spelling(st: &DocState, texts: &[Arc<Node>], view: &CanvasView, kept: &mut SpellingMarks, out: &mut Vec<(Point, Point)>) {
|
||||
let mut last = std::mem::take(&mut kept.lines);
|
||||
let inputs = SpellingInputs {
|
||||
fonts: vectorcraft_text::FontDb::global().generation(),
|
||||
@@ -325,10 +353,10 @@ fn collect_spelling(st: &DocState, view: &CanvasView, kept: &mut SpellingMarks,
|
||||
last.clear();
|
||||
kept.inputs = Some(inputs);
|
||||
}
|
||||
walk(&st.doc.layers, &mut |n| {
|
||||
let NodeKind::Text(tx) = &n.kind else { return };
|
||||
for n in texts {
|
||||
let NodeKind::Text(tx) = &n.kind else { continue };
|
||||
if !auto_spell_checks(n) || !in_view(n, view) {
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
let lines = match last.remove(&n.id) {
|
||||
Some((was, lines)) if Arc::ptr_eq(&was, n) => lines,
|
||||
@@ -336,7 +364,7 @@ fn collect_spelling(st: &DocState, view: &CanvasView, kept: &mut SpellingMarks,
|
||||
};
|
||||
out.extend_from_slice(&lines);
|
||||
kept.lines.insert(n.id, (n.clone(), lines));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw Inside's arms on the screen: round the corners of `bounds` (a few pixels outside the
|
||||
|
||||
@@ -40,20 +40,31 @@ fn settled(app: &mut VectorcraftApp, view: &CanvasView, ids: &[NodeId]) -> Vec<A
|
||||
|
||||
/// An unchanged type object keeps its memo entry; an edit lays out only the object edited; a zoom
|
||||
/// reuses the entries (the marks are in document points); a new font generation lays everything out.
|
||||
/// Other tests change the fonts while this one runs, so the edit and the zoom are tried again on a
|
||||
/// new document until the fonts stay the same from the settled pass through the edited one to the
|
||||
/// zoomed one.
|
||||
#[test]
|
||||
fn hidden_characters_lay_out_only_type_that_changed() {
|
||||
let mut app = app();
|
||||
let ids = [text(&mut app, 20, 40, "a b\nc d"), text(&mut app, 20, 160, "e f")];
|
||||
app.ui.view.hidden_chars = true;
|
||||
let before = settled(&mut app, &view(), &ids);
|
||||
app.session.execute("text.setText", &json!({"id": ids[1].0, "text": "e f g"})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
let after = kept_hidden(&app, &ids);
|
||||
let zoomed = CanvasView::new(view().rect, Point::new(100.0, 100.0), 2.0);
|
||||
let (mut app, ids, before, after, zoom) = (0..100)
|
||||
.find_map(|_| {
|
||||
let mut app = app();
|
||||
let ids = [text(&mut app, 20, 40, "a b\nc d"), text(&mut app, 20, 160, "e f")];
|
||||
app.ui.view.hidden_chars = true;
|
||||
let before = settled(&mut app, &view(), &ids);
|
||||
let inputs = app.canvas.hidden_chars.inputs.clone();
|
||||
app.session.execute("text.setText", &json!({"id": ids[1].0, "text": "e f g"})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
let edited = app.canvas.hidden_chars.inputs == inputs;
|
||||
let after = kept_hidden(&app, &ids);
|
||||
marks_of(&mut app, &zoomed);
|
||||
let zoom = kept_hidden(&app, &ids);
|
||||
(edited && app.canvas.hidden_chars.inputs == inputs).then_some((app, ids, before, after, zoom))
|
||||
})
|
||||
.expect("the fonts settle");
|
||||
assert!(Arc::ptr_eq(&before[0], &after[0]), "the object not edited is not laid out again");
|
||||
assert!(!Arc::ptr_eq(&before[1], &after[1]), "the edited object is");
|
||||
let zoomed = CanvasView::new(view().rect, Point::new(100.0, 100.0), 2.0);
|
||||
marks_of(&mut app, &zoomed);
|
||||
assert!(kept_hidden(&app, &ids).iter().zip(&after).all(|(a, b)| Arc::ptr_eq(a, b)), "a zoom lays out no type");
|
||||
assert!(zoom.iter().zip(&after).all(|(a, b)| Arc::ptr_eq(a, b)), "a zoom lays out no type");
|
||||
app.canvas.hidden_chars.inputs = (u64::MAX, String::new());
|
||||
marks_of(&mut app, &view());
|
||||
assert!(kept_hidden(&app, &ids).iter().zip(&after).all(|(a, b)| !Arc::ptr_eq(a, b)), "other fonts lay all type out again");
|
||||
@@ -97,15 +108,204 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() {
|
||||
};
|
||||
marks_of(&mut app, &view());
|
||||
let held = count(&app);
|
||||
assert!(app.canvas.text_nodes.list.is_some(), "the list of the text objects is kept");
|
||||
app.ui.view.hidden_chars = false;
|
||||
marks_of(&mut app, &view());
|
||||
assert!(app.canvas.hidden_chars.marks.is_empty() && count(&app) < held, "off: no node is kept");
|
||||
assert!(app.canvas.text_nodes.list.is_none(), "off: no list of the text objects is kept");
|
||||
app.ui.view.hidden_chars = true;
|
||||
marks_of(&mut app, &view());
|
||||
assert_eq!(app.canvas.hidden_chars.marks.len(), 1);
|
||||
app.session.execute("file.close", &json!({})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
assert!(app.canvas.hidden_chars.marks.is_empty(), "no node of the closed document is kept");
|
||||
assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept");
|
||||
}
|
||||
|
||||
/// `paths` small rectangles and three point type objects with hidden characters and words no
|
||||
/// dictionary knows: the first on the first layer, the second in a group on that layer and the
|
||||
/// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type
|
||||
/// objects, the group and the second layer.
|
||||
fn type_among_paths(paths: usize) -> (VectorcraftApp, [NodeId; 3], NodeId, NodeId) {
|
||||
let mut app = app();
|
||||
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let path = id(app.session.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 5, "height": 5})).unwrap());
|
||||
{
|
||||
let st = app.session.active_mut().unwrap();
|
||||
let doc = Arc::make_mut(&mut st.doc);
|
||||
let template = doc.node(path).unwrap().clone();
|
||||
let more: Vec<_> = (1..paths)
|
||||
.map(|_| {
|
||||
let mut p = template.clone();
|
||||
p.id = doc.alloc_id();
|
||||
Arc::new(p)
|
||||
})
|
||||
.collect();
|
||||
Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(more);
|
||||
doc.drop_lookup_cache();
|
||||
}
|
||||
let a = text(&mut app, 20, 40, "one\ttwo\u{00A0}the\nthree\u{2028}four");
|
||||
let b = text(&mut app, 20, 110, "Qzvbtrw the\u{2003}cat");
|
||||
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let group = id(app.session.execute("object.group", &json!({})).unwrap());
|
||||
let layer = id(app.session.execute("layer.new", &json!({})).unwrap());
|
||||
let c = text(&mut app, 20, 180, "Zvqtrbx the\u{202F}cat\n");
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.iter().find(|l| l.id == layer).and_then(|l| l.children()).map(|c| c.len()), Some(1));
|
||||
app.ui.view.hidden_chars = true;
|
||||
app.ui.view.auto_spell_check = true;
|
||||
(app, [a, b, c], group, layer)
|
||||
}
|
||||
|
||||
/// The list of text objects Show Hidden Characters and Auto Spell Check last drew over.
|
||||
fn listed_type(app: &VectorcraftApp) -> TextList {
|
||||
app.canvas.text_nodes.list.as_ref().map(|(_, l)| l.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// Show Hidden Characters and Auto Spell Check find the type among the document's other objects
|
||||
/// once for each revision, in one list both draw from: passes that change nothing draw from the
|
||||
/// same list, and draw the marks and lines a pass drawing from a new list draws. The list holds the
|
||||
/// visible type in `Document::walk` order.
|
||||
#[test]
|
||||
fn hidden_characters_and_auto_spell_check_share_one_list_of_the_type() {
|
||||
let (mut app, ids, _, _) = type_among_paths(2_000);
|
||||
let mut walked = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) && n.visible {
|
||||
walked.push(n.id);
|
||||
}
|
||||
});
|
||||
assert_eq!(walked.len(), 3);
|
||||
let first = marks_of(&mut app, &view());
|
||||
let list = listed_type(&app);
|
||||
assert_eq!(list.iter().map(|n| n.id).collect::<Vec<_>>(), walked);
|
||||
assert!(list.iter().all(|n| ids.contains(&n.id)), "only type");
|
||||
assert_eq!(first.spelling.len(), 2, "{:?}", first.spelling);
|
||||
for _ in 0..3 {
|
||||
let m = marks_of(&mut app, &view());
|
||||
assert_eq!((m.hidden, m.spelling), (first.hidden.clone(), first.spelling.clone()));
|
||||
assert!(Arc::ptr_eq(&list, &listed_type(&app)), "a pass that changes nothing lists no type");
|
||||
}
|
||||
app.canvas.text_nodes = TextNodes::default();
|
||||
app.canvas.hidden_chars = HiddenChars::default();
|
||||
app.canvas.spelling = SpellingMarks::default();
|
||||
let again = marks_of(&mut app, &view());
|
||||
assert_eq!((again.hidden, again.spelling), (first.hidden, first.spelling), "the marks and lines drawn from a new list");
|
||||
assert!(!Arc::ptr_eq(&list, &listed_type(&app)));
|
||||
}
|
||||
|
||||
/// Auto Spell Check alone keeps the list too, and turning it off drops it.
|
||||
#[test]
|
||||
fn auto_spell_check_alone_keeps_the_list_of_the_type() {
|
||||
let (mut app, _, _, _) = type_among_paths(10);
|
||||
app.ui.view.hidden_chars = false;
|
||||
assert_eq!(marks_of(&mut app, &view()).spelling.len(), 2);
|
||||
let list = listed_type(&app);
|
||||
marks_of(&mut app, &view());
|
||||
assert!(Arc::ptr_eq(&list, &listed_type(&app)), "kept while Auto Spell Check draws");
|
||||
app.ui.view.auto_spell_check = false;
|
||||
marks_of(&mut app, &view());
|
||||
assert!(app.canvas.text_nodes.list.is_none(), "dropped with both off");
|
||||
}
|
||||
|
||||
/// The list follows the document: a new text object, an edit, Undo, Redo and a switch to another
|
||||
/// document each list the type again, and the marks are those of the type the document holds.
|
||||
#[test]
|
||||
fn the_list_of_type_follows_edits_undo_redo_and_the_active_document() {
|
||||
let (mut app, ids, _, _) = type_among_paths(50);
|
||||
// Each listed object's id and node.
|
||||
let nodes = |app: &VectorcraftApp| listed_type(app).iter().map(|n| (n.id, Arc::as_ptr(n))).collect::<Vec<_>>();
|
||||
// The nonbreaking spaces marked in `id`.
|
||||
let no_breaks =
|
||||
|app: &VectorcraftApp, id: NodeId| app.canvas.hidden_chars.marks[&id].1.iter().filter(|p| p.mark == HiddenMark::NoBreakSpace).count();
|
||||
marks_of(&mut app, &view());
|
||||
let first = nodes(&app);
|
||||
assert_eq!(first.len(), 3);
|
||||
let added = text(&mut app, 200, 40, "g h");
|
||||
marks_of(&mut app, &view());
|
||||
let with_new = nodes(&app);
|
||||
assert_eq!(with_new.len(), 4);
|
||||
assert!(with_new.iter().any(|(id, _)| *id == added), "the new object");
|
||||
assert!(app.canvas.hidden_chars.marks.contains_key(&added), "has marks");
|
||||
app.session.execute("text.setText", &json!({"id": ids[0].0, "text": "x\ty"})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
let edited = nodes(&app);
|
||||
let node_of = |list: &[(NodeId, *const Node)], id| list.iter().find(|(i, _)| *i == id).map(|(_, n)| *n);
|
||||
assert_ne!(node_of(&edited, ids[0]), node_of(&with_new, ids[0]), "the edited object's new node");
|
||||
assert_eq!(node_of(&edited, ids[1]), node_of(&with_new, ids[1]), "the others' nodes");
|
||||
assert_eq!(no_breaks(&app, ids[0]), 0, "the marks of the edited text");
|
||||
app.session.execute("edit.undo", &json!({})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
assert_eq!(nodes(&app), with_new, "Undo");
|
||||
assert_eq!(no_breaks(&app, ids[0]), 1, "the marks of the text before");
|
||||
app.session.execute("edit.redo", &json!({})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
assert_eq!(nodes(&app), edited, "Redo");
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
assert!(marks_of(&mut app, &view()).hidden.is_empty(), "another document: none of the first one's marks");
|
||||
assert!(nodes(&app).is_empty() && app.canvas.hidden_chars.marks.is_empty());
|
||||
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
marks_of(&mut app, &view());
|
||||
assert_eq!(nodes(&app), edited, "back to the first document");
|
||||
}
|
||||
|
||||
/// Neither overlay draws over type that the canvas does not draw: a hidden text object, or one in
|
||||
/// a hidden group or layer. Shown again, its marks and lines come back.
|
||||
#[test]
|
||||
fn hidden_characters_and_auto_spell_check_leave_out_type_in_hidden_groups_and_layers() {
|
||||
let (mut app, [a, b, c], group, layer) = type_among_paths(10);
|
||||
let drawn = |app: &mut VectorcraftApp| {
|
||||
let m = marks_of(app, &view());
|
||||
let mut ids: Vec<_> = app.canvas.hidden_chars.marks.keys().copied().collect();
|
||||
ids.sort();
|
||||
let mut spelled: Vec<_> = app.canvas.spelling.lines.keys().copied().collect();
|
||||
spelled.sort();
|
||||
(ids, spelled, m.hidden.len(), m.spelling.len())
|
||||
};
|
||||
let all = drawn(&mut app);
|
||||
assert_eq!((all.0.clone(), all.1.clone(), all.3), (vec![a, b, c], vec![a, b, c], 2));
|
||||
app.session.execute("object.setProps", &json!({"ids": [group.0], "visible": false})).unwrap();
|
||||
let (ids, spelled, marks, lines) = drawn(&mut app);
|
||||
assert_eq!((ids, spelled, lines), (vec![a, c], vec![a, c], 1), "a hidden group");
|
||||
assert!(marks < all.2, "fewer marks: {marks} of {}", all.2);
|
||||
assert!(listed_type(&app).iter().all(|n| n.id != b), "not listed");
|
||||
app.session.execute("object.setProps", &json!({"ids": [group.0], "visible": true})).unwrap();
|
||||
assert_eq!(drawn(&mut app), all, "the group shown again");
|
||||
app.session.execute("layer.setProps", &json!({"id": layer.0, "visible": false})).unwrap();
|
||||
let (ids, spelled, _, lines) = drawn(&mut app);
|
||||
assert_eq!((ids, spelled, lines), (vec![a, b], vec![a, b], 1), "a hidden layer");
|
||||
app.session.execute("layer.setProps", &json!({"id": layer.0, "visible": true})).unwrap();
|
||||
assert_eq!(drawn(&mut app), all, "the layer shown again");
|
||||
app.session.execute("object.setProps", &json!({"ids": [a.0], "visible": false})).unwrap();
|
||||
let (ids, spelled, _, _) = drawn(&mut app);
|
||||
assert_eq!((ids, spelled), (vec![b, c], vec![b, c]), "a hidden text object");
|
||||
app.session.execute("object.setProps", &json!({"ids": [a.0], "visible": true})).unwrap();
|
||||
assert_eq!(drawn(&mut app), all, "the text object shown again");
|
||||
}
|
||||
|
||||
/// An ignored diagnostic for the marks' cost on a document of many paths and a little type: passes
|
||||
/// drawing from the kept list, and passes that list the type again each time. There is no timing
|
||||
/// threshold; run on an idle machine and compare the printed cases.
|
||||
#[test]
|
||||
#[ignore = "manual performance diagnostic; no stable timing threshold"]
|
||||
fn type_marks_on_many_paths_diagnostic() {
|
||||
use std::time::Instant;
|
||||
const PASSES: usize = 50;
|
||||
for paths in [10_000, 100_000] {
|
||||
let (mut app, _, _, _) = type_among_paths(paths);
|
||||
marks_of(&mut app, &view());
|
||||
let t = Instant::now();
|
||||
for _ in 0..PASSES {
|
||||
marks_of(&mut app, &view());
|
||||
}
|
||||
let kept = t.elapsed();
|
||||
let t = Instant::now();
|
||||
for _ in 0..PASSES {
|
||||
app.canvas.text_nodes = TextNodes::default();
|
||||
marks_of(&mut app, &view());
|
||||
}
|
||||
let listed = t.elapsed();
|
||||
eprintln!("{paths} paths: {:?} a pass from the kept list, {:?} a pass listing the type again", kept / PASSES as u32, listed / PASSES as u32);
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected groups' gaps are in their Gap Preview Color, and the list is kept per revision.
|
||||
|
||||
@@ -421,9 +421,16 @@ pub(super) fn cache_key(
|
||||
// Preferences › Performance › Use Monitor Profile for Canvas.
|
||||
display: app.display_profile.key(app.session.prefs.monitor_profile_display),
|
||||
backdrop: backdrop(app, st, app.outline_view()),
|
||||
color: color_key(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`CacheKey::color`] now: the active color settings, the working color settings and the loaded
|
||||
/// profiles' generation.
|
||||
fn color_key() -> (vectorcraft_color::cms::ColorSettings, vectorcraft_color::cms::ColorSettings, u64) {
|
||||
(vectorcraft_color::cms::active_settings(), vectorcraft_color::cms::working_settings(), vectorcraft_color::cms::profiles_generation())
|
||||
}
|
||||
|
||||
/// [`CacheKey::plugins`] of document `st`, one of the documents open in `session`. `keys` holds each
|
||||
/// document's value and the plug-in revision it was checked at, so a document is looked through only
|
||||
/// once after each change of the plug-in revision.
|
||||
@@ -550,10 +557,13 @@ pub(super) fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) {
|
||||
|
||||
/// Upload frame `done` from the render worker when it is of document `key_doc` and not older than
|
||||
/// the frame shown. This prevents canvas freezes during continuous edits (drags, arrow nudges, MCP
|
||||
/// command bursts) while ensuring obsolete out-of-order frames are dropped.
|
||||
/// command bursts) while ensuring obsolete out-of-order frames are dropped. A frame whose color key
|
||||
/// ([`CacheKey::color`]) is not the current one is dropped too: the worker converted its colors
|
||||
/// with the settings in force while it rendered, which may not be the ones in its key, and the next
|
||||
/// frame renders again with the current ones.
|
||||
fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate::render_worker::Done, key_doc: usize) {
|
||||
let not_older = app.canvas.key.as_ref().filter(|k| k.doc == done.key.doc).is_none_or(|k| done.key.revision >= k.revision);
|
||||
if done.key.doc != key_doc || !not_older {
|
||||
if done.key.doc != key_doc || !not_older || done.key.color != color_key() {
|
||||
return;
|
||||
}
|
||||
upload(app, ctx, done.img, done.key.pixel.is_some());
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! centre point, point type's origin, the key anchor). Each rule is a function of the app that returns what to draw;
|
||||
//! `show` hands the results to the framework's controls, which keep what they stroke between passes.
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::{DefaultHasher, Entry};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use craft::behavior::Input;
|
||||
@@ -18,8 +19,9 @@ use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintU
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleCx};
|
||||
use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_engine::{DocState, Prefs};
|
||||
use vectorcraft_engine::{DocState, Prefs, ViewInfo};
|
||||
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point};
|
||||
use vectorcraft_tools::Mods;
|
||||
|
||||
use super::cursor::ViewKey;
|
||||
use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn};
|
||||
@@ -315,15 +317,35 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin
|
||||
primary.and_then(|key| chosen.iter().find(|(k, _)| *k == key)).map(|(_, knots)| knots.clone()).unwrap_or_default(),
|
||||
segment.map(|(_, at)| at),
|
||||
);
|
||||
for (key, knots) in chosen.into_iter().filter(|(key, _)| Some(*key) != primary) {
|
||||
selection = selection.also(key, knots);
|
||||
}
|
||||
selection.others = by_key(chosen.into_iter().filter(|(key, _)| Some(*key) != primary));
|
||||
out.selection = selection;
|
||||
out
|
||||
}
|
||||
|
||||
/// `listed` with the lists of a repeated key joined, each key where it first appears: what
|
||||
/// [`PathSelection::also`] makes of the entries added one at a time, found with one lookup per entry.
|
||||
fn by_key<K: Copy + Eq + Hash, V>(listed: impl IntoIterator<Item = (K, Vec<V>)>) -> Vec<(K, Vec<V>)> {
|
||||
let mut at: HashMap<K, usize> = HashMap::new();
|
||||
let mut out: Vec<(K, Vec<V>)> = Vec::new();
|
||||
for (key, items) in listed {
|
||||
match at.entry(key) {
|
||||
Entry::Occupied(seen) => {
|
||||
if let Some((_, held)) = out.get_mut(*seen.get()) {
|
||||
held.extend(items);
|
||||
}
|
||||
}
|
||||
Entry::Vacant(new) => {
|
||||
new.insert(out.len());
|
||||
out.push((key, items));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The outline of the object under the pointer at document point `at`, at view `zoom`, for Smart Guides › Object
|
||||
/// Highlighting: the object a click of the selection tools would pick, unless it is selected or has too many points.
|
||||
/// Highlighting: the object a click of the selection tools would pick, unless the click keeps the selection (the
|
||||
/// object, or with the Selection tool selected art inside it, is selected) or the object has too many points.
|
||||
/// None while the view moves (`still` false), under Snap to Grid or Pixel Preview, with a tool that is busy or is not
|
||||
/// a selection tool, and with the preference off. `tool` is the tool whose marks show ([`super::shown_tool`]): while
|
||||
/// Cmd is held, the selection tool a press borrows.
|
||||
@@ -337,13 +359,139 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point,
|
||||
}
|
||||
let hit = selection_hit_at(app, at, zoom)?;
|
||||
let id = if tool == "selection" { hit.top_object(st.isolation) } else { hit.leaf };
|
||||
if st.selection.contains(id) {
|
||||
// A Selection tool press on selected art inside `id`, such as a group member picked with Group Selection, keeps
|
||||
// the selection and selects nothing new.
|
||||
let kept = if tool == "selection" {
|
||||
vectorcraft_tools::select::selected_under_in(&st.doc, &st.selection, &hit, id).is_some()
|
||||
} else {
|
||||
st.selection.contains(id)
|
||||
};
|
||||
if kept {
|
||||
return None;
|
||||
}
|
||||
outline_of(st, id)
|
||||
}
|
||||
|
||||
/// The hover outline of `id` in its layer colour, unless it has too many points.
|
||||
fn outline_of(st: &DocState, id: NodeId) -> Option<Hovered> {
|
||||
let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?;
|
||||
Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) })
|
||||
}
|
||||
|
||||
/// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view
|
||||
/// tools, since a press then pans the view; with the Eyedropper, the object its click there acts on
|
||||
/// ([`eyedropper_hover`]); else the selection tools' outline ([`hover`]). `tool`, `zoom` and `still` are as [`hover`]
|
||||
/// takes them.
|
||||
pub(super) fn hover_target(app: &mut VectorcraftApp, tool: &str, at: Point, held: Mods, zoom: f64, still: bool) -> Option<Hovered> {
|
||||
if held.space && (held.cmd || !app.session.tool_wants_text()) {
|
||||
return None;
|
||||
}
|
||||
if tool == "eyedropper" {
|
||||
return eyedropper_hover(app, at, held, still);
|
||||
}
|
||||
let st = app.session.active()?;
|
||||
hover(app, st, tool, at, zoom, still)
|
||||
}
|
||||
|
||||
/// The outline of the object the Eyedropper's click at `at` with `mods` would act on
|
||||
/// ([`vectorcraft_engine::Session::hover_object`]), for Smart Guides › Object Highlighting: the source of a plain
|
||||
/// click (locked and template art included), the selected mesh it recolors, with Alt the object that gets the
|
||||
/// selection's attributes, and with Shift the object the color comes from. A selected object is outlined too, since a
|
||||
/// click on it still acts on it. None under the conditions [`hover`] names.
|
||||
pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, still: bool) -> Option<Hovered> {
|
||||
let (view, prefs) = (&app.ui.view, &app.session.prefs);
|
||||
if !still || !view.smart_guides || !prefs.object_highlighting || view.snap_to_grid || view.pixel_preview || app.session.tool_busy() {
|
||||
return None;
|
||||
}
|
||||
let info = app.view_info();
|
||||
let id = eyedropper_hover_object(app, at, mods, info)?;
|
||||
outline_of(app.session.active()?, id)
|
||||
}
|
||||
|
||||
/// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and
|
||||
/// isolation, the tool's options (an armed pick), the paint defaults and the selected gradient stop, the selection
|
||||
/// tolerance, Eyedropper Options (the raster sample size), whether guides show and are locked, and the view's zoom and
|
||||
/// Outline mode: everything the tool's context gives a click that can change what it acts on.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct HoverObjectKey {
|
||||
at: Point,
|
||||
mods: Mods,
|
||||
doc: (u64, u64),
|
||||
selection: vectorcraft_doc::Selection,
|
||||
isolation: Option<NodeId>,
|
||||
options: serde_json::Value,
|
||||
paint: vectorcraft_tools::PaintDefaults,
|
||||
fill_active: bool,
|
||||
stop: Option<usize>,
|
||||
tolerance: f64,
|
||||
eyedropper: vectorcraft_engine::EyedropperOptions,
|
||||
guides: (bool, bool),
|
||||
zoom: f64,
|
||||
outline: bool,
|
||||
}
|
||||
|
||||
/// [`vectorcraft_engine::Session::hover_object`] at `at`, found again only when its [`HoverObjectKey`] changes: over
|
||||
/// an image, or with Shift held, finding it samples a color. The cached key is compared field by field, the cheap
|
||||
/// fields first, and the key is copied only when it changed.
|
||||
fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view: ViewInfo) -> Option<NodeId> {
|
||||
let st = app.session.active()?;
|
||||
let s = &app.session;
|
||||
let cached = app.canvas.hover_object.as_ref().filter(|(k, _)| {
|
||||
let HoverObjectKey {
|
||||
at: k_at,
|
||||
mods: k_mods,
|
||||
doc,
|
||||
selection,
|
||||
isolation,
|
||||
options,
|
||||
paint,
|
||||
fill_active,
|
||||
stop,
|
||||
tolerance,
|
||||
eyedropper,
|
||||
guides,
|
||||
zoom,
|
||||
outline,
|
||||
} = k;
|
||||
*k_at == at
|
||||
&& *k_mods == mods
|
||||
&& *doc == (st.uid, st.revision)
|
||||
&& *isolation == st.isolation
|
||||
&& *fill_active == s.fill_active
|
||||
&& *stop == s.selected_stop()
|
||||
&& *tolerance == s.prefs.selection_tolerance
|
||||
&& *eyedropper == s.prefs.eyedropper
|
||||
&& *guides == (view.guides, s.guides_locked())
|
||||
&& *zoom == view.zoom
|
||||
&& *outline == view.outline
|
||||
&& *selection == st.selection
|
||||
&& *paint == s.paint
|
||||
&& *options == s.tool_options()
|
||||
});
|
||||
if let Some((_, id)) = cached {
|
||||
return *id;
|
||||
}
|
||||
let key = HoverObjectKey {
|
||||
at,
|
||||
mods,
|
||||
doc: (st.uid, st.revision),
|
||||
selection: st.selection.clone(),
|
||||
isolation: st.isolation,
|
||||
options: app.session.tool_options(),
|
||||
paint: app.session.paint.clone(),
|
||||
fill_active: app.session.fill_active,
|
||||
stop: app.session.selected_stop(),
|
||||
tolerance: app.session.prefs.selection_tolerance,
|
||||
eyedropper: app.session.prefs.eyedropper,
|
||||
guides: (view.guides, app.session.guides_locked()),
|
||||
zoom: view.zoom,
|
||||
outline: view.outline,
|
||||
};
|
||||
let id = app.session.hover_object(at, mods, view);
|
||||
app.canvas.hover_object = Some((key, id));
|
||||
id
|
||||
}
|
||||
|
||||
/// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor.
|
||||
pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots {
|
||||
let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() };
|
||||
@@ -468,11 +616,11 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
|
||||
};
|
||||
// While Cmd is held, the marks of the selection tool a press borrows.
|
||||
let tool = super::shown_tool(app, ui.ctx());
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let hovered = match (kind, app.hover_doc) {
|
||||
(BodyKind::Pane, _) | (_, None) => None,
|
||||
(_, Some(at)) => hover(app, st, tool, at, space.view.zoom, still),
|
||||
(_, Some(at)) => hover_target(app, tool, at, super::held_mods(ui.ctx()), space.view.zoom, still),
|
||||
};
|
||||
let Some(st) = app.session.active() else { return };
|
||||
if let Some(h) = hovered {
|
||||
HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect);
|
||||
}
|
||||
|
||||
@@ -331,6 +331,163 @@ fn hover_outlines_the_object_under_the_pointer_unless_something_hides_it() {
|
||||
assert!(!hovered(&app, true), "a tool that is not a selection tool");
|
||||
}
|
||||
|
||||
fn held(shift: bool, alt: bool, cmd: bool, space: bool) -> Mods {
|
||||
Mods { shift, alt, cmd, space, ..Mods::default() }
|
||||
}
|
||||
|
||||
const NO_KEYS: Mods = Mods { shift: false, alt: false, cmd: false, ctrl: false, space: false };
|
||||
|
||||
/// The box of the hover outline at `at` with `held` keys down, as the canvas finds it: the tool whose marks show
|
||||
/// (with Cmd, the selection tool a press there borrows), then that tool's outline.
|
||||
fn outline_box(app: &mut VectorcraftApp, at: Point, held: Mods) -> Option<vectorcraft_geom::Rect> {
|
||||
let view = app.view_info();
|
||||
let tool = app.session.hover_tool_at(Some(at), &held, view);
|
||||
hover_target(app, tool, at, held, 1.0, true).map(|h| h.path.bounding_box())
|
||||
}
|
||||
|
||||
/// Whether two boxes agree to within a point.
|
||||
fn same_box(a: Option<vectorcraft_geom::Rect>, b: vectorcraft_geom::Rect) -> bool {
|
||||
a.is_some_and(|a| (a.x0 - b.x0).abs() < 1.0 && (a.y0 - b.y0).abs() < 1.0 && (a.x1 - b.x1).abs() < 1.0 && (a.y1 - b.y1).abs() < 1.0)
|
||||
}
|
||||
|
||||
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> vectorcraft_geom::Rect {
|
||||
vectorcraft_geom::Rect::new(x0, y0, x1, y1)
|
||||
}
|
||||
|
||||
/// A rectangle filled with `color`, its id.
|
||||
fn filled(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64, color: &str) -> NodeId {
|
||||
let id = id_of(&app.run("shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})).unwrap());
|
||||
app.run("paint.setFill", json!({"ids": [id.0], "color": color})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// With the Eyedropper, Smart Guides › Object Highlighting outlines the object under the pointer as the selection
|
||||
/// tools do, and nothing over empty canvas. While Space is held a press pans the view, so no tool outlines anything.
|
||||
#[test]
|
||||
fn eyedropper_hover_outlines_the_object_under_the_pointer() {
|
||||
let mut app = hover_scene();
|
||||
app.select_tool("eyedropper");
|
||||
let over = Point::new(150.0, 150.0);
|
||||
assert!(same_box(outline_box(&mut app, over, NO_KEYS), rect(100.0, 100.0, 200.0, 200.0)), "the rectangle under the pointer");
|
||||
assert!(outline_box(&mut app, Point::new(300.0, 50.0), NO_KEYS).is_none(), "nothing over empty canvas");
|
||||
for tool in ["eyedropper", "selection"] {
|
||||
app.select_tool(tool);
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "{tool}: outlined");
|
||||
assert!(outline_box(&mut app, over, held(false, false, false, true)).is_none(), "{tool}: Space held");
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "{tool}: Space let go");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eyedropper outlines a selected object too, since its click still acts on it. With Cmd held, a click selects
|
||||
/// with the selection tool lent to it, so the outline is that tool's: none on a selected object, and the object under
|
||||
/// the pointer otherwise. Hiding the object under the pointer, or arming Image Trace's Ignore Color pick (which acts on
|
||||
/// no object), removes the outline without the pointer moving.
|
||||
#[test]
|
||||
fn eyedropper_hover_outline_follows_the_selection_cmd_and_the_document() {
|
||||
let mut app = blank();
|
||||
let id = id_of(&app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap());
|
||||
app.select_tool("eyedropper");
|
||||
let (over, square) = (Point::new(150.0, 150.0), rect(100.0, 100.0, 200.0, 200.0));
|
||||
assert!(app.session.active().unwrap().selection.contains(id));
|
||||
assert!(same_box(outline_box(&mut app, over, NO_KEYS), square), "a selected object");
|
||||
let cmd = held(false, false, true, false);
|
||||
assert!(outline_box(&mut app, over, cmd).is_none(), "Cmd over a selected object");
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(same_box(outline_box(&mut app, over, cmd), square), "Cmd over an unselected object");
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "Cmd let go");
|
||||
app.session.set_tool_option("imageTraceIgnoreColor", &json!({"binding": 1}));
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_none(), "an armed Ignore Color pick");
|
||||
app.session.set_tool_option("imageTraceIgnoreColor", &serde_json::Value::Null);
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "the pick disarmed");
|
||||
app.run("object.hide", json!({"ids": [id.0]})).unwrap();
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_none(), "hidden art");
|
||||
}
|
||||
|
||||
/// With a group member selected (as Group Selection leaves it), the Selection tool outlines nothing over that member,
|
||||
/// where a press keeps the selection, and the group over its other member, where a press selects the group.
|
||||
#[test]
|
||||
fn selection_hover_outline_skips_a_selected_group_member() {
|
||||
let mut app = blank();
|
||||
let a = id_of(&app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap());
|
||||
let b = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap());
|
||||
app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap();
|
||||
app.run("object.group", json!({})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a.0]})).unwrap();
|
||||
app.select_tool("selection");
|
||||
assert!(outline_box(&mut app, Point::new(125.0, 125.0), NO_KEYS).is_none(), "the selected member");
|
||||
let other = outline_box(&mut app, Point::new(225.0, 125.0), NO_KEYS);
|
||||
assert!(same_box(other, rect(100.0, 100.0, 250.0, 150.0)), "the other member: {other:?}");
|
||||
}
|
||||
|
||||
/// For a Shift-click the Eyedropper outlines the object whose color the click samples: the blend where one of its
|
||||
/// steps is drawn, and the rectangle below it in a gap between the steps.
|
||||
#[test]
|
||||
fn eyedropper_shift_hover_outlines_the_object_sampled() {
|
||||
let mut app = blank();
|
||||
filled(&mut app, 20.0, 50.0, 360.0, 150.0, "#00ff00");
|
||||
let a = filled(&mut app, 100.0, 100.0, 20.0, 20.0, "#ff0000");
|
||||
let b = filled(&mut app, 200.0, 100.0, 20.0, 20.0, "#0000ff");
|
||||
app.run("object.blend.make", json!({"ids": [a.0, b.0], "steps": 1})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.select_tool("eyedropper");
|
||||
let shift = held(true, false, false, false);
|
||||
// One step, halfway: (150, 100) to (170, 120).
|
||||
let step = outline_box(&mut app, Point::new(160.0, 110.0), shift);
|
||||
assert!(same_box(step, rect(100.0, 100.0, 220.0, 120.0)), "a blend step: {step:?}");
|
||||
let gap = outline_box(&mut app, Point::new(135.0, 110.0), shift);
|
||||
assert!(same_box(gap, rect(20.0, 50.0, 380.0, 200.0)), "a gap between the steps: {gap:?}");
|
||||
}
|
||||
|
||||
/// The Eyedropper's hover outline follows Smart Guides › Object Highlighting.
|
||||
#[test]
|
||||
fn eyedropper_hover_outline_follows_object_highlighting() {
|
||||
let mut app = hover_scene();
|
||||
app.select_tool("eyedropper");
|
||||
let over = Point::new(150.0, 150.0);
|
||||
app.run("prefs.set", json!({"key": "objectHighlighting", "value": false})).unwrap();
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_none(), "the option off");
|
||||
app.run("prefs.set", json!({"key": "objectHighlighting", "value": true})).unwrap();
|
||||
assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "the option on");
|
||||
}
|
||||
|
||||
/// The Eyedropper outlines the object its click there then acts on: the front object a plain click copies attributes
|
||||
/// from, a locked one included (the Eyedropper reads locked art), and with Alt the unlocked object below it that an
|
||||
/// Alt-click gives the selection's attributes to.
|
||||
#[test]
|
||||
fn eyedropper_hover_outline_is_the_object_the_click_acts_on() {
|
||||
let mut app = blank();
|
||||
let back = filled(&mut app, 100.0, 100.0, 100.0, 100.0, "#0000ff");
|
||||
let front = filled(&mut app, 150.0, 150.0, 100.0, 100.0, "#ff0000");
|
||||
let target = filled(&mut app, 20.0, 20.0, 40.0, 40.0, "#00ff00");
|
||||
app.run("select.set", json!({"ids": [target.0]})).unwrap();
|
||||
app.select_tool("eyedropper");
|
||||
let fill = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint();
|
||||
let click = |app: &mut VectorcraftApp, at: Point, mods: Mods| {
|
||||
let view = app.view_info();
|
||||
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
|
||||
let ev = vectorcraft_tools::PointerEvent { mods, ..vectorcraft_tools::PointerEvent::new(kind, at.x, at.y) };
|
||||
crate::canvas::dispatch(app, &ev, view);
|
||||
}
|
||||
};
|
||||
let over = Point::new(175.0, 175.0);
|
||||
let alt = held(false, true, false, false);
|
||||
let shown = outline_box(&mut app, over, NO_KEYS);
|
||||
assert!(same_box(shown, rect(150.0, 150.0, 250.0, 250.0)), "the front rectangle: {shown:?}");
|
||||
click(&mut app, over, NO_KEYS);
|
||||
assert_eq!(fill(&app, target), fill(&app, front), "the click copied the outlined rectangle's fill");
|
||||
|
||||
app.run("object.lock", json!({"ids": [front.0]})).unwrap();
|
||||
app.run("select.set", json!({"ids": [target.0]})).unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [target.0], "color": "#00ff00"})).unwrap();
|
||||
let shown = outline_box(&mut app, over, NO_KEYS);
|
||||
assert!(same_box(shown, rect(150.0, 150.0, 250.0, 250.0)), "the locked front rectangle is still the source: {shown:?}");
|
||||
let shown = outline_box(&mut app, over, alt);
|
||||
assert!(same_box(shown, rect(100.0, 100.0, 200.0, 200.0)), "with Alt, the unlocked rectangle below: {shown:?}");
|
||||
click(&mut app, over, alt);
|
||||
assert_eq!(fill(&app, back), fill(&app, target), "the Alt-click gave the outlined rectangle the selection's fill");
|
||||
assert_ne!(fill(&app, front), fill(&app, target));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_of_too_many_paths_has_no_hover_outline_and_a_key_outline_of_its_bounds() {
|
||||
let mut app = blank();
|
||||
@@ -401,3 +558,34 @@ fn an_empty_selection_has_no_marks() {
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(dots(&app, st).centers.len() + dots(&app, st).origins.len(), 0);
|
||||
}
|
||||
|
||||
/// A path key that counts the comparisons made with it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Counted<'a>(u64, &'a std::cell::Cell<usize>);
|
||||
|
||||
impl PartialEq for Counted<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.1.set(self.1.get() + 1);
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Counted<'_> {}
|
||||
|
||||
impl Hash for Counted<'_> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.0.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
// Grouping the selected anchors of 2,000 paths compares each key a bounded number of times, not once per path listed
|
||||
// before it, and joins a repeated path's anchors where the path first appears, as `PathSelection::also` does.
|
||||
#[test]
|
||||
fn grouping_selected_anchors_by_path_compares_each_path_a_bounded_number_of_times() {
|
||||
let compared = std::cell::Cell::new(0);
|
||||
let listed = (0..2000u64).map(|key| (Counted(key, &compared), vec![key])).chain([(Counted(5, &compared), vec![9])]);
|
||||
let grouped = by_key(listed);
|
||||
assert_eq!(grouped.iter().map(|(key, _)| key.0).collect::<Vec<_>>(), (0..2000).collect::<Vec<_>>());
|
||||
assert_eq!(grouped[5].1, vec![5, 9]);
|
||||
assert!(compared.get() < 2 * 2001, "{} comparisons for 2,001 entries", compared.get());
|
||||
}
|
||||
@@ -2357,6 +2357,157 @@ fn appearance_of_black_on_screen_shows_pure_black_as_rgb_black() {
|
||||
assert!(near(middle(&mut app).expect("re-rendered"), accurate), "accurate again");
|
||||
}
|
||||
|
||||
/// A change of the color settings, and a profile in use loaded again under its name, re-render the
|
||||
/// canvas through the new conversion. They raise the documents' revisions but leave the art as it
|
||||
/// is, so [`super::raster::changed_pixels`] finds no part of the frame shown that changed: the
|
||||
/// frame's key holds the color settings and the loaded profiles' generation. A frame with nothing
|
||||
/// changed renders nothing.
|
||||
#[test]
|
||||
fn color_settings_and_a_reloaded_profile_render_the_canvas_again() {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_CANVAS_COLOR_SETTINGS";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
// Color settings and loaded profiles are process-wide: change them in a separate test process.
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "canvas::tests::color_settings_and_a_reloaded_profile_render_the_canvas_again", "--nocapture"])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"isolated canvas color test failed:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
return;
|
||||
}
|
||||
use vectorcraft_color::cms;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
// Larger than the view: the middle of the art's raster is its fill.
|
||||
let id = app.run("shape.rectangle", json!({"x": -5000, "y": -5000, "width": 10000, "height": 10000})).unwrap()["id"].clone();
|
||||
app.run("paint.setFill", json!({"ids": [id], "color": {"c": 60, "m": 10, "y": 80, "k": 0}})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
// The middle pixel of the art's raster uploaded by one frame, None when it was not re-rendered.
|
||||
let middle = |app: &mut VectorcraftApp| -> Option<[u8; 4]> {
|
||||
let (_, mut delta) = frame_output(app, &ctx);
|
||||
let art = app.canvas.texture.as_ref().unwrap().id();
|
||||
let px = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| {
|
||||
let egui::ImageData::Color(img) = &d.image;
|
||||
let [w, h] = img.size;
|
||||
img.pixels[h / 2 * w + w / 2].to_array()
|
||||
});
|
||||
delta.clear();
|
||||
px
|
||||
};
|
||||
let ink = vectorcraft_color::Color::cmyk(0.6, 0.1, 0.8, 0.0);
|
||||
let through = |cmyk: &str| {
|
||||
let c = cms::Cms::new(&cms::ColorSettings { cmyk: cmyk.into(), ..cms::working_settings() }).unwrap().display_rgb(&ink);
|
||||
c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
|
||||
};
|
||||
let near = |a: [u8; 4], b: [u8; 3]| a[..3].iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 3);
|
||||
let (generic, device) = (through(cms::GENERIC_CMYK), through(cms::DEVICE_CMYK));
|
||||
assert!(!near([generic[0], generic[1], generic[2], 255], device), "the two CMYK spaces draw the ink differently: {generic:?}, {device:?}");
|
||||
|
||||
let first = middle(&mut app).expect("the first frame renders the art");
|
||||
assert!(near(first, generic), "through the working CMYK space: {first:?}, not {generic:?}");
|
||||
assert_eq!(middle(&mut app), None, "nothing changed: no re-render");
|
||||
app.run("edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})).unwrap();
|
||||
let shown = middle(&mut app).expect("Color Settings re-render the canvas");
|
||||
assert!(near(shown, device), "through the new working CMYK space: {shown:?}, not {device:?}");
|
||||
assert_eq!(middle(&mut app), None, "nothing changed since: no re-render");
|
||||
app.run("edit.colorSettings", json!({"cmyk": cms::GENERIC_CMYK})).unwrap();
|
||||
assert!(near(middle(&mut app).expect("re-rendered"), generic), "back to the first working space");
|
||||
|
||||
// A built-in CMYK profile's file renamed `name`: padded with spaces, which names drop.
|
||||
let renamed = |builtin: &str, name: &str| {
|
||||
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec();
|
||||
let (from, to) = (utf16(builtin), utf16(&format!("{name:<width$}", width = builtin.len())));
|
||||
let at = bytes.windows(from.len()).position(|w| w == from).unwrap();
|
||||
bytes[at..at + to.len()].copy_from_slice(&to);
|
||||
bytes
|
||||
};
|
||||
let name = "Canvas Reload CMYK";
|
||||
let dir = vectorcraft_testkit::temp_dir("canvas-reload-cmyk");
|
||||
let load = |app: &mut VectorcraftApp, builtin: &str| {
|
||||
let path = dir.join(format!("{}.icc", builtin.len()));
|
||||
std::fs::write(&path, renamed(builtin, name)).unwrap();
|
||||
let r = app.run("color.loadProfile", json!({"path": path.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(r["name"], name);
|
||||
};
|
||||
load(&mut app, cms::GENERIC_CMYK);
|
||||
app.run("edit.assignProfile", json!({"cmyk": name})).unwrap();
|
||||
let assigned = middle(&mut app).expect("assigning a profile re-renders the canvas");
|
||||
assert!(near(assigned, generic), "through the assigned copy of the working space: {assigned:?}, not {generic:?}");
|
||||
assert_eq!(middle(&mut app), None, "nothing changed: no re-render");
|
||||
// The same name, the settings as they were: only the profile's file is new.
|
||||
load(&mut app, cms::DEVICE_CMYK);
|
||||
let reloaded = middle(&mut app).expect("the profile loaded again re-renders the canvas");
|
||||
assert!(near(reloaded, device), "through the profile's new file: {reloaded:?}, not {device:?}");
|
||||
assert_eq!(middle(&mut app), None, "nothing changed since: no re-render");
|
||||
|
||||
// A proof of the working CMYK space converts through the working settings. With the document's
|
||||
// assigned profile in place of the working CMYK space, a new working CMYK space leaves the
|
||||
// active settings as they were and changes only the proof.
|
||||
app.run("view.proofSetup", json!({"target": "workingCmyk"})).unwrap();
|
||||
app.run("view.proofColors", json!({"on": true})).unwrap();
|
||||
let proofed = middle(&mut app).expect("Proof Colors re-renders the canvas");
|
||||
assert_eq!(middle(&mut app), None, "nothing changed: no re-render");
|
||||
let active = cms::active_settings();
|
||||
app.run("edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})).unwrap();
|
||||
let reproofed = middle(&mut app).expect("a new working CMYK space re-renders the proof");
|
||||
assert_eq!(cms::active_settings(), active, "the assigned profile keeps the active settings");
|
||||
assert!(!near(reproofed, [proofed[0], proofed[1], proofed[2]]), "the proof through the new working CMYK space: {reproofed:?}, not {proofed:?}");
|
||||
assert_eq!(middle(&mut app), None, "nothing changed since: no re-render");
|
||||
}
|
||||
|
||||
/// A frame from the render worker whose color key is not the current one is not shown, and the
|
||||
/// canvas asks for the frame again. The worker converts colors with the settings in force while it
|
||||
/// renders, so a frame asked for before a change of the color settings may hold colors of the new
|
||||
/// settings under the old key, and a return to the old settings would keep it.
|
||||
#[test]
|
||||
fn a_worker_frame_of_other_color_settings_is_not_shown() {
|
||||
keeping_color_settings(a_worker_frame_of_other_color_settings);
|
||||
}
|
||||
|
||||
fn a_worker_frame_of_other_color_settings() {
|
||||
use vectorcraft_color::cms;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.canvas.worker_started = true;
|
||||
let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel();
|
||||
app.canvas.worker = Some(worker);
|
||||
let ctx = crate::testing::ui_context();
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
let raw =
|
||||
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), time: Some(1.0), ..Default::default() };
|
||||
ctx.run_ui(raw, |ui| show(app, ui)).textures_delta.clear();
|
||||
};
|
||||
frame(&mut app);
|
||||
done_tx.send(finished(&jobs.try_recv().expect("the first frame"))).unwrap();
|
||||
frame(&mut app);
|
||||
let first = app.canvas.key.clone().expect("the first frame is shown");
|
||||
|
||||
// A pan's frame goes to the worker, and the color settings change before it is finished.
|
||||
app.view_mut().unwrap().center.x += 5.0;
|
||||
frame(&mut app);
|
||||
let pan = jobs.try_recv().expect("the pan's frame goes to the worker");
|
||||
let settings = cms::ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..cms::active_settings() };
|
||||
assert_ne!(settings, cms::active_settings(), "other color settings");
|
||||
cms::with_active(std::sync::Arc::new(cms::Cms::new(&settings).unwrap()), || {
|
||||
done_tx.send(finished(&pan)).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(app.canvas.key.as_ref(), Some(&first), "the pan's frame, of other color settings, is not shown");
|
||||
let again = jobs.try_recv().expect("the pan's frame is asked for with the current color settings");
|
||||
assert_ne!(again.key.color, pan.key.color);
|
||||
});
|
||||
// Back to the settings in the pan's key: the pan's frame is asked for again.
|
||||
frame(&mut app);
|
||||
let back = jobs.try_recv().expect("the pan's frame is asked for again");
|
||||
assert_eq!(back.key, pan.key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_bounding_box_handle_scales_a_default_mirror_repeat() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -437,16 +437,17 @@ fn case_from_attrs(attrs: &Map<String, Value>) -> Option<&'static str> {
|
||||
/// and a final `%` in the percent fields or `°` in Character Rotation.
|
||||
fn typed_number(key: &str, text: &str) -> Option<f64> {
|
||||
let text = text.trim().replace('\u{2212}', "-");
|
||||
let text = vectorcraft_doc::decimal_point(&text);
|
||||
let mark = match key {
|
||||
"size" | "leading" | "baseline_shift" | "tcyUpDown" | "tcyLeftRight" | "stroke_width" => {
|
||||
return vectorcraft_doc::Unit::Points.parse(&text);
|
||||
return vectorcraft_doc::Unit::Points.parse(&vectorcraft_doc::decimal_point(&text));
|
||||
}
|
||||
"h_scale" | "v_scale" | "tsume" | "fill_tint" | "stroke_tint" => Some('%'),
|
||||
"rotation" => Some('°'),
|
||||
_ => None,
|
||||
};
|
||||
vectorcraft_doc::parse_number(mark.and_then(|m| text.strip_suffix(m)).unwrap_or(&text))
|
||||
// The suffix comes off before the comma is read, so `1,000%` is refused as `1,000` is.
|
||||
let number = mark.and_then(|m| text.strip_suffix(m)).unwrap_or(&text);
|
||||
vectorcraft_doc::parse_number(&vectorcraft_doc::decimal_point(number))
|
||||
}
|
||||
|
||||
fn optional_number(d: &Values, key: &str) -> Result<Option<Value>, String> {
|
||||
|
||||
@@ -529,13 +529,25 @@ fn number_fields_take_field_arithmetic() {
|
||||
("leading", "1 in", 72.0),
|
||||
("baseline_shift", "\u{2212}2", -2.0),
|
||||
("kerning", "12,5", 12.5),
|
||||
("h_scale", "12,5%", 12.5),
|
||||
("rotation", "12,5°", 12.5),
|
||||
];
|
||||
for (key, text, want) in typed {
|
||||
let (mut d, _) = dialog_for(json!({}));
|
||||
put(&mut d, key, json!(text));
|
||||
assert_eq!(optional_number(&Values::new(&d), key), Ok(Some(json!(want))), "{key} {text}");
|
||||
}
|
||||
for (key, text) in [("size", "12°"), ("leading", "50%"), ("tracking", "10%"), ("rotation", "45%"), ("h_scale", "1%2"), ("size", "1e3")] {
|
||||
for (key, text) in [
|
||||
("size", "12°"),
|
||||
("leading", "50%"),
|
||||
("tracking", "10%"),
|
||||
("rotation", "45%"),
|
||||
("h_scale", "1%2"),
|
||||
("size", "1e3"),
|
||||
("h_scale", "1,000"),
|
||||
("h_scale", "1,000%"),
|
||||
("rotation", "1,000°"),
|
||||
] {
|
||||
let (mut d, _) = dialog_for(json!({}));
|
||||
put(&mut d, key, json!(text));
|
||||
assert!(optional_number(&Values::new(&d), key).is_err(), "{key} {text}");
|
||||
|
||||
@@ -83,28 +83,24 @@ const PASTE_CHOICES: [(&str, &str); 2] = [("preserveNumbers", "Preserve the colo
|
||||
|
||||
/// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color
|
||||
/// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result
|
||||
/// is `{dialog}`. A file read while another one's question is open waits for its own question
|
||||
/// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file
|
||||
/// is `{dialog}`. A file read while another one's question, or another dialog, is open waits for
|
||||
/// its own question until that one closes (`{dialog, queued: true}`). Opened, the views follow and the file
|
||||
/// goes on the recent files ([`crate::io::opened`]). `background`: the file was read off the UI
|
||||
/// thread, and the rest of its read after an answer is done there too.
|
||||
pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option<String>, background: bool) -> Result<Value, String> {
|
||||
ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture(), background, asked: Value::Null })
|
||||
}
|
||||
|
||||
/// [`open_or_ask`] for a file that has its scope already.
|
||||
/// [`open_or_ask`] for a file that has its scope already. While another dialog is open (a paste
|
||||
/// waiting for its Swatch Conflict answer, say), the question waits for it to close too.
|
||||
fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result<Value, String> {
|
||||
let Some(q) = pending.file.ask() else {
|
||||
let PendingOpen { file, path, scope, .. } = pending;
|
||||
return scope.run(|| {
|
||||
let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?;
|
||||
crate::io::opened(app, &r);
|
||||
if let Some(p) = &path {
|
||||
crate::io::note_recent(app, p);
|
||||
}
|
||||
Ok(r)
|
||||
});
|
||||
// The question is gone (or there was none): a file read off the UI thread does the rest of
|
||||
// its read there, as an answered one does.
|
||||
let scope = pending.scope.clone();
|
||||
return open_now(app, pending, scope);
|
||||
};
|
||||
if app.pending_profile_open.is_some() {
|
||||
if app.pending_profile_open.is_some() || app.any_dialog_open() {
|
||||
app.queued_profile_opens.push_back(pending);
|
||||
return Ok(json!({ "dialog": OPEN_KIND, "queued": true }));
|
||||
}
|
||||
@@ -220,24 +216,29 @@ fn finish_open(app: &mut VectorcraftApp, mut pending: PendingOpen, choice: Profi
|
||||
/// off the UI thread does the rest of its read (its linked files and type) there too
|
||||
/// ([`crate::opening::finish_answered`]).
|
||||
fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> Result<Value, String> {
|
||||
let name = pending.file.name();
|
||||
let r = open_now(app, pending, scope);
|
||||
if let Err(e) = &r {
|
||||
crate::io::report_open_error(app, &name, e);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Open `pending` under `scope` without reporting a failure. A file read off the UI thread with part
|
||||
/// of its read left ([`ReadFile::read_left`]) does that part on a job of its own
|
||||
/// ([`crate::opening::finish_answered`]) → `{background: true, status}`.
|
||||
fn open_now(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> Result<Value, String> {
|
||||
let PendingOpen { file, path, background, .. } = pending;
|
||||
let name = file.name();
|
||||
if let Some(p) = path.as_deref().filter(|_| background && crate::opening::available()) {
|
||||
if let Some(p) = path.as_deref().filter(|_| background && file.read_left() && crate::opening::available()) {
|
||||
return Ok(crate::opening::finish_answered(app, p, file, scope));
|
||||
}
|
||||
scope.run(|| match fileio::open_read(&mut app.session, file) {
|
||||
Ok(r) => {
|
||||
crate::io::opened(app, &r);
|
||||
if let Some(p) = &path {
|
||||
crate::io::note_recent(app, p);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
Err(e) => {
|
||||
let e = e.to_string();
|
||||
crate::io::report_open_error(app, &name, &e);
|
||||
Err(e)
|
||||
scope.run(|| {
|
||||
let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?;
|
||||
crate::io::opened(app, &r);
|
||||
if let Some(p) = &path {
|
||||
crate::io::note_recent(app, p);
|
||||
}
|
||||
Ok(r)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -198,6 +198,49 @@ fn files_opened_together_ask_in_turn(app: &mut VectorcraftApp, tagged: &[u8]) {
|
||||
assert!(!is_open::<ProfileMismatchDialog>(app) && app.pending_profile_open.is_none());
|
||||
}
|
||||
|
||||
/// A file opened while another dialog is open (a message here) waits for it to close and then asks
|
||||
/// its question; the other dialog stays. `tagged` asks with the settings in force.
|
||||
fn a_question_waits_for_an_open_dialog(app: &mut VectorcraftApp, tagged: &[u8]) {
|
||||
let docs = app.session.documents().len();
|
||||
crate::dialogs::confirm::tell(app, "Waiting", "");
|
||||
let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap();
|
||||
assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true }));
|
||||
assert!(is_open::<crate::dialogs::confirm::Message>(app), "the message stays");
|
||||
assert!(!is_open::<ProfileMismatchDialog>(app) && app.pending_profile_open.is_none());
|
||||
let id = open_id::<crate::dialogs::confirm::Message>(app);
|
||||
answer_cancel(app, id);
|
||||
assert!(is_open::<ProfileMismatchDialog>(app) && app.pending_profile_open.is_some(), "then it asks");
|
||||
let id = open_id::<ProfileMismatchDialog>(app);
|
||||
answer_ok(app, id);
|
||||
assert_eq!(app.session.documents().len(), docs + 1);
|
||||
}
|
||||
|
||||
/// A file read off the UI thread waits for another file's question, and Color Settings change so
|
||||
/// that it has none any more: once the first question closes, the rest of its read is done off the
|
||||
/// UI thread too, and it opens when that is done. `tagged` asks with the settings in force, which
|
||||
/// Ask When Opening for a mismatch is one of.
|
||||
fn a_background_open_whose_question_is_gone_finishes_off_the_ui_thread(app: &mut VectorcraftApp, tagged: &[u8]) {
|
||||
let docs = app.session.documents().len();
|
||||
assert_eq!(crate::io::open_bytes(app, "first.vectorcraft", tagged, None).unwrap(), json!({ "dialog": OPEN_KIND }));
|
||||
let path = "/tmp/background.vectorcraft".to_string();
|
||||
let file = fileio::read_for_open_asking("background.vectorcraft", tagged, Some(path.clone()), &json!({}), false, false, true).unwrap();
|
||||
assert!(file.read_left());
|
||||
let r = open_or_ask(app, file, Some(path.clone()), true).unwrap();
|
||||
assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true }));
|
||||
app.run("edit.colorSettings", json!({"askMismatchOpen": false})).unwrap();
|
||||
let id = open_id::<ProfileMismatchDialog>(app);
|
||||
crate::opening::tests::with_threads(|| {
|
||||
answer_cancel(app, id);
|
||||
assert!(app.queued_profile_opens.is_empty());
|
||||
assert_eq!(app.opening.pending.len(), 1, "read off the UI thread");
|
||||
assert_eq!(app.session.documents().len(), docs, "not open before its read is done");
|
||||
crate::opening::tests::open_ready(app);
|
||||
});
|
||||
assert_eq!(app.session.documents().len(), docs + 1);
|
||||
assert_eq!(app.ui.recent_files.first(), Some(&path));
|
||||
app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap();
|
||||
}
|
||||
|
||||
/// Color Settings change the open question while it is open: OK asks the question as it is now
|
||||
/// (another working space) instead of opening, and opens by the policy once there is no question
|
||||
/// (the working space is the file's profile). `tagged` (Wide Gamut RGB) asks with the settings in
|
||||
@@ -391,6 +434,8 @@ fn opening_and_pasting_ask_about_profiles() {
|
||||
open_confirmed_under_roots(&mut app, &tagged);
|
||||
links_read_under_the_roots_of_the_open(&mut app);
|
||||
files_opened_together_ask_in_turn(&mut app, &tagged);
|
||||
a_question_waits_for_an_open_dialog(&mut app, &tagged);
|
||||
a_background_open_whose_question_is_gone_finishes_off_the_ui_thread(&mut app, &tagged);
|
||||
|
||||
// Missing Profiles: Ask When Opening, and a profile the list doesn't offer.
|
||||
app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap();
|
||||
|
||||
@@ -5,15 +5,16 @@
|
||||
//! dialogs live on the dialog host; [`pump`] reads their answers.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt, StartupStage, dialog_id};
|
||||
use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt, dialog_id};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_plugins::safe_mode::{self, Item};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// Key of the choice after a launch that stopped. It holds `UiState::stopped_plugin` (the item as
|
||||
/// `{id, file, name, label}`) until answered. Cancel starts in Safe Mode.
|
||||
/// Key of the choice after a launch that stopped. It holds `UiState::stopped_plugin` until
|
||||
/// answered: `items` (`[{id, file, name, label}]`, the plug-ins that were loading, oldest first)
|
||||
/// and `item` (the first of them). Cancel starts in Safe Mode.
|
||||
pub const STOPPED: &str = "pluginStopped";
|
||||
|
||||
/// Key of Help › Safe Mode's dialog. It has a check box `enable-{k}` (Enable on Re-launch) and the
|
||||
@@ -32,17 +33,17 @@ fn enable_key(k: usize) -> String {
|
||||
|
||||
/// Before any plug-in loads (desktop): starts this launch's marker in `marker_dir` (none: no
|
||||
/// marker), and turns Safe Mode on for `--safe-mode` (`flag`), or until the user chooses after a
|
||||
/// launch that stopped while a plug-in was loading → that plug-in, for [`after_start`]. With `flag`
|
||||
/// nothing is asked, and the plug-in stays pending (`plugin.safeMode`'s `pendingItem`): the next
|
||||
/// launch asks about it.
|
||||
/// launch that stopped while plug-ins were loading → those plug-ins, for [`after_start`]. With
|
||||
/// `flag` nothing is asked, and the plug-ins stay pending (`plugin.safeMode`'s `pendingItems`): the
|
||||
/// next launch asks about them.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn begin_launch(marker_dir: Option<&std::path::Path>, flag: bool) -> Option<Item> {
|
||||
let stopped = marker_dir.and_then(safe_mode::begin_launch);
|
||||
pub fn begin_launch(marker_dir: Option<&std::path::Path>, flag: bool) -> Vec<Item> {
|
||||
let stopped = marker_dir.map(safe_mode::begin_launch).unwrap_or_default();
|
||||
if flag {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
return None;
|
||||
return Vec::new();
|
||||
}
|
||||
if stopped.is_some() {
|
||||
if !stopped.is_empty() {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Startup));
|
||||
}
|
||||
stopped
|
||||
@@ -56,20 +57,21 @@ pub fn end_launch() {
|
||||
|
||||
/// Once the app is made: the choice about `stopped` ([`begin_launch`]), or in Safe Mode a status
|
||||
/// line saying so.
|
||||
pub fn after_start(app: &mut VectorcraftApp, stopped: Option<Item>) {
|
||||
match stopped {
|
||||
Some(item) => ask_about_stopped(app, &item),
|
||||
None if safe_mode::active() => app.status(vectorcraft_plugins::Error::SafeMode.to_string()),
|
||||
None => {}
|
||||
pub fn after_start(app: &mut VectorcraftApp, stopped: Vec<Item>) {
|
||||
if !stopped.is_empty() {
|
||||
ask_about_stopped(app, &stopped);
|
||||
} else if safe_mode::active() {
|
||||
app.status(vectorcraft_plugins::Error::SafeMode.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask what to do about `item`, the plug-in the last launch was loading when it stopped. Safe Mode
|
||||
/// is on until the user chooses. The app holds the item; [`pump`] puts the question on the dialog
|
||||
/// host once the host exists and no other dialog holds it, so a dialog that takes the choice's
|
||||
/// place leaves it waiting.
|
||||
pub fn ask_about_stopped(app: &mut VectorcraftApp, item: &Item) {
|
||||
app.ui.stopped_plugin = Some(item.to_json());
|
||||
/// Ask what to do about `items`, the plug-ins the last launch was loading when it stopped. Safe
|
||||
/// Mode is on until the user chooses. The app holds the items; [`pump`] puts the question on the
|
||||
/// dialog host once the host exists and no other dialog holds it, so a dialog that takes the
|
||||
/// choice's place leaves it waiting.
|
||||
pub fn ask_about_stopped(app: &mut VectorcraftApp, items: &[Item]) {
|
||||
let items: Vec<Value> = items.iter().map(Item::to_json).collect();
|
||||
app.ui.stopped_plugin = Some(json!({ "item": items.first(), "items": items }));
|
||||
}
|
||||
|
||||
/// The choice's Cancel, Start in Safe Mode: Safe Mode stays on for this launch, and the plug-in
|
||||
@@ -95,27 +97,56 @@ fn item_of(v: &Value) -> Item {
|
||||
Item { id: s("id"), file: s("file"), name: s("name") }
|
||||
}
|
||||
|
||||
/// The question about the stopped plug-in `item`.
|
||||
fn stopped_prompt(item: &Value) -> StandardPrompt {
|
||||
let name = item_of(item).label();
|
||||
let text = crate::i18n::fmt(
|
||||
tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."),
|
||||
&[("name", &name)],
|
||||
);
|
||||
/// The items the held choice names: its `items`, else its `item`.
|
||||
fn stopped_items(fields: &Value) -> Vec<Item> {
|
||||
match fields.get("items").and_then(Value::as_array).filter(|i| !i.is_empty()) {
|
||||
Some(items) => items.iter().map(item_of).collect(),
|
||||
None => fields.get("item").filter(|i| i.is_object()).map(item_of).into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The question about the stopped plug-ins the held choice `fields` names.
|
||||
fn stopped_prompt(fields: &Value) -> StandardPrompt {
|
||||
let items = stopped_items(fields);
|
||||
let (text, proceed) = if let [item] = items.as_slice() {
|
||||
let text = crate::i18n::fmt(
|
||||
tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."),
|
||||
&[("name", &item.label())],
|
||||
);
|
||||
(text, tl!("Disable and Continue").to_string())
|
||||
} else {
|
||||
let mut text =
|
||||
tl!("The last launch of VectorCraft stopped while these plug-ins were loading. Any one of them, or none, may be what stopped it.")
|
||||
.to_string();
|
||||
text.push('\n');
|
||||
for item in &items {
|
||||
// A name made safe to show: control and reordering characters removed, bounded.
|
||||
text.push('\n');
|
||||
text.push_str(&safe_mode::display_name(&item.label()));
|
||||
}
|
||||
(text, tl!("Disable Listed Plug-ins and Continue").to_string())
|
||||
};
|
||||
StandardPrompt::custom(text)
|
||||
.title(tl!("Safe Mode").to_string())
|
||||
.button(PromptChoice::Proceed, tl!("Disable and Continue").to_string())
|
||||
.button(PromptChoice::Proceed, proceed)
|
||||
.button(PromptChoice::Alternate, tl!("Start Normally").to_string())
|
||||
.button(PromptChoice::Cancel, tl!("Start in Safe Mode").to_string())
|
||||
}
|
||||
|
||||
/// The choice's Disable and Continue (`normal` false) or Start Normally: Safe Mode ends and the
|
||||
/// plug-ins load, without the stopped one for Disable and Continue (kept off for later launches
|
||||
/// plug-ins load, without the stopped ones for Disable and Continue (kept off for later launches
|
||||
/// too).
|
||||
fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) {
|
||||
let item = item_of(&app.ui.stopped_plugin.take().unwrap_or(Value::Null));
|
||||
// When the disabled plug-in can't be saved for the next launch, that launch asks again.
|
||||
let saved = normal || (safe_mode::disable(item) && app.session.store_disabled_plugins());
|
||||
let items = stopped_items(&app.ui.stopped_plugin.take().unwrap_or(Value::Null));
|
||||
// When a disabled plug-in can't be saved for the next launch, that launch asks again. Every
|
||||
// listed plug-in is turned off for this launch, whether or not the one before it was saved.
|
||||
let saved = normal || {
|
||||
let mut all = true;
|
||||
for item in items {
|
||||
all &= safe_mode::disable(item);
|
||||
}
|
||||
all && app.session.store_disabled_plugins()
|
||||
};
|
||||
if saved {
|
||||
safe_mode::forget_previous();
|
||||
} else {
|
||||
@@ -203,14 +234,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
fn pump_stopped(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(item) = app.ui.stopped_plugin.clone() else { return };
|
||||
let Some(fields) = app.ui.stopped_plugin.clone() else { return };
|
||||
// PLAN: assumed `VectorcraftApp::dialogs() -> Option<handle>` whose `with(|host: &mut DialogHost| ..)` runs on the host (wg.S1).
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let answered = dialogs.with(|h| {
|
||||
let answered = h.take::<StandardPrompt>();
|
||||
// An empty host has neither an open dialog nor a queued one: otherwise the choice waits.
|
||||
// An empty host has neither an open dialog nor a queued one: otherwise the choice waits. It opens now rather
|
||||
// than through the startup queue, which the host drains only in its next pass: a frame may have no other.
|
||||
if answered.is_none() && h.is_empty() {
|
||||
h.enqueue(StartupStage::Warning, stopped_prompt(&item));
|
||||
h.open(stopped_prompt(&fields));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
answered
|
||||
|
||||
@@ -251,7 +251,8 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin
|
||||
select(app, next.as_deref().unwrap_or("Default"));
|
||||
}
|
||||
Action::Import => {
|
||||
let request = PickRequest::open("tracingPresets").filter("Tracing presets", TRACE_PRESET_EXTS);
|
||||
let name = file_asks::filter_name(crate::i18n::current(), "Tracing presets");
|
||||
let request = PickRequest::open("tracingPresets").filter(name, TRACE_PRESET_EXTS);
|
||||
// The answer, or its failure, reaches the status bar from the continuation; nothing is pending here.
|
||||
let _ = file_asks::ask(app, request, Owner::Free, picked);
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
//! `outSide2`, `outTotalWidth` and `outLinked`.
|
||||
//!
|
||||
//! OK and Delete on existing points, one or several, are refused when those points changed since
|
||||
//! the dialog opened or another document is active; the dialog stays open and says why.
|
||||
//! the dialog opened (their place, their widths, or which of them pair as a discontinuous point) or
|
||||
//! another document is active; the dialog stays open and says why.
|
||||
|
||||
// PLAN: the app's manifest depends on `craft-ui`, not on the `craft` facade, so the `craft::` paths below need hub-w2's manifest change.
|
||||
use craft::behavior::Mixed;
|
||||
@@ -208,6 +209,14 @@ fn pairs(points: &[(f64, f64, f64)]) -> Vec<Option<usize>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The sets of side widths that edit width point `i`, `[incoming, outgoing]`, with the points
|
||||
/// paired as `pairs` pairs them: an outgoing half is not edited by the incoming set, and an
|
||||
/// incoming half not by the outgoing set.
|
||||
fn sets(pairs: &[Option<usize>], i: usize) -> [bool; 2] {
|
||||
let outgoing = i.checked_sub(1).is_some_and(|a| pairs[a] == Some(i));
|
||||
[!outgoing, pairs[i].is_none()]
|
||||
}
|
||||
|
||||
/// The width points `indices` of `id` names, each discontinuous point's two halves together.
|
||||
fn target(app: &VectorcraftApp, id: u64, indices: &Value) -> Result<Resolved, String> {
|
||||
const NONE: &str = "no such width point";
|
||||
@@ -238,7 +247,7 @@ fn target(app: &VectorcraftApp, id: u64, indices: &Value) -> Result<Resolved, St
|
||||
let half = st.width / 2.0;
|
||||
let entry = |i: usize| {
|
||||
let (t, l, r) = points[i];
|
||||
Entry { index: i, t, left: l * half, right: r * half, sets: [!outgoing(i), pairs[i].is_none()] }
|
||||
Entry { index: i, t, left: l * half, right: r * half, sets: sets(&pairs, i) }
|
||||
};
|
||||
Ok(Resolved::Several(picked.into_iter().map(entry).collect()))
|
||||
}
|
||||
@@ -768,6 +777,12 @@ fn opened_profile(app: &VectorcraftApp, id: u64, open: &[Entry]) -> Result<(Widt
|
||||
return Err(NONE.into());
|
||||
}
|
||||
}
|
||||
// Each point is still a continuous point or the same half of a discontinuous one: a point added
|
||||
// at the place of one would leave it changing only one half.
|
||||
let pairs = pairs(&profile.points);
|
||||
if open.iter().any(|o| o.sets != sets(&pairs, o.index)) {
|
||||
return Err(NONE.into());
|
||||
}
|
||||
Ok((profile, half))
|
||||
}
|
||||
|
||||
|
||||
@@ -904,3 +904,30 @@ fn one_point_refuses_a_change_since_the_dialog_opened() {
|
||||
assert_eq!(app.session.doc().unwrap().doc, paired, "{field}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_points_refuse_a_change_in_which_points_pair() {
|
||||
// A point added at a selected point's place, after it, pairs with it; a third point at a
|
||||
// discontinuous point's place unpairs its halves. The selected points keep their index, place
|
||||
// and widths.
|
||||
let cases = [
|
||||
(
|
||||
three_app as fn() -> (VectorcraftApp, u64),
|
||||
json!([1, 3]),
|
||||
json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [0.75, 0.3, 0.3], [1, 1, 1]]),
|
||||
),
|
||||
(pair_app, json!([0, 1]), json!([[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [0.5, 0.3, 0.3], [1, 1, 1]])),
|
||||
];
|
||||
for (make, indices, points) in cases {
|
||||
for field in ["side2", "delete"] {
|
||||
let (mut app, id) = make();
|
||||
app.run("ui.widthPointEdit", json!({"id": id, "indices": indices})).unwrap();
|
||||
assert!(fields(&app).get("indices").is_some(), "{indices}: the several-point dialog opened");
|
||||
app.run("stroke.widthProfile.set", json!({"ids": [id], "points": points})).unwrap();
|
||||
let changed = app.session.doc().unwrap().doc.clone();
|
||||
assert!(press_field(&mut app, field).is_err(), "{indices} {field}");
|
||||
assert!(is_open(&app), "a refused press keeps the dialog open: {indices} {field}");
|
||||
assert_eq!(app.session.doc().unwrap().doc, changed, "{indices} {field}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,9 +201,21 @@ pub(crate) fn answer_path(app: &mut VectorcraftApp, dialog: DialogId, key: Strin
|
||||
});
|
||||
}
|
||||
|
||||
/// The file types of `list`, `(label, extensions)` as the engine lists them, as a picker offers them.
|
||||
/// The file types of `list`, `(label, extensions)` as the engine lists them, as a picker offers them,
|
||||
/// named in the interface language.
|
||||
pub(crate) fn filters(list: &[(&str, &[&str])]) -> Vec<FileFilter> {
|
||||
list.iter().map(|&(name, extensions)| FileFilter::new(name, extensions)).collect()
|
||||
filters_in(crate::i18n::current(), list)
|
||||
}
|
||||
|
||||
/// [`filters`] with the names in `lang`: a label's `file-filter` row, else its plain row, else the
|
||||
/// English label.
|
||||
pub(crate) fn filters_in(lang: crate::i18n::Lang, list: &[(&str, &[&str])]) -> Vec<FileFilter> {
|
||||
list.iter().map(|&(name, extensions)| FileFilter::new(filter_name(lang, name), extensions)).collect()
|
||||
}
|
||||
|
||||
/// The name a picker shows for the file type labeled `name` in `lang`.
|
||||
pub(crate) fn filter_name(lang: crate::i18n::Lang, name: &str) -> &str {
|
||||
crate::i18n::tr_ctx(lang, "file-filter", name)
|
||||
}
|
||||
|
||||
/// The first file of an Open answer as the params of an open command: `path`, or the bytes with the
|
||||
|
||||
@@ -6676,6 +6676,9 @@ file-filter Flattener presets Предварителни настройки за
|
||||
file-filter PDF presets Предварителни настройки за PDF
|
||||
file-filter PDF-compatible .ai Съвместими с PDF .ai файлове
|
||||
file-filter Print presets Предварителни настройки за печат
|
||||
file-filter Tracing presets Предварителни настройки за трасиране
|
||||
file-filter Action sets Набори от действия
|
||||
file-filter Composite fonts Съставни шрифтове
|
||||
file-filter Preferences Настройки
|
||||
file-filter Export presets Набори за експортиране
|
||||
file-filter SVG Compressed Компресиран SVG
|
||||
@@ -7367,6 +7370,7 @@ axis Y Axis Y ос
|
||||
Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизация поиска инсталирането на тази приставка. За да я инсталирате, изберете Обект › Приставки › Инсталиране на приставка… сами.
|
||||
File SHA-256: {hash} SHA-256 на файла: {hash}
|
||||
Read the objects it is given Четене на обектите, които получава
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Четене на обектите, които получава, както и на настройките, работните области, слоевете и образците на документа
|
||||
Change, add and delete objects in the document Промяна, добавяне и изтриване на обекти в документа
|
||||
Keep data of its own with the document Съхраняване на собствени данни в документа
|
||||
Change how the objects its effect is applied to are drawn Промяна на начина, по който се рисуват обектите, към които е приложен ефектът му
|
||||
@@ -9065,3 +9069,15 @@ file-filter Applications Приложения
|
||||
@msg image {_1} cannot be distorted this way: its corners would not make a convex shape изображението {_1} не може да се изкриви така: ъглите му не биха образували изпъкнала форма
|
||||
@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon изображението {_1} не може да се изкриви така: ъглите му биха пресекли хоризонта на деформацията
|
||||
@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map изображението {_1} не може да се изкриви така: ъглите му биха били твърде близо един до друг за перспективно преобразуване
|
||||
@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` трябва да е повече от 0 и най-много {MAX_DISTANCE} pt
|
||||
@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` трябва да е от 0 до {MAX_DISTANCE} pt
|
||||
@msg `{key}` must be from 0.01 to 1000 pt `{key}` трябва да е от 0,01 до 1000 pt
|
||||
@msg select the banner, or mark every artboard изберете банера или маркирайте всички работни области
|
||||
@msg the banner has no width or height банерът няма ширина или височина
|
||||
@msg the grommet inset is too large for the banner отстъпът на капсите е твърде голям за банера
|
||||
@msg the hem is too deep for the banner подгъвът е твърде дълбок за банера
|
||||
@msg the spacing makes more than {MAX_GROMMETS} grommets разстоянието дава повече от {MAX_GROMMETS} капси
|
||||
@msg there is no banner to mark няма банер за маркиране
|
||||
@msg turn on at least one side включете поне една страна
|
||||
@msg with no hem and no grommets there is nothing to mark без подгъв и без капси няма нищо за маркиране
|
||||
@msg {saving} failed: {e} {saving} неуспешно: {e}
|
||||
|
Can't render this file because it is too large.
|
@@ -6316,6 +6316,9 @@ file-filter Swatch libraries Biblioteke uzoraka boja
|
||||
file-filter Flattener presets Predlošci spljoštavanja
|
||||
file-filter PDF presets PDF predlošci
|
||||
file-filter Print presets Predlošci štampanja
|
||||
file-filter Tracing presets Predlošci praćenja
|
||||
file-filter Action sets Skupovi akcija
|
||||
file-filter Composite fonts Kompozitni fontovi
|
||||
file-filter Preferences Postavke
|
||||
file-filter Export presets Predlošci izvoza
|
||||
file-filter SVG Compressed Komprimirani SVG
|
||||
@@ -6724,6 +6727,7 @@ axis Y Axis Y osa
|
||||
@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}” je drugi modul od dodatka s ID-om {_1} i dobio bi postavke i predmemoriju sačuvane za njega: instalirajte ga s `replace: true` kada korisnik pristane
|
||||
File SHA-256: {hash} SHA-256 datoteke: {hash}
|
||||
Read the objects it is given Čitati objekte koje dobije
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Čitati objekte koje dobije, kao i postavke, radne ploče, slojeve i uzorke boja dokumenta
|
||||
Change, add and delete objects in the document Mijenjati, dodavati i brisati objekte u dokumentu
|
||||
Keep data of its own with the document Čuvati vlastite podatke uz dokument
|
||||
Change how the objects its effect is applied to are drawn Mijenjati kako se crtaju objekti na koje je primijenjen njegov efekt
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -7745,6 +7745,10 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc ha retornat 0 (sense memòria)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc ha retornat un bloc fora de la memòria
|
||||
@msg vc_run returned error code {packed} vc_run ha retornat el codi d’error {packed}
|
||||
@msg did not finish loading within {secs} s no ha acabat de carregar-se en {secs} s
|
||||
@msg no thread was left to load it no ha quedat cap fil per carregar-lo
|
||||
@msg panicked while loading ha fallat inesperadament en carregar-se
|
||||
@msg panicked while loading: {what} ha fallat inesperadament en carregar-se: {what}
|
||||
@msg {_1} is not a file {_1} no és un fitxer
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} té {_2} bytes (límit {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objectes (límit {MAX_OBJECTS})
|
||||
@@ -7904,6 +7908,10 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
@msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades
|
||||
@msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior
|
||||
@msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read`
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Llegir els objectes que rep, i la configuració, els taulers, les capes i les mostres del document
|
||||
@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` ha de llistar seccions diferents: settings, artboards, layers o swatches
|
||||
@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` és per a un filtre, o un efecte dinàmic amb `commands`, amb `api` 3 o posterior i el permís `doc.read`
|
||||
@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes la informació del document que demana el complement és massa gran per passar-la: com a màxim {MAX_CONTEXT_ITEMS} taulers, capes i mostres en {MAX_CONTEXT_BYTES} bytes
|
||||
@msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left})
|
||||
@msg object budget (more than {MAX_OBJECTS} read-only objects) pressupost d’objectes (més de {MAX_OBJECTS} objectes de només lectura)
|
||||
@msg instruction budget pressupost d’instruccions
|
||||
@@ -7951,6 +7959,9 @@ file-filter Flattener presets Preajustos de l’aplanador
|
||||
file-filter PDF presets Preajustos de PDF
|
||||
file-filter PDF-compatible .ai .ai compatible amb PDF
|
||||
file-filter Print presets Preajustos d’impressió
|
||||
file-filter Tracing presets Preajustos de traçat
|
||||
file-filter Action sets Conjunts d’accions
|
||||
file-filter Composite fonts Tipus de lletra compostos
|
||||
file-filter Preferences Preferències
|
||||
file-filter Export presets Preajustos d’exportació
|
||||
file-filter SVG Compressed SVG comprimit
|
||||
@@ -8833,6 +8844,18 @@ breakText Glyphs Glifs
|
||||
Margin Marge
|
||||
Box Caixa
|
||||
Swatch Mostra
|
||||
@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` ha de ser més gran que 0 i com a màxim {MAX_DISTANCE} pt
|
||||
@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` ha d’estar entre 0 i {MAX_DISTANCE} pt
|
||||
@msg `{key}` must be from 0.01 to 1000 pt `{key}` ha d’estar entre 0,01 i 1000 pt
|
||||
@msg select the banner, or mark every artboard seleccioneu la pancarta o marqueu tots els taulers
|
||||
@msg the banner has no width or height la pancarta no té amplada ni alçada
|
||||
@msg the grommet inset is too large for the banner la distància dels ullets a la vora és massa gran per a la pancarta
|
||||
@msg the hem is too deep for the banner la vora és massa profunda per a la pancarta
|
||||
@msg the spacing makes more than {MAX_GROMMETS} grommets l’espaiat genera més de {MAX_GROMMETS} ullets
|
||||
@msg there is no banner to mark no hi ha cap pancarta per marcar
|
||||
@msg turn on at least one side activeu almenys un costat
|
||||
@msg with no hem and no grommets there is nothing to mark sense vora ni ullets no hi ha res per marcar
|
||||
@msg {saving} failed: {e} {saving} ha fallat: {e}
|
||||
Banner Hems and Grommets… Vores i ullets de pancarta…
|
||||
Banner Hems and Grommets Vores i ullets de pancarta
|
||||
Hem Vora
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6787,6 +6787,9 @@ file-filter Swatch libraries Knihovny vzorníků
|
||||
file-filter Flattener presets Přednastavení sloučení průhlednosti
|
||||
file-filter PDF presets Přednastavení PDF
|
||||
file-filter Print presets Přednastavení tisku
|
||||
file-filter Tracing presets Přednastavení vektorizace
|
||||
file-filter Action sets Sady akcí
|
||||
file-filter Composite fonts Složená písma
|
||||
file-filter Preferences Předvolby
|
||||
file-filter Export presets Přednastavení exportu
|
||||
file-filter SVG Compressed Komprimované SVG
|
||||
@@ -7356,6 +7359,10 @@ axis Y Axis osa Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc vrátila 0 (nedostatek paměti)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc vrátila blok mimo paměť
|
||||
@msg vc_run returned error code {packed} vc_run vrátila chybový kód {packed}
|
||||
@msg did not finish loading within {secs} s nedokončil načítání do {secs} s
|
||||
@msg no thread was left to load it nezbylo žádné vlákno, které by ho načetlo
|
||||
@msg panicked while loading při načítání došlo k panice
|
||||
@msg panicked while loading: {what} při načítání došlo k panice: {what}
|
||||
@msg {_1} is not a file {_1} není soubor
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} má {_2} bajtů (limit {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektů (limit {MAX_OBJECTS})
|
||||
@@ -7514,6 +7521,10 @@ axis Y Axis osa Y
|
||||
@msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát
|
||||
@msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší
|
||||
@msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read`
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Číst objekty, které dostane, a nastavení, pracovní plochy, vrstvy a vzorky dokumentu
|
||||
@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musí uvádět různé oddíly: settings, artboards, layers nebo swatches
|
||||
@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` je pro filtr nebo živý efekt s `commands`, s `api` 3 nebo vyšším a s oprávněním `doc.read`
|
||||
@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes informace o dokumentu, které zásuvný modul požaduje, jsou příliš velké na předání: nejvýše {MAX_CONTEXT_ITEMS} pracovních ploch, vrstev a vzorků v {MAX_CONTEXT_BYTES} bajtech
|
||||
@msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left})
|
||||
@msg object budget (more than {MAX_OBJECTS} read-only objects) rozpočet objektů (více než {MAX_OBJECTS} objektů jen pro čtení)
|
||||
@msg instruction budget rozpočet instrukcí
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -574,6 +574,10 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc returnerede 0 (ikke mere hukommelse)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc returnerede en blok uden for hukommelsen
|
||||
@msg vc_run returned error code {packed} vc_run returnerede fejlkoden {packed}
|
||||
@msg did not finish loading within {secs} s blev ikke færdig med at indlæse inden for {secs} s
|
||||
@msg no thread was left to load it der var ingen tråd tilbage til at indlæse den
|
||||
@msg panicked while loading gik ned under indlæsningen
|
||||
@msg panicked while loading: {what} gik ned under indlæsningen: {what}
|
||||
@msg {_1} is not a file {_1} er ikke en fil
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} fylder {_2} byte (grænse {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objekter (grænse {MAX_OBJECTS})
|
||||
@@ -714,6 +718,10 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange
|
||||
@msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere
|
||||
@msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read`
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Læse de objekter, den får, og dokumentets indstillinger, tegneflader, lag og farveprøver
|
||||
@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` skal angive forskellige afsnit: settings, artboards, layers eller swatches
|
||||
@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` er til et filter eller en live-effekt med `commands`, ved `api` 3 eller senere og med tilladelsen `doc.read`
|
||||
@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes de dokumentoplysninger, som plug-in'et beder om, er for store til at blive overdraget: højst {MAX_CONTEXT_ITEMS} tegneflader, lag og farveprøver i {MAX_CONTEXT_BYTES} byte
|
||||
@msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage)
|
||||
@msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (mere end {MAX_OBJECTS} skrivebeskyttede objekter)
|
||||
@msg instruction budget instruktionsbudget
|
||||
@@ -8847,6 +8855,9 @@ file-filter Swatch libraries Farveprøvebiblioteker
|
||||
file-filter Flattener presets Flattener-forudindstillinger
|
||||
file-filter PDF presets PDF-forudindstillinger
|
||||
file-filter Print presets Printforudindstillinger
|
||||
file-filter Tracing presets Vektoriseringsforudindstillinger
|
||||
file-filter Action sets Handlingssæt
|
||||
file-filter Composite fonts Sammensatte skrifttyper
|
||||
file-filter Preferences Præferencer
|
||||
file-filter Export presets Eksportforudindstillinger
|
||||
file-filter SVG Compressed Komprimeret SVG
|
||||
@@ -10838,6 +10849,7 @@ breakText Glyphs Glyffer
|
||||
Box Ramme
|
||||
Swatch Farveprøve
|
||||
Direction Retning
|
||||
@msg {saving} failed: {e} {saving} mislykkedes: {e}
|
||||
Banner Hems and Grommets… Bannersømme og maljer…
|
||||
Banner Hems and Grommets Bannersømme og maljer
|
||||
Hem Søm
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1463,6 +1463,9 @@ file-filter Swatch libraries Farbfeldbibliotheken
|
||||
file-filter Flattener presets Reduzierungsvorgaben
|
||||
file-filter PDF presets PDF-Vorgaben
|
||||
file-filter Print presets Druckvorgaben
|
||||
file-filter Tracing presets Nachzeichnervorgaben
|
||||
file-filter Action sets Aktionssätze
|
||||
file-filter Composite fonts Zusammengesetzte Schriften
|
||||
file-filter Preferences Voreinstellungen
|
||||
file-filter Export presets Exportvorgaben
|
||||
file-filter SVG Compressed SVG komprimiert
|
||||
@@ -6939,6 +6942,10 @@ axis Y Axis Y-Achse
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc hat 0 zurückgegeben (kein Speicher mehr)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc hat einen Block außerhalb des Speichers zurückgegeben
|
||||
@msg vc_run returned error code {packed} vc_run hat den Fehlercode {packed} zurückgegeben
|
||||
@msg did not finish loading within {secs} s wurde nicht innerhalb von {secs} s fertig geladen
|
||||
@msg no thread was left to load it es war kein Thread mehr frei, um es zu laden
|
||||
@msg panicked while loading ist beim Laden abgestürzt
|
||||
@msg panicked while loading: {what} ist beim Laden abgestürzt: {what}
|
||||
@msg {_1} is not a file {_1} ist keine Datei
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} ist {_2} Byte groß (Grenze {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} Objekte (Grenze {MAX_OBJECTS})
|
||||
@@ -7097,6 +7104,10 @@ axis Y Axis Y-Achse
|
||||
@msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf
|
||||
@msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher
|
||||
@msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read`
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Die Objekte lesen, die es erhält, sowie die Einstellungen, Zeichenflächen, Ebenen und Farbfelder des Dokuments
|
||||
@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` muss verschiedene Abschnitte aufführen: settings, artboards, layers oder swatches
|
||||
@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gilt für einen Filter oder einen Live-Effekt mit `commands`, mit `api` 3 oder höher und der Berechtigung `doc.read`
|
||||
@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes die Dokumentinformationen, die das Plug-in anfordert, sind zu groß zum Übergeben: höchstens {MAX_CONTEXT_ITEMS} Zeichenflächen, Ebenen und Farbfelder in {MAX_CONTEXT_BYTES} Byte
|
||||
@msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben)
|
||||
@msg object budget (more than {MAX_OBJECTS} read-only objects) Objektbudget (mehr als {MAX_OBJECTS} schreibgeschützte Objekte)
|
||||
@msg instruction budget Anweisungsbudget
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3219,6 +3219,9 @@ file-filter Flattener presets Προεπιλογές ισοπέδωσης
|
||||
file-filter PDF presets Προεπιλογές PDF
|
||||
file-filter PDF-compatible .ai .ai συμβατό με PDF
|
||||
file-filter Print presets Προεπιλογές εκτύπωσης
|
||||
file-filter Tracing presets Προεπιλογές ανίχνευσης περιγραμμάτων
|
||||
file-filter Action sets Σύνολα ενεργειών
|
||||
file-filter Composite fonts Σύνθετες γραμματοσειρές
|
||||
file-filter Preferences Προτιμήσεις
|
||||
file-filter Export presets Προκαθορισμένα εξαγωγής
|
||||
file-filter SVG Compressed Συμπιεσμένο SVG
|
||||
@@ -7345,6 +7348,10 @@ axis Y Axis Άξονας Y
|
||||
@msg vc_alloc returned 0 (out of memory) η vc_alloc επέστρεψε 0 (η μνήμη εξαντλήθηκε)
|
||||
@msg vc_alloc returned a block outside memory η vc_alloc επέστρεψε ένα μπλοκ εκτός μνήμης
|
||||
@msg vc_run returned error code {packed} η vc_run επέστρεψε τον κωδικό σφάλματος {packed}
|
||||
@msg did not finish loading within {secs} s δεν ολοκλήρωσε τη φόρτωση μέσα σε {secs} s
|
||||
@msg no thread was left to load it δεν έμεινε νήμα για να το φορτώσει
|
||||
@msg panicked while loading κατέρρευσε κατά τη φόρτωση
|
||||
@msg panicked while loading: {what} κατέρρευσε κατά τη φόρτωση: {what}
|
||||
@msg {_1} is not a file το {_1} δεν είναι αρχείο
|
||||
@msg {_1} is {_2} bytes (limit {_3}) το {_1} έχει {_2} byte (όριο {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} αντικείμενα (όριο {MAX_OBJECTS})
|
||||
@@ -7504,6 +7511,10 @@ axis Y Axis Άξονας Y
|
||||
@msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές
|
||||
@msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο
|
||||
@msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read`
|
||||
Read the objects it is given, and the document's settings, artboards, layers and swatches Ανάγνωση των αντικειμένων που του δίνονται, καθώς και των ρυθμίσεων, των πινάκων σχεδίασης, των επιπέδων και των δειγμάτων χρωμάτων του εγγράφου
|
||||
@msg `context` must list distinct sections: settings, artboards, layers or swatches το `context` πρέπει να απαριθμεί διαφορετικές ενότητες: settings, artboards, layers ή swatches
|
||||
@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` το `context` ισχύει για φίλτρο ή ζωντανό εφέ με `commands`, με `api` 3 ή νεότερο και το δικαίωμα `doc.read`
|
||||
@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes οι πληροφορίες εγγράφου που ζητά το πρόσθετο είναι πολύ μεγάλες για να παραδοθούν: το πολύ {MAX_CONTEXT_ITEMS} πίνακες σχεδίασης, επίπεδα και δείγματα χρωμάτων σε {MAX_CONTEXT_BYTES} byte
|
||||
@msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left})
|
||||
@msg object budget (more than {MAX_OBJECTS} read-only objects) προϋπολογισμός αντικειμένων (περισσότερα από {MAX_OBJECTS} αντικείμενα μόνο για ανάγνωση)
|
||||
@msg instruction budget προϋπολογισμός εντολών
|
||||
@@ -8805,6 +8816,18 @@ breakText Glyphs Γλύφοι
|
||||
Margin Περιθώριο
|
||||
Box Πλαίσιο
|
||||
Swatch Δείγμα χρώματος
|
||||
@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt το `spacing` πρέπει να είναι μεγαλύτερο από 0 και το πολύ {MAX_DISTANCE} pt
|
||||
@msg `{key}` must be from 0 to {MAX_DISTANCE} pt το `{key}` πρέπει να είναι από 0 έως {MAX_DISTANCE} pt
|
||||
@msg `{key}` must be from 0.01 to 1000 pt το `{key}` πρέπει να είναι από 0,01 έως 1000 pt
|
||||
@msg select the banner, or mark every artboard επιλέξτε το πανό ή σημειώστε όλους τους πίνακες σχεδίασης
|
||||
@msg the banner has no width or height το πανό δεν έχει πλάτος ή ύψος
|
||||
@msg the grommet inset is too large for the banner η απόσταση των τρουκς από την άκρη είναι πολύ μεγάλη για το πανό
|
||||
@msg the hem is too deep for the banner το στρίφωμα είναι πολύ βαθύ για το πανό
|
||||
@msg the spacing makes more than {MAX_GROMMETS} grommets το διάστημα δημιουργεί περισσότερα από {MAX_GROMMETS} τρουκς
|
||||
@msg there is no banner to mark δεν υπάρχει πανό για σήμανση
|
||||
@msg turn on at least one side ενεργοποιήστε τουλάχιστον μία πλευρά
|
||||
@msg with no hem and no grommets there is nothing to mark χωρίς στρίφωμα και χωρίς τρουκς δεν υπάρχει τίποτα για σήμανση
|
||||
@msg {saving} failed: {e} {saving}: απέτυχε: {e}
|
||||
Banner Hems and Grommets… Στριφώματα και τρουκς πανό…
|
||||
Banner Hems and Grommets Στριφώματα και τρουκς πανό
|
||||
Hem Στρίφωμα
|
||||
|
||||
|
Can't render this file because it is too large.
|