Merge main into fix/swatches-browser-selection-set
@@ -83,11 +83,18 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/cursors/cursor-mark-ring.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-mark-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-mark-star.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-move.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-not-allowed.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-pen-convert.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-pen-curvature.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-pen-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-pen-new.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-reshape-segment.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-resize-h.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-resize-nesw.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-resize-nwse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-resize-v.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/cursors/cursor-type-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
|
||||
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
|
||||
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
|
||||
@@ -248,6 +255,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-new-item.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-new-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-new-sublayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: a layer row with a new-item square nested under it | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-objects-on-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three small squares along a curve | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-para-bullets.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three dots, each before a line | MIT OR Apache-2.0 | |
|
||||
|
||||
@@ -1256,7 +1256,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1298,7 +1298,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1319,7 +1319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1331,7 +1331,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1339,7 +1339,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1364,7 +1364,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1383,7 +1383,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1401,7 +1401,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1410,7 +1410,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1418,7 +1418,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1427,12 +1427,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1452,7 +1452,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
@@ -1468,7 +1468,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1478,7 +1478,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1486,7 +1486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1512,7 +1512,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1528,7 +1528,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1536,7 +1536,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1555,7 +1555,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"craft-dxf",
|
||||
@@ -1565,7 +1565,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1577,7 +1577,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1587,12 +1587,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
@@ -1602,7 +1602,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1617,7 +1617,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1636,7 +1636,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1645,7 +1645,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1668,12 +1668,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1681,7 +1681,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1689,7 +1689,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1702,7 +1702,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -1732,7 +1732,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1759,7 +1759,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1777,7 +1777,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1785,7 +1785,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1796,7 +1796,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1811,7 +1811,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1825,7 +1825,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1843,7 +1843,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1855,7 +1855,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1866,7 +1866,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1876,7 +1876,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1885,7 +1885,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1901,7 +1901,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-texture",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1910,7 +1910,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1921,7 +1921,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1933,7 +1933,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1966,7 +1966,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1975,7 +1975,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1999,7 +1999,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -2010,7 +2010,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -2024,7 +2024,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -2035,7 +2035,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -2048,7 +2048,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2057,7 +2057,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2076,7 +2076,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2093,7 +2093,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2104,7 +2104,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2125,7 +2125,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2137,7 +2137,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2162,7 +2162,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -2170,7 +2170,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2185,7 +2185,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2200,7 +2200,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2210,7 +2210,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2219,7 +2219,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2234,12 +2234,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2253,7 +2253,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2270,7 +2270,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2308,7 +2308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2319,7 +2319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2337,7 +2337,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2358,7 +2358,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2379,7 +2379,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2398,7 +2398,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2430,7 +2430,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2441,7 +2441,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2451,7 +2451,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2462,7 +2462,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2470,7 +2470,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2502,7 +2502,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -3862,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3871,7 +3871,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3889,7 +3889,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3907,12 +3907,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4895,7 +4895,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -5052,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -8792,6 +8792,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.25.1",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
@@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# 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 = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with.
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# 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 = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# 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 = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -200,13 +200,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
|
||||
# It stays at this rev until craft-libs#5222 merges.
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
|
||||
@@ -28,7 +28,7 @@ egui_extras = { 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 = "dbc6b20e78327f702371fcfc7887fc099fbedee8", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -140,7 +140,8 @@ mod platform {
|
||||
let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom));
|
||||
// The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its
|
||||
// whole monitor, which it no longer does once trimmed.
|
||||
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| {
|
||||
let frame = super::frame_limit(hwnd.GetDpiForWindow());
|
||||
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work, frame).or_else(|| {
|
||||
super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()
|
||||
}) else {
|
||||
return;
|
||||
@@ -238,21 +239,29 @@ impl<H> Viewports<H> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about
|
||||
/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being
|
||||
/// dragged or snapped, and is left alone.
|
||||
const FRAME: i32 = 32;
|
||||
/// How far, in physical pixels at 96 DPI (100 %), a parked maximize reaches past a monitor or
|
||||
/// work-area edge at most: the resize border is about 8 px at 100 %. Past that, a maximized
|
||||
/// window's rect is not parked but being dragged or snapped, and is left alone.
|
||||
const FRAME_AT_96_DPI: i32 = 32;
|
||||
|
||||
/// [`FRAME_AT_96_DPI`] for a window at `dpi`, which the resize border grows with; never less than
|
||||
/// at 96 DPI, so an unknown DPI (0) counts as 100 %.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn frame_limit(dpi: u32) -> i32 {
|
||||
let scaled = i64::from(FRAME_AT_96_DPI) * i64::from(dpi) / 96;
|
||||
i32::try_from(scaled).unwrap_or(i32::MAX).max(FRAME_AT_96_DPI)
|
||||
}
|
||||
|
||||
/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize
|
||||
/// border it was parked with, or `None` when it already does or `rect` (`left, top, right,
|
||||
/// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's
|
||||
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The
|
||||
/// border is read from the edges that have no taskbar, and every edge must sit that far outside
|
||||
/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the
|
||||
/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested
|
||||
/// everywhere.
|
||||
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates;
|
||||
/// `frame` is the largest border a parked maximize has ([`frame_limit`]). The border is read from
|
||||
/// the edges that have no taskbar, and every edge must sit that far outside either the monitor
|
||||
/// (where Windows puts a caption-less maximize) or the work area (where the guard puts it), so a
|
||||
/// rect it already moved is left alone. Platform-neutral so it is tested everywhere.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32), frame: i32) -> Option<(i32, i32, i32, i32)> {
|
||||
let (l, t, r, b) = rect;
|
||||
let (ml, mt, mr, mb) = monitor;
|
||||
let (wl, wt, wr, wb) = work;
|
||||
@@ -269,7 +278,7 @@ fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work:
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|n| (0..=FRAME).contains(n))
|
||||
.filter(|n| (0..=frame).contains(n))
|
||||
.min()?;
|
||||
let parked = |monitor: Option<i32>, work: Option<i32>| monitor == Some(border) || work == Some(border);
|
||||
if !parked(ml.checked_sub(l), wl.checked_sub(l))
|
||||
@@ -304,9 +313,11 @@ fn covers(rect: Rect, monitor: Rect) -> bool {
|
||||
}
|
||||
|
||||
/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the
|
||||
/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden
|
||||
/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie
|
||||
/// outside the monitor.
|
||||
/// taskbar's center, or `None` when the taskbar is not this monitor's. A shown taskbar lies wholly
|
||||
/// on its monitor. An auto-hidden taskbar is parked mostly past its edge with a sliver left on the
|
||||
/// monitor, so its center can lie outside the monitor; the part past the edge can lie on a
|
||||
/// neighboring monitor, which a taskbar that is neither wholly on the monitor nor mostly off it
|
||||
/// belongs to.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
|
||||
let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3));
|
||||
@@ -314,6 +325,12 @@ fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
|
||||
if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb {
|
||||
return None;
|
||||
}
|
||||
let inside = tl >= ml && tt >= mt && tr <= mr && tb <= mb;
|
||||
let area = |l: i64, t: i64, r: i64, b: i64| i128::from(r - l) * i128::from(b - t);
|
||||
let on_monitor = area(tl.max(ml), tt.max(mt), tr.min(mr), tb.min(mb));
|
||||
if !inside && on_monitor * 2 >= area(tl, tt, tr, tb) {
|
||||
return None;
|
||||
}
|
||||
// The center and the distances are doubled, so nothing is rounded.
|
||||
let (cx, cy) = (tl + tr, tt + tb);
|
||||
[(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)]
|
||||
@@ -346,7 +363,12 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
use super::{Edge, Viewports, frame_limit, short_of_autohide_taskbars, taskbar_edge};
|
||||
|
||||
/// [`super::clamped_rect`] for a window at 96 DPI (100 %).
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
|
||||
super::clamped_rect(rect, monitor, work, frame_limit(96))
|
||||
}
|
||||
|
||||
fn viewport(name: &str) -> egui::ViewportId {
|
||||
egui::ViewportId::from_hash_of(name)
|
||||
@@ -453,6 +475,22 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frame_limit_grows_with_the_monitor_dpi() {
|
||||
// At 500 % (480 DPI) the resize border is about 40 px, past the limit at 100 %.
|
||||
let (monitor, work) = ((0, 0, 3840, 2160), (0, 0, 3840, 2000));
|
||||
let rect = (-40, -40, 3880, 2200);
|
||||
assert_eq!(clamped_rect(rect, monitor, work), None, "100 %");
|
||||
let Some(clamped) = super::clamped_rect(rect, monitor, work, frame_limit(480)) else {
|
||||
panic!("500 %: the maximized frame is not clamped");
|
||||
};
|
||||
assert_eq!((clamped.0, clamped.1, clamped.2), (rect.0, rect.1, rect.2), "500 %: only the bottom edge moves");
|
||||
assert_eq!(clamped.3 - work.3, monitor.1 - rect.1, "500 %: the bottom border hangs below the work area as the top one above the monitor");
|
||||
assert_eq!(super::clamped_rect((-8, -8, 1928 + 40, 1088), (0, 0, 1920, 1080), (0, 0, 1920, 1046), frame_limit(96)), None, "past the limit");
|
||||
assert_eq!(frame_limit(0), frame_limit(96), "an unknown DPI counts as 100 %");
|
||||
assert!(frame_limit(u32::MAX) > frame_limit(480), "no overflow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_without_a_reserved_taskbar_is_left_alone() {
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
@@ -503,6 +541,12 @@ mod tests {
|
||||
assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left));
|
||||
assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right));
|
||||
assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor");
|
||||
// With monitors stacked, the part of the upper monitor's auto-hidden taskbar parked past its
|
||||
// bottom edge lies on the monitor below, which it does not belong to.
|
||||
let below = (0, 1080, 1920, 2160);
|
||||
assert_eq!(taskbar_edge((0, 1078, 1920, 1126), below), None, "neighbor's auto-hidden taskbar");
|
||||
assert_eq!(taskbar_edge((0, 2158, 1920, 2206), below), Some(Edge::Bottom), "its own auto-hidden taskbar");
|
||||
assert_eq!(taskbar_edge((0, 1080, 1920, 1128), below), Some(Edge::Top), "its own shown top taskbar");
|
||||
assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M11 5h2v14h-2Z"/><path d="M5 11h14v2H5Z"/><path d="M12 1.5L15.5 5.5H8.5Z"/><path d="M12 22.5L8.5 18.5H15.5Z"/><path d="M1.5 12L5.5 8.5V15.5Z"/><path d="M22.5 12L18.5 15.5V8.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 289 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path fill-rule="evenodd" d="M12 4a8 8 0 1 1 0 16a8 8 0 1 1 0-16ZM12 6a6 6 0 1 0 0 12a6 6 0 1 0 0-12Z"/><path d="M6.9 15.7L15.7 6.9L17.1 8.3L8.3 17.1Z"/></svg>
|
||||
|
After Width: | Height: | Size: 255 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M5 11h14v2H5Z"/><path d="M1.5 12L6 8V16Z"/><path d="M22.5 12L18 16V8Z"/></svg>
|
||||
|
After Width: | Height: | Size: 183 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M17.3 5.3L5.3 17.3L6.7 18.7L18.7 6.7Z"/><path d="M21.5 2.5L14.5 3.5L20.5 9.5Z"/><path d="M2.5 21.5L9.5 20.5L3.5 14.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 231 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M6.7 5.3L18.7 17.3L17.3 18.7L5.3 6.7Z"/><path d="M2.5 2.5L9.5 3.5L3.5 9.5Z"/><path d="M21.5 21.5L14.5 20.5L20.5 14.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 231 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M11 5h2v14h-2Z"/><path d="M12 1.5L16 6H8Z"/><path d="M12 22.5L8 18H16Z"/></svg>
|
||||
|
After Width: | Height: | Size: 184 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M5 11.25h14v1.5H5Z"/><path d="M4.25 8.5h1.5v7h-1.5Z"/><path d="M18.25 8.5h1.5v7h-1.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 199 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="butt" stroke-linejoin="miter"><rect x="3" y="3" width="18" height="4.5" stroke-width="1.25" /><path d="M6 7.5V16H10" stroke-width="1.25" /><rect x="10" y="11" width="11" height="10" stroke-width="1.25" /><path d="M15.5 13.5V18.5M13 16H18" stroke-width="1.5" /></svg>
|
||||
|
After Width: | Height: | Size: 419 B |
@@ -62,9 +62,72 @@ pub fn use_own_worker_for(limit: std::time::Duration) {
|
||||
/// The largest DXF rendition kept for the next read of the same drawing (128 MiB).
|
||||
const MAX_KEPT: usize = 128 << 20;
|
||||
|
||||
/// Is `bytes` a DWG drawing (an `AC10nn` version code first)?
|
||||
/// Is `bytes` a DWG drawing (an `AC10nn` or `AD10nn` version code first)?
|
||||
pub fn is_dwg(bytes: &[u8]) -> bool {
|
||||
craft_dwg::is_dwg(bytes)
|
||||
craft_dwg::is_dwg(bytes) || craft_dwg::is_dwg(&ac_code(bytes))
|
||||
}
|
||||
|
||||
/// The first six bytes of `bytes`, with an `AD10` start read as `AC10`.
|
||||
fn ac_code(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut head = bytes.get(..bytes.len().min(7)).unwrap_or(bytes).to_vec();
|
||||
if head.starts_with(b"AD10") {
|
||||
head[1] = b'C';
|
||||
}
|
||||
head
|
||||
}
|
||||
|
||||
/// The version codes of DWG drawings and the name of each version, oldest first
|
||||
/// (<https://en.wikipedia.org/wiki/.dwg#Version_history>).
|
||||
const VERSIONS: [(&str, &str); 21] = [
|
||||
("MC0.0", "R1.0"),
|
||||
("AC1.2", "R1.2"),
|
||||
("AC1.40", "R1.40"),
|
||||
("AC1.50", "R2.05"),
|
||||
("AC2.10", "R2.10"),
|
||||
("AC2.21", "R2.21"),
|
||||
("AC2.22", "R2.22"),
|
||||
("AC1001", "R2.22"),
|
||||
("AC1002", "R2.50"),
|
||||
("AC1003", "R2.60"),
|
||||
("AC1004", "R9"),
|
||||
("AC1006", "R10"),
|
||||
("AC1009", "R11/12"),
|
||||
("AC1012", "R13"),
|
||||
("AC1014", "R14"),
|
||||
("AC1015", "2000"),
|
||||
("AC1018", "2004"),
|
||||
("AC1021", "2007"),
|
||||
("AC1024", "2010"),
|
||||
("AC1027", "2013"),
|
||||
("AC1032", "2018"),
|
||||
];
|
||||
|
||||
/// The version codes the DWG reader reads, each also with `AD` in place of `AC` except `AC1006`.
|
||||
const READS: [&str; 10] = ["AC1006", "AC1009", "AC1012", "AC1014", "AC1015", "AC1018", "AC1021", "AC1024", "AC1027", "AC1032"];
|
||||
|
||||
/// Why `bytes` can't be read when they start with a DWG version code that the DWG reader does
|
||||
/// not read: the message names the version and says to save the drawing as DXF or as a DWG
|
||||
/// version that is read. `None` for any other bytes, a DWG drawing of a version that is read
|
||||
/// included.
|
||||
pub fn unreadable(bytes: &[u8]) -> Option<String> {
|
||||
let head = ac_code(bytes);
|
||||
let numbered = head.starts_with(b"AC10");
|
||||
if !numbered && ![&b"MC0."[..], b"AC1.", b"AC2."].iter().any(|m| head.starts_with(m)) {
|
||||
return None;
|
||||
}
|
||||
if numbered && READS.iter().any(|c| head.starts_with(c.as_bytes())) && !bytes.starts_with(b"AD1006") {
|
||||
return None;
|
||||
}
|
||||
let named = match VERSIONS.iter().find(|(c, _)| head.starts_with(c.as_bytes())) {
|
||||
Some((code, name)) => format!("DWG {name} ({})", if bytes.starts_with(b"AD") { code.replacen("AC", "AD", 1) } else { code.to_string() }),
|
||||
None => {
|
||||
let shown: String = bytes.iter().take(6).take_while(|b| b.is_ascii_graphic()).map(|&b| char::from(b)).collect();
|
||||
format!("DWG version {shown}")
|
||||
}
|
||||
};
|
||||
Some(format!(
|
||||
"this drawing is {named}, a DWG version VectorCraft can't read: save it from the CAD app as a DXF, or as a DWG from R10 to 2018, and open that"
|
||||
))
|
||||
}
|
||||
|
||||
/// A DWG drawing as DXF bytes, and what the conversion left out.
|
||||
@@ -173,6 +236,9 @@ pub fn hold(bytes: &[u8]) -> Result<Held, String> {
|
||||
}
|
||||
|
||||
fn convert(bytes: &[u8]) -> Result<Converted, String> {
|
||||
if let Some(why) = unreadable(bytes) {
|
||||
return Err(why);
|
||||
}
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?;
|
||||
Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() })
|
||||
}
|
||||
@@ -278,4 +344,49 @@ mod tests {
|
||||
let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them");
|
||||
assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as() {
|
||||
let named = [
|
||||
(&b"AC1001\x00\x00\x00\x00"[..], "DWG R2.22 (AC1001)"),
|
||||
(b"AD1006\x00\x00\x00\x00", "DWG R10 (AD1006)"),
|
||||
(b"AD1004\x00\x00\x00\x00", "DWG R9 (AD1004)"),
|
||||
(b"AC1.50\x00\x00\x00\x00", "DWG R2.05 (AC1.50)"),
|
||||
(b"AC1.2\x00\x00\x00\x00", "DWG R1.2 (AC1.2)"),
|
||||
(b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"),
|
||||
(b"AC1033\x00\x00\x00\x00", "DWG version AC1033"),
|
||||
(b"AC1010\x00\x00\x00\x00", "DWG version AC1010"),
|
||||
(b"AC10\x00\x00\x00\x00", "DWG version AC10"),
|
||||
];
|
||||
for (bytes, name) in named {
|
||||
let why = unreadable(bytes).unwrap_or_default();
|
||||
assert!(why.starts_with(&format!("this drawing is {name},")), "{name}: {why}");
|
||||
assert!(why.contains("as a DXF, or as a DWG from R10 to 2018"), "{why}");
|
||||
}
|
||||
for read in [
|
||||
&b"AC1006\x00\x00"[..],
|
||||
b"AC1009\x00\x00",
|
||||
b"AD1009\x00\x00",
|
||||
b"AC1018\x00\x00",
|
||||
b"AC1032\x00\x00",
|
||||
b"AD1015\x00\x00",
|
||||
b"0\nSECTION\n",
|
||||
b"AC",
|
||||
b"",
|
||||
] {
|
||||
assert_eq!(unreadable(read), None, "{:?}", String::from_utf8_lossy(read));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ad_version_code_is_a_dwg_drawing() {
|
||||
assert!(is_dwg(b"AD1018\x00\x00") && is_dwg(b"AC1018\x00\x00"));
|
||||
assert!(!is_dwg(b"AD10\x00\x00\x00") && !is_dwg(b"AD1018") && !is_dwg(b"0\nSECTION\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_the_reader_skips_is_refused_before_converting() {
|
||||
let e = hold(b"AC1004\x00\x00\x00\x00").unwrap_err();
|
||||
assert!(e.starts_with("this drawing is DWG R9 (AC1004),"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
|
||||
//! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art
|
||||
//! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on
|
||||
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid
|
||||
//! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols
|
||||
//! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour),
|
||||
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid and
|
||||
//! gradient hatches, pattern hatches' lines, solids and regions become paths; text and multiline
|
||||
//! text point type; named blocks symbols
|
||||
//! (anonymous ones, such as dimensions, groups of their art); raster images linked images of the
|
||||
//! files they name, clipped by their clip boundaries. Colours (indexed and true colour),
|
||||
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
|
||||
//! them. What can't come in is listed in the warnings.
|
||||
//!
|
||||
@@ -15,6 +17,7 @@
|
||||
//! blocks and layouts.
|
||||
//! - `entity`: entities to items (geometry and properties).
|
||||
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
|
||||
//! - `hatch`: pattern hatches' lines and gradient hatches' fills.
|
||||
//! - `text`: text values to plain text.
|
||||
//! - `acis`: a region's solid-modeler data as its outline.
|
||||
//! - `build`: items to the document.
|
||||
@@ -23,6 +26,7 @@ mod acis;
|
||||
mod build;
|
||||
mod curve;
|
||||
mod entity;
|
||||
mod hatch;
|
||||
mod reader;
|
||||
mod text;
|
||||
|
||||
@@ -108,15 +112,18 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
|
||||
/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read
|
||||
/// left out: where the file is damaged, and what the DWG conversion couldn't read.
|
||||
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
|
||||
if let Some(why) = crate::dwg::unreadable(bytes) {
|
||||
return Err(why);
|
||||
}
|
||||
if crate::dwg::is_dwg(bytes) {
|
||||
let converted = crate::dwg::to_dxf(bytes)?;
|
||||
let (tags, mut notes) = dxf_tags(&converted.dxf)?;
|
||||
notes.extend(converted.notes.iter().cloned());
|
||||
return Ok((tags, notes));
|
||||
}
|
||||
// R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number.
|
||||
if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) {
|
||||
return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into());
|
||||
// A DWG version code with nothing after it.
|
||||
if [&b"AC10"[..], b"AD10"].iter().any(|magic| bytes.starts_with(magic)) {
|
||||
return Err("DWG: the file is cut short".into());
|
||||
}
|
||||
dxf_tags(bytes)
|
||||
}
|
||||
@@ -240,4 +247,6 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_dwg;
|
||||
#[cfg(test)]
|
||||
mod tests_image;
|
||||
#[cfg(test)]
|
||||
mod tests_region;
|
||||
|
||||
@@ -7,13 +7,17 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::BezPath;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject};
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, ImageBlob, ImageObject, LAYER_COLORS, LayerColor, LineCap, LinkInfo, Node, NodeKind,
|
||||
Symbol, TextObject,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect};
|
||||
|
||||
use super::ImportOptions;
|
||||
use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem};
|
||||
use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Shade, Span, TextItem};
|
||||
use super::hatch::{Grad, Second};
|
||||
use super::reader::{Drawing, LayoutDef};
|
||||
use crate::{CAP_HEIGHT, MAX_NEST};
|
||||
|
||||
@@ -22,7 +26,7 @@ const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
/// The stroke weight of lineweight 0 (CAD apps draw it one device pixel wide), in points.
|
||||
const THINNEST: f64 = 0.25;
|
||||
/// The most objects an import makes.
|
||||
const MAX_NODES: usize = 2_000_000;
|
||||
const MAX_NODES: usize = if cfg!(test) { 100_000 } else { 2_000_000 };
|
||||
/// The most block work an import does, whatever it produces: one per insert copy drawn, and one
|
||||
/// per item of the block looked at for it (art on hidden layers too).
|
||||
const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 };
|
||||
@@ -38,6 +42,9 @@ const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
|
||||
const MAX_FAMILY_BYTES: usize = 256;
|
||||
/// How far from the origin art may lie (points): the canvas.
|
||||
pub(crate) const MAX_EXTENT: f64 = 4.0e6;
|
||||
/// How far from a symbol's origin its image clip points may lie (points): as far as an insert at
|
||||
/// the smallest scale it accepts (1e-12) still brings back onto the canvas.
|
||||
const MAX_SYMBOL_EXTENT: f64 = MAX_EXTENT * 1e12;
|
||||
|
||||
const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are left out";
|
||||
const XREFS: &str = "blocks referencing other drawings (external references) are left out";
|
||||
@@ -46,6 +53,27 @@ const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points:
|
||||
const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out";
|
||||
const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid";
|
||||
const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out";
|
||||
const NO_IMAGE_FILE: &str = "images that name no image file are left out";
|
||||
const FAR_CLIPS: &str = "images whose clip boundaries reach out of range are left out";
|
||||
const IMAGE_SIZE: &str = "images with no size in pixels, or more than 1,048,576 pixels a side, are left out";
|
||||
/// The most pixels an image may have a side.
|
||||
const MAX_IMAGE_SIDE: f64 = 1_048_576.0;
|
||||
/// The key of the image data of the images showing the file at a path: the placeholder, until
|
||||
/// the file is read.
|
||||
const IMAGE_KEY: &str = "dxf-image-";
|
||||
|
||||
/// How a path paints.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Look<'g> {
|
||||
/// Stroked at its width or lineweight, in its linetype.
|
||||
Line,
|
||||
/// Filled with its color.
|
||||
Fill,
|
||||
/// Filled with a gradient hatch's gradient.
|
||||
Gradient(&'g Grad),
|
||||
/// Pattern hatch lines: stroked without the linetype; `dots` take round caps.
|
||||
Pattern { dots: bool },
|
||||
}
|
||||
|
||||
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
|
||||
/// and opacity where the art says "by block", and its layer for art on layer 0.
|
||||
@@ -58,6 +86,35 @@ struct Inherit {
|
||||
layer: Option<String>,
|
||||
}
|
||||
|
||||
/// Objects, path elements, dash lengths and text bytes taken from the import's limits.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Cost {
|
||||
nodes: usize,
|
||||
elements: usize,
|
||||
dash_values: usize,
|
||||
text_bytes: usize,
|
||||
}
|
||||
|
||||
impl Cost {
|
||||
fn minus(self, o: Cost) -> Cost {
|
||||
Cost {
|
||||
nodes: self.nodes.saturating_sub(o.nodes),
|
||||
elements: self.elements.saturating_sub(o.elements),
|
||||
dash_values: self.dash_values.saturating_sub(o.dash_values),
|
||||
text_bytes: self.text_bytes.saturating_sub(o.text_bytes),
|
||||
}
|
||||
}
|
||||
|
||||
fn plus(self, o: Cost) -> Cost {
|
||||
Cost {
|
||||
nodes: self.nodes.saturating_add(o.nodes),
|
||||
elements: self.elements.saturating_add(o.elements),
|
||||
dash_values: self.dash_values.saturating_add(o.dash_values),
|
||||
text_bytes: self.text_bytes.saturating_add(o.text_bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Build<'d, 'a> {
|
||||
d: &'d Drawing<'a>,
|
||||
o: &'d ImportOptions,
|
||||
@@ -74,6 +131,21 @@ pub(crate) struct Build<'d, 'a> {
|
||||
next_suffix: HashMap<String, usize>,
|
||||
/// Blocks being drawn, outermost first.
|
||||
stack: Vec<String>,
|
||||
/// How many symbols' art is being drawn: above 0, art is in a symbol's own space.
|
||||
in_symbol: u32,
|
||||
/// The box of the image clip points in the symbol being drawn, in its own space, and of each
|
||||
/// symbol made (none: its art has no clips).
|
||||
clip_reach: Option<Rect>,
|
||||
symbol_reach: HashMap<String, Rect>,
|
||||
/// What each symbol's own art took from the limits (not the symbols made while drawing it),
|
||||
/// how many instances place each symbol, and what the symbols made inside the one being
|
||||
/// drawn took.
|
||||
symbol_cost: HashMap<String, Cost>,
|
||||
uses: HashMap<String, usize>,
|
||||
nested: Cost,
|
||||
/// Each symbol's place in the document's symbols, and the symbols whose art was taken out.
|
||||
symbol_slot: HashMap<String, usize>,
|
||||
empty: HashSet<String>,
|
||||
/// Document space per drawing unit, and its symbols' (no translation).
|
||||
map: Affine,
|
||||
symbol_map: Affine,
|
||||
@@ -137,6 +209,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
symbol_names: HashSet::new(),
|
||||
next_suffix: HashMap::new(),
|
||||
stack: vec![],
|
||||
in_symbol: 0,
|
||||
clip_reach: None,
|
||||
symbol_reach: HashMap::new(),
|
||||
symbol_cost: HashMap::new(),
|
||||
uses: HashMap::new(),
|
||||
symbol_slot: HashMap::new(),
|
||||
empty: HashSet::new(),
|
||||
nested: Cost::default(),
|
||||
map: Affine::IDENTITY,
|
||||
symbol_map: Affine::IDENTITY,
|
||||
lw_scale: 1.0,
|
||||
@@ -169,6 +249,72 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the import has taken from its limits so far.
|
||||
fn cost(&self) -> Cost {
|
||||
Cost { nodes: self.nodes, elements: self.elements, dash_values: self.dash_values, text_bytes: self.text_bytes }
|
||||
}
|
||||
|
||||
fn set_cost(&mut self, c: Cost) {
|
||||
self.nodes = c.nodes;
|
||||
self.elements = c.elements;
|
||||
self.dash_values = c.dash_values;
|
||||
self.text_bytes = c.text_bytes;
|
||||
}
|
||||
|
||||
/// Take symbol `name`'s art out when no instance places it, giving back its share of the limits
|
||||
/// and its art's instances of other symbols (and in turn those that no instance places any
|
||||
/// more); the art, when it was taken. The symbol stays empty until [`Self::restore`] puts the
|
||||
/// art back or [`Self::symbol`] draws it again, and is dropped at the end if still empty.
|
||||
fn take_unused(&mut self, name: &str) -> Option<Arc<Node>> {
|
||||
let first = self.take_art(name)?;
|
||||
// A worklist, not recursion: chains of symbols can be long.
|
||||
let mut todo = placed_symbols(&first);
|
||||
while let Some(s) = todo.pop() {
|
||||
if let Some(n) = self.uses.get_mut(&s) {
|
||||
*n = n.saturating_sub(1);
|
||||
}
|
||||
if let Some(art) = self.take_art(&s) {
|
||||
todo.extend(placed_symbols(&art));
|
||||
}
|
||||
}
|
||||
Some(first)
|
||||
}
|
||||
|
||||
/// Symbol `name`'s art, taken out with its share of the limits when no instance places it.
|
||||
fn take_art(&mut self, name: &str) -> Option<Arc<Node>> {
|
||||
if self.uses.get(name).is_some_and(|n| *n > 0) || self.empty.contains(name) {
|
||||
return None;
|
||||
}
|
||||
let i = *self.symbol_slot.get(name)?;
|
||||
let id = self.doc.alloc_id();
|
||||
let art = std::mem::replace(&mut self.doc.symbols.get_mut(i)?.art, Arc::new(Node::group(id, vec![])));
|
||||
self.set_cost(self.cost().minus(self.symbol_cost.get(name).copied().unwrap_or_default()));
|
||||
self.empty.insert(name.to_string());
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// Put `art`, taken from symbol `name` by [`Self::take_unused`], back, charging its share of
|
||||
/// the limits again; false (nothing changed) when that share no longer fits.
|
||||
fn restore(&mut self, name: &str, art: Arc<Node>) -> bool {
|
||||
let t = self.cost().plus(self.symbol_cost.get(name).copied().unwrap_or_default());
|
||||
let inner = placed_symbols(&art);
|
||||
// Its instances of symbols that are empty now need those drawn again.
|
||||
let fits = t.nodes < MAX_NODES && t.elements <= MAX_ELEMENTS && t.dash_values <= MAX_DASH_VALUES && t.text_bytes <= MAX_TEXT_BYTES;
|
||||
if !fits || inner.iter().any(|s| self.empty.contains(s)) {
|
||||
return false;
|
||||
}
|
||||
let Some(slot) = self.symbol_slot.get(name).and_then(|i| self.doc.symbols.get_mut(*i)) else {
|
||||
return false;
|
||||
};
|
||||
slot.art = art;
|
||||
self.set_cost(t);
|
||||
self.empty.remove(name);
|
||||
for s in inner {
|
||||
*self.uses.entry(s).or_default() += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own
|
||||
/// unit and at the scale asked for (fitting computes its own).
|
||||
pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec<String>), String> {
|
||||
@@ -183,6 +329,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if !layers.is_empty() {
|
||||
doc.layers = layers;
|
||||
}
|
||||
drop_unplaced_symbols(&mut doc);
|
||||
if let Some(a) = doc.artboards.first_mut() {
|
||||
a.rect = Rect::from_origin_size(Point::ZERO, size);
|
||||
}
|
||||
@@ -291,7 +438,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
/// An item's bounds in world coordinates (type: an estimate from its height and length).
|
||||
fn item_bounds(&mut self, it: &Item, depth: u32) -> Option<Rect> {
|
||||
match &it.geom {
|
||||
Geom::Path { bp, .. } => super::curve::bounds(bp),
|
||||
Geom::Path { bp, .. } | Geom::Shaded { bp, .. } => super::curve::bounds(bp),
|
||||
Geom::Text(t) => {
|
||||
let lines = t.text.lines().count().max(1) as f64;
|
||||
let longest = t.text.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64;
|
||||
@@ -314,6 +461,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let attribs: Vec<Option<Rect>> = ins.attribs.iter().map(|a| self.item_bounds(a, depth)).collect();
|
||||
cells.map(Some).chain(attribs).fold(None, vectorcraft_geom::union_opt)
|
||||
}
|
||||
Geom::Image(im) => {
|
||||
self.image_file(im)?;
|
||||
let (w, h) = self.image_size(im)?;
|
||||
let place = im.placement(h);
|
||||
let whole = place.transform_rect_bbox(Rect::new(0.0, 0.0, w, h));
|
||||
let clip = im.clip.as_ref().and_then(|c| c.iter().map(|p| place * *p).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b)));
|
||||
Some(clip.map_or(whole, |c| c.intersect(whole)))
|
||||
}
|
||||
}
|
||||
.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()))
|
||||
}
|
||||
@@ -331,8 +486,17 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
for it in items.iter() {
|
||||
let p = &it.props;
|
||||
let on_zero = p.layer == "0";
|
||||
s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock;
|
||||
s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER");
|
||||
// Fills draw no stroke, and pattern lines carry their own dashes.
|
||||
let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. });
|
||||
let stroked = !filled;
|
||||
let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. });
|
||||
s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock;
|
||||
s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK");
|
||||
s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER"));
|
||||
if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom {
|
||||
let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer);
|
||||
s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c));
|
||||
}
|
||||
if let Geom::Insert(ins) = &it.geom {
|
||||
s |= !ins.attribs.is_empty() || self.is_sensitive(&ins.block, depth + 1);
|
||||
}
|
||||
@@ -391,6 +555,23 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient `g` as paint, placed by `map`; its colors resolved as the hatch's own would be.
|
||||
fn gradient(&self, g: &Grad, p: &Props, map: Affine, inh: &Inherit) -> Paint {
|
||||
let rgb = |c: Col| self.rgb(&Props { color: c, ..p.clone() }, inh);
|
||||
let first = rgb(g.first);
|
||||
let second = match g.second {
|
||||
Second::Col(c) => rgb(c),
|
||||
Second::Tint(t) => Grad::tinted(first, t),
|
||||
};
|
||||
let stops = g.stops.iter().map(|(at, two)| GradientStop::new(*at, rgb_color(if *two { second } else { first }))).collect();
|
||||
let mut geom = g.geom;
|
||||
geom.transform(map, g.kind);
|
||||
let mut paint = GradientPaint::new(Gradient::new(g.kind, stops));
|
||||
paint.angle = geom.angle_deg();
|
||||
paint.geom = Some(geom);
|
||||
Paint::Gradient(Box::new(paint))
|
||||
}
|
||||
|
||||
/// What a block placed by an insert with `p` inherits.
|
||||
fn inherit(&self, p: &Props, inh: &Inherit) -> Inherit {
|
||||
Inherit {
|
||||
@@ -479,16 +660,75 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
return None;
|
||||
}
|
||||
let mut node = match &it.geom {
|
||||
Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?,
|
||||
Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?,
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?,
|
||||
Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?,
|
||||
Geom::Text(t) => self.text(t, &it.props, map, inh)?,
|
||||
Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth),
|
||||
Geom::Image(im) => self.image(im, map)?,
|
||||
};
|
||||
node.opacity = self.opacity(&it.props, inh);
|
||||
self.nodes += 1;
|
||||
Some(node)
|
||||
}
|
||||
|
||||
fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
/// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no
|
||||
/// length go on a path of their own with round caps, grouped with the dashes, which keep
|
||||
/// butt caps and their lengths.
|
||||
fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
if !dots {
|
||||
return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
}
|
||||
let (mut dashes, mut points) = (BezPath::new(), BezPath::new());
|
||||
let (mut dash_count, mut dot_count) = (0usize, 0usize);
|
||||
let mut from = None;
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(a) => from = Some(a),
|
||||
PathEl::LineTo(b) => {
|
||||
if let Some(a) = from {
|
||||
let (out, count) = if a == b { (&mut points, &mut dot_count) } else { (&mut dashes, &mut dash_count) };
|
||||
out.move_to(a);
|
||||
out.line_to(b);
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if dashes.elements().is_empty() {
|
||||
return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh);
|
||||
}
|
||||
if points.elements().is_empty() {
|
||||
return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
}
|
||||
// Every object the split makes: the group (`item` counts it), the two paths, and each
|
||||
// piece of a path with more than one (`path` counts those).
|
||||
let loops = |count: usize| if count > 1 { count } else { 0 };
|
||||
if loops(dash_count).saturating_add(loops(dot_count)).saturating_add(3) > MAX_NODES.saturating_sub(self.nodes) {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
if dashes.elements().len().saturating_add(points.elements().len()) > MAX_ELEMENTS.saturating_sub(self.elements) {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
return None;
|
||||
}
|
||||
// A split that loses either path is left out whole, and charges nothing.
|
||||
let (nodes, elements) = (self.nodes, self.elements);
|
||||
let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
let dots = lines.as_ref().and_then(|_| self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh));
|
||||
let (Some(lines), Some(dots)) = (lines, dots) else {
|
||||
(self.nodes, self.elements) = (nodes, elements);
|
||||
return None;
|
||||
};
|
||||
self.nodes += 2;
|
||||
Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)]))
|
||||
}
|
||||
|
||||
/// A path painted as `look` says; `width`: a line's width in drawing units (0: the
|
||||
/// lineweight).
|
||||
fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
let fill = matches!(look, Look::Fill | Look::Gradient(_));
|
||||
let n = bp.elements().len();
|
||||
if self.elements.saturating_add(n) > MAX_ELEMENTS {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
@@ -498,7 +738,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let mut bp = bp.clone();
|
||||
bp.apply_affine(map);
|
||||
super::curve::bounds(&bp)?;
|
||||
let paint = Paint::solid(rgb_color(self.rgb(p, inh)));
|
||||
let paint = match look {
|
||||
Look::Gradient(g) => self.gradient(g, p, map, inh),
|
||||
_ => Paint::solid(rgb_color(self.rgb(p, inh))),
|
||||
};
|
||||
let pattern = match look {
|
||||
Look::Pattern { dots } => Some(dots),
|
||||
_ => None,
|
||||
};
|
||||
let scale = map.determinant().abs().sqrt();
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
// A compound path's loops each keep a copy of its appearance, beside its own.
|
||||
@@ -515,7 +762,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
f64::from(lw) / 100.0 * PT_PER_MM * self.lw_scale
|
||||
};
|
||||
let mut ap = Appearance::basic(Paint::None, paint, w);
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
// Pattern lines carry their own dashes; dots of no length show with round caps.
|
||||
if let Some(dots) = pattern {
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& dots
|
||||
{
|
||||
s.cap = LineCap::Round;
|
||||
}
|
||||
} else if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
|
||||
{
|
||||
match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) {
|
||||
@@ -590,6 +844,92 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj))))
|
||||
}
|
||||
|
||||
/// The non-empty, trimmed file path that image `im`'s IMAGEDEF names.
|
||||
fn image_file(&self, im: &ImageItem) -> Option<String> {
|
||||
im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// The size in pixels of image `im`: its own, else its file's as its IMAGEDEF gives it.
|
||||
fn image_size(&self, im: &ImageItem) -> Option<(f64, f64)> {
|
||||
let def = im.def.and_then(|h| self.d.images.get(&h)).map_or([0.0; 2], |f| f.size);
|
||||
let size = if im.size.iter().all(|v| *v >= 1.0) { im.size } else { def };
|
||||
let [w, h] = size.map(f64::round);
|
||||
[w, h].iter().all(|v| (1.0..=MAX_IMAGE_SIDE).contains(v)).then_some((w, h))
|
||||
}
|
||||
|
||||
/// A raster image, linked to the file its IMAGEDEF names (the path as the drawing stores it,
|
||||
/// found from the drawing's folder when the document opens): until the file is read it shows
|
||||
/// a placeholder over its pixels. A clip boundary makes it a clip group.
|
||||
fn image(&mut self, im: &ImageItem, map: Affine) -> Option<Node> {
|
||||
let Some(path) = self.image_file(im) else {
|
||||
self.warn(NO_IMAGE_FILE);
|
||||
return None;
|
||||
};
|
||||
let Some((w, h)) = self.image_size(im) else {
|
||||
self.warn(IMAGE_SIZE);
|
||||
return None;
|
||||
};
|
||||
let xf = map * im.placement(h);
|
||||
if !(xf.as_coeffs().iter().all(|v| v.is_finite()) && xf.determinant() != 0.0) {
|
||||
return None;
|
||||
}
|
||||
// The clip boundary, unless it shows the whole image. Its path and the image are objects of
|
||||
// their own (`item` counts the group), and its points and the close are path elements: both
|
||||
// are checked against the limits before the points are read.
|
||||
let clip = im.clip.as_ref().filter(|c| !covers(c, w, h));
|
||||
let elements = clip.map_or(0, |c| c.len().saturating_add(1));
|
||||
if clip.is_some() && self.nodes.saturating_add(2) >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
if self.elements.saturating_add(elements) > MAX_ELEMENTS {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
return None;
|
||||
}
|
||||
// In document space, or in a symbol's own space, where each instance places it.
|
||||
let clip: Option<Vec<Point>> = clip.map(|c| c.iter().map(|p| xf * *p).collect());
|
||||
let local = self.in_symbol > 0;
|
||||
let limit = if local { MAX_SYMBOL_EXTENT } else { MAX_EXTENT };
|
||||
let fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= limit && p.y.abs() <= limit;
|
||||
if clip.as_ref().is_some_and(|c| !c.iter().all(fits)) {
|
||||
self.warn(FAR_CLIPS);
|
||||
return None;
|
||||
}
|
||||
// Each image keeps its own copy of the path.
|
||||
if !self.charge_text(path.len()) {
|
||||
return None;
|
||||
}
|
||||
let key = format!("{IMAGE_KEY}{}", vectorcraft_doc::links::hash_bytes(path.as_bytes()));
|
||||
if !self.doc.images.contains_key(&key) {
|
||||
let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder()?);
|
||||
let blob = ImageBlob {
|
||||
mime: vectorcraft_doc::links::PROXY_MIME.into(),
|
||||
bytes: bytes.clone(),
|
||||
proxy: Some(bytes),
|
||||
file_font: Default::default(),
|
||||
};
|
||||
self.doc.images.insert(key.clone(), blob);
|
||||
}
|
||||
let (w_px, h_px) = (w as u32, h as u32);
|
||||
let image = ImageObject { key, width: w_px, height: h_px, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None };
|
||||
let image = Node::new(self.doc.alloc_id(), NodeKind::Image(Box::new(image)));
|
||||
let Some(clip) = clip else { return Some(image) };
|
||||
// A symbol's clips are checked where each of its instances places them.
|
||||
if local && let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) {
|
||||
self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b)));
|
||||
}
|
||||
self.nodes += 2;
|
||||
self.elements += elements;
|
||||
let mut bp = BezPath::new();
|
||||
for (i, p) in clip.iter().enumerate() {
|
||||
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
|
||||
}
|
||||
bp.close_path();
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
let clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false });
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true }))
|
||||
}
|
||||
|
||||
/// An insert: a symbol instance per copy (anonymous blocks: a group of their art), grouped
|
||||
/// with its attributes.
|
||||
fn insert(&mut self, ins: &InsertItem, p: &Props, map: Affine, inh: &Inherit, depth: u32) -> Option<Node> {
|
||||
@@ -597,11 +937,53 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let base = self.d.blocks.get(&ins.block).map_or(Point::ZERO, |b| b.base);
|
||||
let unbase = Affine::translate(-base.to_vec2());
|
||||
let anonymous = ins.block.starts_with('*');
|
||||
let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth) };
|
||||
// An empty symbol is drawn again only for a cell that places an instance of it.
|
||||
let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth, false) };
|
||||
// The symbol's art when this insert took it out.
|
||||
let mut taken = None;
|
||||
let mut parts = vec![];
|
||||
for cell in &ins.cells {
|
||||
let node = match &symbol {
|
||||
Some(name) => {
|
||||
let xf = map * *cell * self.symbol_map.inverse();
|
||||
// Its image clips where this instance places them: inside another symbol, their
|
||||
// box joins that symbol's; else, when it may leave the canvas, this placement
|
||||
// draws the block's art, which checks each clip where it lands.
|
||||
let reach_of = |b: &Self| b.symbol_reach.get(name).map(|r| placed_reach(xf, *r));
|
||||
let leaves =
|
||||
|r: Option<Rect>| r.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT));
|
||||
let mut reach = reach_of(self);
|
||||
// An empty symbol is drawn again (or its taken art put back) unless this placement
|
||||
// draws the art anyway; the art drawn again may reach further.
|
||||
if self.empty.contains(name) && (self.in_symbol > 0 || !leaves(reach)) {
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
}
|
||||
let back = taken.take().is_some_and(|art| self.restore(name, art));
|
||||
if !back && self.symbol(&ins.block, &child, depth, true).is_none() {
|
||||
continue;
|
||||
}
|
||||
reach = reach_of(self);
|
||||
}
|
||||
// Joins the enclosing symbol's box once the instance is kept.
|
||||
let inside = reach.filter(|_| self.in_symbol > 0);
|
||||
if inside.is_none() && leaves(reach) {
|
||||
// This placement draws the art instead of the symbol. The art of a symbol
|
||||
// no instance places yet is taken out, so that it isn't kept and charged
|
||||
// as well; an instance in a later cell puts it back.
|
||||
if taken.is_none() {
|
||||
taken = self.take_unused(name);
|
||||
}
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
}
|
||||
parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth));
|
||||
continue;
|
||||
}
|
||||
// Checked here, after the art drawn in its place: that art gets back the
|
||||
// share of an unused symbol.
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
@@ -609,7 +991,10 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if !self.charge_text(name.len()) {
|
||||
break;
|
||||
}
|
||||
let xf = map * *cell * self.symbol_map.inverse();
|
||||
if let Some(b) = inside {
|
||||
self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b)));
|
||||
}
|
||||
*self.uses.entry(name.clone()).or_default() += 1;
|
||||
self.nodes += 1;
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf }))
|
||||
}
|
||||
@@ -664,30 +1049,124 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol for block `name` placed with `inh` (made once per look).
|
||||
fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32) -> Option<String> {
|
||||
/// The symbol for block `name` placed with `inh` (made once per look). One whose art was
|
||||
/// taken out is drawn again when `draw` is set, and else returned empty.
|
||||
fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32, draw: bool) -> Option<String> {
|
||||
let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() };
|
||||
let key = (name.to_string(), inh);
|
||||
if let Some(s) = self.symbols.get(&key) {
|
||||
return s.clone();
|
||||
}
|
||||
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
|
||||
let map = self.symbol_map * Affine::translate(-base.to_vec2());
|
||||
let art = self.art(name, map, &key.1, depth);
|
||||
let made = art.and_then(|art| {
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
|
||||
// The symbol keeps its name: text, as its instances' copies of it are.
|
||||
if !self.charge_text(label.len()) {
|
||||
return None;
|
||||
let s = s.clone()?;
|
||||
if !draw || !self.empty.contains(&s) {
|
||||
return Some(s);
|
||||
}
|
||||
let (art, reach, cost) = self.symbol_art(name, &key.1, depth);
|
||||
let slot = self.symbol_slot.get(&s).and_then(|i| self.doc.symbols.get_mut(*i));
|
||||
return match (art, slot) {
|
||||
(Some(art), Some(slot)) => {
|
||||
slot.art = Arc::new(art);
|
||||
self.symbol_cost.insert(s.clone(), cost);
|
||||
match reach {
|
||||
Some(b) => self.symbol_reach.insert(s.clone(), b),
|
||||
None => self.symbol_reach.remove(&s),
|
||||
};
|
||||
self.empty.remove(&s);
|
||||
Some(s)
|
||||
}
|
||||
// Nothing of it fits now: what it took goes back, and it stays empty.
|
||||
_ => {
|
||||
self.set_cost(self.cost().minus(cost));
|
||||
self.nested = self.nested.minus(cost);
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
let (art, reach, cost) = self.symbol_art(name, &key.1, depth);
|
||||
let made = art.map(|art| {
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
|
||||
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
|
||||
self.symbol_names.insert(symbol.clone());
|
||||
if let Some(b) = reach {
|
||||
self.symbol_reach.insert(symbol.clone(), b);
|
||||
}
|
||||
self.symbol_slot.insert(symbol.clone(), self.doc.symbols.len());
|
||||
self.symbol_cost.insert(symbol.clone(), cost);
|
||||
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
|
||||
Some(symbol)
|
||||
symbol
|
||||
});
|
||||
self.symbols.insert(key, made.clone());
|
||||
made
|
||||
}
|
||||
|
||||
/// The art of the symbol for block `name` placed with `inh`, the box of its image clips, and
|
||||
/// what it took from the limits itself (not the symbols made while drawing it, which other
|
||||
/// instances may use).
|
||||
fn symbol_art(&mut self, name: &str, inh: &Inherit, depth: u32) -> (Option<Node>, Option<Rect>, Cost) {
|
||||
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
|
||||
let map = self.symbol_map * Affine::translate(-base.to_vec2());
|
||||
let outer = self.clip_reach.take();
|
||||
let before = self.cost();
|
||||
let outer_nested = std::mem::take(&mut self.nested);
|
||||
self.in_symbol += 1;
|
||||
let art = self.art(name, map, inh, depth);
|
||||
self.in_symbol -= 1;
|
||||
let reach = std::mem::replace(&mut self.clip_reach, outer);
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()).len();
|
||||
// The symbol keeps its name: text, as its instances' copies of it are.
|
||||
let art = art.filter(|_| self.charge_text(label));
|
||||
let total = self.cost().minus(before);
|
||||
let own = total.minus(self.nested);
|
||||
self.nested = outer_nested.plus(total);
|
||||
(art, reach, own)
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of `r` placed by `xf`. A box that is not finite, or whose placed corners are not (an
|
||||
/// overflow, which a union or a bounding box would drop as NaN), is the whole plane, so every
|
||||
/// placement of it is out of range.
|
||||
pub(crate) fn placed_reach(xf: Affine, r: Rect) -> Rect {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|p| xf * p);
|
||||
match corners.iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
|
||||
true => corners.iter().fold(Rect::from_points(corners[0], corners[0]), |b, p| b.union_pt(*p)),
|
||||
false => Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY),
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol of each instance in `art`, once per instance.
|
||||
fn placed_symbols(art: &Node) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n: &Node| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
out.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Every symbol of `doc` that no instance on its layers places, directly or through other
|
||||
/// symbols, removed.
|
||||
fn drop_unplaced_symbols(doc: &mut Document) {
|
||||
let index: HashMap<&str, usize> = doc.symbols.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect();
|
||||
let mut placed = vec![false; doc.symbols.len()];
|
||||
let mut todo: Vec<usize> = vec![];
|
||||
// Each symbol is queued once, however many instances place it.
|
||||
let note = |n: &Node, placed: &mut Vec<bool>, todo: &mut Vec<usize>| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& let Some(&i) = index.get(symbol.as_str())
|
||||
&& let Some(seen) = placed.get_mut(i)
|
||||
&& !*seen
|
||||
{
|
||||
*seen = true;
|
||||
todo.push(i);
|
||||
}
|
||||
};
|
||||
doc.walk(|n| note(n, &mut placed, &mut todo));
|
||||
while let Some(i) = todo.pop() {
|
||||
if let Some(s) = doc.symbols.get(i) {
|
||||
s.art.walk(&mut |n: &Node| note(n, &mut placed, &mut todo));
|
||||
}
|
||||
}
|
||||
let mut keep = placed.into_iter();
|
||||
doc.symbols.retain(|_| keep.next().unwrap_or(false));
|
||||
}
|
||||
|
||||
/// Fit text stretched or squeezed across, aligned text scaled as a whole, to run its span
|
||||
@@ -704,6 +1183,22 @@ fn fill_span(obj: &mut TextObject, span: Span, s: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does clip boundary `clip` (pixel space) show the whole `w` × `h` image: is it a rectangle
|
||||
/// square to the image that holds it?
|
||||
fn covers(clip: &[Point], w: f64, h: f64) -> bool {
|
||||
if clip.len() != 4 || clip.iter().enumerate().any(|(i, p)| clip[..i].contains(p)) {
|
||||
return false;
|
||||
}
|
||||
let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { return false };
|
||||
let corner = |p: &Point| (p.x == b.x0 || p.x == b.x1) && (p.y == b.y0 || p.y == b.y1);
|
||||
// Each point a distinct corner, and each edge along one side: the four corners in order around.
|
||||
let side = |i: usize| {
|
||||
let (p, q) = (clip[i], clip[(i + 1) % clip.len()]);
|
||||
(p.x == q.x) != (p.y == q.y)
|
||||
};
|
||||
clip.len() == 4 && clip.iter().all(corner) && (0..4).all(side) && b.x0 <= 0.0 && b.y0 <= 0.0 && b.x1 >= w && b.y1 >= h
|
||||
}
|
||||
|
||||
fn rgb_color([r, g, b]: [u8; 3]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
@@ -735,3 +1230,59 @@ fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EMPTY: &[u8] = b" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nEOF\n";
|
||||
|
||||
fn props() -> Props {
|
||||
Props {
|
||||
layer: "0".into(),
|
||||
color: Col::Rgb([0, 0, 0]),
|
||||
lineweight: Lw::Default,
|
||||
linetype: "CONTINUOUS".into(),
|
||||
ltscale: 1.0,
|
||||
alpha: Alpha::Opacity(1.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two dashes and two dots: the group, its two paths and four pieces, in 8 path elements.
|
||||
fn mixed() -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
for (a, b) in [((0.0, 0.0), (1.0, 0.0)), ((0.0, 1.0), (1.0, 1.0)), ((2.0, 0.0), (2.0, 0.0)), ((2.0, 1.0), (2.0, 1.0))] {
|
||||
bp.move_to(a);
|
||||
bp.line_to(b);
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_patterns_fit_every_object_and_point_or_charge_nothing() {
|
||||
let (tags, _) = super::super::tags(EMPTY).unwrap();
|
||||
let d = Drawing::read(craft_dxf::model::Document::read(&tags));
|
||||
let o = ImportOptions::default();
|
||||
let (p, inh) = (props(), Inherit::default());
|
||||
// Seven objects with six slots free: refused; with seven: drawn, the group left to `item`.
|
||||
let mut b = Build::new(&d, &o);
|
||||
b.nodes = MAX_NODES - 6;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
|
||||
assert_eq!(b.nodes, MAX_NODES - 6);
|
||||
b.nodes = MAX_NODES - 7;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_some());
|
||||
assert_eq!(b.nodes, MAX_NODES - 1);
|
||||
// Eight points with seven left: refused without charging them, so a 4-point path that
|
||||
// follows still fits.
|
||||
let mut b = Build::new(&d, &o);
|
||||
b.elements = MAX_ELEMENTS - 7;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
|
||||
assert_eq!(b.elements, MAX_ELEMENTS - 7);
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1.0, 0.0));
|
||||
line.line_to((1.0, 1.0));
|
||||
line.line_to((0.0, 1.0));
|
||||
assert!(b.path(&line, Look::Line, 0.0, &p, Affine::IDENTITY, &inh).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::rc::Rc;
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape};
|
||||
use vectorcraft_doc::Justify;
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
@@ -12,6 +12,7 @@ use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
|
||||
|
||||
use super::acis;
|
||||
use super::curve::{self, Vertex};
|
||||
use super::hatch::{self, Grad, NoPattern};
|
||||
use super::reader::{aci_paper, point};
|
||||
|
||||
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
|
||||
@@ -22,6 +23,10 @@ const LINE_SPACING: f64 = 5.0 / 3.0;
|
||||
const MAX_CELLS: i64 = 10_000;
|
||||
/// The most copies all the array inserts of a file make together.
|
||||
const MAX_TOTAL_CELLS: i64 = 2_000_000;
|
||||
/// The most winding steps for island nesting: loops times boundary elements times samples.
|
||||
const MAX_ISLAND_WORK: usize = if cfg!(test) { 1_000 } else { 10_000_000 };
|
||||
/// The most segment midpoints sampled just inside each loop for island nesting.
|
||||
const MAX_ISLAND_SAMPLES: usize = 16;
|
||||
/// Art farther than this from the origin (drawing units) is damaged data, left out.
|
||||
const MAX_COORD: f64 = 1e12;
|
||||
/// How far fit and aligned text may be squeezed or stretched to span their two points: at width
|
||||
@@ -148,6 +153,31 @@ pub(crate) struct InsertItem {
|
||||
pub attribs: Vec<Item>,
|
||||
}
|
||||
|
||||
/// A raster image: the file its IMAGEDEF names, shown on a parallelogram.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageItem {
|
||||
/// The handle of its IMAGEDEF.
|
||||
pub def: Option<u64>,
|
||||
/// The lower-left corner, and one pixel along the width and up the height (world
|
||||
/// coordinates, drawing units).
|
||||
pub insert: Point,
|
||||
pub u: Vec2,
|
||||
pub v: Vec2,
|
||||
/// Its size in pixels (0: its IMAGEDEF's).
|
||||
pub size: [f64; 2],
|
||||
/// The clip boundary in pixel space ([`ImageItem::placement`]); `None`: the whole image.
|
||||
pub clip: Option<Vec<Point>>,
|
||||
}
|
||||
|
||||
impl ImageItem {
|
||||
/// Pixel space (the top-left corner at the origin, x right, y down, one unit a pixel) to world
|
||||
/// coordinates, for an image `height` pixels high.
|
||||
pub fn placement(&self, height: f64) -> Affine {
|
||||
let top = self.insert + self.v * height;
|
||||
Affine::new([self.u.x, self.u.y, -self.v.x, -self.v.y, top.x, top.y])
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Geom {
|
||||
/// A path in world coordinates; `fill`: a filled area (hatch, solid), else a line of
|
||||
@@ -157,8 +187,24 @@ pub(crate) enum Geom {
|
||||
fill: bool,
|
||||
width: f64,
|
||||
},
|
||||
/// A hatch filled with a gradient, or a pattern hatch's lines (`bp`, world coordinates).
|
||||
Shaded {
|
||||
bp: BezPath,
|
||||
shade: Shade,
|
||||
},
|
||||
Text(TextItem),
|
||||
Insert(InsertItem),
|
||||
Image(ImageItem),
|
||||
}
|
||||
|
||||
/// How a [`Geom::Shaded`] path paints.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Shade {
|
||||
/// The area filled with a gradient.
|
||||
Gradient(Box<Grad>),
|
||||
/// Pattern lines, stroked at the lineweight without a linetype; `dots`: some pieces have no
|
||||
/// length and need round caps to show.
|
||||
Pattern { dots: bool },
|
||||
}
|
||||
|
||||
/// An entity as art: its geometry and its properties.
|
||||
@@ -176,16 +222,26 @@ pub(crate) struct Converter {
|
||||
pub warnings: Vec<String>,
|
||||
/// Array insert copies made so far, against [`MAX_TOTAL_CELLS`].
|
||||
cells: i64,
|
||||
/// The pattern budget shared by entity sections and blocks.
|
||||
patterns: hatch::Budget,
|
||||
/// The binary solid-modeler data of regions, by handle (DXF 2013 and later).
|
||||
regions: Rc<HashMap<u64, Vec<u8>>>,
|
||||
}
|
||||
|
||||
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
|
||||
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
|
||||
const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries";
|
||||
const DENSE_PATTERN: &str =
|
||||
"pattern hatches of more than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping steps come in as their boundaries";
|
||||
const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries";
|
||||
const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries";
|
||||
const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary";
|
||||
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
|
||||
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
|
||||
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
|
||||
const FAR_AWAY: &str = "entities with coordinates out of range are left out";
|
||||
const FLAT_IMAGES: &str = "images with no width or height are left out";
|
||||
const IMAGE_ADJUSTMENTS: &str = "the brightness, contrast and fade of images are left out";
|
||||
const OPAQUE_IMAGES: &str = "images set to show opaque keep their file's transparency";
|
||||
const INVERTED_CLIPS: &str = "inverted image clips are left out: those images show whole";
|
||||
const REGION_CURVES: &str = "region edges of some curve types come in as straight lines";
|
||||
const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines";
|
||||
const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve";
|
||||
@@ -215,7 +271,7 @@ impl Converter {
|
||||
if !m.common.visible {
|
||||
continue;
|
||||
}
|
||||
match self.geom(e, &m) {
|
||||
match self.geom(e, &m).map(usable_paint) {
|
||||
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
|
||||
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
|
||||
None if is_known(e.kind) => {}
|
||||
@@ -259,7 +315,7 @@ impl Converter {
|
||||
face(&mut bp, &corners);
|
||||
(!bp.elements().is_empty()).then_some(bp).and_then(path)
|
||||
}
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs, Props::read(&m.common).color),
|
||||
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
|
||||
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
|
||||
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
|
||||
@@ -267,11 +323,39 @@ impl Converter {
|
||||
model::EntityKind::Dimension(d) => {
|
||||
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
|
||||
}
|
||||
// Group 70 without its Show Image bit: a hidden image (an IMAGE without group 70 shows).
|
||||
model::EntityKind::Image(_) if g.i(70).is_some_and(|flags| flags & 1 == 0) => None,
|
||||
model::EntityKind::Image(im) => self.image(im, g.i(70).is_some()),
|
||||
_ if e.kind == "REGION" => self.region(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An IMAGE (its points are in world coordinates).
|
||||
fn image(&mut self, im: &model::Image, has_display: bool) -> Option<Geom> {
|
||||
let (u, v) = (point(im.u).to_vec2(), point(im.v).to_vec2());
|
||||
let area = u.cross(v);
|
||||
if !(area.is_finite() && area != 0.0) {
|
||||
self.warn(FLAT_IMAGES);
|
||||
return None;
|
||||
}
|
||||
if (im.brightness, im.contrast, im.fade) != (50, 50, 0) {
|
||||
self.warn(IMAGE_ADJUSTMENTS);
|
||||
}
|
||||
if has_display && im.display & 8 == 0 {
|
||||
self.warn(OPAQUE_IMAGES);
|
||||
}
|
||||
let clip = if !im.clipping || (has_display && im.display & 4 == 0) {
|
||||
None
|
||||
} else if im.clip_inverted {
|
||||
self.warn(INVERTED_CLIPS);
|
||||
None
|
||||
} else {
|
||||
image_clip(im)
|
||||
};
|
||||
Some(Geom::Image(ImageItem { def: im.image_def, insert: point(im.insert), u, v, size: im.size, clip }))
|
||||
}
|
||||
|
||||
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
|
||||
// Meshes are in world coordinates, seen from above.
|
||||
if p.is_polyface() || p.is_mesh() {
|
||||
@@ -426,27 +510,153 @@ impl Converter {
|
||||
Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 })
|
||||
}
|
||||
|
||||
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
|
||||
let mut bp = BezPath::new();
|
||||
/// A hatch's art; `own`: its color, which a gradient without color records takes.
|
||||
fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option<Geom> {
|
||||
let mut loops = Vec::new();
|
||||
for l in &h.loops {
|
||||
let Some(path) = boundary(&l.path) else { break };
|
||||
bp.extend(path);
|
||||
loops.push(path);
|
||||
}
|
||||
let mut max_depth = match h.style {
|
||||
1 => Some(1),
|
||||
2 => Some(0),
|
||||
_ => None,
|
||||
};
|
||||
if max_depth.is_some() {
|
||||
let elements = loops.iter().fold(0usize, |total, path| total.saturating_add(path.elements().len()));
|
||||
// Count each loop's samples against every loop, including its own containment checks.
|
||||
if loops.len().saturating_mul(elements).saturating_mul(MAX_ISLAND_SAMPLES) > MAX_ISLAND_WORK {
|
||||
self.warn(MUCH_ISLAND_WORK);
|
||||
max_depth = None;
|
||||
}
|
||||
}
|
||||
let nesting: Vec<_> = if max_depth.is_some() {
|
||||
loops
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let bounds = path.bounding_box();
|
||||
// Center each loop independently so distant loops do not erase small geometry.
|
||||
let center = bounds.center();
|
||||
let local = transformed(path.clone(), Affine::translate(-center.to_vec2()));
|
||||
let area = local.area();
|
||||
// Area divided by perimeter measures thickness independently of the loop's rotation.
|
||||
let perimeter = local.perimeter(bounds.width().max(bounds.height()) * 1e-3);
|
||||
let inset = if perimeter > 0.0 { area.abs() / perimeter * 1e-3 * area.signum() } else { 0.0 };
|
||||
let step = local.segments().count().div_ceil(MAX_ISLAND_SAMPLES).max(1);
|
||||
let mut samples: Vec<_> = local
|
||||
.segments()
|
||||
.step_by(step)
|
||||
.filter_map(|segment| {
|
||||
let tangent = match segment {
|
||||
PathSeg::Line(line) => line.deriv().eval(0.5),
|
||||
PathSeg::Quad(quad) => quad.deriv().eval(0.5),
|
||||
PathSeg::Cubic(cubic) => cubic.deriv().eval(0.5),
|
||||
}
|
||||
.to_vec2();
|
||||
let tangent = if tangent.hypot() > 0.0 { tangent } else { segment.end() - segment.start() };
|
||||
let length = tangent.hypot();
|
||||
if length == 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Positive area puts the interior to the left of the tangent in y-up coordinates.
|
||||
Some(segment.eval(0.5) + Vec2::new(-tangent.y, tangent.x) * (inset / length))
|
||||
})
|
||||
.take(MAX_ISLAND_SAMPLES)
|
||||
.filter(|sample| local.winding(*sample) != 0)
|
||||
.collect();
|
||||
if samples.is_empty()
|
||||
&& let Some(PathEl::MoveTo(first)) = local.elements().first()
|
||||
{
|
||||
samples.push(*first);
|
||||
}
|
||||
(bounds, center, local, area.abs(), samples)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut bp = BezPath::new();
|
||||
for (i, path) in loops.iter().enumerate() {
|
||||
if let Some(limit) = max_depth {
|
||||
let (bounds, center, _, area, samples) = &nesting[i];
|
||||
// Require geometric containment and a majority of samples so a shared
|
||||
// edge or a single vertex on the boundary does not decide nesting.
|
||||
let depth = nesting
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(j, _)| {
|
||||
let (other_bounds, other_center, other, other_area, _) = &nesting[*j];
|
||||
let offset = *center - *other_center;
|
||||
*j != i
|
||||
&& area < other_area
|
||||
&& bounds.x0 >= other_bounds.x0
|
||||
&& bounds.y0 >= other_bounds.y0
|
||||
&& bounds.x1 <= other_bounds.x1
|
||||
&& bounds.y1 <= other_bounds.y1
|
||||
&& samples.iter().filter(|p| other.winding(**p + offset) != 0).count() > samples.len() / 2
|
||||
})
|
||||
.count();
|
||||
if depth > limit {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
bp.extend(path.iter());
|
||||
}
|
||||
if bp.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bp = transformed(bp, ocs);
|
||||
if h.gradient.is_some() {
|
||||
self.warn(GRADIENT_HATCH);
|
||||
} else if !h.solid {
|
||||
self.warn(PATTERN_HATCH);
|
||||
return Some(Geom::Path { bp, fill: false, width: 0.0 });
|
||||
if let Some(g) = &h.gradient {
|
||||
let shade = hatch::gradient(g, &bp, ocs, own).map(|g| Shade::Gradient(Box::new(g)));
|
||||
let bp = transformed(bp, ocs);
|
||||
return Some(match shade {
|
||||
Some(shade) => Geom::Shaded { bp, shade },
|
||||
None => Geom::Path { bp, fill: true, width: 0.0 },
|
||||
});
|
||||
}
|
||||
if h.solid {
|
||||
return Some(Geom::Path { bp: transformed(bp, ocs), fill: true, width: 0.0 });
|
||||
}
|
||||
// The pattern lines are in the hatch's plane, as its boundary is.
|
||||
let doubled;
|
||||
let lines = if h.pattern_type == 0 && h.double && h.pattern_lines.len() == 1 {
|
||||
doubled = hatch::doubled(&h.pattern_lines);
|
||||
&doubled
|
||||
} else {
|
||||
&h.pattern_lines
|
||||
};
|
||||
match hatch::pattern(lines, &bp, &mut self.patterns) {
|
||||
Ok((lines, _)) if lines.elements().is_empty() => None,
|
||||
Ok((lines, dots)) => Some(Geom::Shaded { bp: transformed(lines, ocs), shade: Shade::Pattern { dots } }),
|
||||
Err(why) => {
|
||||
self.warn(match why {
|
||||
NoPattern::Undefined => PATTERN_HATCH,
|
||||
NoPattern::TooDense => DENSE_PATTERN,
|
||||
NoPattern::DrawingPieces => MANY_PATTERNS,
|
||||
NoPattern::DrawingWork => MUCH_PATTERN_WORK,
|
||||
});
|
||||
Some(Geom::Path { bp: transformed(bp, ocs), fill: false, width: 0.0 })
|
||||
}
|
||||
}
|
||||
Some(Geom::Path { bp, fill: true, width: 0.0 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the geometry within [`MAX_COORD`] of the origin?
|
||||
/// A gradient hatch whose gradient cannot be placed (numbers out of range) as a solid fill.
|
||||
fn usable_paint(g: Geom) -> Geom {
|
||||
match g {
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(grad) } => {
|
||||
let geom = &grad.geom;
|
||||
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if finite(geom.start) && finite(geom.end) && geom.aspect.is_finite() && geom.focal.is_none_or(finite) {
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(grad) }
|
||||
} else {
|
||||
Geom::Path { bp, fill: true, width: 0.0 }
|
||||
}
|
||||
}
|
||||
g => g,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the geometry within [`MAX_COORD`] of the origin? A gradient's handles may lie beyond it.
|
||||
fn in_range(g: &Geom) -> bool {
|
||||
let near = |p: Point| p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD;
|
||||
let origin = |m: &Affine| near(m.translation().to_point());
|
||||
@@ -454,8 +664,30 @@ fn in_range(g: &Geom) -> bool {
|
||||
Geom::Path { bp, width, .. } => {
|
||||
curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD
|
||||
}
|
||||
Geom::Shaded { bp, .. } => curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))),
|
||||
Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD,
|
||||
Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)),
|
||||
Geom::Image(i) => {
|
||||
let [w, h] = i.size;
|
||||
let far = i.insert + i.u * w + i.v * h;
|
||||
near(i.insert) && near(far) && [i.u.x, i.u.y, i.v.x, i.v.y, w, h].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The clip boundary of IMAGE `im` in pixel space ([`ImageItem::placement`]): two opposite corners
|
||||
/// of a rectangle, or a polygon of three points or more. The boundary's points are pixel centres
|
||||
/// counted from the top-left pixel, so the image's own corners are at (−0.5, −0.5) and
|
||||
/// (width − 0.5, height − 0.5). `None` when it has too few points.
|
||||
fn image_clip(im: &model::Image) -> Option<Vec<Point>> {
|
||||
let pts: Vec<Point> = im.clip.iter().map(|[x, y]| Point::new(x + 0.5, y + 0.5)).collect();
|
||||
match pts.as_slice() {
|
||||
[a, b] if im.clip_type == 1 => {
|
||||
let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y));
|
||||
Some(vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)])
|
||||
}
|
||||
p if p.len() >= 3 => Some(p.to_vec()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,6 +711,7 @@ fn is_known(kind: &str) -> bool {
|
||||
| "MTEXT"
|
||||
| "INSERT"
|
||||
| "DIMENSION"
|
||||
| "IMAGE"
|
||||
| "ATTDEF"
|
||||
| "SEQEND"
|
||||
| "VERTEX"
|
||||
|
||||
@@ -0,0 +1,847 @@
|
||||
//! Hatch fills other than solid: a pattern hatch's line families clipped to its boundary and cut
|
||||
//! into their dashes, and a gradient hatch's colors and placement. Both work in the hatch's own
|
||||
//! plane (its object coordinate system), where the boundary and the pattern lines are given.
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_color::{GradientGeom, GradientKind};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use craft_dxf::model::{self, PatternLine};
|
||||
|
||||
use super::entity::Col;
|
||||
use super::reader::aci_paper;
|
||||
|
||||
/// The most dashes and dots one pattern hatch draws.
|
||||
pub(crate) const MAX_PIECES: usize = 20_000;
|
||||
/// The most boundary edges a pattern hatch is clipped against, once its curves are flattened.
|
||||
const MAX_EDGES: usize = 200_000;
|
||||
/// The most work one pattern hatch does: each pattern line drawn costs one step per boundary
|
||||
/// edge, and each dash, gap or dot looked at one more.
|
||||
const MAX_WORK: usize = 20_000_000;
|
||||
/// The most dashes and dots all pattern hatches draw together.
|
||||
pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 };
|
||||
/// The most clipping and dash steps all pattern hatches take together.
|
||||
pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 };
|
||||
/// How far flattened boundary curves may stray, as a fraction of their loop's larger side.
|
||||
const FLATNESS: f64 = 1e-4;
|
||||
/// Spans, line spacings and dash periods shorter than this many units of the last place of their
|
||||
/// coordinates count as none.
|
||||
const LOCAL_TINY: f64 = 64.0 * f64::EPSILON;
|
||||
|
||||
/// Why a pattern hatch is not drawn as its pattern.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum NoPattern {
|
||||
/// The hatch holds no pattern lines.
|
||||
Undefined,
|
||||
/// Drawing it would take more than [`MAX_PIECES`] pieces, [`MAX_EDGES`] boundary edges or
|
||||
/// [`MAX_WORK`] steps.
|
||||
TooDense,
|
||||
/// The drawing reaches its total piece limit.
|
||||
DrawingPieces,
|
||||
/// The drawing reaches its total work limit.
|
||||
DrawingWork,
|
||||
}
|
||||
|
||||
/// The remaining pattern budget; discarded patterns also use it.
|
||||
pub(crate) struct Budget {
|
||||
pieces: usize,
|
||||
work: usize,
|
||||
stopped: Option<NoPattern>,
|
||||
}
|
||||
|
||||
impl Default for Budget {
|
||||
fn default() -> Self {
|
||||
Self { pieces: MAX_TOTAL_PIECES, work: MAX_TOTAL_WORK, stopped: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn piece(&mut self, pieces: &mut usize) -> Result<(), NoPattern> {
|
||||
if *pieces >= MAX_PIECES {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
if self.pieces == 0 {
|
||||
self.stopped = Some(NoPattern::DrawingPieces);
|
||||
return Err(NoPattern::DrawingPieces);
|
||||
}
|
||||
*pieces += 1;
|
||||
self.pieces -= 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn work(&mut self, work: &mut usize, steps: usize) -> Result<(), NoPattern> {
|
||||
if steps > MAX_WORK - *work {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
if steps > self.work {
|
||||
self.stopped = Some(NoPattern::DrawingWork);
|
||||
return Err(NoPattern::DrawingWork);
|
||||
}
|
||||
*work += steps;
|
||||
self.work -= steps;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a perpendicular family when the pattern holds only one family.
|
||||
pub(crate) fn doubled(lines: &[PatternLine]) -> Vec<PatternLine> {
|
||||
let mut out = lines.to_vec();
|
||||
if let [line] = lines {
|
||||
out.push(PatternLine { angle: line.angle + 90.0, base: line.base, offset: [-line.offset[1], line.offset[0]], dashes: line.dashes.clone() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A pattern hatch's lines inside `boundary` (closed loops; even-odd, as solid hatches fill):
|
||||
/// each family's lines, cut into dashes and dots that start from the line's own base point.
|
||||
/// `Ok` holds the pieces (empty when no line crosses the area) and whether any of them is a dot.
|
||||
pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Budget) -> Result<(BezPath, bool), NoPattern> {
|
||||
if lines.is_empty() {
|
||||
return Err(NoPattern::Undefined);
|
||||
}
|
||||
let exhausted = if budget.pieces == 0 {
|
||||
Some(NoPattern::DrawingPieces)
|
||||
} else if budget.work == 0 {
|
||||
Some(NoPattern::DrawingWork)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(why) = budget.stopped.or(exhausted) {
|
||||
budget.stopped = Some(why);
|
||||
return Err(why);
|
||||
}
|
||||
let mut out = BezPath::new();
|
||||
let Some(b) = super::curve::bounds(boundary) else { return Ok((out, false)) };
|
||||
let size = b.width().max(b.height());
|
||||
if !(size > 0.0 && size.is_finite()) {
|
||||
return Ok((out, false));
|
||||
}
|
||||
let edges = edges(boundary)?;
|
||||
if edges.is_empty() {
|
||||
return Ok((out, false));
|
||||
}
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
|
||||
let center = b.center();
|
||||
// The precision of the boundary's coordinates: spacings and periods below it draw nothing apart.
|
||||
let tiny = LOCAL_TINY * center.to_vec2().hypot().max(size);
|
||||
let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false);
|
||||
for l in lines {
|
||||
let a = l.angle.to_radians();
|
||||
let d = Vec2::new(a.cos(), a.sin());
|
||||
let n = Vec2::new(-d.y, d.x);
|
||||
let base = Point::new(l.base[0], l.base[1]);
|
||||
let offset = Vec2::new(l.offset[0], l.offset[1]);
|
||||
let step = offset.dot(n);
|
||||
// A family with numbers out of range is damaged: the others still draw.
|
||||
if ![a, base.x, base.y, offset.x, offset.y].iter().all(|v| v.is_finite()) || l.dashes.iter().any(|v| !v.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
usable = true;
|
||||
// Lines no distance apart, or closer than the coordinates can tell apart, fill the area
|
||||
// past what can be drawn.
|
||||
if step.abs() <= tiny {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
let period: f64 = l.dashes.iter().map(|v| v.abs()).sum();
|
||||
if !l.dashes.is_empty() && period <= tiny {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
// The same family from the line nearest the boundary's center, a whole number of offsets
|
||||
// away. The base and the center are each measured from the line through the origin
|
||||
// first, so a base far away keeps the fraction of the center's position.
|
||||
let (bn, cn) = (base.to_vec2().dot(n), center.to_vec2().dot(n));
|
||||
let (to_origin, to_center) = (-(bn / step).round(), (cn / step).round());
|
||||
let across = (bn + to_origin * step) + (to_center * step - cn);
|
||||
let last = -(across / step).round();
|
||||
let across = across + last * step;
|
||||
// Where the dashes start on that line, from its point nearest the center. Each line is
|
||||
// measured from its own point nearest the center, so its spans stay near the boundary
|
||||
// however long the dash period is. Each term is reduced to within half a period before
|
||||
// the terms are added, so a distant base or a large offset count keeps its remainder.
|
||||
let od = offset.dot(d);
|
||||
let along = if l.dashes.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
let ([o, oe], [c, ce]) = (product_parts(to_origin, od), product_parts(to_center + last, od));
|
||||
sum_rem(&[base.to_vec2().dot(d), -center.to_vec2().dot(d), o, oe, c, ce], period)
|
||||
};
|
||||
if !(across.is_finite() && along.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
// The dash start nearest a line's point nearest the center, as a signed distance.
|
||||
let phase = |k: f64| {
|
||||
let [p, e] = product_parts(k, od);
|
||||
sum_rem(&[along, p, e], period)
|
||||
};
|
||||
let base = center + n * across;
|
||||
// The lines crossing the boundary's box: base + k * step along the normal for whole k.
|
||||
let h = corners.map(|c| (c - base).dot(n) / step);
|
||||
let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil();
|
||||
let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor();
|
||||
if hi < lo {
|
||||
continue;
|
||||
}
|
||||
let count = hi - lo + 1.0;
|
||||
if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
let mut t = Vec::new();
|
||||
for k in (lo as i64)..=(hi as i64) {
|
||||
budget.work(&mut work, edges.len())?;
|
||||
let q = base + n * (step * k as f64);
|
||||
crossings(&edges, q, d, n, &mut t);
|
||||
for &[ta, tb] in t.as_chunks::<2>().0 {
|
||||
// Spans of no length at the precision of their own coordinates are dropped.
|
||||
if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) {
|
||||
continue;
|
||||
}
|
||||
let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> {
|
||||
budget.piece(&mut pieces)?;
|
||||
out.move_to(q + d * s0);
|
||||
out.line_to(q + d * s1);
|
||||
Ok(())
|
||||
};
|
||||
if l.dashes.is_empty() {
|
||||
emit(ta, tb, budget)?;
|
||||
continue;
|
||||
}
|
||||
// The dashes run from the line's dash start, element by element, from the period
|
||||
// the span starts in.
|
||||
let start = phase(k as f64);
|
||||
let mut at = start + ((ta - start) / period).floor() * period;
|
||||
// Periods too short to move along the span, or more dashes than one hatch may
|
||||
// look at, are refused before any of them is looked at.
|
||||
let steps = ((tb - at) / period + 2.0) * l.dashes.len() as f64;
|
||||
if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
// An element from `s` to `e`: a dash when `v` is positive, a dot when it is zero.
|
||||
let mut element = |s: f64, e: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> {
|
||||
budget.work(&mut work, 1)?;
|
||||
if v > 0.0 {
|
||||
let (s0, s1) = (s.max(ta), e.min(tb));
|
||||
if s1 > s0 {
|
||||
emit(s0, s1, budget)?;
|
||||
}
|
||||
} else if v == 0.0 && s >= ta {
|
||||
emit(s, s, budget)?;
|
||||
dots = true;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
// When that period starts on the span's start, or past it, the elements that end
|
||||
// the period before are measured back from its end, so a dot there is kept and a
|
||||
// long period does not move them. Each element's start and end are the distances
|
||||
// summed back from that end, so a long element does not move its known end.
|
||||
if at >= ta {
|
||||
let (mut back, mut first) = (vec![0.0], l.dashes.len());
|
||||
while first > 0 && at - back[back.len() - 1] >= ta {
|
||||
first -= 1;
|
||||
back.push(back[back.len() - 1] + l.dashes[first].abs());
|
||||
}
|
||||
for (i, v) in l.dashes[first..].iter().enumerate() {
|
||||
let rest = back.len() - 1 - i;
|
||||
element(at - back[rest], at - back[rest - 1], *v, budget)?;
|
||||
}
|
||||
}
|
||||
'span: loop {
|
||||
for v in &l.dashes {
|
||||
if at > tb {
|
||||
break 'span;
|
||||
}
|
||||
element(at, at + v.abs(), *v, budget)?;
|
||||
at += v.abs();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !usable {
|
||||
return Err(NoPattern::Undefined);
|
||||
}
|
||||
Ok((out, dots))
|
||||
}
|
||||
|
||||
/// `x` less the whole number of periods nearest it, within half a period of zero. Both steps
|
||||
/// are exact: the remainder of a division, then one period added or taken away.
|
||||
fn near_rem(x: f64, period: f64) -> f64 {
|
||||
let r = x % period;
|
||||
if r > period / 2.0 {
|
||||
r - period
|
||||
} else if r < -period / 2.0 {
|
||||
r + period
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// `a * b` as the rounded product and its rounding error, which add up to it exactly.
|
||||
fn product_parts(a: f64, b: f64) -> [f64; 2] {
|
||||
let p = a * b;
|
||||
[p, a.mul_add(b, -p)]
|
||||
}
|
||||
|
||||
/// The sum of `terms` reduced as [`near_rem`] does. Each term is reduced first, so a large term
|
||||
/// keeps its remainder, and the reduced terms are added with their rounding errors kept apart, so
|
||||
/// a small term is kept when larger ones cancel.
|
||||
fn sum_rem(terms: &[f64], period: f64) -> f64 {
|
||||
let (mut hi, mut lo) = (0.0, 0.0);
|
||||
for &t in terms {
|
||||
let t = near_rem(t, period);
|
||||
let s = hi + t;
|
||||
let v = s - hi;
|
||||
lo += (hi - (s - v)) + (t - v);
|
||||
hi = s;
|
||||
}
|
||||
near_rem(near_rem(hi, period) + near_rem(lo, period), period)
|
||||
}
|
||||
|
||||
/// The boundary's edges as straight segments, each loop closed and its curves flattened to
|
||||
/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out.
|
||||
fn edges(boundary: &BezPath) -> Result<Vec<(Point, Point)>, NoPattern> {
|
||||
let mut loops: Vec<BezPath> = Vec::new();
|
||||
for el in boundary.elements() {
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
loops.push(BezPath::new());
|
||||
}
|
||||
if let Some(l) = loops.last_mut() {
|
||||
l.push(*el);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut over = false;
|
||||
let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| {
|
||||
if out.len() >= MAX_EDGES {
|
||||
over = true;
|
||||
} else if a != b {
|
||||
out.push((a, b));
|
||||
}
|
||||
};
|
||||
for lp in &loops {
|
||||
let Some(b) = super::curve::bounds(lp) else { continue };
|
||||
let tolerance = b.width().max(b.height()) * FLATNESS;
|
||||
if !(tolerance > 0.0 && tolerance.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let (mut start, mut last) = (None::<Point>, None::<Point>);
|
||||
kurbo::flatten(lp.iter(), tolerance, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
start = Some(p);
|
||||
last = Some(p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
if let Some(l) = last {
|
||||
push(l, p, &mut out);
|
||||
}
|
||||
last = Some(p);
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let (Some(s), Some(l)) = (start, last) {
|
||||
push(l, s, &mut out);
|
||||
}
|
||||
last = start;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
if let (Some(s), Some(l)) = (start, last) {
|
||||
push(l, s, &mut out);
|
||||
}
|
||||
}
|
||||
if over { Err(NoPattern::TooDense) } else { Ok(out) }
|
||||
}
|
||||
|
||||
/// Where the line through `q` along `d` (unit; `n` its normal) crosses the edges, as distances
|
||||
/// from `q` along `d`, sorted into `t`. A vertex on the line counts once, for the edge that leaves
|
||||
/// the side the previous one came from.
|
||||
fn crossings(edges: &[(Point, Point)], q: Point, d: Vec2, n: Vec2, t: &mut Vec<f64>) {
|
||||
t.clear();
|
||||
for (p0, p1) in edges {
|
||||
let (h0, h1) = ((*p0 - q).dot(n), (*p1 - q).dot(n));
|
||||
if (h0 > 0.0) != (h1 > 0.0) {
|
||||
let p = p0.lerp(*p1, h0 / (h0 - h1));
|
||||
t.push((p - q).dot(d));
|
||||
}
|
||||
}
|
||||
t.sort_by(f64::total_cmp);
|
||||
}
|
||||
|
||||
/// The second color of a gradient: a color of its own, or for a one-color gradient the first
|
||||
/// one shaded toward black (tint 0) or tinted toward white (tint 1); 0.5 keeps it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum Second {
|
||||
Col(Col),
|
||||
Tint(f64),
|
||||
}
|
||||
|
||||
/// A gradient hatch's fill, placed in world coordinates (drawing units, y up).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Grad {
|
||||
pub kind: GradientKind,
|
||||
/// Linear: where the first stop sits and the last; radial: the center, a point on the outer
|
||||
/// ellipse and its aspect (a circle in the hatch's plane, an ellipse when the plane is seen
|
||||
/// at a slant).
|
||||
pub geom: GradientGeom,
|
||||
pub first: Col,
|
||||
pub second: Second,
|
||||
/// Each stop's position and whether it takes the second color (else the first).
|
||||
pub stops: Vec<(f32, bool)>,
|
||||
}
|
||||
|
||||
impl Grad {
|
||||
/// `first` shaded or tinted by `tint` (see [`Second::Tint`]).
|
||||
pub fn tinted([r, g, b]: [u8; 3], tint: f64) -> [u8; 3] {
|
||||
let t = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 0.5 };
|
||||
let mix = |c: u8| {
|
||||
let c = f64::from(c);
|
||||
let v = if t < 0.5 { c * t * 2.0 } else { c + (255.0 - c) * (t - 0.5) * 2.0 };
|
||||
v.round().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
[mix(r), mix(g), mix(b)]
|
||||
}
|
||||
}
|
||||
|
||||
fn col(c: model::Color) -> Col {
|
||||
match c {
|
||||
model::Color::Rgb(rgb) => Col::Rgb(rgb),
|
||||
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
|
||||
model::Color::ByBlock => Col::ByBlock,
|
||||
model::Color::ByLayer => Col::ByLayer,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill of gradient `g` over `boundary` (in the hatch's plane; `ocs` takes it to world
|
||||
/// coordinates), `own` standing in for colors the gradient lacks. The gradient runs at its angle
|
||||
/// across the boundary's extent in that direction. VectorCraft draws the named gradients this way:
|
||||
/// `LINEAR` the first color to the second; `CYLINDER` the second color in the middle of the first;
|
||||
/// `SPHERICAL` a circle from the second color at the center to the first; `HEMISPHERICAL` the same
|
||||
/// circle centered on the bottom edge; `CURVED` the second color at the bottom to the first at the
|
||||
/// top; each `INV` name the two colors the other way round; any other name as `LINEAR`. The shift
|
||||
/// moves the center up and left by up to a quarter of the extent.
|
||||
pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own: Col) -> Option<Grad> {
|
||||
let angle = if g.angle.is_finite() { g.angle } else { 0.0 };
|
||||
let mut frame = boundary.clone();
|
||||
frame.apply_affine(Affine::rotate(-angle));
|
||||
let r = super::curve::bounds(&frame)?;
|
||||
let (w, h) = (r.width(), r.height());
|
||||
let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let c = r.center() + Vec2::new(-w, h) * (shift / 4.0);
|
||||
// How far the shift moves the center left and up.
|
||||
let (dx, dy) = (c.x - r.center().x, c.y - r.center().y);
|
||||
let name = g.name.trim().to_uppercase();
|
||||
let (inverse, name) = match name.strip_prefix("INV") {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, name.as_str()),
|
||||
};
|
||||
let swap = |stops: &[(f32, bool)]| stops.iter().map(|(o, s)| (*o, *s != inverse)).collect::<Vec<_>>();
|
||||
let (kind, start, end, stops) = match name {
|
||||
"CYLINDER" => {
|
||||
(GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (0.5, true), (1.0, false)]))
|
||||
}
|
||||
"SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])),
|
||||
"HEMISPHERICAL" => {
|
||||
let center = Point::new(c.x, r.y0 + dy);
|
||||
(GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)]))
|
||||
}
|
||||
"CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])),
|
||||
_ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])),
|
||||
};
|
||||
let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None };
|
||||
geom.transform(ocs * Affine::rotate(angle), kind);
|
||||
let first = g.colors.first().map_or(own, |c| col(*c));
|
||||
let second = if g.single { Second::Tint(g.tint) } else { Second::Col(g.colors.get(1).map_or(first, |c| col(*c))) };
|
||||
Some(Grad { kind, geom, first, second, stops })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pattern(lines: &[PatternLine], boundary: &BezPath) -> Result<(BezPath, bool), NoPattern> {
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
super::pattern(lines, boundary, &mut budget)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_budgets_charge_discarded_patterns_and_stop_later_hatches() {
|
||||
let lines = [line(0.0, [0.0, 1.0], &[])];
|
||||
let boundary = square(10.0);
|
||||
let mut budget = Budget { pieces: 3, work: 100, stopped: None };
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
|
||||
assert_eq!(budget.pieces, 0);
|
||||
assert!(budget.work < 100);
|
||||
let work = budget.work;
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
|
||||
assert_eq!(budget.work, work, "later hatches do no clipping");
|
||||
|
||||
let mut budget = Budget { pieces: 100, work: 9, stopped: None };
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!(budget.work, 1, "two lines cost four edges each");
|
||||
let pieces = budget.pieces;
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!((budget.work, budget.pieces), (1, pieces));
|
||||
|
||||
let gaps = [line(0.0, [0.0, 1.0], &[-0.01])];
|
||||
let mut budget = Budget { pieces: 100, work: 20, stopped: None };
|
||||
assert_eq!(super::pattern(&gaps, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!((budget.work, budget.pieces), (0, 100), "gaps cost work without drawing pieces");
|
||||
}
|
||||
|
||||
fn square(side: f64) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((side, 0.0));
|
||||
bp.line_to((side, side));
|
||||
bp.line_to((0.0, side));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
fn line(angle: f64, offset: [f64; 2], dashes: &[f64]) -> PatternLine {
|
||||
PatternLine { angle, base: [0.0, 0.0], offset, dashes: dashes.to_vec() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doubling_adds_a_perpendicular_family_only_when_one_is_present() {
|
||||
let mut level = line(0.0, [3.0, 10.0], &[4.0, -2.0]);
|
||||
level.base = [2.0, 5.0];
|
||||
let lines = doubled(&[level.clone()]);
|
||||
let [first, second] = &lines[..] else { panic!("two families") };
|
||||
assert_eq!((first.angle, first.base, first.offset, &first.dashes), (level.angle, level.base, level.offset, &level.dashes));
|
||||
assert_eq!(second.angle, level.angle + 90.0);
|
||||
assert_eq!(second.offset, [-level.offset[1], level.offset[0]]);
|
||||
assert_eq!((second.base, &second.dashes), (level.base, &level.dashes));
|
||||
let kept = doubled(&lines);
|
||||
assert_eq!(kept.len(), lines.len());
|
||||
for (a, b) in kept.iter().zip(&lines) {
|
||||
assert_eq!((a.angle, a.base, a.offset, &a.dashes), (b.angle, b.base, b.offset, &b.dashes));
|
||||
}
|
||||
}
|
||||
|
||||
/// The pieces as (start, end) pairs.
|
||||
fn pieces(bp: &BezPath) -> Vec<(Point, Point)> {
|
||||
let mut out = vec![];
|
||||
let mut from = Point::ZERO;
|
||||
for el in bp.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => from = *p,
|
||||
PathEl::LineTo(p) => out.push((from, *p)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_lines_stop_at_the_boundary_and_skip_holes() {
|
||||
// Horizontal lines 10 apart, through y 5, 15 … 95, across a 100 square with a 20 square
|
||||
// hole in the middle.
|
||||
let mut boundary = square(100.0);
|
||||
let mut hole = square(20.0);
|
||||
hole.apply_affine(Affine::translate((40.0, 40.0)));
|
||||
boundary.extend(hole);
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 5.0], offset: [0.0, 10.0], dashes: vec![] };
|
||||
let (bp, dots) = pattern(&[l], &boundary).unwrap();
|
||||
assert!(!dots);
|
||||
let p = pieces(&bp);
|
||||
// Ten lines, the two through the hole (y 45 and 55) each cut in two.
|
||||
assert_eq!(p.len(), 12, "{p:?}");
|
||||
for (a, b) in &p {
|
||||
assert!((a.y - b.y).abs() < 1e-9 && a.x >= -1e-9 && b.x <= 100.0 + 1e-9);
|
||||
}
|
||||
let middle: Vec<_> = p.iter().filter(|(a, _)| (a.y - 45.0).abs() < 1e-9).collect();
|
||||
assert_eq!(middle.len(), 2);
|
||||
assert!(middle.iter().all(|(a, b)| b.x <= 40.0 + 1e-9 || a.x >= 60.0 - 1e-9), "{middle:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashes_start_at_each_lines_base_point() {
|
||||
// Dash 3, gap 2, a dot, gap 5: period 10 from x = 0, lines staggered by 5 along them.
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 0.0], offset: [5.0, 50.0], dashes: vec![3.0, -2.0, 0.0, -5.0] };
|
||||
let (bp, dots) = pattern(&[l], &square(100.0)).unwrap();
|
||||
assert!(dots);
|
||||
let p = pieces(&bp);
|
||||
let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::<Vec<_>>();
|
||||
let first = row(50.0);
|
||||
assert!(first.len() > 4, "{first:?}");
|
||||
// The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary.
|
||||
assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]);
|
||||
assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_across_the_boundary_is_cut_there() {
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9));
|
||||
// The second dash, 40 to 70, crosses the boundary at 50 and stops there.
|
||||
assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}");
|
||||
assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_spans_far_apart_keep_their_pieces_and_curves() {
|
||||
// Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its
|
||||
// one-unit spans.
|
||||
let strip = |x: f64| {
|
||||
let mut s = square(1.0);
|
||||
s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0));
|
||||
s
|
||||
};
|
||||
let mut boundary = strip(0.0);
|
||||
boundary.extend(strip(1e10));
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] };
|
||||
let (bp, _) = pattern(std::slice::from_ref(&l), &boundary).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 4, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}");
|
||||
// Unit circles as far apart keep their round outlines: the line through y 0.5 spans
|
||||
// 2 * sqrt(0.75) of each.
|
||||
let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1);
|
||||
let mut boundary = circle(0.0);
|
||||
boundary.extend(circle(1e10));
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] };
|
||||
let (bp, _) = pattern(&[l], &boundary).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let chord = 2.0 * 0.75f64.sqrt();
|
||||
assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_lines_across_squares_far_apart_are_drawn() {
|
||||
// Two unit squares 10 billion units apart, lines 0.5 apart: two lines cross each square.
|
||||
let mut boundary = square(1.0);
|
||||
let mut far = square(1.0);
|
||||
far.apply_affine(Affine::translate((1e10, 0.0)));
|
||||
boundary.extend(far);
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[])], &boundary).unwrap();
|
||||
assert_eq!(pieces(&bp).len(), 4, "{:?}", pieces(&bp));
|
||||
// Dashes 0.25 long with 0.25 gaps: two per line in each square.
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[0.25, -0.25])], &boundary).unwrap();
|
||||
assert_eq!(pieces(&bp).len(), 8, "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_based_far_away_draw_the_same_lines() {
|
||||
// Lines one apart from a base 1e19 up are the lines one apart from the origin.
|
||||
let mut far = line(0.0, [0.0, 1.0], &[]);
|
||||
far.base = [0.0, 1e19];
|
||||
let (bp, _) = pattern(&[far], &square(100.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 100, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0 && (0.0..100.0).contains(&a.y)), "{p:?}");
|
||||
// A staggered family based 100 lines away keeps each line's dash phase.
|
||||
let mut near = line(0.0, [5.0, 10.0], &[3.0, -7.0]);
|
||||
near.base = [-497.0, 0.0];
|
||||
let mut away = near.clone();
|
||||
away.base = [3.0, 1000.0];
|
||||
let sorted = |l: PatternLine| {
|
||||
let mut p = pieces(&pattern(&[l], &square(100.0)).unwrap().0);
|
||||
p.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal));
|
||||
p
|
||||
};
|
||||
let (a, b) = (sorted(near), sorted(away));
|
||||
assert_eq!(a.len(), b.len());
|
||||
assert!(!a.is_empty());
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_based_far_away_keep_lines_off_a_fractional_center() {
|
||||
// A 3 square centered on y 1.5: lines one apart from a base 1e19 up run at whole y, not
|
||||
// through the center.
|
||||
let mut far = line(0.0, [0.0, 1.0], &[]);
|
||||
far.base = [0.0, 1e19];
|
||||
let (bp, _) = pattern(&[far], &square(3.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!(p.len() >= 2, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_periods_far_longer_than_the_boundary_still_draw() {
|
||||
// Dashes 1e16 long from x 0, and from x -7.5e15: each row of the 100 square lies in a
|
||||
// dash, so every row is drawn across the square.
|
||||
for x in [0.0, -7.5e15] {
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
|
||||
l.base = [x, 0.0];
|
||||
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
let rows: Vec<_> = p.iter().filter(|(a, _)| a.y > 0.0 && a.y < 100.0).collect();
|
||||
assert_eq!(rows.len(), 9, "base x {x}: {p:?}");
|
||||
assert!(rows.iter().all(|(a, b)| a.x.abs() < 1e-9 && (b.x - 100.0).abs() < 1e-9), "base x {x}: {p:?}");
|
||||
}
|
||||
// From x 5e15 the square lies in a gap: nothing is drawn.
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
|
||||
l.base = [5e15, 0.0];
|
||||
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
|
||||
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_offset_counts_that_cancel_keep_the_dash_start() {
|
||||
// A 100 square 2^40 up, its family based on the row through its middle with offsets
|
||||
// 2^30 along: the row's dashes start at x 0, so it draws 0 to 30.
|
||||
let b = 2f64.powi(40);
|
||||
let mut boundary = square(100.0);
|
||||
boundary.apply_affine(Affine::translate((0.0, b)));
|
||||
let mut l = line(0.0, [2f64.powi(30), 1024.0], &[30.0, -70.0]);
|
||||
l.base = [0.0, b + 50.0];
|
||||
let p = pieces(&pattern(&[l], &boundary).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == b + 50.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row.len(), 1, "{p:?}");
|
||||
assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_phase_terms_that_cancel_keep_a_small_one() {
|
||||
// Based and offset by 2^54 along and 10 up: the line one offset back runs along the
|
||||
// bottom of the unit square with its dash 16 long from x 0, so it covers 0 to 1.
|
||||
let big = 2f64.powi(54);
|
||||
let mut l = line(0.0, [big, 10.0], &[16.0, -(2f64.powi(57) - 16.0)]);
|
||||
l.base = [big, 10.0];
|
||||
let p = pieces(&pattern(&[l], &square(1.0)).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 0.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row, [(0.0, 1.0)], "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() {
|
||||
// A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square
|
||||
// lies in the gap, so nothing is drawn.
|
||||
let mut l = line(0.0, [0.0, 10.0], &[-1e16, 1e16]);
|
||||
l.base = [0.0, 0.5];
|
||||
let (bp, _) = pattern(&[l], &square(1.0)).unwrap();
|
||||
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_bases_keep_their_dash_remainder() {
|
||||
// Dash 1, gap 5 from x 1e19, which is 4 more than a whole number of periods of 6: the
|
||||
// dashes run 4 to 5, 10 to 11 … 94 to 95 in squares centered on a whole and a half x.
|
||||
for side in [96.0, 98.0] {
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1.0, -5.0]);
|
||||
l.base = [1e19, 0.0];
|
||||
let p = pieces(&pattern(&[l], &square(side)).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 50.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row.len(), 16, "side {side}: {row:?}");
|
||||
assert!(
|
||||
row.iter().enumerate().all(|(i, (a, e))| (a - (4.0 + 6.0 * i as f64)).abs() < 1e-9 && (e - a - 1.0).abs() < 1e-9),
|
||||
"side {side}: {row:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_on_the_start_of_a_span_is_kept() {
|
||||
// A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom.
|
||||
let (bp, dots) = pattern(&[line(0.0, [0.0, 20.0], &[-5.0, 0.0])], &square(10.0)).unwrap();
|
||||
assert!(dots);
|
||||
let xs: Vec<f64> = pieces(&bp).iter().filter(|(a, _)| a.y == 0.0).map(|(a, _)| a.x).collect();
|
||||
assert_eq!(xs, [0.0, 5.0, 10.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slanted_lines_fill_a_square_evenly() {
|
||||
// 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one
|
||||
// side of the square to another.
|
||||
let offset = [-(0.5f64.sqrt()), 0.5f64.sqrt()];
|
||||
let (bp, _) = pattern(&[line(45.0, offset, &[])], &square(10.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!((14..=15).contains(&p.len()), "{} lines", p.len());
|
||||
let on_edge = |q: Point| [q.x, q.y].iter().any(|v| v.abs() < 1e-6 || (v - 10.0).abs() < 1e-6);
|
||||
assert!(p.iter().all(|(a, b)| on_edge(*a) && on_edge(*b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_dense_patterns_and_missing_ones_are_reported() {
|
||||
assert_eq!(pattern(&[], &square(10.0)), Err(NoPattern::Undefined));
|
||||
// Lines 0.001 apart across a 1,000 square: a million lines.
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 0.001], &[])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// Few lines, but dashes far shorter than the square: more pieces than allowed.
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// A tiny nonempty dash period is too dense; only an empty list draws continuous lines.
|
||||
// It is refused once the first line is clipped, before any of its dashes is looked at.
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
|
||||
assert_eq!(budget.work, usize::MAX - 4, "one line clipped against four edges, no dashes looked at");
|
||||
// A period below the coordinates' precision is refused before any line is clipped.
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-15])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
|
||||
assert_eq!(budget.work, usize::MAX, "no work done");
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap();
|
||||
assert!(!pieces(&bp).is_empty());
|
||||
// Lines on top of each other, or as good as, are as dense as can be.
|
||||
assert_eq!(pattern(&[line(0.0, [5.0, 0.0], &[])], &square(10.0)), Err(NoPattern::TooDense));
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 1e-7], &[])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// Only damaged families: no pattern to draw.
|
||||
assert_eq!(pattern(&[line(f64::NAN, [0.0, 1.0], &[])], &square(10.0)), Err(NoPattern::Undefined));
|
||||
}
|
||||
|
||||
fn grad(name: &str, angle: f64, shift: f64) -> model::Gradient {
|
||||
model::Gradient {
|
||||
name: name.into(),
|
||||
angle,
|
||||
shift,
|
||||
single: false,
|
||||
tint: 0.0,
|
||||
colors: vec![model::Color::Index(1), model::Color::Rgb([0, 0, 255])],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_run_across_the_boundary_at_their_angle() {
|
||||
let box_ = {
|
||||
let mut b = square(100.0);
|
||||
b.apply_affine(Affine::scale_non_uniform(2.0, 1.0));
|
||||
b
|
||||
};
|
||||
let g = gradient(&grad("LINEAR", 0.0, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.kind, g.geom.start, g.geom.end), (GradientKind::Linear, Point::new(0.0, 50.0), Point::new(200.0, 50.0)));
|
||||
assert_eq!((g.first, g.second), (Col::Rgb(aci_paper(1)), Second::Col(Col::Rgb([0, 0, 255]))));
|
||||
assert_eq!(g.stops, [(0.0, false), (1.0, true)]);
|
||||
// At a quarter turn it runs bottom to top.
|
||||
let g = gradient(&grad("LINEAR", std::f64::consts::FRAC_PI_2, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert!(g.geom.start.distance(Point::new(100.0, 0.0)) < 1e-9 && g.geom.end.distance(Point::new(100.0, 100.0)) < 1e-9, "{g:?}");
|
||||
// Shifted, the center moves up and left: a sphere's center and a cylinder's middle.
|
||||
let g = gradient(&grad("SPHERICAL", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.kind, g.geom.start), (GradientKind::Radial, Point::new(50.0, 75.0)));
|
||||
assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center");
|
||||
let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0));
|
||||
// A curved gradient runs bottom to top, so the shift moves it up.
|
||||
for name in ["CURVED", "INVCURVED"] {
|
||||
let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}");
|
||||
}
|
||||
// A plane stretched twice as wide stretches the circle into an ellipse with it.
|
||||
let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap();
|
||||
assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_gradients_swap_their_colors() {
|
||||
for (name, inv) in
|
||||
[("CYLINDER", "INVCYLINDER"), ("SPHERICAL", "INVSPHERICAL"), ("HEMISPHERICAL", "INVHEMISPHERICAL"), ("CURVED", "INVCURVED")]
|
||||
{
|
||||
let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}");
|
||||
let count = if name == "CYLINDER" { 3 } else { 2 };
|
||||
assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}");
|
||||
assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_color_gradients_shade_or_tint_their_color() {
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.0), [0, 0, 0]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.5), [200, 100, 0]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 1.0), [255, 255, 255]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.25), [100, 50, 0]);
|
||||
let mut g = grad("LINEAR", 0.0, 0.0);
|
||||
(g.single, g.tint, g.colors) = (true, 0.75, vec![]);
|
||||
let g = gradient(&g, &square(10.0), Affine::IDENTITY, Col::ByBlock).unwrap();
|
||||
assert_eq!((g.first, g.second), (Col::ByBlock, Second::Tint(0.75)), "no color record: the hatch's own color");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
|
||||
//! linetype and text style tables; the blocks; the entities; the layouts.
|
||||
//! linetype and text style tables; the blocks; the entities; the layouts; the image files.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
@@ -50,6 +50,15 @@ pub(crate) struct BlockDef<'a> {
|
||||
pub xref: bool,
|
||||
}
|
||||
|
||||
/// A raster image file that IMAGE entities show (an IMAGEDEF object).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageFile {
|
||||
/// The file's path as the drawing stores it (absolute, or relative to the drawing).
|
||||
pub path: String,
|
||||
/// Its size in pixels (0 when not given).
|
||||
pub size: [f64; 2],
|
||||
}
|
||||
|
||||
/// A layout: model space, or a paper layout with the block holding its art.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LayoutDef {
|
||||
@@ -80,6 +89,8 @@ pub(crate) struct Drawing<'a> {
|
||||
pub entities: Vec<EntityRecord<'a>>,
|
||||
/// Model space first, then the paper layouts in tab order.
|
||||
pub layouts: Vec<LayoutDef>,
|
||||
/// The image files by the handle of their IMAGEDEF.
|
||||
pub images: HashMap<u64, ImageFile>,
|
||||
/// How many sections the file has (none: not a drawing).
|
||||
pub sections: usize,
|
||||
/// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in
|
||||
@@ -116,6 +127,11 @@ impl<'a> Drawing<'a> {
|
||||
}
|
||||
let block_names = doc.block_names();
|
||||
d.layouts = layouts(&doc, &block_names);
|
||||
for def in doc.objects_of("IMAGEDEF").map(model::objects::ImageDef::read) {
|
||||
if let Some(h) = def.handle {
|
||||
d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size });
|
||||
}
|
||||
}
|
||||
d.regions = Rc::new(region_data(&doc));
|
||||
for b in doc.blocks {
|
||||
if b.name.is_empty() {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurve;
|
||||
use kurbo::{ParamCurve, Shape};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, Node, NodeKind, TextObject, Unit};
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit};
|
||||
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
@@ -505,6 +505,593 @@ fn solid_hatches_fill_and_pattern_hatches_outline() {
|
||||
assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
}
|
||||
|
||||
/// [`hatch`]'s square with a round hole, as a pattern hatch of level lines 10 apart through
|
||||
/// y 5, 15 … 95, in linetype `linetype`, with `dashes` (79 and 49 groups).
|
||||
fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> {
|
||||
let mut e = hatch("0");
|
||||
e.insert(1, (6, linetype));
|
||||
let seeds = e.iter().position(|p| *p == (98, "0")).unwrap();
|
||||
let mut lines = vec![(78, "1"), (53, "0"), (43, "0"), (44, "5"), (45, "0"), (46, "10")];
|
||||
lines.extend_from_slice(if dashes.is_empty() { &[(79, "0")] } else { dashes });
|
||||
e.splice(seeds..seeds, lines);
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_islands_hatches_fill_and_pattern_through_the_hole() {
|
||||
let mut e = hatch("1");
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "ignore islands leaves only the outer square");
|
||||
assert!(path.subpaths[0].closed);
|
||||
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
let box_area = bounds(area).area();
|
||||
assert!((path.to_bezpath().area().abs() - box_area).abs() < box_area * 1e-9, "the whole square is filled");
|
||||
|
||||
let mut e = pattern_hatch("CONTINUOUS", &[]);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
assert_eq!(children.len(), 10, "the ten level lines are not cut by the hole");
|
||||
let width = bounds(lines).width();
|
||||
assert!(children.iter().all(|c| (bounds(c).width() - width).abs() < width * 1e-9), "each line spans the square");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_island_styles_select_nested_boundary_levels() {
|
||||
let mut e = hatch("1");
|
||||
let count = e.iter().position(|p| p.0 == 91).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
e[count] = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
// Innermost first so nesting depends on geometry, not boundary order or flags.
|
||||
for (lo, hi) in [("40", "60"), ("0", "100"), ("20", "80")] {
|
||||
loops.extend([
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, lo),
|
||||
(20, lo),
|
||||
(10, hi),
|
||||
(20, lo),
|
||||
(10, hi),
|
||||
(20, hi),
|
||||
(10, lo),
|
||||
(20, hi),
|
||||
(97, "0"),
|
||||
]);
|
||||
}
|
||||
e.splice(count + 1..end, loops);
|
||||
// The sides of the squares each style keeps: normal and unknown styles all three, outer the
|
||||
// outermost and middle ones, ignore the outermost alone.
|
||||
for (style, expected) in [("0", &[20.0, 60.0, 100.0][..]), ("1", &[60.0, 100.0]), ("2", &[100.0]), ("3", &[20.0, 60.0, 100.0])] {
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let mut sides: Vec<f64> = match &area.kind {
|
||||
NodeKind::Compound { children, rule } => {
|
||||
assert_eq!(*rule, FillRule::EvenOdd);
|
||||
children.iter().map(|c| bounds(c).width().round()).collect()
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(area.path_data().unwrap().subpaths.len(), 1);
|
||||
vec![bounds(area).width().round()]
|
||||
}
|
||||
};
|
||||
sides.sort_by(f64::total_cmp);
|
||||
assert_eq!(sides, expected, "boundary loops for island style {style}");
|
||||
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_small_island_far_from_origin() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("100000000", "100000001"), ("100000000.2", "100000000.8")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Centered, so the art far from the drawing's origin lands on the canvas.
|
||||
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the small island far from the origin is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_small_island_with_distant_outer_loop() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("0", "1"), ("0.2", "0.8"), ("100000000", "100000001")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
|
||||
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "the island is removed and both outer squares remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_tiny_island_with_distant_outer_loop() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("0", "0.000001"), ("0.0000002", "0.0000008"), ("100000000000", "100000000001")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
|
||||
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "the tiny island is removed and both outer squares remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_keeps_squares_sharing_an_edge() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// The first vertex lies on the second square's left edge.
|
||||
for vertices in [[("10", "0"), ("10", "10"), ("0", "10"), ("0", "0")], [("10", "0"), ("20", "0"), ("20", "10"), ("10", "10")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "adjacent squares are both boundaries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_square_touching_outer_boundary_at_a_vertex() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// The island's first vertex touches the outer square's right edge, where
|
||||
// winding is zero. Its other vertices and all segment midpoints are inside.
|
||||
for vertices in [[("100", "50"), ("75", "75"), ("50", "50"), ("75", "25")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the touching island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_square_sharing_two_outer_edges() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for vertices in [[("50", "50"), ("100", "50"), ("100", "100"), ("50", "100")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the island sharing two outer edges is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_thin_island() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for vertices in [
|
||||
[("0", "0"), ("100", "0"), ("100", "0.00001"), ("0", "0.00001")],
|
||||
[("10", "0.000002"), ("90", "0.000002"), ("90", "0.000008"), ("10", "0.000008")],
|
||||
] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the thin island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_rotated_thin_island() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// These are the previous test's corners turned 45 degrees about the origin.
|
||||
for vertices in [
|
||||
[("0", "0"), ("70.7106781187", "70.7106781187"), ("70.7106710476", "70.7106851897"), ("-0.00000707106781187", "0.00000707106781187")],
|
||||
[
|
||||
("7.07106639765", "7.07106922608"),
|
||||
("63.6396088926", "63.6396117210"),
|
||||
("63.6396046499", "63.6396159636"),
|
||||
("7.07106215421", "7.07107346952"),
|
||||
],
|
||||
] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the rotated thin island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_island_work_limit_keeps_all_loops_and_warns_only_for_island_styles() {
|
||||
let mut e = hatch("1");
|
||||
let count = e.iter().position(|p| p.0 == 91).unwrap();
|
||||
let hole = e.iter().position(|p| *p == (92, "0")).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
e[count] = (91, "16");
|
||||
// Keep the outer square and add 15 inner squares. With at least five path elements
|
||||
// per square, 16 loops require at least 1,280 steps, over the test-time limit.
|
||||
// Without the fallback, ignore style removes the inner squares.
|
||||
let inner = [
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, "20"),
|
||||
(20, "20"),
|
||||
(10, "80"),
|
||||
(20, "20"),
|
||||
(10, "80"),
|
||||
(20, "80"),
|
||||
(10, "20"),
|
||||
(20, "80"),
|
||||
(97, "0"),
|
||||
];
|
||||
e.splice(hole..end, inner.repeat(15));
|
||||
for style in ["2", "0"] {
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
|
||||
let r = open(&entities(&e), &points());
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let count = match &area.kind {
|
||||
NodeKind::Compound { children, .. } => children.len(),
|
||||
_ => area.path_data().unwrap().subpaths.len(),
|
||||
};
|
||||
assert_eq!(count, 16, "every boundary loop is kept for style {style}");
|
||||
if style == "2" {
|
||||
assert_eq!(r.warnings, ["hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"]);
|
||||
} else {
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_hatches_draw_their_lines_inside_the_boundary() {
|
||||
// A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them.
|
||||
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
|
||||
let r = open(&drawing(&[], &tables, &[], &pattern_hatch("DASHED", &[])), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
// Ten lines; the four that cross the hole (y 35 to 65) are cut in two.
|
||||
assert_eq!(children.len(), 14);
|
||||
assert_eq!(stroke_rgb(lines), [255, 0, 0, 255]);
|
||||
assert!(lines.appearance.fill().is_none_or(|f| f.paint.is_none()), "the lines are not filled");
|
||||
assert!(lines.appearance.stroke().is_some_and(|s| s.dash.is_none()), "no linetype dashes on pattern lines");
|
||||
let h = height(&r.document);
|
||||
for c in children {
|
||||
let pts = path_points(c);
|
||||
let (a, b) = (pts[0], *pts.last().unwrap());
|
||||
let y = h - a.y;
|
||||
assert!((a.y - b.y).abs() < 1e-9 && (y - 5.0).rem_euclid(10.0) < 1e-9, "level lines through y 5, 15 …: {a:?} {b:?}");
|
||||
assert!(a.x.min(b.x) >= -1e-9 && a.x.max(b.x) <= 100.0 + 1e-9, "inside the square: {a:?} {b:?}");
|
||||
let mid = Point::new((a.x + b.x) / 2.0, y);
|
||||
assert!(mid.distance(Point::new(50.0, 50.0)) > 20.0, "outside the hole: {a:?} {b:?}");
|
||||
}
|
||||
assert!(lines.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
|
||||
// A pattern of dots (no length) shows them with round caps.
|
||||
let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points());
|
||||
let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings);
|
||||
// Dashes and dots together: the dots take round caps on a path of their own, and the dashes
|
||||
// keep butt caps, so they do not grow into their gaps.
|
||||
let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")];
|
||||
let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) };
|
||||
assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
|
||||
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round));
|
||||
let length = |n: &Node| {
|
||||
let pts = path_points(n);
|
||||
pts[0].distance(*pts.last().unwrap())
|
||||
};
|
||||
let pieces = |n: &Node| match &n.kind {
|
||||
NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(),
|
||||
_ => vec![n.clone()],
|
||||
};
|
||||
assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes");
|
||||
assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots");
|
||||
// Without its pattern lines a pattern hatch still comes in as its boundary, with a note.
|
||||
let r = open(&entities(&hatch("0")), &points());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_defined_double_hatches_draw_level_and_vertical_lines() {
|
||||
for double in ["1", "0"] {
|
||||
let mut e = pattern_hatch("CONTINUOUS", &[]);
|
||||
let kind = e.iter().position(|p| *p == (76, "1")).unwrap();
|
||||
e[kind] = (76, "0");
|
||||
e.insert(kind + 1, (77, double));
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
let (mut level, mut vertical) = (0, 0);
|
||||
for c in children {
|
||||
let pts = path_points(c);
|
||||
let (a, b) = (pts[0], *pts.last().unwrap());
|
||||
if (a.y - b.y).abs() < 1e-9 && (a.x - b.x).abs() > 1e-9 {
|
||||
level += 1;
|
||||
} else if (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() > 1e-9 {
|
||||
vertical += 1;
|
||||
} else {
|
||||
panic!("level or vertical piece: {a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
assert!(level > 0, "level pieces with double = {double}");
|
||||
assert_eq!(vertical > 0, double == "1", "vertical pieces with double = {double}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_hatches_share_the_drawings_budget() {
|
||||
// Keep the fixture's square alone so every fallback is one closed path.
|
||||
let mut hatch = pattern_hatch("CONTINUOUS", &[]);
|
||||
let hole = hatch.iter().position(|p| *p == (92, "0")).unwrap();
|
||||
let end = hatch.iter().position(|p| p.0 == 75).unwrap();
|
||||
hatch.drain(hole..end);
|
||||
*hatch.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "1");
|
||||
let limit = super::hatch::MAX_TOTAL_PIECES;
|
||||
let count = limit / 10 + 5;
|
||||
let e = hatch.repeat(count);
|
||||
let r = open(&entities(&e), &points());
|
||||
assert_eq!(r.warnings.len(), 1, "{:?}", r.warnings);
|
||||
assert!(r.warnings[0].contains("2,000,000 dashes in all"), "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), count, "each hatch keeps its place");
|
||||
let mut pieces = 0;
|
||||
let mut boundaries = 0;
|
||||
for n in art {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
assert_eq!(boundaries, 0, "all hatches after exhaustion keep their boundaries");
|
||||
pieces += children.len();
|
||||
assert!(children.iter().all(|c| c.path_data().is_some_and(|p| p.subpaths.iter().all(|s| !s.closed))));
|
||||
} else {
|
||||
let path = n.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(path.subpaths[0].closed);
|
||||
boundaries += 1;
|
||||
}
|
||||
}
|
||||
assert!(pieces > 0 && pieces <= limit, "{pieces} pieces against {limit}");
|
||||
assert!(boundaries >= 5, "hatches past the budget keep their boundaries");
|
||||
}
|
||||
|
||||
/// [`hatch`]'s square with a round hole, filled with gradient `name` at `angle` (radians) from
|
||||
/// a true color (red) to color 5 (blue), or from red alone with `tint`.
|
||||
fn gradient_hatch(name: &'static str, angle: &'static str, tint: Option<&'static str>) -> Vec<(i32, &'static str)> {
|
||||
let mut e = hatch("1");
|
||||
e.extend([(450, "1"), (451, "0"), (452, if tint.is_some() { "1" } else { "0" }), (453, "2"), (460, angle), (461, "0")]);
|
||||
e.extend([(462, tint.unwrap_or("0")), (463, "0"), (63, "1"), (421, "16711680"), (463, "1"), (63, "5"), (470, name)]);
|
||||
e
|
||||
}
|
||||
|
||||
fn gradient_of(n: &Node) -> vectorcraft_color::GradientPaint {
|
||||
match n.appearance.fill().map(|f| &f.paint) {
|
||||
Some(Paint::Gradient(g)) => (**g).clone(),
|
||||
other => panic!("not a gradient: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hatches_keep_their_gradient() {
|
||||
let r = open(&entities(&gradient_hatch("LINEAR", "0", None)), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let g = gradient_of(area);
|
||||
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
|
||||
assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Linear);
|
||||
assert_eq!(colors, [[255, 0, 0, 255], [0, 0, 255, 255]], "the true color, then color 5");
|
||||
// Level, across the square from left to right through its middle.
|
||||
let (h, geom) = (height(&r.document), g.geom.unwrap());
|
||||
assert!(geom.start.distance(Point::new(0.0, h - 50.0)) < 1e-9 && geom.end.distance(Point::new(100.0, h - 50.0)) < 1e-9, "{geom:?}");
|
||||
// A quarter turn runs it up the square: from the bottom (larger y in the document) to the top.
|
||||
let r = open(&entities(&gradient_hatch("LINEAR", "1.5707963267948966", None)), &points());
|
||||
let geom = gradient_of(&r.document.layers[0].children().unwrap()[0]).geom.unwrap();
|
||||
assert!(geom.start.distance(Point::new(50.0, h)) < 1e-6 && geom.end.distance(Point::new(50.0, h - 100.0)) < 1e-6, "{geom:?}");
|
||||
// A one-color sphere tinted to white: white in the center, red at the edge.
|
||||
let r = open(&entities(&gradient_hatch("SPHERICAL", "0", Some("1"))), &points());
|
||||
let g = gradient_of(&r.document.layers[0].children().unwrap()[0]);
|
||||
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
|
||||
assert_eq!((g.gradient.kind, colors), (vectorcraft_color::GradientKind::Radial, vec![[255; 4], [255, 0, 0, 255]]));
|
||||
assert!(g.geom.unwrap().start.distance(Point::new(50.0, h - 50.0)) < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_gradient_stops_keep_the_inserts_color() {
|
||||
for (color, layer) in [("0", "Doors"), ("256", "0")] {
|
||||
for (second, tint) in [(false, None), (true, None), (false, Some("1"))] {
|
||||
let mut hatch = gradient_hatch("LINEAR", "0", tint);
|
||||
// The hatch's explicit color and other properties do not need insert inheritance.
|
||||
hatch.splice(1..1, [(8, layer), (6, "CONTINUOUS"), (370, "25")]);
|
||||
hatch.retain(|p| p.0 != 421);
|
||||
let stop = hatch.iter_mut().filter(|p| p.0 == 63).nth(usize::from(second)).unwrap();
|
||||
*stop = (63, color);
|
||||
let inserts = [(0, "INSERT"), (8, "Doors"), (2, "Door"), (62, "3"), (10, "0"), (20, "0")];
|
||||
let r = open(&with_door(&hatch, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [symbol] = &r.document.symbols[..] else { panic!("one symbol") };
|
||||
let g = gradient_of(&symbol.art);
|
||||
let stop = &g.gradient.stops[usize::from(second)];
|
||||
let expected = if color == "0" { [0, 255, 0, 255] } else { [0, 0, 255, 255] };
|
||||
assert_eq!(stop.color.to_rgba8(1.0), expected, "color {color}, second {second}, tint {tint:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hatches_far_out_keep_their_fill() {
|
||||
// A sphere hatch on a strip 10 wide ending 1e12 out: its circle reaches past 1e12, and the
|
||||
// strip still comes in, centered on the artboard.
|
||||
let mut e = vec![(0, "HATCH"), (62, "1"), (10, "0"), (20, "0"), (30, "0"), (2, "SOLID"), (70, "1"), (71, "0"), (91, "1")];
|
||||
e.extend([(92, "3"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [("999999999990", "0"), ("1000000000000", "0"), ("1000000000000", "100"), ("999999999990", "100")] {
|
||||
e.extend([(10, x), (20, y)]);
|
||||
}
|
||||
e.extend([(97, "0"), (75, "0"), (76, "1"), (98, "0")]);
|
||||
e.extend([(450, "1"), (451, "0"), (452, "0"), (453, "2"), (460, "0"), (461, "0")]);
|
||||
e.extend([(462, "0"), (463, "0"), (63, "1"), (463, "1"), (63, "5"), (470, "SPHERICAL")]);
|
||||
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
assert_eq!(gradient_of(area).gradient.kind, vectorcraft_color::GradientKind::Radial);
|
||||
assert_eq!(bounds(area).width().round(), 10.0);
|
||||
}
|
||||
|
||||
/// [`with_door`] with a dashed linetype `DASHED` in the drawing.
|
||||
fn with_dashed_door(block_art: &[(i32, &'static str)], inserts: &[(i32, &'static str)]) -> Vec<u8> {
|
||||
let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Door"), (70, "0"), (10, "5"), (20, "5"), (3, "Door")];
|
||||
blocks.extend_from_slice(block_art);
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let tables = [
|
||||
(0, "TABLE"),
|
||||
(2, "LTYPE"),
|
||||
(0, "LTYPE"),
|
||||
(2, "DASHED"),
|
||||
(73, "2"),
|
||||
(40, "15"),
|
||||
(49, "10"),
|
||||
(49, "-5"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "TABLE"),
|
||||
(2, "LAYER"),
|
||||
(0, "LAYER"),
|
||||
(2, "Doors"),
|
||||
(70, "0"),
|
||||
(62, "5"),
|
||||
(6, "CONTINUOUS"),
|
||||
(0, "ENDTAB"),
|
||||
];
|
||||
drawing(&[], &tables, &blocks, inserts)
|
||||
}
|
||||
|
||||
/// Whether `n` or any object inside it has a dashed stroke.
|
||||
fn dashed(n: &Node) -> bool {
|
||||
n.appearance.stroke().is_some_and(|s| s.dash.is_some()) || n.children().is_some_and(|c| c.iter().any(|c| dashed(c)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_pattern_hatches_ignore_the_inserts_linetype() {
|
||||
let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")];
|
||||
// Pattern lines draw without a linetype: inserts of other colors share one symbol.
|
||||
let mut lines = pattern_hatch("BYBLOCK", &[]);
|
||||
lines.splice(1..1, [(8, "Doors"), (370, "25")]);
|
||||
let r = open(&with_door(&lines, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.document.symbols.len(), 1);
|
||||
// A pattern hatch drawn as its boundary strokes it in the insert's linetype.
|
||||
let mut boundary = hatch("0");
|
||||
boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]);
|
||||
let r = open(&with_door(&boundary, &inserts), &points());
|
||||
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
|
||||
|
||||
// Inserts of one color, one dashed and one continuous.
|
||||
let inserts =
|
||||
[(0, "INSERT"), (2, "Door"), (6, "DASHED"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (6, "CONTINUOUS"), (10, "200"), (20, "0")];
|
||||
let r = open(&with_dashed_door(&lines, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [symbol] = &r.document.symbols[..] else { panic!("one symbol for both linetypes") };
|
||||
assert!(!dashed(&symbol.art), "pattern lines carry no linetype dashes");
|
||||
// The boundary drawn for each insert takes that insert's linetype.
|
||||
let r = open(&with_dashed_door(&boundary, &inserts), &points());
|
||||
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
|
||||
let looks: Vec<bool> = leaves(&r.document)
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { panic!("{:?}", n.kind) };
|
||||
dashed(&r.document.symbols.iter().find(|s| s.name == *symbol).unwrap().art)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(looks, [true, false], "the dashed insert's boundary is dashed, the continuous one's is not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_declaring_many_absent_source_handles_parses_quickly() {
|
||||
let base = hatch("1");
|
||||
|
||||
@@ -77,9 +77,24 @@ fn a_damaged_dwg_is_an_error_that_names_dwg() {
|
||||
let e = import(&cut, &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
assert!(info(&cut).is_err());
|
||||
// An R1.x or R2.x drawing is refused without reading it.
|
||||
for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] {
|
||||
// A drawing of a version the DWG reader skips is refused by its version, without reading it.
|
||||
for (old, name) in [
|
||||
(&b"AC1.50\x00\x00\x00\x00"[..], "DWG R2.05 (AC1.50)"),
|
||||
(b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"),
|
||||
(b"AC1004\x00\x00\x00\x00", "DWG R9 (AC1004)"),
|
||||
] {
|
||||
let e = import(old, &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}");
|
||||
assert!(e.starts_with(&format!("this drawing is {name},")) && e.contains("DXF"), "{e}");
|
||||
assert_eq!(info(old).unwrap_err(), e);
|
||||
}
|
||||
assert_eq!(import(b"AC1018", &ImportOptions::default()).unwrap_err(), "DWG: the file is cut short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_drawing_with_an_ad_version_code_comes_in_as_its_ac_one_does() {
|
||||
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
|
||||
let ac = dwg();
|
||||
let mut ad = ac.clone();
|
||||
ad[1] = b'D';
|
||||
assert_eq!(art(&import(&ad, &o).unwrap().document), art(&import(&ac, &o).unwrap().document));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,620 @@
|
||||
//! Raster images: an IMAGE comes in as an image linked to the file its IMAGEDEF names, placed as
|
||||
//! its corner and pixel vectors say and clipped by its clip boundary; images the export wrote come
|
||||
//! back where they were.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Unit};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use super::*;
|
||||
use crate::{DxfOptions, DxfVersion};
|
||||
|
||||
/// A DXF file of `entities` and `objects` (each a run of pairs).
|
||||
fn drawing(entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec<u8> {
|
||||
with_blocks(&[], entities, objects)
|
||||
}
|
||||
|
||||
/// A DXF file of `blocks`, `entities` and `objects` (each a run of pairs).
|
||||
fn with_blocks(blocks: &[(i32, &str)], entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec<u8> {
|
||||
let mut p: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")];
|
||||
p.extend([(0, "SECTION"), (2, "BLOCKS")]);
|
||||
p.extend_from_slice(blocks);
|
||||
p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES")]);
|
||||
p.extend_from_slice(entities);
|
||||
p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]);
|
||||
p.extend_from_slice(objects);
|
||||
p.extend([(0, "ENDSEC"), (0, "EOF")]);
|
||||
p.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
/// An IMAGEDEF with handle `handle` naming `file`, 30 × 10 pixels.
|
||||
fn def<'a>(handle: &'a str, file: &'a str) -> Vec<(i32, &'a str)> {
|
||||
vec![(0, "IMAGEDEF"), (5, handle), (100, "AcDbRasterImageDef"), (1, file), (10, "30"), (20, "10")]
|
||||
}
|
||||
|
||||
/// An IMAGE of IMAGEDEF `def` with its lower-left corner at (10, 20) and 2-unit pixels, `size`
|
||||
/// pixels (none given: `None`), followed by `more` groups.
|
||||
fn image<'a>(def: &'a str, size: Option<(&'a str, &'a str)>, more: &[(i32, &'a str)]) -> Vec<(i32, &'a str)> {
|
||||
let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "0"), (22, "2")];
|
||||
if let Some((w, h)) = size {
|
||||
e.extend([(13, w), (23, h)]);
|
||||
}
|
||||
e.push((340, def));
|
||||
e.extend_from_slice(more);
|
||||
e
|
||||
}
|
||||
|
||||
/// Points at 1:1, not centred: drawing (x, y) lands at document (x, artboard height − y).
|
||||
fn points() -> ImportOptions {
|
||||
ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }
|
||||
}
|
||||
|
||||
fn nodes(doc: &Document) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| out.push(n.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
fn images(doc: &Document) -> Vec<ImageObject> {
|
||||
nodes(doc)
|
||||
.into_iter()
|
||||
.filter_map(|n| match n.kind {
|
||||
NodeKind::Image(im) => Some(*im),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where image `im`'s pixel corner `(x, y)` lands.
|
||||
fn at(im: &ImageObject, x: f64, y: f64) -> Point {
|
||||
im.xf * Point::new(x, y)
|
||||
}
|
||||
|
||||
fn near(a: Point, b: Point) -> bool {
|
||||
a.distance(b) < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_comes_in_linked_to_its_file_with_its_top_left_pixel_at_the_top_left() {
|
||||
let bytes = drawing(&image("1F", Some(("30", "10")), &[]), &def("1F", r"photos\scan.png"));
|
||||
let r = import(&bytes, &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings);
|
||||
let doc = &r.document;
|
||||
assert_eq!(doc.layers.iter().filter_map(|l| l.name.as_deref()).collect::<Vec<_>>(), ["Photos"]);
|
||||
let ims = images(doc);
|
||||
assert_eq!(ims.len(), 1);
|
||||
let im = &ims[0];
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(r"photos\scan.png"));
|
||||
assert_eq!((im.width, im.height), (30, 10));
|
||||
// The drawing's 60 × 20 units from (10, 20): y up there, y down here.
|
||||
let h = doc.artboards[0].rect.height();
|
||||
assert!(near(at(im, 0.0, 0.0), Point::new(10.0, h - 40.0)), "{:?}", at(im, 0.0, 0.0));
|
||||
assert!(near(at(im, 30.0, 10.0), Point::new(70.0, h - 20.0)), "{:?}", at(im, 30.0, 10.0));
|
||||
// Until its file is read it shows the placeholder.
|
||||
assert!(doc.images.get(&im.key).is_some_and(ImageBlob::is_proxy));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_without_its_own_size_takes_its_file_s_and_two_images_of_one_file_share_its_data() {
|
||||
let mut e = image("1F", None, &[]);
|
||||
e.extend(image("1F", Some(("30", "10")), &[]));
|
||||
let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
let ims = images(&doc);
|
||||
assert_eq!(ims.iter().map(|im| (im.width, im.height)).collect::<Vec<_>>(), [(30, 10), (30, 10)]);
|
||||
assert_eq!(ims[0].key, ims[1].key);
|
||||
assert_eq!(doc.images.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() {
|
||||
// Pixels 5 to 14 across and 2 to 6 down: a 20 × 10 unit window.
|
||||
let part = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]);
|
||||
let r = import(&drawing(&part, &def("1F", "scan.png")), &points()).unwrap();
|
||||
let all = nodes(&r.document);
|
||||
let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group");
|
||||
let children = group.children().unwrap();
|
||||
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert!(matches!(children[1].kind, NodeKind::Image(_)));
|
||||
let h = r.document.artboards[0].rect.height();
|
||||
let clip = children[0].geometric_bounds().unwrap();
|
||||
// x 10 + 2·5 to 10 + 2·15; y down from the image's top (20 + 2·10) 2·2 to 2·7.
|
||||
let want = Rect::new(20.0, h - 40.0 + 4.0, 40.0, h - 40.0 + 14.0);
|
||||
assert!([(clip.x0, want.x0), (clip.y0, want.y0), (clip.x1, want.x1), (clip.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-9), "{clip:?}");
|
||||
// The default boundary, the whole image, makes no group; clipping off ignores a boundary.
|
||||
let whole = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "9.5")]);
|
||||
let off = image("1F", Some(("30", "10")), &[(280, "0"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]);
|
||||
for e in [whole, off] {
|
||||
let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
assert!(!nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })), "no clip group");
|
||||
assert_eq!(images(&doc).len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_boundary_with_a_repeated_corner_still_clips_the_image() {
|
||||
let boundary = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[
|
||||
(280, "1"),
|
||||
(71, "2"),
|
||||
(91, "4"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "29.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "-0.5"),
|
||||
(24, "9.5"),
|
||||
],
|
||||
);
|
||||
let doc = import(&drawing(&boundary, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
let all = nodes(&doc);
|
||||
let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group");
|
||||
let children = group.children().unwrap();
|
||||
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert!(matches!(children[1].kind, NodeKind::Image(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_display_flags_control_clipping_only_when_present() {
|
||||
for (display, clipping, clipped) in [(None, "1", true), (Some("9"), "1", false), (Some("13"), "1", true), (Some("13"), "0", false)] {
|
||||
let mut boundary = vec![(280, clipping), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")];
|
||||
if let Some(flags) = display {
|
||||
boundary.push((70, flags));
|
||||
}
|
||||
let e = image("1F", Some(("30", "10")), &boundary);
|
||||
let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), 1);
|
||||
assert_eq!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), clipped, "{display:?}, {clipping}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_requested_opaque_warn_once_and_other_images_do_not() {
|
||||
for (display, opaque) in [(None, false), (Some("9"), false), (Some("1"), true), (Some("5"), true)] {
|
||||
let flags: Vec<_> = display.map(|flags| (70, flags)).into_iter().collect();
|
||||
let mut e = image("1F", Some(("30", "10")), &flags);
|
||||
e.extend(image("1F", Some(("30", "10")), &flags));
|
||||
let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), 2);
|
||||
let warnings: Vec<_> = r.warnings.iter().filter(|w| w.contains("opaque") && w.contains("transparency")).collect();
|
||||
assert_eq!(warnings.len(), usize::from(opaque), "{display:?}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polygon_clip_keeps_its_points_and_an_inverted_clip_shows_the_whole_image_with_a_warning() {
|
||||
let tri = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")],
|
||||
);
|
||||
let doc = import(&drawing(&tri, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
let clip = nodes(&doc).into_iter().find(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).expect("a clip path");
|
||||
let NodeKind::Path { path, .. } = &clip.kind else { panic!("not a path") };
|
||||
let im = &images(&doc)[0];
|
||||
let mut corners: Vec<Point> = path.to_bezpath().elements().iter().filter_map(|el| el.end_point()).collect();
|
||||
// The path may draw its closing edge as a line back to the start.
|
||||
if corners.len() > 1 && corners.first() == corners.last() {
|
||||
corners.pop();
|
||||
}
|
||||
assert_eq!(corners.len(), 3, "{corners:?}");
|
||||
for (c, (x, y)) in corners.iter().zip([(0.0, 0.0), (30.0, 0.0), (0.0, 10.0)]) {
|
||||
assert!(near(*c, at(im, x, y)), "{c:?}");
|
||||
}
|
||||
// The same triangle closed by repeating its first point still clips: three corners of the
|
||||
// image's box and a repeat are not the box.
|
||||
let closed = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[
|
||||
(280, "1"),
|
||||
(71, "2"),
|
||||
(91, "4"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "29.5"),
|
||||
(24, "-0.5"),
|
||||
(14, "29.5"),
|
||||
(24, "9.5"),
|
||||
(14, "-0.5"),
|
||||
(24, "-0.5"),
|
||||
],
|
||||
);
|
||||
let doc = import(&drawing(&closed, &def("1F", "scan.png")), &points()).unwrap().document;
|
||||
assert!(nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), "a clip group");
|
||||
// A clip point far out of range leaves the image out.
|
||||
let far = image(
|
||||
"1F",
|
||||
Some(("30", "10")),
|
||||
&[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")],
|
||||
);
|
||||
let r = import(&drawing(&far, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(images(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let mut inverted = tri.clone();
|
||||
inverted.push((290, "1"));
|
||||
let r = import(&drawing(&inverted, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("inverted image clips")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_without_usable_file_references_do_not_expand_the_artboard() {
|
||||
for objects in [def("1F", "scan.png"), def("2A", " ")] {
|
||||
let mut far = image("2A", Some(("30", "10")), &[]);
|
||||
for (code, value) in &mut far {
|
||||
if *code == 10 || *code == 20 {
|
||||
*value = "100000";
|
||||
}
|
||||
}
|
||||
let mut entities = vec![(0, "LINE"), (10, "0"), (20, "0"), (11, "100"), (21, "50")];
|
||||
entities.extend(far);
|
||||
let r = import(&drawing(&entities, &objects), &points()).unwrap();
|
||||
assert!(images(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("name no image file")), "{:?}", r.warnings);
|
||||
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
let board = r.document.artboards[0].rect;
|
||||
assert!(board.width() < 1000.0 && board.height() < 1000.0, "{board:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Entities, objects, and the warning they give.
|
||||
type Case<'a> = (Vec<(i32, &'a str)>, Vec<(i32, &'a str)>, &'a str);
|
||||
|
||||
#[test]
|
||||
fn images_that_name_no_file_or_have_no_size_or_area_are_left_out_with_warnings() {
|
||||
let cases: [Case; 4] = [
|
||||
(image("2A", Some(("30", "10")), &[]), def("1F", "scan.png"), "name no image file"),
|
||||
(image("1F", Some(("30", "10")), &[]), def("1F", " "), "name no image file"),
|
||||
(image("1F", Some(("0", "10")), &[]), vec![(0, "IMAGEDEF"), (5, "1F"), (1, "scan.png")], "no size in pixels"),
|
||||
(
|
||||
vec![(0, "IMAGE"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "4"), (22, "0"), (13, "30"), (23, "10"), (340, "1F")],
|
||||
def("1F", "scan.png"),
|
||||
"no width or height",
|
||||
),
|
||||
];
|
||||
for (e, o, why) in cases {
|
||||
let r = import(&drawing(&e, &o), &points()).unwrap();
|
||||
assert!(images(&r.document).is_empty(), "{why}");
|
||||
assert!(r.warnings.iter().any(|w| w.contains(why)), "{why}: {:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "an IMAGE is not an unknown entity: {:?}", r.warnings);
|
||||
}
|
||||
// Brightness, contrast and fade are noted.
|
||||
let faded = image("1F", Some(("30", "10")), &[(283, "40")]);
|
||||
let r = import(&drawing(&faded, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), 1);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("fade")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_whose_show_image_flag_is_off_is_hidden() {
|
||||
let o = def("1F", "scan.png");
|
||||
for (flags, shown) in [("3", 1), ("1", 1), ("2", 0), ("0", 0)] {
|
||||
let r = import(&drawing(&image("1F", Some(("30", "10")), &[(70, flags)]), &o), &points()).unwrap();
|
||||
assert_eq!(images(&r.document).len(), shown, "group 70 = {flags}");
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "{:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_on_the_canvas() {
|
||||
// The block's image sits 10,000,000 units out, and the insert moves it back next to the origin.
|
||||
let tri = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
let mut far = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10000010"), (20, "20")];
|
||||
far.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
|
||||
let head = far.len();
|
||||
far.extend_from_slice(&tri);
|
||||
let block_of = |image: &[(i32, &'static str)]| {
|
||||
let mut block = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")];
|
||||
block.extend_from_slice(image);
|
||||
block.push((0, "ENDBLK"));
|
||||
block
|
||||
};
|
||||
let insert = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-10000000"), (20, "0")];
|
||||
let r = import(&with_blocks(&block_of(&far), &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let art = &r.document.symbols.first().expect("a symbol").art;
|
||||
assert!(matches!(art.kind, NodeKind::Group { clip: true, .. }), "{:?}", art.kind);
|
||||
// A clip point far from its own image in the block still leaves the image out.
|
||||
let mut farther = far[..head].to_vec();
|
||||
farther.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
|
||||
let r = import(&with_blocks(&block_of(&farther), &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
// A wide image whose corner is far out, cropped to a part near the origin, comes in too.
|
||||
let mut wide = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "-5000000"), (20, "0")];
|
||||
wide.extend([(11, "1000"), (21, "0"), (12, "0"), (22, "1000"), (13, "10000"), (23, "10"), (340, "1F")]);
|
||||
wide.extend([(280, "1"), (71, "2"), (91, "3"), (14, "5200"), (24, "0"), (14, "5400"), (24, "0"), (14, "5200"), (24, "5")]);
|
||||
let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")];
|
||||
let r = import(&with_blocks(&block_of(&wide), &at_origin, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
assert!(r.document.symbols.first().is_some_and(|s| matches!(s.art.kind, NodeKind::Group { clip: true, .. })));
|
||||
// A block's image near the origin whose clip reaches out of range where the insert places it
|
||||
// is left out with that warning, and the block's other art stays.
|
||||
let mut reaching = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20")];
|
||||
reaching.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
|
||||
reaching.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
|
||||
reaching.extend([(0, "LINE"), (8, "Photos"), (10, "0"), (20, "0"), (11, "50"), (21, "50")]);
|
||||
let r = import(&with_blocks(&block_of(&reaching), &at_origin, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let placed = nodes(&r.document);
|
||||
assert!(!placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Image(_))));
|
||||
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's line");
|
||||
// The block's symbol has no instance left, so it is not kept with the image it holds.
|
||||
assert!(r.document.symbols.is_empty(), "{:?}", r.document.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_that_only_placements_drawn_as_art_use_is_not_charged_twice() {
|
||||
// Block B holds a 600,000-point polyline and an image whose clip reaches out of range where an
|
||||
// insert at the origin places it, so that insert draws B's art instead of an instance.
|
||||
let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())];
|
||||
owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]);
|
||||
owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]);
|
||||
owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]);
|
||||
owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into())]);
|
||||
owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]);
|
||||
for i in 0..600_000 {
|
||||
owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]);
|
||||
}
|
||||
owned.push((0, "ENDBLK".into()));
|
||||
let block: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")];
|
||||
let r = import(&with_blocks(&block, &at_origin, &def("1F", "scan.png")), &points()).unwrap();
|
||||
// 1,200,000 points if the unused symbol stayed charged: past the tests' limit of 1,000,000.
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's polyline");
|
||||
assert!(r.document.symbols.is_empty());
|
||||
// A second insert that places B in range makes the symbol again, which is charged again: its
|
||||
// polyline no longer fits, and the first insert's stays.
|
||||
let both = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0"), (0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-2000000"), (20, "0")];
|
||||
let r = import(&with_blocks(&block, &both, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
let placed = nodes(&r.document);
|
||||
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the first insert's polyline");
|
||||
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the second insert's instance");
|
||||
assert_eq!(r.document.symbols.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_that_only_a_removed_symbol_placed_is_removed_with_it() {
|
||||
// Block B holds a 600,000-point polyline and an image whose clip reaches out of range where the
|
||||
// drawing's insert of block A, which places B, puts it. That insert draws A's art and removes
|
||||
// A's symbol; B's symbol, which only A's art placed, goes too, so drawing B's art fits.
|
||||
let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())];
|
||||
owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]);
|
||||
for i in 0..600_000 {
|
||||
owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]);
|
||||
}
|
||||
owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]);
|
||||
owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]);
|
||||
owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]);
|
||||
owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into()), (0, "ENDBLK".into())]);
|
||||
owned.extend([(0, "BLOCK".into()), (2, "A".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]);
|
||||
owned.extend([(0, "INSERT".into()), (8, "Photos".into()), (2, "B".into()), (10, "0".into()), (20, "0".into()), (0, "ENDBLK".into())]);
|
||||
let blocks: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0")];
|
||||
let r = import(&with_blocks(&blocks, &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "B's polyline");
|
||||
assert!(r.document.symbols.is_empty());
|
||||
}
|
||||
|
||||
/// Block B holds an image clipped by a triangle with a corner at (`far`, −0.5) in pixel space, and
|
||||
/// block A places B by `inner` beside an image of its own clipped near it; the drawing places A
|
||||
/// at the origin scaled by `outer`.
|
||||
fn nested(far: &'static str, inner: &[(i32, &'static str)], outer: &'static str) -> Vec<u8> {
|
||||
let clipped = |x: &'static str, corner: &'static str| {
|
||||
let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, x), (20, "20")];
|
||||
e.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
|
||||
e.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, corner), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
|
||||
e
|
||||
};
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")];
|
||||
blocks.extend(clipped("10", far));
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "A"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
blocks.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]);
|
||||
blocks.extend_from_slice(inner);
|
||||
blocks.extend(clipped("100", "29.5"));
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0"), (41, outer), (42, outer)];
|
||||
with_blocks(&blocks, &insert, &def("1F", "scan.png"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_s_clip_point_beyond_any_usable_range_leaves_its_image_out_even_where_inserts_scale_it_back() {
|
||||
// B's clip corner is 2e19 units out in its own space, and two inserts at the smallest scale
|
||||
// would bring it back next to the origin.
|
||||
let r = import(&nested("1e19", &[(41, "1e-12"), (42, "1e-12")], "1e-12"), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
let mut held = 0;
|
||||
for s in &r.document.symbols {
|
||||
s.art.walk(&mut |n: &Node| held += usize::from(matches!(n.kind, NodeKind::Image(_))));
|
||||
}
|
||||
assert_eq!(held + images(&r.document).len(), 1, "A's own image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_reach_placed_by_an_overflowing_transform_is_unbounded() {
|
||||
use super::build::placed_reach;
|
||||
let out = |b: Rect| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite());
|
||||
// Across, the terms of every corner overflow with opposite signs to NaN, which a union with
|
||||
// another symbol's reach would drop; the reach is unbounded instead.
|
||||
let h = 1e300;
|
||||
let xf = Affine::new([h, 1.0, -h, 1.0, 0.0, 0.0]);
|
||||
let r = Rect::new(1e10, 1e10, 2e10, 2e10);
|
||||
let near = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
let whole = placed_reach(xf, r);
|
||||
assert!(out(whole.union(near)), "{whole:?}");
|
||||
// An unbounded reach stays unbounded wherever it is placed.
|
||||
assert!(out(placed_reach(Affine::scale(1e-12), whole).union(near)));
|
||||
assert!(out(placed_reach(Affine::IDENTITY, whole).union(near)));
|
||||
// A placement that stays finite is the box of the placed corners.
|
||||
let b = placed_reach(Affine::new([0.0, 1.0, -1.0, 0.0, 5.0, 0.0]), near);
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (-5.0, 0.0, 5.0, 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_paths_count_against_the_path_point_limit() {
|
||||
// A 1,000-point clip in an anonymous block placed 1,100 times: 1,001,000 path elements, past
|
||||
// the tests' limit of 1,000,000.
|
||||
let mut clip: Vec<(i32, String)> = vec![(280, "1".into()), (71, "2".into()), (91, "1000".into())];
|
||||
for i in 0..1000 {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 1000.0;
|
||||
clip.extend([(14, format!("{}", 14.5 + 10.0 * a.cos())), (24, format!("{}", 4.5 + 4.0 * a.sin()))]);
|
||||
}
|
||||
let clip: Vec<(i32, &str)> = clip.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
let mut block = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
block.extend(image("1F", Some(("30", "10")), &clip));
|
||||
block.push((0, "ENDBLK"));
|
||||
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "1100"), (44, "100")];
|
||||
let r = import(&with_blocks(&block, &insert, &def("1F", "scan.png")), &points()).unwrap();
|
||||
let clips = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).count();
|
||||
assert!((900..1000).contains(&clips), "{clips} clip paths");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_drawn_as_art_gets_back_its_unused_symbol_s_objects_at_the_object_limit() {
|
||||
// Block B holds a line and an image whose clip reaches out of range where B's insert places
|
||||
// it: 4 objects as a symbol. 99,996 lines before it leave exactly room for that symbol under
|
||||
// the tests' limit of 100,000 objects, so its insert draws B's art in the room the unused
|
||||
// symbol gives back.
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
|
||||
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
blocks.extend(image("1F", Some(("30", "10")), &reaching));
|
||||
blocks.push((0, "ENDBLK"));
|
||||
// An insert makes at most 10,000 copies: nine of 100 × 100 and one of 84 × 119.
|
||||
let mut entities = vec![];
|
||||
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("84", "119")]) {
|
||||
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
|
||||
}
|
||||
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]);
|
||||
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
|
||||
let lines = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).count();
|
||||
assert_eq!(lines, 99_997, "the lines and B's line");
|
||||
assert!(r.document.symbols.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_drawn_as_art_past_the_object_limit_stop_without_looking_at_the_block() {
|
||||
// Block B: 200 lines and an image whose clip reaches out of range unless its copy sits left of
|
||||
// the origin. 99,796 lines, B's symbol and the first copy's instance fill the tests' limit of
|
||||
// 100,000 objects; the next 9,999 copies would each look at B's 201 items, past the tests'
|
||||
// block-work limit of 1,000,000.
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
for _ in 0..200 {
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
|
||||
}
|
||||
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
blocks.extend(image("1F", Some(("30", "10")), &reaching));
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let mut entities = vec![];
|
||||
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("79", "124")]) {
|
||||
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
|
||||
}
|
||||
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-35"), (20, "0"), (70, "10000"), (44, "10")]);
|
||||
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_of_a_symbol_taken_out_at_the_object_limit_are_not_drawn_again() {
|
||||
// Block B: an image whose clip reaches out of range only for the first copy, and 200 lines.
|
||||
// 99,800 lines and the first copy, drawn as art in the room its unused symbol gives back,
|
||||
// fill the tests' limit of 100,000 objects; each of the next 9,999 copies would draw the
|
||||
// symbol again from B's 201 items, past the tests' block-work limit of 1,000,000.
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
|
||||
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
|
||||
blocks.extend(image("1F", Some(("30", "10")), &reaching));
|
||||
for _ in 0..200 {
|
||||
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
|
||||
}
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let mut entities = vec![];
|
||||
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("98", "100")]) {
|
||||
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
|
||||
}
|
||||
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-25"), (20, "0"), (70, "10000"), (44, "-10")]);
|
||||
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A document with a 4 × 2 pixel image, 5 pt pixels, its top-left corner at (10, 20).
|
||||
fn image_doc() -> Document {
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[0u8, 0, 255, 255].repeat(8),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let layer = d.add_layer(Some("Photos"));
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
width: 4,
|
||||
height: 2,
|
||||
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
|
||||
d
|
||||
}
|
||||
|
||||
/// Import `bytes`, written from [`image_doc`], and check its one image: linked to `name`, the file
|
||||
/// the export wrote, and the size and way up it had.
|
||||
fn written_and_read(bytes: &[u8], name: &str) {
|
||||
let doc = import(bytes, &points()).unwrap().document;
|
||||
let ims = images(&doc);
|
||||
assert_eq!(ims.len(), 1, "{:?}", nodes(&doc).iter().map(|n| &n.kind).collect::<Vec<_>>());
|
||||
let im = &ims[0];
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(name));
|
||||
assert_eq!((im.width, im.height), (4, 2));
|
||||
// 20 × 10 pt with the top-left pixel at the top-left, as it was.
|
||||
let (tl, br) = (at(im, 0.0, 0.0), at(im, 4.0, 2.0));
|
||||
assert!((br.x - tl.x - 20.0).abs() < 1e-6 && (br.y - tl.y - 10.0).abs() < 1e-6, "{tl:?} {br:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_the_export_wrote_comes_back_linked_to_the_file_it_wrote() {
|
||||
let d = image_doc();
|
||||
let out = crate::export(&d, &DxfOptions { region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }).unwrap();
|
||||
assert_eq!(out.images.len(), 1);
|
||||
written_and_read(&out.bytes, &out.images[0].name);
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn an_image_in_a_dwg_drawing_comes_in_as_in_its_dxf() {
|
||||
let d = image_doc();
|
||||
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() };
|
||||
let out = crate::export(&d, &o).unwrap();
|
||||
crate::dwg::allow_in_process();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&out.bytes, "AC1018").unwrap();
|
||||
written_and_read(&dwg, &out.images[0].name);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ spine-count = []
|
||||
symbol-read-count = []
|
||||
# `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only).
|
||||
locked-artboard-count = []
|
||||
# `vectorcraft_doc::swatches::swatch_scans` for other crates' tests (dev-dependencies only).
|
||||
swatch-scans = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
@@ -39,3 +41,6 @@ flate2 = { workspace = true }
|
||||
zune-jpeg = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# The counter vectorcraft-ui-egui's tests turn on, also when this crate is tested without
|
||||
# vectorcraft-ui-egui (`cargo xtask ci shard`).
|
||||
vectorcraft-doc = { path = ".", features = ["swatch-scans"] }
|
||||
|
||||
@@ -119,7 +119,7 @@ pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::changed_nodes;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies};
|
||||
pub use orient::OrientedBox;
|
||||
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
|
||||
pub use perspective::PerspectiveAttachment;
|
||||
|
||||
@@ -25,7 +25,9 @@ mod opacity;
|
||||
mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use attributes::{
|
||||
ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use changed::COUNTERPART_LOOKUPS;
|
||||
pub use changed::changed_nodes;
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::live_shape::LiveShape;
|
||||
use super::{Deserialize, Node, Serialize};
|
||||
|
||||
/// Window → Attributes: an object's settings that don't change how it prints.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ObjectAttributes {
|
||||
/// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]).
|
||||
@@ -45,6 +45,34 @@ pub struct ObjectAttributes {
|
||||
pub tags: Vec<ObjectTag>,
|
||||
}
|
||||
|
||||
impl Clone for ObjectAttributes {
|
||||
fn clone(&self) -> Self {
|
||||
ATTRIBUTE_COPIES.set(ATTRIBUTE_COPIES.get().saturating_add(1));
|
||||
Self {
|
||||
show_center: self.show_center,
|
||||
image_map: self.image_map,
|
||||
url: self.url.clone(),
|
||||
note: self.note.clone(),
|
||||
data: self.data.clone(),
|
||||
events: self.events.clone(),
|
||||
classes: self.classes.clone(),
|
||||
foreign: self.foreign.clone(),
|
||||
tags: self.tags.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`attribute_copies`] of this thread.
|
||||
static ATTRIBUTE_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times an object's [`ObjectAttributes`] have been copied on this thread. Tags can hold
|
||||
/// up to [`MAX_TAGS`] values of [`MAX_TAG_TEXT`] bytes each, so each copy can cost megabytes.
|
||||
pub fn attribute_copies() -> u64 {
|
||||
ATTRIBUTE_COPIES.get()
|
||||
}
|
||||
|
||||
/// The most tags one object has.
|
||||
pub const MAX_TAGS: usize = 64;
|
||||
|
||||
|
||||
@@ -16,6 +16,23 @@ use vectorcraft_color::{Color, Paint, Swatch, tint_percent};
|
||||
|
||||
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
thread_local! {
|
||||
/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by
|
||||
/// name on this thread.
|
||||
static SWATCH_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by
|
||||
/// name on this thread, for other crates' tests that count how much work their lookups by name do (the
|
||||
/// `swatch-scans` feature, dev-dependencies only). A lookup compares the swatches up to the one it finds, or all of
|
||||
/// them for a name the document does not hold.
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
#[doc(hidden)]
|
||||
pub fn swatch_scans() -> usize {
|
||||
SWATCH_SCANS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Every swatch: the ungrouped ones first, then each colour group's in order.
|
||||
pub fn swatches_iter(&self) -> impl Iterator<Item = &Swatch> {
|
||||
@@ -27,7 +44,12 @@ impl Document {
|
||||
/// Swatch `name`, the built-in Registration swatch ([`vectorcraft_color::swatch::registration`])
|
||||
/// included.
|
||||
pub fn swatch(&self, name: &str) -> Option<&Swatch> {
|
||||
self.swatches_iter().find(|s| s.name == name).or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
|
||||
let found = self.swatches_iter().find(|s| {
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
SWATCH_SCANS.with(|c| c.set(c.get() + 1));
|
||||
s.name == name
|
||||
});
|
||||
found.or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
|
||||
}
|
||||
pub fn swatch_mut(&mut self, name: &str) -> Option<&mut Swatch> {
|
||||
self.swatches_iter_mut().find(|s| s.name == name)
|
||||
@@ -74,7 +96,12 @@ impl Document {
|
||||
}
|
||||
/// Is `name` used by a swatch or a colour group (they share one namespace)?
|
||||
pub fn swatch_name_taken(&self, name: &str) -> bool {
|
||||
self.swatch(name).is_some() || self.swatch_groups.iter().any(|g| g.name == name)
|
||||
self.swatch(name).is_some()
|
||||
|| self.swatch_groups.iter().any(|g| {
|
||||
#[cfg(any(test, feature = "swatch-scans"))]
|
||||
SWATCH_SCANS.with(|c| c.set(c.get() + 1));
|
||||
g.name == name
|
||||
})
|
||||
}
|
||||
/// `base`, or the first of "base 2", "base 3"… no swatch or colour group uses.
|
||||
pub fn free_swatch_name(&self, base: &str) -> String {
|
||||
|
||||
@@ -1072,8 +1072,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
members_meshes(fx, &shapes, b, options, total, limit)
|
||||
}
|
||||
|
||||
/// The meshes of the members `shapes` of a group with Revolve `fx`, each swept about the axis of `b`
|
||||
/// with `options` and painted with its surface's fill or stroke at its member's opacity, in order.
|
||||
/// Members with no fill or stroke are left out. Each mesh is counted against `limit`
|
||||
/// ([`crate::solids::keep_mesh`]) before the next is built.
|
||||
fn members_meshes(
|
||||
fx: &Effect,
|
||||
shapes: &[Profile],
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
total: &mut usize,
|
||||
limit: usize,
|
||||
) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
// The graphics go on the side of the member with the longest profile, as the canvas draws them.
|
||||
let longest = if options.map_surface { graphics_member(&shapes, b, options) } else { None };
|
||||
let longest = if options.map_surface { graphics_member(shapes, b, options) } else { None };
|
||||
let mut out = vec![];
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
@@ -1099,9 +1114,18 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil
|
||||
if !has_revolve(n) {
|
||||
return None;
|
||||
}
|
||||
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
|
||||
let n = &*match resolve_for(doc, n, "Revolve", false) {
|
||||
Ok(n) => n,
|
||||
Err(error) => {
|
||||
// Art that has to be resolved draws only the Revolve on the object itself.
|
||||
if n.appearance.effects.iter().find(|e| e.visible && is_revolve(&e.id)).is_some_and(crate::renders_image) {
|
||||
warning.get_or_insert(error);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if is_container(n) {
|
||||
return group_art(doc, n, expand, check_only, warning);
|
||||
return group_art(doc, n, expand, build, warning);
|
||||
}
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
@@ -1115,37 +1139,8 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
// Rendered, the surface's image, with the shadows of every light on the surface and on the
|
||||
// shadow plane; the shaded faces when it can't be made, and for vector measurements.
|
||||
let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| {
|
||||
let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) {
|
||||
Err(crate::solids::rendered::PATHS_ONLY.into())
|
||||
} else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let options = rule_options(fx, rule);
|
||||
surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| {
|
||||
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
|
||||
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) {
|
||||
Some(shadow) => {
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let faces = cast_surface(&mut caster, &path, b, options, None)?;
|
||||
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces])
|
||||
}
|
||||
None => lighting,
|
||||
};
|
||||
if build == Build::Bounds {
|
||||
crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
|
||||
} else {
|
||||
crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Err(crate::solids::rendered::OPAQUE_ONLY.into())
|
||||
};
|
||||
crate::solids::rendered::reported(result, warning)
|
||||
});
|
||||
let later = n.appearance.effects.get(index + 1..).unwrap_or_default();
|
||||
let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &path, rule, item, warning);
|
||||
if check_only {
|
||||
return None;
|
||||
}
|
||||
@@ -1180,13 +1175,22 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil
|
||||
for (original, item) in originals.into_iter().zip(&items) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let fx = item.effects().get(index)?;
|
||||
if crate::renders_image(fx) {
|
||||
warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into());
|
||||
}
|
||||
if check_only {
|
||||
if check_only && !crate::renders_image(fx) {
|
||||
continue;
|
||||
}
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
// Rendered, this fill's or stroke's surface as an image, under the effects after its
|
||||
// Revolve, with the shadows in the image.
|
||||
let later = item.effects().get(index + 1..).unwrap_or_default();
|
||||
let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &p, rule, item, warning);
|
||||
if check_only {
|
||||
continue;
|
||||
}
|
||||
if let Some(mut image) = image {
|
||||
Arc::make_mut(&mut image).appearance.effects = later.iter().filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
children.push(image);
|
||||
continue;
|
||||
}
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
|
||||
@@ -1218,6 +1222,126 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// What a rendered image is made for: the object `id` it is art of, the document `doc` whose raster
|
||||
/// effects resolution it takes, and the art `build` it goes in.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ImageFor<'a> {
|
||||
doc: Option<&'a Document>,
|
||||
id: NodeId,
|
||||
build: Build,
|
||||
}
|
||||
|
||||
/// The rendered image of Revolve `fx` for `to`, swept from `path` (filled under `rule`) about its
|
||||
/// own bounds and painted with `item`; `later` are the effects after `fx`. `None` when `fx` draws no
|
||||
/// image or `to.build` takes none, and when the image can't be made, with the reason in `warning`:
|
||||
/// the caller then draws the shaded faces.
|
||||
fn surface_image(
|
||||
to: ImageFor,
|
||||
fx: &Effect,
|
||||
later: &[Effect],
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
item: &AppearanceItem,
|
||||
warning: &mut Option<String>,
|
||||
) -> Option<Arc<Node>> {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?;
|
||||
let paint = item.paint();
|
||||
let opacity = item.opacity();
|
||||
let result = if crate::solids::rendered::reshapes_paths_only(later) {
|
||||
Err(crate::solids::rendered::PATHS_ONLY.into())
|
||||
} else if !crate::mapped_graphics(&p).is_empty()
|
||||
|| !crate::solids::rendered::takes([item], false)
|
||||
|| crate::solids::mesh_color(paint, opacity)[3] != 1.0
|
||||
{
|
||||
Err(crate::solids::rendered::OPAQUE_ONLY.into())
|
||||
} else if let Some(b) = path.bounds() {
|
||||
let options = rule_options(fx, rule);
|
||||
surface_meshes(path, rule, b, fx, options, (paint, opacity, 1.0), true).and_then(|meshes| {
|
||||
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
|
||||
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) {
|
||||
Some(shadow) => {
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let faces = cast_surface(&mut caster, path, b, options, None)?;
|
||||
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces])
|
||||
}
|
||||
None => lighting,
|
||||
};
|
||||
image_for(to, &lighting, &meshes, settings)
|
||||
})
|
||||
} else {
|
||||
Err("Revolve requires a shape with at least two anchors".into())
|
||||
};
|
||||
crate::solids::rendered::reported(result, warning)
|
||||
}
|
||||
|
||||
/// [`surface_image`] of the members `shapes` of a group, every member swept about the axis of `b`
|
||||
/// with `options` into one image, as the shaded faces draw them in one order. The shaded faces are
|
||||
/// drawn instead when a member's surface is not an opaque solid color in Normal blending, or when a
|
||||
/// member, or a group it is in, has an opacity below 100%, a blending mode or an opacity mask.
|
||||
fn members_image(
|
||||
to: ImageFor,
|
||||
fx: &Effect,
|
||||
later: &[Effect],
|
||||
shapes: &[Profile],
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
warning: &mut Option<String>,
|
||||
) -> Option<Arc<Node>> {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?;
|
||||
let profiles = shapes.iter().filter(|s| surface_item(&s.items).is_some());
|
||||
let surfaces = profiles.clone().filter_map(|s| surface_item(&s.items));
|
||||
let result = if profiles.clone().next().is_none() {
|
||||
Err("Revolve requires a group holding a shape with a fill or stroke".into())
|
||||
} else if crate::solids::rendered::reshapes_paths_only(later) {
|
||||
Err(crate::solids::rendered::PATHS_ONLY.into())
|
||||
} else if crate::mapped_graphics(&p).is_empty()
|
||||
&& crate::solids::rendered::takes(surfaces, crate::solids::profiles_have_masks(profiles))
|
||||
&& shapes.iter().all(|s| {
|
||||
let Some(item) = surface_item(&s.items) else { return true };
|
||||
crate::solids::mesh_color(item.paint(), item.opacity() * s.opacity)[3] == 1.0
|
||||
})
|
||||
{
|
||||
members_meshes(fx, shapes, b, options, &mut 0, crate::solids::MAX_MESH_TRIANGLES).and_then(|meshes| {
|
||||
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
|
||||
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting) {
|
||||
Some(shadow) => {
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut faces = vec![];
|
||||
for s in shapes {
|
||||
let Some((_, opacity, _)) = surface_item(&s.items).map(paint_of) else { continue };
|
||||
if crate::solids::shadow::casts(opacity * s.opacity) {
|
||||
faces.push(cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, None)?);
|
||||
}
|
||||
}
|
||||
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &faces)
|
||||
}
|
||||
None => lighting,
|
||||
};
|
||||
image_for(to, &lighting, &meshes, settings)
|
||||
})
|
||||
} else {
|
||||
Err(crate::solids::rendered::OPAQUE_ONLY.into())
|
||||
};
|
||||
crate::solids::rendered::reported(result, warning)
|
||||
}
|
||||
|
||||
/// The rendered image of `meshes` lit by `lighting` for `to`: for [`Build::Bounds`] its rectangle
|
||||
/// without pixels, for [`Build::Check`] only the check of its limits.
|
||||
fn image_for(
|
||||
to: ImageFor,
|
||||
lighting: &crate::solids::rendered::Lighting,
|
||||
meshes: &[crate::SolidMesh],
|
||||
settings: crate::solids::wireframe::RenderSettings,
|
||||
) -> Result<Option<Arc<Node>>, String> {
|
||||
if to.build == Build::Bounds {
|
||||
crate::solids::rendered::bounds_art(to.doc, to.id, lighting, meshes, settings)
|
||||
} else {
|
||||
crate::solids::rendered::art(to.doc, to.id, lighting, meshes, settings, to.build == Build::Check)
|
||||
}
|
||||
}
|
||||
|
||||
/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each
|
||||
/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its
|
||||
/// opacity, blending mode and opacity mask, so each applies once, to the faces it holds together.
|
||||
@@ -1338,19 +1462,43 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
|
||||
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
|
||||
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
|
||||
fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option<String>) -> Option<Node> {
|
||||
fn group_art(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option<String>) -> Option<Node> {
|
||||
let check_only = build == Build::Check;
|
||||
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
if crate::renders_image(fx) {
|
||||
warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into());
|
||||
if check_only && !crate::renders_image(fx) {
|
||||
return None;
|
||||
}
|
||||
let prepared = members(n, "Revolve").and_then(|mut shapes| {
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
Ok((shapes, b, options))
|
||||
});
|
||||
let (shapes, b, options) = match prepared {
|
||||
Ok(prepared) => prepared,
|
||||
Err(e) => {
|
||||
// In rendered mode the reason the members can't be revolved is reported, as the reason
|
||||
// an image can't be made is; the canvas then draws the source art.
|
||||
if crate::renders_image(fx) {
|
||||
warning.get_or_insert(e);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// Rendered, one image of every member's surface, with the shadows of every light on the
|
||||
// surfaces and on the shadow plane; the shaded faces when it can't be made.
|
||||
let later = n.appearance.effects.get(index + 1..).unwrap_or_default();
|
||||
let image = members_image(ImageFor { doc, id: n.id, build }, fx, later, &shapes, b, options, warning);
|
||||
if check_only {
|
||||
return None;
|
||||
}
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let b = union_bounds(&shapes)?;
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
if let Some(image) = image {
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children: vec![image], clip: false };
|
||||
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
|
||||
return Some(art);
|
||||
}
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of every member's faces, with no shadow.
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
|
||||
|
||||
@@ -689,7 +689,12 @@ fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> {
|
||||
|
||||
/// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal?
|
||||
pub(crate) fn has_masks(shapes: &[Profile]) -> bool {
|
||||
shapes.iter().any(|s| s.scopes.iter().any(composites))
|
||||
profiles_have_masks(shapes.iter())
|
||||
}
|
||||
|
||||
/// Does any profile sit in a scope with an opacity mask or a blending mode other than Normal?
|
||||
pub(crate) fn profiles_have_masks<'a>(mut shapes: impl Iterator<Item = &'a Profile>) -> bool {
|
||||
shapes.any(|s| s.scopes.iter().any(composites))
|
||||
}
|
||||
|
||||
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
|
||||
@@ -721,7 +726,7 @@ const MAX_MEMBERS: usize = 4096;
|
||||
|
||||
/// The most triangles the meshes of one 3D effect hold together (about 290 MB of corners and
|
||||
/// normals): past it the object is too complex to export.
|
||||
const MAX_MESH_TRIANGLES: usize = 2_000_000;
|
||||
pub(crate) const MAX_MESH_TRIANGLES: usize = 2_000_000;
|
||||
|
||||
/// The most facets of solid colors under colored lights that one 3D effect draws as faces of their
|
||||
/// own, to go in one order with other solids' faces. Each such face is about 16 nodes, a composite
|
||||
|
||||
@@ -35,9 +35,6 @@ pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces.
|
||||
pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead";
|
||||
|
||||
/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image.
|
||||
/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back.
|
||||
pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option<String> {
|
||||
|
||||
@@ -796,7 +796,7 @@ fn rendered_images_are_reused_until_an_input_changes() {
|
||||
/// faces, which apply them; without either, the group draws the image.
|
||||
#[test]
|
||||
fn masked_or_blended_members_draw_the_shaded_faces() {
|
||||
for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] {
|
||||
for id in FOUR {
|
||||
let group = |member: Node| {
|
||||
let mut g = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]);
|
||||
g.appearance.effects.push(crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
@@ -817,23 +817,170 @@ fn masked_or_blended_members_draw_the_shaded_faces() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Revolve on a group, or on a fill or stroke, draws the shaded faces and reports why.
|
||||
/// The page rectangle image `i` covers.
|
||||
fn image_rect(i: &vectorcraft_doc::ImageObject) -> Rect {
|
||||
let [a, _, _, d, e, f] = i.xf.as_coeffs();
|
||||
Rect::new(e, f, e + a * f64::from(i.width), f + d * f64::from(i.height))
|
||||
}
|
||||
|
||||
/// Revolve on a group draws one image of every member's surface, over the area of the shaded faces
|
||||
/// of all of them, and its painted bounds are that image's rectangle; nothing is reported.
|
||||
#[test]
|
||||
fn revolve_on_a_group_or_a_paint_reports_objects_only() {
|
||||
fn revolve_on_a_group_draws_one_image_of_every_member() {
|
||||
let doc = vectorcraft_doc::Document::new(600.0, 400.0);
|
||||
let member =
|
||||
|id: u64, x: f64, color: Color| Node::path(NodeId(id), square(x, 100.0, 100.0), Appearance::basic(Paint::solid(color), Paint::None, 0.0));
|
||||
let members =
|
||||
vec![std::sync::Arc::new(member(11, 100.0, Color::rgb(0.2, 0.5, 0.8))), std::sync::Arc::new(member(12, 300.0, Color::rgb(0.8, 0.3, 0.2)))];
|
||||
let mut group = Node::group(NodeId(10), members);
|
||||
group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &group), None, "a group's rendered Revolve reports a fallback");
|
||||
let art = crate::revolve_art_drawn_in(Some(&doc), &group).unwrap();
|
||||
let found = images(&art);
|
||||
assert_eq!(found.len(), 1, "a group's Revolve draws one image of every member, not the shaded faces");
|
||||
assert!(faces_bounds(&art).is_none(), "a group's rendered Revolve draws no shaded faces");
|
||||
let shaded = faces_bounds(&crate::revolve_art_in(Some(&doc), &group).unwrap()).unwrap();
|
||||
let rect = image_rect(&found[0]);
|
||||
let grown = rect.inflate(1.0, 1.0);
|
||||
assert!(grown.contains(shaded.origin()) && grown.contains(Point::new(shaded.x1, shaded.y1)), "the image {rect:?} misses the faces {shaded:?}");
|
||||
let bounds = crate::three_d_bounds_art_in(Some(&doc), &group).unwrap();
|
||||
let measured = images(&bounds);
|
||||
assert_eq!(measured.len(), 1, "the painted bounds of a group's rendered Revolve are its image's rectangle");
|
||||
assert_eq!(image_rect(&measured[0]), rect);
|
||||
}
|
||||
|
||||
/// A group's rendered Revolve draws the shaded faces, and reports why, when a member is not opaque.
|
||||
#[test]
|
||||
fn revolve_on_a_group_with_a_see_through_member_draws_the_shaded_faces() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let mut member =
|
||||
Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0));
|
||||
member.opacity = 0.5;
|
||||
let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]);
|
||||
group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OPAQUE_ONLY), "member at 50%");
|
||||
let art = drawn(&group);
|
||||
assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "member at 50%");
|
||||
}
|
||||
|
||||
/// A member with no surface paint does not prevent the group's Revolve from rendering.
|
||||
#[test]
|
||||
fn revolve_on_a_group_ignores_blending_on_an_unpainted_member() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let painted = Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0));
|
||||
let mut unpainted = Node::path(NodeId(12), square(250.0, 100.0, 100.0), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
unpainted.blend = vectorcraft_doc::color::BlendMode::Multiply;
|
||||
let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(painted), std::sync::Arc::new(unpainted)]);
|
||||
group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &group), None);
|
||||
assert_eq!(images(&drawn(&group)).len(), 1);
|
||||
}
|
||||
|
||||
/// A group whose members can't be revolved reports why in rendered mode.
|
||||
#[test]
|
||||
fn revolve_on_a_group_that_cant_be_revolved_reports_why() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let mut group = Node::group(NodeId(10), vec![]);
|
||||
group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
let warning = crate::rendered_warning(&doc, &group);
|
||||
assert!(warning.as_deref().is_some_and(|w| w.starts_with("Revolve requires")), "an empty group's rendered Revolve reports {warning:?}");
|
||||
// An image with a fill of its own inside a clipping group is refused while the clipping group
|
||||
// is resolved, before the members are listed.
|
||||
let mut clip = Node::path(NodeId(21), square(100.0, 100.0, 100.0), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let mut image = Node::new(
|
||||
NodeId(22),
|
||||
NodeKind::Image(Box::new(vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::translate((150.0, 150.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
image.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
|
||||
let clipped = Node::new(NodeId(20), NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true });
|
||||
let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(clipped.clone())]);
|
||||
group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
let warning = crate::rendered_warning(&doc, &group);
|
||||
assert!(warning.as_deref().is_some_and(|w| w.contains("trace it first")), "a clipped image's rendered Revolve reports {warning:?}");
|
||||
// A clipping group draws no Revolve on its own fill, so that one reports nothing.
|
||||
let mut on_fill = clipped;
|
||||
on_fill.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
|
||||
on_fill.appearance.items[0].effects_mut().push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered"}})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &on_fill), None, "a clipping group's fill Revolve");
|
||||
}
|
||||
|
||||
/// A group's rendered Revolve reports when no member has a fill or stroke.
|
||||
#[test]
|
||||
fn revolve_on_a_group_without_surface_paint_reports_why() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let member = Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]);
|
||||
group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some("Revolve requires a group holding a shape with a fill or stroke"));
|
||||
}
|
||||
|
||||
/// Revolve on a fill, or on a stroke, draws an image of that paint's surface under the effects
|
||||
/// after it, with nothing reported; with both, each draws its own image. A fill at 50% draws the
|
||||
/// shaded faces and reports why.
|
||||
#[test]
|
||||
fn revolve_on_a_fill_or_a_stroke_draws_its_image() {
|
||||
use vectorcraft_doc::AppearanceItem;
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let rendered = || crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap();
|
||||
let member = || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0));
|
||||
let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member())]);
|
||||
group.appearance.effects.push(rendered());
|
||||
assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OBJECTS_ONLY), "group");
|
||||
assert!(images(&drawn(&group)).is_empty(), "group");
|
||||
let mut fill = member();
|
||||
fill.appearance.items[0].effects_mut().push(rendered());
|
||||
assert_eq!(crate::rendered_warning(&doc, &fill).as_deref(), Some(OBJECTS_ONLY), "fill");
|
||||
assert!(images(&drawn(&fill)).is_empty(), "fill");
|
||||
let painted = || {
|
||||
Node::path(
|
||||
NodeId(11),
|
||||
square(100.0, 100.0, 100.0),
|
||||
Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 4.0),
|
||||
)
|
||||
};
|
||||
let at = |n: &Node, stroke: bool| n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)) == stroke).unwrap();
|
||||
for stroke in [false, true] {
|
||||
let mut n = painted();
|
||||
let i = at(&n, stroke);
|
||||
n.appearance.items[i].effects_mut().push(rendered());
|
||||
n.appearance.items[i].effects_mut().push(crate::new_effect("stylize.dropShadow", &json!({})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &n), None, "stroke {stroke}: a paint's rendered Revolve reports a fallback");
|
||||
let art = crate::revolve_art_drawn_in(Some(&doc), &n).unwrap();
|
||||
let mut later = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Image(_)) {
|
||||
later.push(c.appearance.effects.iter().map(|e| e.id.clone()).collect::<Vec<_>>());
|
||||
}
|
||||
});
|
||||
assert_eq!(later, [["stylize.dropShadow"]], "stroke {stroke}: Revolve on one paint draws one image under the effects after it");
|
||||
}
|
||||
let mut both = painted();
|
||||
for item in &mut both.appearance.items {
|
||||
item.effects_mut().push(rendered());
|
||||
}
|
||||
assert_eq!(images(&crate::revolve_art_drawn_in(Some(&doc), &both).unwrap()).len(), 2, "each paint draws its own image");
|
||||
let mut faint = painted();
|
||||
let i = at(&faint, false);
|
||||
faint.appearance.items[i].effects_mut().push(rendered());
|
||||
if let AppearanceItem::Fill(f) = &mut faint.appearance.items[i] {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
assert_eq!(crate::rendered_warning(&doc, &faint).as_deref(), Some(OPAQUE_ONLY), "fill at 50%");
|
||||
assert!(images(&drawn(&faint)).is_empty(), "fill at 50%");
|
||||
assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None);
|
||||
}
|
||||
|
||||
/// A rendered Revolve on an empty fill profile reports why it cannot render.
|
||||
#[test]
|
||||
fn revolve_on_an_empty_fill_profile_reports_why() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let mut n = Node::path(NodeId(1), PathData::new(vec![]), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
n.appearance.items[0].effects_mut().push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
|
||||
assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some("Revolve requires a shape with at least two anchors"));
|
||||
}
|
||||
|
||||
/// Baking a rendered object's appearance, as an envelope with Distort Appearance does, keeps its
|
||||
/// image, for Revolve and the other 3D effects.
|
||||
#[test]
|
||||
|
||||
@@ -17,6 +17,11 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"]
|
||||
# feature still recognizes the files and refuses them with a message. The apps list it beside
|
||||
# `bundled-fonts`.
|
||||
heif = ["dep:heic-rs", "dep:rayon"]
|
||||
# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges
|
||||
# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm`
|
||||
# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in
|
||||
# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`).
|
||||
cgm = ["vectorcraft-metafile/cgm"]
|
||||
|
||||
[dependencies]
|
||||
craft-codepage = { workspace = true }
|
||||
|
||||
@@ -16,6 +16,10 @@ mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use color::screen_marks::{
|
||||
LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer,
|
||||
managed_owners as screen_marks_owners, owned_by as screen_marks_of, release as release_screen_marks, retag as retag_screen_marks,
|
||||
};
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
@@ -4,15 +4,17 @@
|
||||
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
|
||||
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, Create Screen Print Marks
|
||||
//! ([`screen_marks`]) draws registration targets and ink and file lines on the artboard, Apply
|
||||
//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and
|
||||
//! Randomize Fill Colors ([`random_fill`]) gives each filled path its own color at random. Its
|
||||
//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
mod random_fill;
|
||||
pub mod screen_marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -106,6 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
.chain(screen_marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
//! Create Screen Print Marks (`addon.color.screenMarks`; Object › Plug-ins › Color Effects ›
|
||||
//! Create Screen Print Marks…): registration targets at chosen corners and side centers of an
|
||||
//! artboard, in [Registration] or a spot ink, with optional lines that list the document's spot
|
||||
//! inks (each name in its own ink) and give the file name with the date and time. The marks are
|
||||
//! document art, one group per artboard on a locked "Screen Print Marks" layer at the bottom of the
|
||||
//! stack, so they print and export with the rest. Running it again replaces that artboard's marks,
|
||||
//! in one undo step, and makes none when the marks would come out the same.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, index_opt, switch_or, text_param};
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.color.screenMarks",
|
||||
"Create Screen Print Marks",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), activeArtboard?: index (the active artboard the journal records for a replay; used when artboard is left out; omitted from recorded actions), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}",
|
||||
has_doc,
|
||||
screen_marks
|
||||
)]
|
||||
}
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.screenMarks";
|
||||
|
||||
/// Where a target can go, in the order the command draws them.
|
||||
pub const POSITIONS: [&str; 8] = ["topLeft", "top", "topRight", "left", "right", "bottomLeft", "bottom", "bottomRight"];
|
||||
/// The targets drawn when `positions` is left out.
|
||||
pub const DEFAULT_POSITIONS: [&str; 4] = ["top", "bottom", "left", "right"];
|
||||
/// The name of the layer the marks go on, and of each artboard's group.
|
||||
pub const LAYER_NAME: &str = "Screen Print Marks";
|
||||
/// The object data key that marks the layer (`layer`) and each artboard's group (the artboard's id).
|
||||
pub const KEY: &str = "vc-screen-print-marks";
|
||||
/// Most spot inks one line names.
|
||||
const MAX_INKS: usize = 256;
|
||||
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && range.contains(n))
|
||||
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One of `options` for `key`, else `default`.
|
||||
fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static str) -> Result<&'static str> {
|
||||
match text_param(p, key, COMMAND)? {
|
||||
None => Ok(default),
|
||||
Some(v) => options.into_iter().find(|o| *o == v).ok_or_else(|| bad(COMMAND, format!("`{key}` must be {} or {}", options[0], options[1]))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The target positions `p` asks for, in [`POSITIONS`] order.
|
||||
fn positions(p: &Value) -> Result<Vec<&'static str>> {
|
||||
let asked: Vec<&str> = match p.get("positions") {
|
||||
None => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()),
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(COMMAND, "`positions` must be a list of position names")),
|
||||
};
|
||||
for (i, w) in asked.iter().enumerate() {
|
||||
if !POSITIONS.contains(w) {
|
||||
return Err(bad(COMMAND, format!("`{w}` is not a position: give {}", POSITIONS.join(", "))));
|
||||
}
|
||||
if asked[..i].contains(w) {
|
||||
return Err(bad(COMMAND, format!("`positions` names `{w}` twice")));
|
||||
}
|
||||
}
|
||||
Ok(POSITIONS.into_iter().filter(|w| asked.contains(w)).collect())
|
||||
}
|
||||
|
||||
/// The paint of ink `name`: [Registration], or a spot swatch linked to it.
|
||||
fn ink_paint(doc: &Document, name: &str) -> Result<Paint> {
|
||||
if name == REGISTRATION {
|
||||
return Ok(Paint::registration());
|
||||
}
|
||||
let w = doc.swatch(name).ok_or_else(|| bad(COMMAND, format!("no swatch named `{name}`")))?;
|
||||
if !w.spot || w.tint_of().is_some() || w.paint.color().is_none() {
|
||||
return Err(bad(COMMAND, format!("`{name}` is not a spot color swatch: give [Registration] or a spot swatch")));
|
||||
}
|
||||
super::super::super::paint::swatch_solid(doc, name, None).map_err(|e| bad(COMMAND, e))
|
||||
}
|
||||
|
||||
/// The document's spot inks in panel order, each with the paint that links to it: spot color
|
||||
/// swatches that are not tints, [Registration] left out.
|
||||
fn spot_inks(doc: &Document) -> Vec<(String, Paint)> {
|
||||
doc.swatches_iter()
|
||||
.filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some())
|
||||
.map(|w| (w.name.clone(), super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The index of the view's active artboard: when the document no longer has it, the one the
|
||||
/// document opened on, else the first.
|
||||
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))
|
||||
}
|
||||
|
||||
/// The settings every artboard's marks are drawn with.
|
||||
struct Marks {
|
||||
positions: Vec<&'static str>,
|
||||
size: f64,
|
||||
weight: f64,
|
||||
inset: f64,
|
||||
ink: Paint,
|
||||
/// The lines of type, top to bottom: each a list of (text, fill) runs.
|
||||
lines: Vec<Vec<(String, Paint)>>,
|
||||
style: CharStyle,
|
||||
system_layout: bool,
|
||||
top: bool,
|
||||
left: bool,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
/// The center of the target at `position` on artboard `r`.
|
||||
fn center(&self, r: Rect, position: &str) -> Point {
|
||||
let near = self.inset + self.size / 2.0;
|
||||
let x = if position.ends_with("Left") || position == "left" {
|
||||
r.x0 + near
|
||||
} else if position.ends_with("Right") || position == "right" {
|
||||
r.x1 - near
|
||||
} else {
|
||||
r.center().x
|
||||
};
|
||||
let y = if position.starts_with("top") {
|
||||
r.y0 + near
|
||||
} else if position.starts_with("bottom") {
|
||||
r.y1 - near
|
||||
} else {
|
||||
r.center().y
|
||||
};
|
||||
Point::new(x, y)
|
||||
}
|
||||
|
||||
/// The target at `c`: a circle half the target's width and a cross the target's width, stroked.
|
||||
fn target(&self, c: Point, alloc: &mut dyn FnMut() -> NodeId) -> Node {
|
||||
let ap = Appearance::basic(Paint::None, self.ink.clone(), self.weight);
|
||||
let (half, ring) = (self.size / 2.0, self.size / 4.0);
|
||||
let paths = [
|
||||
shapes::ellipse(Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring)),
|
||||
shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)),
|
||||
shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)),
|
||||
];
|
||||
let children = paths.into_iter().map(|path| Arc::new(Node::path(alloc(), path, ap.clone()))).collect();
|
||||
let mut g = Node::group(alloc(), children);
|
||||
g.name = Some("Registration Target".into());
|
||||
g
|
||||
}
|
||||
|
||||
/// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or
|
||||
/// its bottom corner there when `from_bottom`, with its box.
|
||||
fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, Rect) {
|
||||
let runs: Vec<TextRun> = runs
|
||||
.iter()
|
||||
.map(|(text, fill)| {
|
||||
let mut style = self.style.clone();
|
||||
style.fill = fill.clone();
|
||||
style.stroke = Paint::None;
|
||||
TextRun::new(text.clone(), style)
|
||||
})
|
||||
.collect();
|
||||
let mut t = TextObject::point(Point::ZERO, "", self.style.clone());
|
||||
t.runs = runs;
|
||||
t.para = super::super::super::create::new_type_para();
|
||||
t.system_layout = self.system_layout;
|
||||
super::super::super::typecmd::refresh_bounds(&mut t);
|
||||
let b = t.cached_bounds.unwrap_or(Rect::new(0.0, -self.style.size * 0.8, 0.0, self.style.size * 0.2));
|
||||
let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 };
|
||||
let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 };
|
||||
t.xf = Affine::translate((dx, dy));
|
||||
(t, Rect::new(b.x0 + dx, b.y0 + dy, b.x1 + dx, b.y1 + dy))
|
||||
}
|
||||
|
||||
/// The lines placed in a column from `y`, at `x`: down from `y` at the top, up
|
||||
/// from it at the bottom. Each with its box.
|
||||
fn column(&self, x: f64, mut y: f64) -> Vec<(TextObject, Rect)> {
|
||||
let gap = self.style.size * 0.25;
|
||||
let mut placed = Vec::with_capacity(self.lines.len());
|
||||
if self.top {
|
||||
for runs in &self.lines {
|
||||
let (t, b) = self.line(runs, Point::new(x, y), false);
|
||||
y += b.height() + gap;
|
||||
placed.push((t, b));
|
||||
}
|
||||
} else {
|
||||
for runs in self.lines.iter().rev() {
|
||||
let (t, b) = self.line(runs, Point::new(x, y), true);
|
||||
y -= b.height() + gap;
|
||||
placed.insert(0, (t, b));
|
||||
}
|
||||
}
|
||||
placed
|
||||
}
|
||||
|
||||
/// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last).
|
||||
fn group(&self, r: Rect, board: u32, alloc: &mut dyn FnMut() -> NodeId) -> Node {
|
||||
let mut children: Vec<Arc<Node>> = self.positions.iter().map(|w| Arc::new(self.target(self.center(r, w), alloc))).collect();
|
||||
if !self.lines.is_empty() {
|
||||
// The lines start past a target in the corner they start from.
|
||||
let corner = match (self.top, self.left) {
|
||||
(true, true) => "topLeft",
|
||||
(true, false) => "topRight",
|
||||
(false, true) => "bottomLeft",
|
||||
(false, false) => "bottomRight",
|
||||
};
|
||||
let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 };
|
||||
let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip };
|
||||
let (edge, sign) = if self.top { (r.y0, 1.0) } else { (r.y1, -1.0) };
|
||||
let mut placed = self.column(x, edge + sign * self.inset);
|
||||
// Lines that would cross the center target on their side move in past it, unless they
|
||||
// would then cross another target or leave the artboard.
|
||||
let side = if self.top { "top" } else { "bottom" };
|
||||
// A target's paint: its two bars and the box of its ring, each with half the stroke weight.
|
||||
let (half, ring, w2) = (self.size / 2.0, self.size / 4.0 + self.weight / 2.0, self.weight / 2.0);
|
||||
let crosses = |placed: &[(TextObject, Rect)], w: &str| {
|
||||
let c = self.center(r, w);
|
||||
let paint = [
|
||||
Rect::new(c.x - half - w2, c.y - w2, c.x + half + w2, c.y + w2),
|
||||
Rect::new(c.x - w2, c.y - half - w2, c.x + w2, c.y + half + w2),
|
||||
Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring),
|
||||
];
|
||||
placed.iter().any(|(_, b)| paint.iter().any(|p| b.x0 < p.x1 && b.x1 > p.x0 && b.y0 < p.y1 && b.y1 > p.y0))
|
||||
};
|
||||
if self.positions.contains(&side) && crosses(&placed, side) {
|
||||
let moved = self.column(x, edge + sign * (self.inset + self.size + self.weight / 2.0 + self.style.size * 0.25));
|
||||
if moved.iter().all(|(_, b)| b.y0 >= r.y0 && b.y1 <= r.y1) && !self.positions.iter().any(|w| crosses(&moved, w)) {
|
||||
placed = moved;
|
||||
}
|
||||
}
|
||||
children.extend(placed.into_iter().map(|(t, _)| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t))))));
|
||||
}
|
||||
let mut g = Node::group(alloc(), children);
|
||||
g.name = Some(LAYER_NAME.into());
|
||||
g.edit_attrs(|a| a.data.push((KEY.into(), board.to_string())));
|
||||
g
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks layer: the top-level layer whose data says so.
|
||||
fn marks_layer(doc: &Document) -> Option<&Arc<Node>> {
|
||||
doc.layers.iter().find(|l| tag(l) == Some("layer"))
|
||||
}
|
||||
|
||||
/// What `n`'s data holds under [`KEY`].
|
||||
fn tag(n: &Node) -> Option<&str> {
|
||||
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The id of the artboard marks group `n` belongs to, from its data.
|
||||
fn owner(n: &Node) -> Option<u32> {
|
||||
tag(n)?.parse().ok()
|
||||
}
|
||||
|
||||
/// Each marks group on the marks layer of `d`, with the id of the artboard it belongs to.
|
||||
pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap<NodeId, u32> {
|
||||
marks_layer(d).and_then(|l| l.children()).into_iter().flatten().filter_map(|k| Some((k.id, owner(k)?))).collect()
|
||||
}
|
||||
|
||||
/// The id of the marks layer of `d`, when it has one.
|
||||
pub(crate) fn layer_id(d: &Document) -> Option<NodeId> {
|
||||
marks_layer(d).map(|l| l.id)
|
||||
}
|
||||
|
||||
/// Is `n` the marks group of one of the artboards with ids `boards`?
|
||||
pub(crate) fn owned_by(n: &Node, boards: &[u32]) -> bool {
|
||||
owner(n).is_some_and(|o| boards.contains(&o))
|
||||
}
|
||||
|
||||
/// Each marks group on the marks layer of `d` that goes with an artboard copy, in paint order,
|
||||
/// with the id of the artboard it belongs to. Locked and hidden ones, and all of them while the
|
||||
/// marks layer is locked or hidden, only with `locked_and_hidden`.
|
||||
pub(crate) fn copied_owners(d: &Document, locked_and_hidden: bool) -> Vec<(NodeId, u32)> {
|
||||
let layer = marks_layer(d).filter(|l| l.rides_with_artboard(locked_and_hidden));
|
||||
let kids = layer.and_then(|l| l.children()).into_iter().flatten();
|
||||
kids.filter(|k| k.rides_with_artboard(locked_and_hidden)).filter_map(|k| Some((k.id, owner(k)?))).collect()
|
||||
}
|
||||
|
||||
/// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data
|
||||
/// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call
|
||||
/// it on each copy they make. → whether `n` was such a group.
|
||||
pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool {
|
||||
if owner(n) != Some(from) {
|
||||
return false;
|
||||
}
|
||||
let (from, to) = (from.to_string(), to.to_string());
|
||||
n.edit_attrs(|a| {
|
||||
for (k, v) in a.data.iter_mut() {
|
||||
if k == KEY && *v == from {
|
||||
v.clone_from(&to);
|
||||
}
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Make the marks groups of the deleted artboards with ids `gone` ordinary art: a file opened
|
||||
/// again can give a new artboard one of those ids, and its marks are drawn afresh.
|
||||
pub(crate) fn release(d: &mut Document, gone: &std::collections::HashSet<u32>) {
|
||||
// Groups moved off the marks layer keep their tag and count too.
|
||||
let mut groups: Vec<NodeId> = vec![];
|
||||
for l in &d.layers {
|
||||
l.walk(&mut |n: &Node| {
|
||||
if owner(n).is_some_and(|o| gone.contains(&o)) {
|
||||
groups.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
for id in groups {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard,
|
||||
/// the marks layer, when the document has none.
|
||||
pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) {
|
||||
if marks_layer(d).is_some() || !d.layers.iter().any(|l| l.id == layer) {
|
||||
return;
|
||||
}
|
||||
if let Some(l) = d.node_mut(layer) {
|
||||
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way.
|
||||
fn without_ids(n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = NodeId(0);
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(without_ids(c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn screen_marks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let positions = positions(p)?;
|
||||
let size = number(p, "size", 36.0, 4.0..=1000.0)?;
|
||||
let weight = number(p, "weight", 1.0, 0.1..=20.0)?;
|
||||
let inset = number(p, "inset", 18.0, -1000.0..=1000.0)?;
|
||||
let text_size = number(p, "textSize", 9.0, 4.0..=72.0)?;
|
||||
let top = choice(p, "textPlace", ["top", "bottom"], "bottom")? == "top";
|
||||
let left = choice(p, "textAlign", ["left", "right"], "left")? == "left";
|
||||
let want_inks = switch_or(p, "inks", false, C)?;
|
||||
let want_info = switch_or(p, "info", false, C)?;
|
||||
let all = switch_or(p, "allArtboards", false, C)?;
|
||||
let given_time = date_param(p, "time", C)?;
|
||||
let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string();
|
||||
// Defaults are for values left out; only `time` takes null (no date).
|
||||
if let Some((key, _)) = p.as_object().and_then(|o| o.iter().find(|(k, v)| v.is_null() && *k != "time")) {
|
||||
return Err(bad(C, format!("`{key}` must not be null: leave it out for the default")));
|
||||
}
|
||||
let artboard = index_opt(p, "artboard", C)?;
|
||||
if all && artboard.is_some() {
|
||||
return Err(bad(C, "give `artboard` or `allArtboards`, not both"));
|
||||
}
|
||||
// The active artboard, noted in the journal (`activeArtboard`) so a replay marks the same one;
|
||||
// recorded actions leave it out and use the active artboard when played.
|
||||
let recorded = index_opt(p, "activeArtboard", C)?;
|
||||
let artboard = match artboard {
|
||||
None if !all => {
|
||||
let i = match recorded {
|
||||
Some(i) => Some(i),
|
||||
None => active_artboard(s.doc()?),
|
||||
};
|
||||
if let Some(i) = i {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
i
|
||||
}
|
||||
given => given,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
if doc.artboards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboards"));
|
||||
}
|
||||
let boards: Vec<(Rect, u32)> = if all {
|
||||
doc.artboards.iter().map(|a| (a.rect, a.id)).collect()
|
||||
} else {
|
||||
let i = artboard.unwrap_or(0);
|
||||
let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?;
|
||||
vec![(a.rect, a.id)]
|
||||
};
|
||||
let ink = ink_paint(doc, &ink_name)?;
|
||||
let inks = if want_inks { spot_inks(doc) } else { vec![] };
|
||||
if inks.len() > MAX_INKS {
|
||||
return Err(bad(C, format!("a line names at most {MAX_INKS} spot inks")));
|
||||
}
|
||||
let file = st
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| std::path::Path::new(path).file_name())
|
||||
.map(|f| f.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| doc.title.clone());
|
||||
let system_layout = doc.setup.system_layout;
|
||||
if positions.is_empty() && inks.is_empty() && !want_info {
|
||||
let why = if want_inks { "the document has no spot inks" } else { "give `positions`, `inks` or `info`" };
|
||||
return Err(bad(C, format!("nothing to draw: {why}")));
|
||||
}
|
||||
let mut lines: Vec<Vec<(String, Paint)>> = vec![];
|
||||
if !inks.is_empty() {
|
||||
let last = inks.len() - 1;
|
||||
lines.push(
|
||||
inks.iter().enumerate().map(|(i, (name, paint))| (if i < last { format!("{name} ") } else { name.clone() }, paint.clone())).collect(),
|
||||
);
|
||||
}
|
||||
if want_info {
|
||||
let date = clock_date(s, "time", given_time).map(|t| {
|
||||
let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t);
|
||||
format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC")
|
||||
});
|
||||
let text = match date {
|
||||
Some(date) => format!("{file} {date}"),
|
||||
None => file,
|
||||
};
|
||||
lines.push(vec![(text, ink.clone())]);
|
||||
}
|
||||
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?;
|
||||
let marks = Marks { positions, size, weight, inset, ink, lines, style, system_layout, top, left };
|
||||
let names: Vec<String> = inks.into_iter().map(|(name, _)| name).collect();
|
||||
|
||||
// The marks as they would come out, to tell whether anything changes.
|
||||
let st = s.doc()?;
|
||||
let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default()));
|
||||
let drawn: Vec<Node> = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect();
|
||||
// Only the stroked targets reach past their paths, by half the target weight. The lines of type
|
||||
// have no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well.
|
||||
let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD);
|
||||
let beyond = |n: &Node| match &n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0))
|
||||
}
|
||||
_ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight / 2.0)),
|
||||
};
|
||||
if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) {
|
||||
return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)")));
|
||||
}
|
||||
// Each existing group under the artboard it belongs to, worked out once.
|
||||
let mut owned: std::collections::HashMap<u32, Vec<&Arc<Node>>> = std::collections::HashMap::new();
|
||||
for k in layer.iter().flat_map(|(_, kids)| kids) {
|
||||
if let Some(board) = owner(k) {
|
||||
owned.entry(board).or_default().push(k);
|
||||
}
|
||||
}
|
||||
if let Some((layer, _)) = &layer {
|
||||
let same = boards
|
||||
.iter()
|
||||
.zip(&drawn)
|
||||
.all(|((_, board), new)| matches!(owned.get(board).map(Vec::as_slice), Some([one]) if without_ids(one) == without_ids(new)));
|
||||
if same {
|
||||
let ids: Vec<u64> = boards.iter().filter_map(|(_, board)| owned.get(board).and_then(|g| g.first()).map(|g| g.id.0)).collect();
|
||||
return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names }));
|
||||
}
|
||||
}
|
||||
let owned: std::collections::HashMap<u32, Vec<NodeId>> = owned.into_iter().map(|(b, g)| (b, g.into_iter().map(|k| k.id).collect())).collect();
|
||||
let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| {
|
||||
let layer = match marks_layer(d).map(|l| l.id) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let id = d.alloc_id();
|
||||
let color = LayerColor::Preset((d.layers.len() % LAYER_COLORS.len()) as u8);
|
||||
let mut l = Node::layer(id, LAYER_NAME, color);
|
||||
l.locked = true;
|
||||
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
|
||||
d.insert(None, 0, l)?;
|
||||
id
|
||||
}
|
||||
};
|
||||
let mut ids = Vec::with_capacity(boards.len());
|
||||
for (r, board) in &boards {
|
||||
let kids = d.children(Some(layer)).cloned().unwrap_or_default();
|
||||
let old: Vec<NodeId> = owned.get(board).cloned().unwrap_or_default();
|
||||
let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX);
|
||||
// Only what the selection holds of the marks leaves it; the rest of the selection stays as it is.
|
||||
let mut held = vec![];
|
||||
for k in kids.iter().filter(|k| old.contains(&k.id)) {
|
||||
k.walk(&mut |n: &Node| {
|
||||
if sel.objects.contains(&n.id) || sel.anchors.contains_key(&n.id) || sel.segments.contains_key(&n.id) {
|
||||
held.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
if !held.is_empty() {
|
||||
sel.remove_all(held);
|
||||
}
|
||||
d.remove_many(&old)?;
|
||||
let g = marks.group(*r, *board, &mut || d.alloc_id());
|
||||
ids.push(g.id.0);
|
||||
d.insert(Some(layer), at, g)?;
|
||||
}
|
||||
Ok((layer, ids))
|
||||
})?;
|
||||
Ok(json!({ "changed": true, "layer": layer.0, "ids": ids, "inks": names }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,935 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::{COMMAND, LAYER_NAME};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: Value) -> Value {
|
||||
s.execute(COMMAND, &p).unwrap()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: u64) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone()
|
||||
}
|
||||
|
||||
/// The targets of group `g`: each one's three paths.
|
||||
fn targets(g: &Node) -> Vec<Vec<Node>> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() == Some("Registration Target"))
|
||||
.map(|t| t.children().unwrap().iter().map(|p| (**p).clone()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The type lines of group `g`, top to bottom as stored.
|
||||
fn lines(g: &Node) -> Vec<vectorcraft_doc::TextObject> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some((**t).clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bounds(n: &Node) -> Rect {
|
||||
n.geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// The swatch solid paint `p` links to.
|
||||
fn swatch_of(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Solid { swatch, .. } => swatch.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_targets_go_on_a_locked_bottom_layer_in_registration_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, json!({}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(art)], "the selection is kept");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let layer = &doc.layers[0];
|
||||
assert_eq!(layer.id.0, r["layer"].as_u64().unwrap(), "the marks layer is at the bottom of the stack");
|
||||
assert_eq!(layer.name.as_deref(), Some(LAYER_NAME));
|
||||
assert!(layer.locked && layer.visible, "the marks layer is locked");
|
||||
assert_eq!(doc.layers.len(), 2);
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 1, "one group for the active artboard");
|
||||
let g = node(&s, ids[0].as_u64().unwrap());
|
||||
assert_eq!(super::tag(&g), Some(doc.artboards[0].id.to_string().as_str()));
|
||||
let t = targets(&g);
|
||||
assert_eq!(t.len(), 4, "top, bottom, left and right by default");
|
||||
assert!(lines(&g).is_empty(), "no type lines unless asked for");
|
||||
for paths in &t {
|
||||
assert_eq!(paths.len(), 3, "a ring and two cross lines");
|
||||
for p in paths {
|
||||
assert!(p.appearance.stroke_paint().is_registration(), "stroked in [Registration]");
|
||||
assert!(p.appearance.fill_paint().is_none());
|
||||
assert!(close(p.appearance.stroke_width(), 1.0));
|
||||
}
|
||||
}
|
||||
// The top target: its 36 pt box 18 pt in from the top edge, centered across.
|
||||
let top = &t[0];
|
||||
let ring = bounds(&top[0]);
|
||||
assert!(close(ring.width(), 18.0) && close(ring.center().x, 300.0) && close(ring.center().y, 36.0), "{ring:?}");
|
||||
let across = bounds(&top[1]);
|
||||
assert!(close(across.x0, 282.0) && close(across.x1, 318.0), "{across:?}");
|
||||
let down = bounds(&top[2]);
|
||||
assert!(close(down.y0, 18.0) && close(down.y1, 54.0), "{down:?}");
|
||||
// Left, right and bottom.
|
||||
let centers: Vec<_> = t.iter().map(|p| bounds(&p[0]).center()).collect();
|
||||
assert!(close(centers[1].x, 36.0) && close(centers[1].y, 200.0), "left: {:?}", centers[1]);
|
||||
assert!(close(centers[2].x, 564.0) && close(centers[2].y, 200.0), "right: {:?}", centers[2]);
|
||||
assert!(close(centers[3].x, 300.0) && close(centers[3].y, 364.0), "bottom: {:?}", centers[3]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "undo removes the layer and its marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_size_weight_inset_and_a_spot_ink_shape_the_targets() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
let p = json!({"positions": ["bottomRight", "topLeft"], "size": 20, "weight": 0.5, "inset": -30, "ink": "Plate Red"});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let t = targets(&g);
|
||||
assert_eq!(t.len(), 2);
|
||||
// Drawn in POSITIONS order: top left first. A negative inset puts the targets outside.
|
||||
let tl = bounds(&t[0][0]).center();
|
||||
let br = bounds(&t[1][0]).center();
|
||||
assert!(close(tl.x, -20.0) && close(tl.y, -20.0), "{tl:?}");
|
||||
assert!(close(br.x, 620.0) && close(br.y, 420.0), "{br:?}");
|
||||
assert!(close(bounds(&t[0][0]).width(), 10.0), "the ring is half the target's width");
|
||||
assert!(close(bounds(&t[0][1]).width(), 20.0));
|
||||
for p in t.iter().flatten() {
|
||||
assert_eq!(swatch_of(&p.appearance.stroke_paint()).as_deref(), Some("Plate Red"), "the stroke links to the spot swatch");
|
||||
assert!(close(p.appearance.stroke_width(), 0.5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let first = run(&mut s, json!({"size": 30}));
|
||||
let layer = first["layer"].clone();
|
||||
let undo = undo_len(&s);
|
||||
let again = run(&mut s, json!({"size": 30}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
assert_eq!(again["ids"], first["ids"], "the same group stays");
|
||||
assert_eq!(undo_len(&s), undo, "nothing changed: no undo step");
|
||||
let r = run(&mut s, json!({"size": 40, "positions": ["top"]}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(r["layer"], layer, "the same layer is reused");
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.layers.len(), 2, "no second marks layer");
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
assert_eq!(kids.len(), 1, "the earlier marks are replaced");
|
||||
let t = targets(&kids[0]);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert!(close(bounds(&t[0][1]).width(), 40.0));
|
||||
assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_an_artboard_without_changing_the_marks_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let p = json!({"positions": ["topLeft"]});
|
||||
let first = run(&mut s, p.clone());
|
||||
let before = node(&s, first["ids"][0].as_u64().unwrap());
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 800})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let again = run(&mut s, p);
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
assert_eq!(again["ids"], first["ids"], "the same group stays");
|
||||
assert!(node(&s, again["ids"][0].as_u64().unwrap()) == before, "the existing group stays unchanged");
|
||||
assert_eq!(undo_len(&s), undo, "unchanged marks add no undo step after a resize");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_marks_keeps_a_selected_slice_selected() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("object.slice.make", &json!({})).unwrap();
|
||||
s.execute("select.object.slices", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
assert!(!before.slices.is_empty());
|
||||
let r = run(&mut s, json!({"size": 50}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert!(s.doc().unwrap().selection == before, "the selection is kept as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_past_the_canvas_edge_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 3999000, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "inset": -1000})).unwrap_err().to_string();
|
||||
assert!(err.contains("edge of the canvas"), "{err}");
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() {
|
||||
let mut s = session();
|
||||
// The artboard ends 10 pt inside the canvas edge.
|
||||
s.execute("artboard.new", &json!({"x": 3999090, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
let p = json!({"artboard": 1, "positions": [], "info": true, "textAlign": "right", "inset": 0, "weight": 20});
|
||||
let r = run(&mut s, p);
|
||||
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_reaches_past_its_paths_by_half_its_weight_at_the_canvas_edge() {
|
||||
let mut s = session();
|
||||
// The artboard ends at the canvas edge.
|
||||
s.execute("artboard.new", &json!({"x": 3999100, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
// The cross ends 15 pt inside the edge, and its 20 pt stroke reaches 10 pt past that.
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 15}));
|
||||
assert_eq!(targets(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
|
||||
// 5 pt inside the edge, the stroke reaches 5 pt past it.
|
||||
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 5})).unwrap_err().to_string();
|
||||
assert!(err.contains("edge of the canvas"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 800, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let r = run(&mut s, json!({"allArtboards": true, "positions": ["top"]}));
|
||||
assert_eq!(r["ids"].as_array().unwrap().len(), 2);
|
||||
let second = node(&s, r["ids"][1].as_u64().unwrap());
|
||||
let c = bounds(&targets(&second)[0][0]).center();
|
||||
assert!(close(c.x, 900.0) && close(c.y, 36.0), "the second artboard's own target: {c:?}");
|
||||
let only = run(&mut s, json!({"artboard": 1, "positions": ["bottom"]}));
|
||||
assert_eq!(only["ids"].as_array().unwrap().len(), 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
assert_eq!(kids.len(), 2, "the first artboard's marks stay");
|
||||
assert!(kids.iter().any(|k| k.id.0 == r["ids"][0].as_u64().unwrap()));
|
||||
let c = bounds(&targets(&node(&s, only["ids"][0].as_u64().unwrap()))[0][0]).center();
|
||||
assert!(close(c.x, 900.0) && close(c.y, 64.0), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ink_line_names_each_spot_ink_in_its_own_ink_and_the_file_line_gives_name_and_time() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Blue", "color": "#1122cc", "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"colors": [{"swatch": "Plate Red", "tint": 50}]})).unwrap();
|
||||
// A tint swatch marked spot, as a file can hold one, is still a tint of its ink.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let mut tints = 0;
|
||||
for w in std::sync::Arc::make_mut(&mut st.doc).swatches_iter_mut().filter(|w| w.tint_of().is_some()) {
|
||||
w.spot = true;
|
||||
tints += 1;
|
||||
}
|
||||
assert_eq!(tints, 1);
|
||||
let title = s.doc().unwrap().doc.title.clone();
|
||||
// 2026-03-04 05:06 UTC.
|
||||
let r = run(&mut s, json!({"positions": [], "inks": true, "info": true, "time": 1772600760}));
|
||||
assert_eq!(r["inks"], json!(["Plate Red", "Plate Blue"]), "spot inks only: process, tints and [Registration] left out");
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(targets(&g).is_empty());
|
||||
let l = lines(&g);
|
||||
assert_eq!(l.len(), 2);
|
||||
let names: Vec<_> = l[0].runs.iter().map(|run| (run.text.trim().to_string(), swatch_of(&run.style.fill))).collect();
|
||||
assert_eq!(names, [("Plate Red".into(), Some("Plate Red".into())), ("Plate Blue".into(), Some("Plate Blue".into()))]);
|
||||
assert_eq!(l[1].plain_text(), format!("{title} 2026-03-04 05:06 UTC"));
|
||||
assert!(l[1].runs[0].style.fill.is_registration(), "the file line prints on every plate");
|
||||
assert!(l.iter().all(|t| close(t.runs[0].style.size, 9.0)));
|
||||
// At the bottom left by default: the file line is the lower one, both 18 pt in.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let kids = g.children().unwrap();
|
||||
let texts: Vec<_> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).collect();
|
||||
assert!(texts[0].y1 <= texts[1].y0 + 1e-6, "the ink line sits above the file line");
|
||||
assert!((texts[1].y1 - 382.0).abs() < 0.5 && (texts[0].x0 - 18.0).abs() < 0.5, "{texts:?}");
|
||||
// No date without a time.
|
||||
let r = run(&mut s, json!({"positions": [], "info": true, "time": null}));
|
||||
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap()))[0].plain_text(), title);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_at_the_top_right_start_past_a_corner_target() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
let p = json!({"positions": ["topRight"], "inks": true, "textPlace": "top", "textAlign": "right", "textSize": 12});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let target = bounds(&targets(&g)[0][1]);
|
||||
// 600 - 18 (inset) - 36 (target) - 12 (a gap of the type size).
|
||||
assert!((text.x1 - 534.0).abs() < 0.5, "{text:?}");
|
||||
assert!(text.x1 < target.x0, "the line clears the corner target");
|
||||
assert!((text.y0 - 18.0).abs() < 0.5, "{text:?}");
|
||||
assert!(close(lines(&g)[0].runs[0].style.size, 12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_move_up_past_a_bottom_center_target_they_would_cross() {
|
||||
let mut s = session();
|
||||
let p = json!({"positions": ["bottom"], "info": true, "time": 1772600760, "textSize": 72});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the line is long enough to reach the target: {text:?} {target:?}");
|
||||
assert!(text.y1 <= target.y0, "the line sits above the bottom target: {text:?} {target:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_do_not_move_above_a_short_artboard_to_clear_a_bottom_target() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 100, "height": 56})).unwrap();
|
||||
let p = json!({"positions": [], "info": true, "time": 1772600760});
|
||||
let original = run(&mut s, p.clone());
|
||||
let original_bounds = bounds(&node(&s, original["ids"][0].as_u64().unwrap()));
|
||||
let mut with_target = p;
|
||||
with_target["positions"] = json!(["bottom"]);
|
||||
let r = run(&mut s, with_target);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| bounds(n)).unwrap();
|
||||
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the file line reaches the bottom target: {text:?} {target:?}");
|
||||
assert!(text.y0 >= 0.0 && text.y1 <= 56.0, "the line stays vertically inside the artboard: {text:?}");
|
||||
assert_eq!(text, original_bounds, "the line keeps its original placement when shifting would leave the artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_do_not_move_onto_the_opposite_target_on_a_short_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 110})).unwrap();
|
||||
let p = json!({"artboard": 1, "positions": ["top", "bottom"], "info": true, "time": 1772600760, "textSize": 24});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let top = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x1 <= top.x0 || text.y0 >= top.y1, "the line stays off the top target: {text:?} {top:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_duplicated_artboard_belong_to_the_copy() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(kids(&s), 2, "the duplicate carries a copy of the marks");
|
||||
let copy = run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the duplicate replaces the copy");
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
|
||||
assert_eq!(kids(&s), 2);
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(copy["ids"][0].as_u64().unwrap())).is_some(), "the duplicate's marks stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |k| k.len())).sum::<usize>();
|
||||
let before = kids(&s);
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(kids(&s), before, "marking the pasted artboard replaces the pasted copy");
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the marks layer, which stays locked");
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_from_an_unnamed_marks_layer_paste_back_into_it() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(layer).unwrap().name = None;
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the unnamed marks layer, which stays locked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let plain = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let kids = |s: &Session, l: NodeId| s.doc().unwrap().doc.node(l).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(kids(&s, layer), Some((true, 2)), "the pasted marks go into the locked marks layer");
|
||||
assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_without_a_marks_layer_make_one_and_skip_a_layer_of_the_same_name() {
|
||||
for props in [json!({}), json!({"visible": false}), json!({"locked": true})] {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let plain = s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].clone();
|
||||
let mut set = props.clone();
|
||||
set["id"] = plain.clone();
|
||||
s.execute("layer.setProps", &set).unwrap();
|
||||
let plain = NodeId(plain.as_u64().unwrap());
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards.len(), 2, "{props}");
|
||||
assert_eq!(doc.node(plain).and_then(|l| l.children().map(|k| k.len())), Some(0), "the ordinary layer stays empty: {props}");
|
||||
let made: Vec<_> = doc.layers.iter().filter(|l| l.id != plain && l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(made.len(), 1, "a marks layer is made: {props}");
|
||||
assert_eq!(made[0].children().map_or(0, |k| k.len()), 1, "the pasted marks go into it: {props}");
|
||||
let made = made[0].id.0;
|
||||
let r = run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(r["layer"], json!(made), "the command uses the made layer: {props}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_and_art_from_a_layer_of_the_same_name_paste_into_separate_layers() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "name": "Renamed Marks"})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
for paste in 1..=2 {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let marks = super::layer_id(doc).expect("a marks layer is made");
|
||||
let named: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(named.len(), 2, "the marks layer and the ordinary layer are separate: paste {paste}");
|
||||
for l in named {
|
||||
let items = l.children().unwrap().len();
|
||||
assert_eq!(items, paste, "each paste adds one item to each layer: paste {paste}, marks {}", l.id == marks);
|
||||
}
|
||||
let ordinary = doc.layers.iter().find(|l| l.name.as_deref() == Some(LAYER_NAME) && l.id != marks).unwrap();
|
||||
assert_eq!(ordinary.children().unwrap().len(), paste, "the ordinary layer holds one rectangle per paste: paste {paste}");
|
||||
assert!(
|
||||
ordinary.children().unwrap().iter().all(|k| k.children().is_none()),
|
||||
"only the rectangle goes into the ordinary layer: paste {paste}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_pasted_again_skips_a_marks_layer_above_its_ordinary_layer() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let ordinary = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
|
||||
for paste in 1..=2 {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let marks = super::layer_id(doc).expect("a marks layer is made");
|
||||
assert_ne!(marks, ordinary);
|
||||
let kids = |l: NodeId| doc.node(l).unwrap().children().unwrap().iter().map(|k| k.children().is_none()).collect::<Vec<_>>();
|
||||
assert_eq!(kids(ordinary), vec![true; paste], "the rectangles go into the ordinary layer: paste {paste}");
|
||||
assert_eq!(kids(marks), vec![false; paste], "only marks go into the marks layer: paste {paste}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
let b = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert!(b.x0 >= 600.0, "the marks lie wholly off the artboard: {b:?}");
|
||||
let p = json!({"index": 0, "dy": 500, "copy": true, "moveArt": true, "lockedAndHidden": true});
|
||||
s.execute("artboard.move", &p).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(kids(&s), 2, "the copy carries a copy of the marks");
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": other, "locked": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("edit.paste", &json!({})).unwrap_err().to_string();
|
||||
assert!(err.contains("locked or hidden"), "{err}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing is pasted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_after_their_layer_was_deleted_are_found_again() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("layer.delete", &json!({"ids": [r["layer"]]})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let layers: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(layers.len(), 1, "one marks layer");
|
||||
assert_eq!(layers[0].children().unwrap().len(), 1, "marking the pasted artboard replaces the pasted copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_artboards_marks_lying_on_a_copied_artboard_stay_with_their_own() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let b = bounds(&g);
|
||||
assert!(b.x0 >= 700.0 && b.x1 <= 1300.0, "the marks lie wholly on the second artboard: {b:?}");
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), 1, "duplicating the second artboard leaves the first one's marks out");
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let copied = s.execute("artboard.copy", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(copied["copied"], json!(0), "copying the second artboard leaves the first one's marks out");
|
||||
let again = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_overlapping_artboards_copies_marks_lying_on_both_once() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
|
||||
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the second artboard's copy carries its marks");
|
||||
let copy = run(&mut s, json!({"artboard": 3, "positions": ["left"], "size": 30}));
|
||||
assert_eq!(copy["changed"], json!(true));
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "marking that copy replaces the copied marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let p = json!({"positions": ["right"], "inset": -200});
|
||||
run(&mut s, p.clone());
|
||||
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks");
|
||||
run(&mut s, json!({"artboard": 2, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the first artboard's copy replaces the copied marks");
|
||||
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
/// `target` (`index` or `indices`) with the parameters each artboard copy command takes: an
|
||||
/// Alt-drag for `artboard.move`, and the artboards' art for the others.
|
||||
fn copy_params(command: &str, target: Value) -> Value {
|
||||
let mut p = match command {
|
||||
"artboard.move" => json!({"moveArt": true, "copy": true, "dy": 500, "lockedAndHidden": true}),
|
||||
_ => json!({"art": true, "lockedAndHidden": true}),
|
||||
};
|
||||
if let (Some(p), Some(t)) = (p.as_object_mut(), target.as_object()) {
|
||||
p.extend(t.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_artboard_copies_keep_one_marks_group_per_owner() {
|
||||
for command in ["artboard.duplicate", "artboard.move", "artboard.copy"] {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let first = run(&mut s, json!({"artboard": 0, "positions": ["right"]}));
|
||||
let second = run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let originals = [node(&s, first["ids"][0].as_u64().unwrap()), node(&s, second["ids"][0].as_u64().unwrap())];
|
||||
let p = copy_params(command, json!({"indices": [0, 1]}));
|
||||
s.execute(command, &p).unwrap();
|
||||
if command == "artboard.copy" {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let groups = d.layers[0].children().unwrap();
|
||||
assert_eq!(groups.len(), 4, "{command}");
|
||||
for (source, original) in originals.iter().enumerate() {
|
||||
assert!(d.node(original.id).unwrap() == original, "{command}");
|
||||
let copied_board = &d.artboards[source + 2];
|
||||
let copies: Vec<_> = groups.iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
|
||||
assert_eq!(copies.len(), 1, "{command}: owner {source}");
|
||||
let offset = copied_board.rect.origin() - d.artboards[source].rect.origin();
|
||||
assert_eq!(bounds(copies[0]), bounds(original) + offset, "{command}: owner {source}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before, "{command}: one undo restores both artboards and marks");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_board_marks_follow_artboard_copies_and_cuts_by_owner() {
|
||||
for command in ["artboard.duplicate", "artboard.move", "artboard.copy", "artboard.cut"] {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
|
||||
let original = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
|
||||
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
|
||||
assert!(bounds(&original).y1 < 0.0);
|
||||
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let p = copy_params(command, json!({"index": 0}));
|
||||
let reply = s.execute(command, &p).unwrap();
|
||||
if command == "artboard.cut" {
|
||||
assert_eq!(reply["copied"], json!(1));
|
||||
assert!(s.doc().unwrap().doc.node(original.id).is_none());
|
||||
}
|
||||
if matches!(command, "artboard.copy" | "artboard.cut") {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let copied_board = d.artboards.last().unwrap();
|
||||
let copies: Vec<_> = d.layers[0].children().unwrap().iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
|
||||
assert_eq!(copies.len(), 1, "{command}");
|
||||
assert!(d.node(foreign.id).unwrap() == &foreign, "{command}: another artboard's marks stay unchanged");
|
||||
let offset = copied_board.rect.origin() - before.artboards[0].rect.origin();
|
||||
assert_eq!(bounds(copies[0]), bounds(&original) + offset, "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
if command == "artboard.cut" {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_uses_marks_ownership_instead_of_containment() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let outside = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
|
||||
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
|
||||
let own = node(&s, outside["ids"][0].as_u64().unwrap());
|
||||
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
|
||||
assert!(bounds(&own).y1 < 0.0);
|
||||
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for (move_art, all) in [(false, true), (true, false)] {
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": move_art, "lockedAndHidden": all})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own);
|
||||
assert!(node(&s, foreign.id.0) == foreign);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let start = bounds(&own);
|
||||
let moved = bounds(&node(&s, own.id.0));
|
||||
let expected = (start.x0, start.y0 + 500.0, start.x1, start.y1 + 500.0);
|
||||
assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), expected, "the marks move 500 pt down with their artboard");
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!(board.y0, before.artboards[0].rect.y0 + 500.0, "the artboard itself moved");
|
||||
assert!(moved.y1 < board.y0, "the top marks stay above their moved artboard");
|
||||
assert!(node(&s, foreign.id.0) == foreign);
|
||||
assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let p = json!({"positions": ["right"], "inset": -200});
|
||||
run(&mut s, p.clone());
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap();
|
||||
assert_eq!(kids(&s), 1, "the locked marks stay without lockedAndHidden");
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks lying on the second artboard");
|
||||
run(&mut s, json!({"artboard": 3, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
|
||||
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[1].children().unwrap().len();
|
||||
let before = kids(&s);
|
||||
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), before + 1, "the duplicate carries a copy of the moved group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_of_a_deleted_artboard_are_copied_like_other_art() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
s.execute("artboard.delete", &json!({"indices": [0]})).unwrap();
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the duplicate carries a copy of the marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "width": 500})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the copy's marks are not the source's");
|
||||
assert_eq!(kids(&s), 2);
|
||||
run(&mut s, json!({"artboard": 1}));
|
||||
assert_eq!(kids(&s), 2, "marking the resized duplicate replaces the copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrinking_an_artboard_keeps_its_marks_when_a_new_artboard_covers_more_of_the_stored_rectangle() {
|
||||
let mut s = session();
|
||||
let original = run(&mut s, json!({}));
|
||||
let id = original["ids"][0].as_u64().unwrap();
|
||||
let before = node(&s, id);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 120, "y": 0, "width": 480, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"artboard": 1}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "marking the new artboard keeps the original group");
|
||||
assert!(node(&s, id) == before, "the original group's art and metadata stay unchanged");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
run(&mut s, json!({"artboard": 0}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none(), "marking the resized source replaces its old group");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_that_reach_onto_the_next_artboard_stay_with_their_own() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 620, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 2);
|
||||
for id in ids {
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some(), "group {id} is kept");
|
||||
}
|
||||
let again = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_leave_the_document_unchanged() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_len(&s);
|
||||
for bad in [
|
||||
json!({"positions": ["middle"]}),
|
||||
json!({"positions": ["top", "top"]}),
|
||||
json!({"positions": "top"}),
|
||||
json!({"positions": [1]}),
|
||||
json!({"size": 2}),
|
||||
json!({"size": "36"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"inset": 5000}),
|
||||
json!({"textSize": 100}),
|
||||
json!({"textPlace": "middle"}),
|
||||
json!({"textAlign": 1}),
|
||||
json!({"ink": "Nope"}),
|
||||
json!({"ink": "Process"}),
|
||||
json!({"ink": 3}),
|
||||
json!({"inks": "yes"}),
|
||||
json!({"info": 1}),
|
||||
json!({"time": "today", "info": true}),
|
||||
json!({"artboard": 5}),
|
||||
json!({"artboard": -1}),
|
||||
json!({"artboard": 0, "allArtboards": true}),
|
||||
json!({"positions": null}),
|
||||
json!({"artboard": null}),
|
||||
json!({"size": null}),
|
||||
json!({"positions": [], "inks": false, "info": false}),
|
||||
json!({"positions": [], "inks": true}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
// An ink line with no spot inks draws the targets and no line.
|
||||
let r = run(&mut s, json!({"inks": true}));
|
||||
assert_eq!(r["inks"], json!([]));
|
||||
assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_of_a_deleted_artboard_belong_to_no_artboard_that_later_takes_its_id() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
let gone = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "the marks stay as art");
|
||||
// A reopened file does not remember the deleted id, so a new artboard can take it.
|
||||
assert!(!super::managed_owners(&s.doc().unwrap().doc).values().any(|o| *o == gone), "no marks group names the deleted artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_moved_off_the_marks_layer_forget_their_deleted_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
|
||||
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
|
||||
assert_eq!(super::owner(&node(&s, r["ids"][0].as_u64().unwrap())), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_leaves_its_marks_lying_on_another_locked_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let own = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "Move Artboard leaves them on the locked artboard");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "a new position leaves them on the locked artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboard_scaled_in_the_same_call_leaves_a_moving_artboards_marks_to_it() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
let edits = json!([{"index": 1, "width": 1200}, {"index": 0, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let moved = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert_eq!((moved.x0, moved.y0, moved.width()), (start.x0, start.y0 + 500.0, start.width()), "the marks move with their own artboard, unscaled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_on_an_artboard_unlocked_in_the_same_call_stay_when_their_own_artboard_moves() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let own = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "the marks lay on a locked artboard when the call began");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "width": 1200}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "the artboard scaled in the same call leaves them too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marks_group_of_a_missing_artboard_goes_with_the_first_listed_artboard() {
|
||||
let mut s = session();
|
||||
for _ in 0..2 {
|
||||
s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
}
|
||||
let r = run(&mut s, json!({"artboard": 2, "positions": ["top"]}));
|
||||
// A file saved before deleting an artboard cleared its marks' tag.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.remove(2);
|
||||
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
let edits = json!([{"index": 0, "width": 1200}, {"index": 1, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let now = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert!(close(now.width(), start.width() * 2.0), "it scales with the first artboard listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_by_its_position_takes_its_own_marks_and_leaves_others() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let own = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}))["ids"][0].as_u64().unwrap();
|
||||
let foreign = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}))["ids"][0].as_u64().unwrap();
|
||||
let (own, foreign) = (node(&s, own), node(&s, foreign));
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let start = bounds(&own);
|
||||
let moved = bounds(&node(&s, own.id.0));
|
||||
assert_eq!((moved.x0, moved.y0), (start.x0, start.y0 + 500.0), "the marks lying above the artboard move with it");
|
||||
assert!(node(&s, foreign.id.0) == foreign, "another artboard's marks lying on it stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_drawn_on_the_active_artboard_record_it_for_a_replay() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(second);
|
||||
let start = s.journal.len();
|
||||
run(&mut s, json!({"positions": ["right"]}));
|
||||
let (cmd, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, COMMAND);
|
||||
assert_eq!(recorded["activeArtboard"], json!(1), "the journal names the artboard the marks went on");
|
||||
// A replay on another active artboard marks the recorded one.
|
||||
let first = s.doc().unwrap().doc.artboards[0].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(first);
|
||||
let replayed = run(&mut s, recorded);
|
||||
assert_eq!(replayed["changed"], json!(false), "the second artboard's marks are drawn again the same");
|
||||
// A recorded action leaves it out and marks the artboard active when it plays.
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action.len(), 2, "the action holds the first run and the replay");
|
||||
assert!(action.iter().all(|(_, p)| p.get("activeArtboard").is_none()));
|
||||
}
|
||||
@@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
src.children()
|
||||
.and_then(|c| c.first())
|
||||
@@ -1225,17 +1225,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
// Tracing again keeps the tracing's own object settings: opacity, blend mode, its
|
||||
// appearance items, visibility and lock.
|
||||
if !expand && is_trace_group(&src) {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
// Tracing again keeps the tracing's note, tags and URL, including when expanding.
|
||||
// Without expansion, it also keeps the tracing's other object settings.
|
||||
if is_trace_group(&src) {
|
||||
// The attributes move from `src`, this edit's own copy of the tracing, without another copy.
|
||||
if src.extras().attrs.is_some() {
|
||||
g.extras_mut().attrs = src.extras_mut().attrs.take();
|
||||
}
|
||||
if !expand {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
}
|
||||
}
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
|
||||
@@ -174,7 +174,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it (in the document the style was picked in; elsewhere it is not linked), and its placed gradients fit the frame text wrap gives it",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -255,6 +255,7 @@ fn insert_look_turned(
|
||||
}
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let pre = wrap_snapshot(d, &n, &look);
|
||||
let mut into = None;
|
||||
match (mode, inside) {
|
||||
(crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => {
|
||||
@@ -274,6 +275,7 @@ fn insert_look_turned(
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
}
|
||||
place_after_wrap(d, pre, id, &look);
|
||||
if select {
|
||||
sel.set([id]);
|
||||
}
|
||||
@@ -988,20 +990,42 @@ fn text_parent(s: &Session, p: &Value) -> Result<Option<NodeId>> {
|
||||
}
|
||||
|
||||
/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected.
|
||||
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result<Value> {
|
||||
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewArt, bbox_angle: f64) -> Result<Value> {
|
||||
let id = s.edit("Type", |d, sel| {
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
NewArt::plain(Appearance::default()).apply(d, &mut n);
|
||||
look.apply(d, &mut n);
|
||||
super::object::align_new_object(d, &mut n);
|
||||
n.bbox_angle = bbox_angle;
|
||||
let pre = wrap_snapshot(d, &n, &look);
|
||||
d.insert(Some(parent), usize::MAX, n)?;
|
||||
place_after_wrap(d, pre, id, &look);
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The document before new type `n` goes in, when `look` places gradients on it: text wrap can
|
||||
/// reflow the type once it is in ([`place_after_wrap`]).
|
||||
fn wrap_snapshot(d: &vectorcraft_doc::Document, n: &Node, look: &NewArt) -> Option<vectorcraft_doc::Document> {
|
||||
(matches!(n.kind, NodeKind::Text(_)) && look.places_gradients()).then(|| d.clone())
|
||||
}
|
||||
|
||||
/// New type `id` just inserted into `d` (`pre`: `d` before, from [`wrap_snapshot`]): text wrap
|
||||
/// reflows it now, and when that changes its bounds (an Auto Size frame below a wrap object grows),
|
||||
/// `look`'s gradients are placed on the bounds it ends with.
|
||||
fn place_after_wrap(d: &mut vectorcraft_doc::Document, pre: Option<vectorcraft_doc::Document>, id: NodeId, look: &NewArt) {
|
||||
let Some(pre) = pre else { return };
|
||||
let placed_on = d.node(id).and_then(Node::geometric_bounds);
|
||||
super::textwrap::refresh(&pre, d);
|
||||
if let Some(n) = d.node_mut(id)
|
||||
&& n.geometric_bounds() != placed_on
|
||||
{
|
||||
look.place(n);
|
||||
}
|
||||
}
|
||||
|
||||
fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parent = text_parent(s, p)?;
|
||||
let x = f64_req(p, "x", "text.create")?;
|
||||
@@ -1040,11 +1064,16 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
// New art's fills, strokes and effects (New Art Has Basic Appearance off, or a graphic style
|
||||
// picked with nothing selected), with the characters' paint under Override Character Color as
|
||||
// graphicStyle.apply gives type; a `color` given keeps the characters' fill.
|
||||
let look = s.new_type_look();
|
||||
if s.prefs.override_char_color {
|
||||
super::style::override_text_chars(&mut t, &look.appearance, p.get("color").and_then(color_value).is_none());
|
||||
}
|
||||
let made = match parent {
|
||||
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?,
|
||||
None => {
|
||||
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?
|
||||
}
|
||||
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), look, bbox_turn(rotation))?,
|
||||
None => insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), look, None, true, bbox_turn(rotation), true)?,
|
||||
};
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
|
||||
@@ -26,7 +26,9 @@ pub use perspective::perspective_click;
|
||||
use perspective::{
|
||||
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
|
||||
};
|
||||
pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again};
|
||||
pub(crate) use perspective::{
|
||||
finish_edit_text, grid_kept, grid_of, only_grid_view_changed, perspective_rewrite, silent, store_grid, transform_again,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
|
||||
@@ -24,6 +24,37 @@ pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
|
||||
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
|
||||
}
|
||||
|
||||
/// Whether `now` differs from `before` only in the view state of its perspective grid (whether it
|
||||
/// shows, the active plane, the point Automatic Plane Positioning holds and the view options), the
|
||||
/// changes [`silent`] makes without an undo step.
|
||||
pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool {
|
||||
let (a, b) = (now.unknown.get(persp::DOC_KEY), before.unknown.get(persp::DOC_KEY));
|
||||
if a == b {
|
||||
return false;
|
||||
}
|
||||
let (mut g, mut was) = (PerspectiveGrid::current(now), PerspectiveGrid::current(before));
|
||||
g.visible = was.visible;
|
||||
g.plane = was.plane;
|
||||
g.inferred = was.inferred;
|
||||
g.locked = was.locked;
|
||||
g.lock_station = was.lock_station;
|
||||
g.snap = was.snap;
|
||||
g.rulers = was.rulers;
|
||||
g.attached.clear();
|
||||
was.attached.clear();
|
||||
if serde_json::to_value(&g).ok() != serde_json::to_value(&was).ok() {
|
||||
return false;
|
||||
}
|
||||
let mut rest = now.clone();
|
||||
let mut normalized_before = before.clone();
|
||||
PerspectiveGrid::current(before).store(&mut normalized_before);
|
||||
match normalized_before.unknown.get(persp::DOC_KEY) {
|
||||
Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()),
|
||||
None => rest.unknown.remove(persp::DOC_KEY),
|
||||
};
|
||||
rest == normalized_before
|
||||
}
|
||||
|
||||
/// Change view state of the grid without an undo step.
|
||||
pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result<PerspectiveGrid> {
|
||||
let st = s.doc_mut()?;
|
||||
|
||||
@@ -189,7 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted, except the Screen Print Marks layer for the marks copied with their artboard). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
@@ -1363,17 +1363,15 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let clipped = clipped_ancestors(d, ids.iter().copied());
|
||||
let parents: Vec<_> = if keep_empty {
|
||||
Vec::new()
|
||||
} else {
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect()
|
||||
};
|
||||
let emptied = if keep_empty { Vec::new() } else { emptied_compounds(d, &ids) };
|
||||
// A compound path inside another emptied one leaves with it.
|
||||
let outer: Vec<NodeId> = emptied
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|p| !d.ancestry(*p).unwrap_or_default().iter().rev().skip(1).any(|a| emptied.binary_search(a).is_ok()))
|
||||
.collect();
|
||||
d.remove_many(&ids)?;
|
||||
for p in parents {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
d.remove(p)?;
|
||||
}
|
||||
}
|
||||
d.remove_many(&outer)?;
|
||||
if with_guides {
|
||||
let gone = sel.guides.clone();
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
@@ -1390,6 +1388,27 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The compound paths that deleting the objects `ids` together leaves with no members, sorted by
|
||||
/// id: a compound path counts when each of its members is deleted or is such a compound path, so
|
||||
/// a compound path holding only an emptied inner one is emptied too.
|
||||
fn emptied_compounds(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut gone: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut emptied = BTreeSet::new();
|
||||
loop {
|
||||
let parents: BTreeSet<NodeId> = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect();
|
||||
let found: BTreeSet<NodeId> = parents
|
||||
.into_iter()
|
||||
.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))
|
||||
.filter(|p| d.children(Some(*p)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id))))
|
||||
.collect();
|
||||
if found.is_empty() {
|
||||
return emptied.into_iter().collect();
|
||||
}
|
||||
gone.extend(found.iter().copied());
|
||||
emptied.extend(found);
|
||||
}
|
||||
}
|
||||
|
||||
/// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else
|
||||
/// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a
|
||||
/// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined`
|
||||
@@ -1638,9 +1657,16 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
&& inside.is_none()
|
||||
&& (st.doc.paste_remembers_layers || boards.is_some())
|
||||
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
|
||||
// Screen print marks copied with an artboard that is pasted once go back into the marks layer,
|
||||
// locked or hidden as it is.
|
||||
let pasted_once: Vec<u32> = match boards {
|
||||
Some((all, _)) => all.iter().map(|a| a.id).filter(|id| all.iter().filter(|a| a.id == *id).count() == 1).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
let marks: Vec<bool> = clip.nodes.iter().map(|n| super::addons::screen_marks_of(n, &pasted_once)).collect();
|
||||
// Each object's remembered layer, found before anything is pasted: a hidden or locked one
|
||||
// refuses the whole paste.
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] };
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, &marks, same_doc)? } else { vec![] };
|
||||
// Front/back: relative to the selection (top-most / bottom-most selected object); with
|
||||
// nothing selected, the top / bottom of the current layer. Art other than paths goes beside
|
||||
// the compound path that holds the selected object, not into it.
|
||||
@@ -1681,13 +1707,22 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let mut imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
let made_boards: Vec<(u32, usize)> = boards
|
||||
.into_iter()
|
||||
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
|
||||
.map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv))
|
||||
.map(|(a, dv)| (a.id, super::panelcmds::push_artboard_copy(d, a, a.rect + dv)))
|
||||
.collect();
|
||||
let artboards: Vec<usize> = made_boards.iter().map(|(_, i)| *i).collect();
|
||||
// Screen print marks copied with an artboard pasted once belong to the pasted artboard.
|
||||
let board_ids: Vec<(u32, u32)> = made_boards
|
||||
.iter()
|
||||
.filter(|(src, _)| made_boards.iter().filter(|(s, _)| s == src).count() == 1)
|
||||
.filter_map(|(src, i)| d.artboards.get(*i).map(|a| (*src, a.id)))
|
||||
.collect();
|
||||
// The layers made for remembered layers the document lacks, by parent and name.
|
||||
let mut made = HashMap::new();
|
||||
// The marks layer made for screen print marks, kept apart from ordinary layers of its name.
|
||||
let mut made_marks: HashMap<(Option<NodeId>, String), NodeId> = HashMap::new();
|
||||
// Objects pasted into each parent so far (keeps their order in front and back pastes).
|
||||
let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new();
|
||||
let mut new_ids = vec![];
|
||||
@@ -1702,6 +1737,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c, d);
|
||||
let marks = board_ids.iter().any(|(from, to)| super::addons::retag_screen_marks(&mut c, *from, *to));
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
@@ -1710,7 +1746,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
let layer = match remembered.get(k) {
|
||||
Some(Some(Remembered::Layer(l))) => Some(*l),
|
||||
Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?,
|
||||
Some(Some(Remembered::Make { parent, names })) => make_remembered(d, &mut made, &mut made_marks, marks, *parent, names)?,
|
||||
_ => None,
|
||||
};
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: art pasted
|
||||
@@ -1850,18 +1886,27 @@ enum Remembered {
|
||||
Make { parent: Option<NodeId>, names: Vec<String> },
|
||||
}
|
||||
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new();
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer. The objects
|
||||
/// `marks` marks are screen print marks groups, which may go back into the marks layer while it
|
||||
/// is locked or hidden.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], marks: &[bool], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<(&SourceLayer, bool), Remembered> = HashMap::new();
|
||||
sources
|
||||
.iter()
|
||||
.map(|src| {
|
||||
.enumerate()
|
||||
.map(|(k, src)| {
|
||||
// A marks group goes into the marks layer even when the layer it was copied from has
|
||||
// no name.
|
||||
if marks.get(k).copied().unwrap_or(false) && src.is_none() {
|
||||
return Ok(Some(marks_layer_target(d)));
|
||||
}
|
||||
let Some(src) = src else { return Ok(None) };
|
||||
if let Some(r) = found.get(src) {
|
||||
let key = (src, marks.get(k).copied().unwrap_or(false));
|
||||
if let Some(r) = found.get(&key) {
|
||||
return Ok(Some(r.clone()));
|
||||
}
|
||||
let r = remembered_layer(d, src, same_doc)?;
|
||||
found.insert(src, r.clone());
|
||||
let r = remembered_layer(d, src, key.1, same_doc)?;
|
||||
found.insert(key, r.clone());
|
||||
Ok(Some(r))
|
||||
})
|
||||
.collect()
|
||||
@@ -1872,8 +1917,15 @@ fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bo
|
||||
/// it still where they were (by id) are kept. Below them, and in another document from the top,
|
||||
/// each name is matched among the layers inside the one above (the topmost of the same name whose
|
||||
/// layers match the most names, a shown and unlocked one first). The names left unmatched are
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> {
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error. A screen
|
||||
/// print marks group (`marks`) goes into the document's marks layer, locked or hidden as it is,
|
||||
/// or into a new top-level marks layer when the document has none.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result<Remembered> {
|
||||
// A marks group goes into the document's marks layer, never into an ordinary layer of the
|
||||
// same name.
|
||||
if marks {
|
||||
return Ok(marks_layer_target(d));
|
||||
}
|
||||
let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last());
|
||||
let kept = if same_doc && src.ids.last().is_some_and(held) {
|
||||
src.ids.len()
|
||||
@@ -1898,6 +1950,15 @@ fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<R
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a screen print marks group goes: the document's marks layer, locked or hidden as it is,
|
||||
/// or a new top-level marks layer when the document has none.
|
||||
fn marks_layer_target(d: &Document) -> Remembered {
|
||||
match super::addons::screen_marks_layer(d) {
|
||||
Some(l) => Remembered::Layer(l),
|
||||
None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] },
|
||||
}
|
||||
}
|
||||
|
||||
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
|
||||
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
|
||||
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
|
||||
@@ -1908,7 +1969,9 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
None => Some(&d.layers),
|
||||
Some(p) => d.node(p).and_then(Node::children),
|
||||
};
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
|
||||
// Ordinary art never goes into the screen print marks layer by its name.
|
||||
let marks_layer = parent.is_none().then(|| super::addons::screen_marks_layer(d)).flatten();
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str()) && Some(l.id) != marks_layer) {
|
||||
let (end, n, open) = named_chain(d, Some(l.id), rest);
|
||||
let chain = (end, n + 1, open && l.visible && !l.locked);
|
||||
if (chain.1, chain.2) > (best.1, best.2) {
|
||||
@@ -1918,6 +1981,25 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
best
|
||||
}
|
||||
|
||||
/// Makes the layers of a `Remembered::Make` for one pasted object. The marks layer for a screen
|
||||
/// print marks group (`marks`) is made apart from ordinary layers of its name (`made_marks`) and
|
||||
/// becomes the marks layer, so Create Screen Print Marks finds the copy there.
|
||||
fn make_remembered(
|
||||
d: &mut Document,
|
||||
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
made_marks: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
marks: bool,
|
||||
parent: Option<NodeId>,
|
||||
names: &[String],
|
||||
) -> Result<Option<NodeId>> {
|
||||
let is_marks = marks && parent.is_none() && matches!(names, [n] if n == super::addons::SCREEN_MARKS_LAYER);
|
||||
let last = make_layers(d, if is_marks { made_marks } else { made }, parent, names)?;
|
||||
if let (true, Some(l)) = (is_marks, last) {
|
||||
super::addons::adopt_screen_marks_layer(d, l);
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
|
||||
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
|
||||
/// none when `names` is empty.
|
||||
|
||||
@@ -400,3 +400,59 @@ fn selected_roots_are_found_once_for_each_document_and_selection() {
|
||||
selected_roots(&s).unwrap();
|
||||
assert_eq!(roots_found() - before, 2, "an edit finds the roots once again");
|
||||
}
|
||||
|
||||
/// Clear removes a compound path whose members are cleared paths and a compound path the clear
|
||||
/// empties, whichever order the ids come in, and the tracing guard's set counts both as deleted.
|
||||
#[test]
|
||||
fn clear_removes_a_compound_path_emptied_through_an_emptied_inner_one() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = new_doc();
|
||||
let outer_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (outer, outer_members) = compound(&mut s, &outer_paths);
|
||||
let inner_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (inner, inner_members) = compound(&mut s, &inner_paths);
|
||||
s.edit("Nest", |d, _| {
|
||||
let taken = d.remove_many(&[inner])?;
|
||||
d.insert(Some(outer), 1, (*taken[0]).clone())?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut ids: Vec<NodeId> = outer_members.iter().chain(&inner_members).copied().collect();
|
||||
if reversed {
|
||||
ids.reverse();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(inner), Some(outer), "the inner compound path is a member of the outer one");
|
||||
let want: Vec<NodeId> = BTreeSet::from([outer, inner]).into_iter().collect();
|
||||
assert_eq!(emptied_compounds(d, &ids), want, "reversed: {reversed}");
|
||||
run(&mut s, "edit.clear", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the emptied inner compound path goes (reversed: {reversed})");
|
||||
assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too (reversed: {reversed})");
|
||||
}
|
||||
}
|
||||
|
||||
/// With a direct-selected anchor of another path in the selection, Clear still removes the outer
|
||||
/// compound path that an emptied inner one leaves empty.
|
||||
#[test]
|
||||
fn clear_with_direct_anchors_removes_a_compound_path_emptied_through_an_emptied_inner_one() {
|
||||
let mut s = new_doc();
|
||||
let outer_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (outer, outer_members) = compound(&mut s, &outer_paths);
|
||||
let inner_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (inner, inner_members) = compound(&mut s, &inner_paths);
|
||||
let other = rect(&mut s);
|
||||
s.edit("Nest", |d, _| {
|
||||
let taken = d.remove_many(&[inner])?;
|
||||
d.insert(Some(outer), 1, (*taken[0]).clone())?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let whole: Vec<NodeId> = outer_members.iter().chain(&inner_members).copied().collect();
|
||||
select_direct(&mut s, &whole, &[(other, two_anchors())]);
|
||||
run(&mut s, "edit.clear", json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the emptied inner compound path goes");
|
||||
assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too");
|
||||
assert!(d.node(other).is_some(), "the path with anchors picked keeps its other sides");
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker).
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT and CGM open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it).
|
||||
@@ -151,9 +151,9 @@ mod formats;
|
||||
pub(crate) use access::FILES_READ;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{READ_TOO_LARGE, check_images_in, check_scripts_of, with_read_limit, with_readable_settings_folder};
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE};
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
@@ -246,6 +246,9 @@ mod tests_svgimport;
|
||||
#[cfg(test)]
|
||||
mod tests_eps;
|
||||
|
||||
// The CGM reader waits on craft-libs#5410 (the `cgm` feature).
|
||||
#[cfg(all(test, feature = "cgm"))]
|
||||
mod tests_cgm;
|
||||
#[cfg(test)]
|
||||
mod tests_dwgimport;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -283,6 +283,23 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
|
||||
|
||||
thread_local! {
|
||||
static READ_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
pub(crate) const READ_TOO_LARGE: &str = "File exceeds scoped read limit";
|
||||
|
||||
pub(crate) fn with_read_limit<T>(max: usize, f: impl FnOnce() -> T) -> T {
|
||||
struct Restore(Option<usize>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
READ_LIMIT.with(|limit| limit.set(self.0));
|
||||
}
|
||||
}
|
||||
let _restore = Restore(READ_LIMIT.with(|limit| limit.replace(Some(limit.get().map_or(max, |outer| outer.min(max))))));
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
thread_local! {
|
||||
/// The paths [`read_file`] has read on this thread, in order.
|
||||
@@ -299,27 +316,35 @@ pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
if crate::file_access::in_script_command() {
|
||||
let max = SCRIPT_OPEN_MAX_BYTES;
|
||||
let read = || -> std::io::Result<Vec<u8>> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let meta = file.metadata()?;
|
||||
if !meta.is_file() {
|
||||
return Err(std::io::Error::other("not a file"));
|
||||
}
|
||||
if meta.len() > max as u64 {
|
||||
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(max as u64 + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > max {
|
||||
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
read().map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
} else {
|
||||
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
// A script command reads at most `SCRIPT_OPEN_MAX_BYTES`, and a scoped limit
|
||||
// (`with_read_limit`) at most its own count, whichever is smaller.
|
||||
let script = crate::file_access::in_script_command().then_some(SCRIPT_OPEN_MAX_BYTES);
|
||||
let scoped = READ_LIMIT.with(std::cell::Cell::get);
|
||||
let Some(cap) = [script, scoped].into_iter().flatten().min() else {
|
||||
return std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")));
|
||||
};
|
||||
let too_large = |bytes: u64| {
|
||||
if script.is_some_and(|max| bytes > max as u64) {
|
||||
Some(EngineError::Other(format!("{path}: {SCRIPT_OPEN_TOO_LARGE}")))
|
||||
} else if scoped.is_some_and(|max| bytes > max as u64) {
|
||||
Some(EngineError::Other(READ_TOO_LARGE.into()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let file = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let meta = file.metadata().map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if !meta.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
if let Some(e) = too_large(meta.len()) {
|
||||
return Err(e);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(cap as u64 + 1).read_to_end(&mut bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
match too_large(bytes.len() as u64) {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -748,6 +773,28 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
#[test]
|
||||
fn scoped_read_limit_bounds_reads_and_restores_the_previous_limit() {
|
||||
let path = std::env::temp_dir().join(format!("vc-access-read-limit-{}", std::process::id()));
|
||||
std::fs::write(&path, b"12345").unwrap();
|
||||
let path_text = path.to_str().unwrap();
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
with_read_limit(5, || {
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
with_read_limit(4, || {
|
||||
assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE);
|
||||
with_read_limit(6, || assert!(read_file(path_text).is_err()));
|
||||
});
|
||||
assert_eq!(read_file(path_text).unwrap(), b"12345");
|
||||
std::fs::write(&path, b"123456").unwrap();
|
||||
assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE);
|
||||
});
|
||||
assert_eq!(read_file(path_text).unwrap(), b"123456");
|
||||
let _ = std::panic::catch_unwind(|| with_read_limit(0, || panic!("test unwind")));
|
||||
assert_eq!(read_file(path_text).unwrap(), b"123456");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
/// An error about a path the client did not give, under roots that don't let it be read: the
|
||||
/// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no
|
||||
/// name or its name is not valid text, and every root and the reason stay whole. A path inside the
|
||||
|
||||
@@ -76,6 +76,16 @@ pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec<S
|
||||
Ok((r.document, r.warnings))
|
||||
}
|
||||
|
||||
/// A note for each linked image of a DXF or DWG drawing whose file is missing (the `missing` rows
|
||||
/// of [`crate::cmd::links::resolve`]): it shows a placeholder.
|
||||
pub(crate) fn missing_image_notes(missing: &[Value]) -> Vec<String> {
|
||||
missing
|
||||
.iter()
|
||||
.filter_map(|row| row["name"].as_str())
|
||||
.map(|name| format!("linked image '{name}' wasn't found: a placeholder keeps its place until it is relinked"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
const INFO: &str = "document.dxfInfo";
|
||||
|
||||
fn dxf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -135,6 +135,27 @@ pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `\` separates folders in a path: on Windows and on the web, where paths may come from
|
||||
/// Windows. On other platforms `\` is a character of a file name.
|
||||
const BACKSLASH_SEPARATES: bool = cfg!(any(windows, target_arch = "wasm32"));
|
||||
|
||||
/// The length of `path`'s folder part, its last separator included.
|
||||
fn dir_len(path: &str, backslash: bool) -> usize {
|
||||
let at = if backslash { path.rfind(['/', '\\']) } else { path.rfind('/') };
|
||||
at.map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dir_tests {
|
||||
#[test]
|
||||
fn a_backslash_is_part_of_a_file_name_where_it_does_not_separate_folders() {
|
||||
assert_eq!(super::dir_len("out/a\\b.svg", false), 4, "the file a\\b.svg is in out/");
|
||||
assert_eq!(super::dir_len("a\\b.svg", false), 0);
|
||||
assert_eq!(super::dir_len("out\\a\\b.svg", true), 6);
|
||||
assert_eq!(super::dir_len("b.svg", true), 0);
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoded {
|
||||
pub(super) fn one(bytes: Vec<u8>) -> Self {
|
||||
Self { files: vec![(None, bytes)], ..Self::default() }
|
||||
@@ -180,7 +201,7 @@ impl Encoded {
|
||||
/// under their own names, then the image maps as `{image stem}.html` or `.map`.
|
||||
pub fn named<'a>(&'a self, doc: &Document, path: &str) -> Vec<(String, Cow<'a, [u8]>)> {
|
||||
// Siblings keep the path's own separators (this runs on every platform and on the web).
|
||||
let dir = &path[..path.rfind(['/', '\\']).map_or(0, |i| i + 1)];
|
||||
let dir = &path[..dir_len(path, BACKSLASH_SEPARATES)];
|
||||
let sibling = |name: &str| format!("{dir}{name}");
|
||||
let mut out: Vec<(String, Cow<[u8]>)> = match self.files.as_slice() {
|
||||
[(_, bytes)] => vec![(path.to_string(), Cow::Borrowed(bytes.as_slice()))],
|
||||
|
||||
@@ -45,9 +45,10 @@ pub(crate) fn unique_file_names_keeping_dots<'a>(names: impl IntoIterator<Item =
|
||||
}))
|
||||
}
|
||||
|
||||
/// `names` with `-2`, `-3`… after a name already used (compared without case).
|
||||
/// `names` with `-2`, `-3`… after a name already used (compared without case, as
|
||||
/// [`super::screens::fold`] compares them).
|
||||
pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<String> {
|
||||
distinct_names_by(names, str::to_lowercase)
|
||||
distinct_names_by(names, super::screens::fold)
|
||||
}
|
||||
|
||||
/// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same
|
||||
@@ -93,6 +94,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)));
|
||||
}
|
||||
}
|
||||
distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write_file(p, bytes)?;
|
||||
@@ -112,6 +114,62 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
|
||||
/// An error when two of `paths` are the same file. A link that leads nowhere is compared by the file
|
||||
/// its write creates; another path whose real path cannot be found (a folder that may not be read)
|
||||
/// is compared as written, and its write then reports its own error. Two names in one folder that
|
||||
/// differ only in letter case are treated as the same file on every volume.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator<Item = &'a str>) -> Result<()> {
|
||||
let mut targets = std::collections::HashSet::new();
|
||||
for path in paths {
|
||||
let real = crate::file_access::resolve(path)
|
||||
.ok()
|
||||
.or_else(|| dangling_target(path))
|
||||
.or_else(|| std::path::absolute(path).ok())
|
||||
.unwrap_or_else(|| std::path::PathBuf::from(path));
|
||||
let key = match (real.parent(), real.file_name().and_then(|n| n.to_str())) {
|
||||
(Some(dir), Some(name)) => dir.join(super::screens::fold(name)),
|
||||
_ => real,
|
||||
};
|
||||
if !targets.insert(key) {
|
||||
return Err(EngineError::Other("output destinations resolve to the same file".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The file a write to `path` creates when `path` is a link (or a chain of at most 40 links) that
|
||||
/// leads to a file that does not exist yet.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn dangling_target(path: &str) -> Option<std::path::PathBuf> {
|
||||
let mut at = std::path::PathBuf::from(path);
|
||||
let mut followed = false;
|
||||
for _ in 0..40 {
|
||||
if !std::fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
break;
|
||||
}
|
||||
let next = std::fs::read_link(&at).ok()?;
|
||||
at = match at.parent() {
|
||||
Some(parent) if next.is_relative() => parent.join(next),
|
||||
_ => next,
|
||||
};
|
||||
followed = true;
|
||||
}
|
||||
if !followed {
|
||||
return None;
|
||||
}
|
||||
// Resolved as the primary destination is; a name that is not UTF-8 keeps its bytes, with its
|
||||
// folder's links followed.
|
||||
match at.to_str() {
|
||||
Some(text) => crate::file_access::resolve(text).ok(),
|
||||
None => {
|
||||
let folder = std::fs::canonicalize(at.parent()?).ok()?;
|
||||
Some(folder.join(at.file_name()?))
|
||||
}
|
||||
}
|
||||
.or_else(|| std::path::absolute(&at).ok())
|
||||
}
|
||||
|
||||
/// `a` with the fields of `b`.
|
||||
pub(crate) fn merge(mut a: Value, b: Value) -> Value {
|
||||
if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) {
|
||||
@@ -143,3 +201,37 @@ pub(crate) fn write_or_return(path: Option<&str>, bytes: &[u8], extra: Value) ->
|
||||
};
|
||||
Ok(merge(out, extra))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn folder(tag: &str) -> std::io::Result<std::path::PathBuf> {
|
||||
let d = std::env::temp_dir().join(format!("vc-export-names-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_differing_only_in_case_are_one_file() {
|
||||
let d = folder("case").unwrap();
|
||||
let s = |n: &str| d.join(n).to_str().unwrap().to_string();
|
||||
assert!(distinct_write_targets([s("a.svg").as_str(), s("A.svg").as_str()]).is_err());
|
||||
assert!(distinct_write_targets([s("ας.svg").as_str(), s("ΑΣ.svg").as_str()]).is_err(), "a final sigma");
|
||||
assert!(distinct_write_targets([s("S.svg").as_str(), s("ſ.svg").as_str()]).is_err(), "a long s");
|
||||
assert_eq!(distinct_names(["ας".to_string(), "ασ".to_string()]), ["ας", "ασ-2"]);
|
||||
assert!(distinct_write_targets([s("a.svg").as_str(), s("b.svg").as_str()]).is_ok());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_dangling_link_to_a_case_variant_of_another_destination_is_the_same_file() {
|
||||
let d = folder("link").unwrap();
|
||||
std::os::unix::fs::symlink("A.svg", d.join("side.svg")).unwrap();
|
||||
let (a, side) = (d.join("a.svg"), d.join("side.svg"));
|
||||
assert!(distinct_write_targets([a.to_str().unwrap(), side.to_str().unwrap()]).is_err());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -577,6 +577,10 @@ pub const FORMATS: &[Format] = &[
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
// Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths,
|
||||
// type and images. Behind the `cgm` feature until craft-libs#5410 merges.
|
||||
#[cfg(feature = "cgm")]
|
||||
reader("cgm", "CGM", &["cgm"], "image/cgm", false),
|
||||
// Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size
|
||||
// composite, the layers combined, or the preview with a note. Exports don't write them.
|
||||
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
|
||||
@@ -640,6 +644,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
@@ -666,7 +672,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers
|
||||
/// offer VectorCraft for them.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here
|
||||
/// when the `cgm` feature is turned on (craft-libs#5410).
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c",
|
||||
"jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
@@ -747,6 +754,8 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
|
||||
@@ -134,6 +134,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
|
||||
return format(kind.id());
|
||||
}
|
||||
if vectorcraft_metafile::is_cgm(bytes) {
|
||||
return format("cgm");
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
|
||||
}
|
||||
@@ -581,6 +584,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings) = super::metafile::import_pict(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"cgm" => {
|
||||
let (doc, warnings) = super::metafile::import_cgm(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"hpgl" => {
|
||||
let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?;
|
||||
(i.document, i.warnings, false)
|
||||
@@ -920,6 +927,9 @@ impl ReadFile {
|
||||
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
|
||||
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
|
||||
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
|
||||
if matches!(self.loaded.format.id, "dxf" | "dwg") {
|
||||
self.loaded.warnings.extend(super::dxfimport::missing_image_notes(&self.links.missing));
|
||||
}
|
||||
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
|
||||
if !self.loaded.warnings.contains(¬e) {
|
||||
self.loaded.warnings.push(note);
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per
|
||||
//! artboard with Use Artboards; raster effects as images, rendered at the document's raster
|
||||
//! effects resolution), `document.open` and File → Place (one artboard, the picture's frame).
|
||||
//! QuickDraw pictures (PICT) open and place the same way; they are never written.
|
||||
//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same
|
||||
//! way; they are never written.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -78,3 +79,9 @@ pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?;
|
||||
Ok((p.document, p.warnings))
|
||||
}
|
||||
|
||||
/// A binary CGM's first picture as a document, and the import's warnings.
|
||||
pub(super) fn import_cgm(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let p = vectorcraft_metafile::import_cgm(bytes).map_err(super::err)?;
|
||||
Ok((p.document, p.warnings))
|
||||
}
|
||||
|
||||
@@ -626,7 +626,7 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> {
|
||||
/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`.
|
||||
/// Dotless `ı` stays `ı`, as NTFS and Unicode case folding outside Turkic languages keep it apart
|
||||
/// from `i` and `I`.
|
||||
fn fold(name: &str) -> String {
|
||||
pub(super) fn fold(name: &str) -> String {
|
||||
name.to_lowercase()
|
||||
.chars()
|
||||
.map(|c| {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Binary CGM files through the commands: `document.open` by extension or by content, File › Place
|
||||
//! as one group clipped to the picture's frame, the dialogs' filters and the format list, and
|
||||
//! files that aren't binary CGM, or a CGM export, refused with a message.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
vectorcraft_format::base64_encode(bytes)
|
||||
}
|
||||
|
||||
/// One element, padded to an even length.
|
||||
fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = ((class << 12) | (id << 5) | data.len() as u16).to_be_bytes().to_vec();
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn words(v: &[i16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A binary CGM whose picture is 1000 × 500 units at 0.2 mm a unit (200 × 100 mm): a solid
|
||||
/// rectangle and a line.
|
||||
fn picture() -> Vec<u8> {
|
||||
let mut b = el(0, 1, b"\x04logo");
|
||||
b.extend(el(1, 1, &words(&[1])));
|
||||
b.extend(el(0, 3, b"\x01p"));
|
||||
b.extend(el(2, 1, &[words(&[1]), 0.2f32.to_be_bytes().to_vec()].concat()));
|
||||
b.extend(el(2, 6, &words(&[0, 0, 1000, 500])));
|
||||
b.extend(el(0, 4, &[]));
|
||||
b.extend(el(5, 22, &words(&[1])));
|
||||
b.extend(el(4, 11, &words(&[100, 100, 400, 300])));
|
||||
b.extend(el(4, 1, &words(&[0, 450, 1000, 450])));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
const MM: f64 = 72.0 / 25.4;
|
||||
|
||||
#[test]
|
||||
fn document_open_reads_a_picture() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": "part.cgm", "dataBase64": b64(&picture())})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("cgm"), Some("part.cgm")), "{r}");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let st = s.doc().unwrap();
|
||||
let size = st.doc.artboards[0].rect.size();
|
||||
assert!((size.width - 200.0 * MM).abs() < 1e-3 && (size.height - 100.0 * MM).abs() < 1e-3, "{size:?}");
|
||||
let mut paths = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
paths.push(n.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 2);
|
||||
let b = paths[0].geometric_bounds().unwrap();
|
||||
assert!((b.x0 - 20.0 * MM).abs() < 1e-3 && (b.width() - 60.0 * MM).abs() < 1e-3, "{b:?}");
|
||||
assert!(st.path.is_none(), "opened as artwork: Save asks for a name");
|
||||
|
||||
// A CGM opens by its content under a name no format reads.
|
||||
for name in ["part.CGM", "part.bin", "part"] {
|
||||
let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap();
|
||||
assert_eq!(r["format"].as_str(), Some("cgm"), "{name}: {r}");
|
||||
}
|
||||
assert_eq!(detect("part.dat", &picture()).map(|f| f.id), Some("cgm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_place_places_a_picture_as_one_clipped_group() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let p = json!({"name": "part.cgm", "dataBase64": b64(&picture()), "at": [400, 400]});
|
||||
let info = s.execute("file.place.info", &p).unwrap();
|
||||
assert_eq!(info["format"], "cgm", "{info}");
|
||||
assert!((info["width"].as_f64().unwrap() - 200.0 * MM).abs() < 1e-3, "{info}");
|
||||
let r = s.execute("file.place", &p).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("cgm"), Some(1)), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
assert_eq!(group.name.as_deref(), Some("part.cgm"));
|
||||
let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) };
|
||||
let b = group.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 200.0 * MM).abs() < 1e-3 && (b.height() - 100.0 * MM).abs() < 1e-3, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_cgm_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let e = s.execute("document.open", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).expect_err("refused");
|
||||
assert!(e.to_string().contains("not a CGM file"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into());
|
||||
assert!(s.execute("file.place", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).is_err());
|
||||
let e = s.execute("document.open", &json!({"name": "text.cgm", "dataBase64": b64(b"BEGMF 'x';")})).expect_err("refused");
|
||||
assert!(e.to_string().contains("only binary CGM files"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": "cgm"})).expect_err("refused").to_string();
|
||||
assert!(e.contains("CGM files can be opened but not written"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dialogs_and_the_format_list_name_cgm() {
|
||||
assert!(OPEN_EXTS.contains(&"cgm") && PLACE_EXTS.contains(&"cgm") && UNASSOCIATED_EXTS.contains(&"cgm"));
|
||||
assert_eq!(format_for_name("a.cgm").map(|f| f.id), Some("cgm"));
|
||||
let filter = ("CGM", &["cgm"][..]);
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = Session::new().execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "cgm").unwrap().clone();
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}");
|
||||
assert_eq!(f["mime"], "image/cgm");
|
||||
assert!(writable_format(None, Some("x/part.cgm")).is_err());
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! DXF through the commands: `document.open` with the DXF options, `document.dxfInfo`,
|
||||
//! File → Place of a drawing (fitted, centred or at its origin), the format table, binary files,
|
||||
//! and a drawing `document.export` wrote opened again.
|
||||
//! a drawing `document.export` wrote opened again, and the image files a drawing links to.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
@@ -268,3 +268,102 @@ fn a_drawing_export_writes_opens_again() {
|
||||
let union = all.iter().copied().reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!((union.width() - 350.0).abs() < 2.0 && (union.y1 - h + 200.0).abs() < 2.0, "{union:?} on {h}");
|
||||
}
|
||||
|
||||
/// A folder of a drawing linking `img\photo.png`, a 30 × 20 pixel PNG beside it, and `gone.png`,
|
||||
/// which isn't there (removed when dropped).
|
||||
struct Linked(std::path::PathBuf);
|
||||
|
||||
impl Linked {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-dxfimage-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("img")).unwrap();
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
30,
|
||||
20,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[230u8, 20, 20, 255].repeat(600),
|
||||
)
|
||||
.unwrap();
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
std::fs::write(dir.join("img").join("photo.png"), png).unwrap();
|
||||
let image = |def: &'static str, x: &'static str| {
|
||||
vec![(0, "IMAGE"), (8, "0"), (10, x), (20, "0"), (11, "1"), (21, "0"), (12, "0"), (22, "1"), (13, "30"), (23, "20"), (340, def)]
|
||||
};
|
||||
let mut pairs: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")];
|
||||
pairs.extend([(0, "SECTION"), (2, "ENTITIES")]);
|
||||
pairs.extend(image("1F", "0"));
|
||||
pairs.extend(image("2A", "100"));
|
||||
pairs.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]);
|
||||
pairs.extend([(0, "IMAGEDEF"), (5, "1F"), (1, r"img\photo.png"), (10, "30"), (20, "20")]);
|
||||
pairs.extend([(0, "IMAGEDEF"), (5, "2A"), (1, "gone.png"), (10, "30"), (20, "20")]);
|
||||
pairs.extend([(0, "ENDSEC"), (0, "EOF")]);
|
||||
let text: String = pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect();
|
||||
std::fs::write(dir.join("plan.dxf"), text).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
fn drawing(&self) -> String {
|
||||
self.0.join("plan.dxf").to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Linked {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The images of the active document: each one's link's file name, size, and whether its pixels
|
||||
/// are its file's (not the placeholder).
|
||||
fn images(s: &Session) -> Vec<(String, (u32, u32), bool)> {
|
||||
let st = s.doc().unwrap();
|
||||
let mut out = vec![];
|
||||
st.doc.visit_images(|_, im| {
|
||||
let read = st.doc.images.get(&im.key).is_some_and(|b| !b.is_proxy());
|
||||
out.push((im.link.as_ref().map(|l| l.name().to_string()).unwrap_or_default(), (im.width, im.height), read));
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() {
|
||||
let dir = Linked::new("open");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"path": dir.drawing()})).unwrap();
|
||||
assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]);
|
||||
let missing = r["missingLinks"].as_array().unwrap();
|
||||
assert_eq!(missing.iter().map(|m| m["name"].as_str()).collect::<Vec<_>>(), [Some("gone.png")], "{r}");
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("photo.png")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() {
|
||||
let dir = Linked::new("place");
|
||||
let mut s = page();
|
||||
let r = s.execute("file.place", &json!({"path": dir.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap();
|
||||
assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]);
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_drawing_keeps_missing_links_anchored_to_its_folder() {
|
||||
let source = Linked::new("place-missing-source");
|
||||
let destination = Linked::new("place-missing-destination");
|
||||
let mut s = page();
|
||||
s.doc_mut().unwrap().path = Some(destination.0.join("art.vectorcraft").to_string_lossy().into_owned());
|
||||
s.execute("file.place", &json!({"path": source.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap();
|
||||
let mut missing = vec![];
|
||||
s.doc().unwrap().doc.visit_images(|_, im| {
|
||||
if let Some(link) = im.link.as_ref().filter(|link| link.name() == "gone.png") {
|
||||
missing.push(std::path::PathBuf::from(&link.path));
|
||||
}
|
||||
});
|
||||
assert_eq!(missing, [source.0.join("gone.png")]);
|
||||
assert!(missing[0].is_absolute());
|
||||
assert!(!missing[0].starts_with(&destination.0));
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|true (50)|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -165,7 +165,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. 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",
|
||||
"{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, and the artboard's own screen print marks group wherever it lies, while another artboard's group lying on it stays with its own), 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
|
||||
),
|
||||
@@ -1273,6 +1273,7 @@ pub(crate) fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Sele
|
||||
for &id in &gone {
|
||||
d.retire_artboard_id(id);
|
||||
}
|
||||
super::addons::release_screen_marks(d, &gone);
|
||||
d.retain_guides(sel, |g| !g.artboard.is_some_and(|a| gone.contains(&a)));
|
||||
count_artboard_pass();
|
||||
Ok(())
|
||||
@@ -1417,7 +1418,6 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let delta = now.origin() - was.origin();
|
||||
let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO;
|
||||
let transform = fit.or_else(|| moving.then(|| Affine::translate(delta)));
|
||||
let art = if transform.is_some() { d.art_moving_with(index, all).into_iter().filter(|id| taken.insert(*id)).collect() } else { vec![] };
|
||||
edits.push(ArtboardEdit {
|
||||
index,
|
||||
now,
|
||||
@@ -1433,9 +1433,29 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
resized,
|
||||
fit,
|
||||
transform,
|
||||
art,
|
||||
art: vec![],
|
||||
});
|
||||
}
|
||||
// The artboards that move take their own screen print marks groups wherever they lie, and not
|
||||
// another artboard's lying on them, as Move Artboard does. An artboard that scales in the same
|
||||
// call leaves a moving artboard's marks lying on it to their own artboard.
|
||||
// One pass for all of them, in the order listed.
|
||||
let movers: Vec<usize> = edits.iter().filter(|e| e.transform.is_some() && e.fit.is_none()).map(|e| e.index).collect();
|
||||
let mut found = super::panelcmds::artboards_art(s, &movers, true, all, true)?.into_iter();
|
||||
let moved: Vec<Option<Vec<NodeId>>> =
|
||||
edits.iter().map(|e| (e.transform.is_some() && e.fit.is_none()).then(|| found.next().map(|(_, a)| a).unwrap_or_default())).collect();
|
||||
// Every group that belongs to a moving artboard, taken by it or left where it is; a group whose
|
||||
// artboard was deleted is ordinary art.
|
||||
let boards: HashSet<u32> = movers.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.id)).collect();
|
||||
let reserved: HashSet<NodeId> = super::addons::screen_marks_owners(d).into_iter().filter(|(_, o)| boards.contains(o)).map(|(id, _)| id).collect();
|
||||
for (e, own) in edits.iter_mut().zip(moved) {
|
||||
let art = match own {
|
||||
Some(art) => art,
|
||||
None if e.fit.is_some() => d.art_moving_with(e.index, all).into_iter().filter(|id| !reserved.contains(id)).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
e.art = art.into_iter().filter(|id| taken.insert(*id)).collect();
|
||||
}
|
||||
// Nothing to change: no undo step.
|
||||
if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) {
|
||||
return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() };
|
||||
|
||||
@@ -2050,6 +2050,36 @@ fn set_found_paths(d: &mut Document, base: LinkBase) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets each relative link path of `d`, a document read from `base`, whose file is not found to
|
||||
/// that path under `base`'s folder, so the link still looks for its file there once the art is
|
||||
/// placed into a document in another folder.
|
||||
pub(crate) fn anchor_missing_relative(d: &mut Document, base: LinkBase) {
|
||||
if base.doc.is_none() {
|
||||
return;
|
||||
}
|
||||
editing_brush_art(d, |d| {
|
||||
let mut anchored: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut look = |l: &LinkInfo| {
|
||||
if Path::new(&l.path).is_relative()
|
||||
&& !anchored.contains_key(&l.path)
|
||||
&& locate(l, base).is_none()
|
||||
&& let Ok(path) = fileio::document_path(&l.path, base.doc)
|
||||
{
|
||||
anchored.insert(l.path.clone(), path);
|
||||
}
|
||||
};
|
||||
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
|
||||
d.visit_placed(|_, p| look(&p.link));
|
||||
if !anchored.is_empty() {
|
||||
d.update_links(|l| {
|
||||
if let Some(path) = anchored.get(&l.path) {
|
||||
l.path = path.clone();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without
|
||||
/// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not
|
||||
/// allow names its file alone, without its relative path or the size and date kept of its file,
|
||||
|
||||
@@ -273,6 +273,12 @@ fn unplace_all(mut ap: Appearance) -> Appearance {
|
||||
ap
|
||||
}
|
||||
|
||||
/// The fills, strokes and effects new art takes from graphic style `g`, placed gradients relative
|
||||
/// to the unit box.
|
||||
fn style_look(g: &GraphicStyle) -> Appearance {
|
||||
if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) }
|
||||
}
|
||||
|
||||
/// How a new object looks ([`Session::new_art_look`]): its appearance and transparency and the
|
||||
/// graphic style it is linked to.
|
||||
pub(crate) struct NewArt {
|
||||
@@ -280,6 +286,8 @@ pub(crate) struct NewArt {
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
style: Option<String>,
|
||||
/// Taken from a graphic style, linked to it or not (a style from another document is not).
|
||||
styled: bool,
|
||||
/// From the template: placed gradients are relative to the unit box.
|
||||
unit_box: bool,
|
||||
}
|
||||
@@ -287,24 +295,47 @@ pub(crate) struct NewArt {
|
||||
impl NewArt {
|
||||
/// A plain look: `appearance`, full opacity, no link.
|
||||
pub(crate) fn plain(appearance: Appearance) -> Self {
|
||||
Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, unit_box: false }
|
||||
Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, styled: false, unit_box: false }
|
||||
}
|
||||
|
||||
/// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and
|
||||
/// it links to the style (type keeps its own transparency).
|
||||
/// it links to the style, taking its isolate and knockout too (type keeps its own transparency
|
||||
/// unless the look is a graphic style's). A look that no longer matches the style's definition
|
||||
/// (the style was redefined after it was picked) is given unlinked ([`NewArt::linked_style`]).
|
||||
pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) {
|
||||
self.place(n);
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !self.styled {
|
||||
return;
|
||||
}
|
||||
(n.opacity, n.blend) = (self.opacity, self.blend);
|
||||
let style = self.linked_style(d);
|
||||
if let Some(g) = style.and_then(|i| d.graphic_styles.get(i)) {
|
||||
(n.isolate, n.knockout) = (g.isolate, g.knockout);
|
||||
}
|
||||
n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i));
|
||||
}
|
||||
|
||||
/// The index in `d` of the graphic style this look links to: its style, while the style's
|
||||
/// fills, strokes, effects, opacity and blend mode are still the ones this look has.
|
||||
pub(crate) fn linked_style(&self, d: &Document) -> Option<usize> {
|
||||
let i = d.graphic_style_index(self.style.as_deref()?)?;
|
||||
let g = d.graphic_styles.get(i)?;
|
||||
((g.opacity, g.blend) == (self.opacity, self.blend) && style_look(g).approx_eq(&self.appearance)).then_some(i)
|
||||
}
|
||||
|
||||
/// Give `n` this look's appearance, its placed gradients relative to `n`'s bounds now.
|
||||
pub(crate) fn place(&self, n: &mut Node) {
|
||||
n.appearance = self.appearance.clone().into();
|
||||
if self.unit_box
|
||||
&& n.appearance.has_placed_gradient()
|
||||
if self.places_gradients()
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
{
|
||||
n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b);
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
return;
|
||||
}
|
||||
(n.opacity, n.blend) = (self.opacity, self.blend);
|
||||
n.extras_mut().graphic_style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)).map(|i| d.graphic_style_id(i));
|
||||
}
|
||||
|
||||
/// Does this look place gradients on the bounds of the object it is given to?
|
||||
pub(crate) fn places_gradients(&self) -> bool {
|
||||
self.unit_box && self.appearance.has_placed_gradient()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +363,32 @@ impl Session {
|
||||
st.width = width;
|
||||
}
|
||||
let (opacity, blend, style) = self.new_art_transparency();
|
||||
NewArt { appearance, opacity, blend, style: style.map(str::to_string), unit_box: true }
|
||||
NewArt { appearance, opacity, blend, style: style.map(str::to_string), styled: self.new_art_styled(), unit_box: true }
|
||||
}
|
||||
|
||||
/// The look of new type (`text.create`): the template's fills, strokes and effects when it is
|
||||
/// more than one plain fill and stroke or comes from a graphic style (of this document or
|
||||
/// another), else none of its own, so the characters' fill and stroke show. The document's own
|
||||
/// default look (its redefined Default Graphic Style, which [`reset`] gives new art) leaves type
|
||||
/// plain as the shipped default does; the same look taken from the selection does not. The
|
||||
/// template is not repainted with the fill and stroke proxies.
|
||||
pub(crate) fn new_type_look(&self) -> NewArt {
|
||||
let plain = || NewArt::plain(Appearance::default());
|
||||
let Some(t) = self.template() else { return plain() };
|
||||
let styled = self.new_art_styled();
|
||||
let default_look =
|
||||
|| !self.paint.inherited && self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t));
|
||||
if !styled && (t.is_basic() || default_look()) {
|
||||
return plain();
|
||||
}
|
||||
let (opacity, blend, style) = self.new_art_transparency();
|
||||
NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), styled, unit_box: true }
|
||||
}
|
||||
|
||||
/// Does the next object drawn take its look from a graphic style, in this document or the one
|
||||
/// the style was taken from?
|
||||
fn new_art_styled(&self) -> bool {
|
||||
!self.basic_only() && self.paint.style.is_some()
|
||||
}
|
||||
|
||||
/// The appearance of the next object drawn (the Appearance panel shows it with nothing
|
||||
@@ -341,9 +397,16 @@ impl Session {
|
||||
self.new_art_look(self.paint.fill.clone(), self.paint.stroke.clone(), self.paint.stroke_width).appearance
|
||||
}
|
||||
|
||||
/// The opacity, blend mode and graphic style (name) of the next object drawn.
|
||||
/// The opacity, blend mode and graphic style (name) of the next object drawn. The style is
|
||||
/// left out in a document other than the one it was taken from, so new art there is not
|
||||
/// linked to a style of the same name.
|
||||
pub fn new_art_transparency(&self) -> (f32, BlendMode, Option<&str>) {
|
||||
if self.basic_only() { (1.0, BlendMode::Normal, None) } else { (self.paint.opacity, self.paint.blend, self.paint.style.as_deref()) }
|
||||
if self.basic_only() {
|
||||
return (1.0, BlendMode::Normal, None);
|
||||
}
|
||||
let here = self.active().map(|st| st.uid);
|
||||
let style = self.paint.style.as_deref().filter(|_| self.paint.style_doc.is_some() && self.paint.style_doc == here);
|
||||
(self.paint.opacity, self.paint.blend, style)
|
||||
}
|
||||
|
||||
/// The stroke of the next object drawn (the Stroke panel shows it with nothing selected).
|
||||
@@ -378,7 +441,7 @@ impl Session {
|
||||
/// A graphic style clicked with nothing selected: new art takes it (`add`: its fills, strokes
|
||||
/// and effects on top of the template's, unlinked).
|
||||
pub(crate) fn new_art_style(&mut self, g: &GraphicStyle, add: bool) {
|
||||
let ap = if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) };
|
||||
let ap = style_look(g);
|
||||
if add {
|
||||
let t = self.new_art_template_mut();
|
||||
t.items.extend(ap.items);
|
||||
@@ -390,14 +453,16 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Make `ap` (placed gradients relative to the unit box) and this transparency the template,
|
||||
/// and its top fill, stroke and weight the proxies.
|
||||
/// and its top fill, stroke and weight the proxies. `style` is a graphic style of the
|
||||
/// document in front.
|
||||
fn take_new_art(&mut self, ap: Appearance, opacity: f32, blend: BlendMode, style: Option<String>, inherited: bool) {
|
||||
let style_doc = style.as_ref().and_then(|_| self.active().map(|st| st.uid));
|
||||
let p = &mut self.paint;
|
||||
(p.fill, p.stroke) = (unplaced(&ap.fill_paint()), unplaced(&ap.stroke_paint()));
|
||||
if let Some(st) = ap.stroke() {
|
||||
p.stroke_width = st.width;
|
||||
}
|
||||
(p.appearance, p.opacity, p.blend, p.style, p.inherited) = (Some(ap), opacity, blend, style, inherited);
|
||||
(p.appearance, p.opacity, p.blend, p.style, p.style_doc, p.inherited) = (Some(ap), opacity, blend, style, style_doc, inherited);
|
||||
}
|
||||
|
||||
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
|
||||
@@ -522,7 +587,9 @@ fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn describe(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (opacity, blend, style) = s.new_art_transparency();
|
||||
let (opacity, blend, _) = s.new_art_transparency();
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let style = s.doc().ok().and_then(|st| look.linked_style(&st.doc)).and_then(|i| s.doc().ok()?.doc.graphic_styles.get(i)).map(|g| g.name.clone());
|
||||
Ok(json!({
|
||||
"basic": s.prefs.new_art_basic,
|
||||
"appearance": s.new_art(),
|
||||
@@ -540,8 +607,7 @@ pub(crate) fn reset(s: &mut Session) {
|
||||
s.paint = PaintDefaults::default();
|
||||
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
|
||||
if let Some(g) = style {
|
||||
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
|
||||
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
|
||||
s.take_new_art(style_look(&g), 1.0, BlendMode::Normal, None, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -901,7 +901,7 @@ fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
|
||||
|
||||
impl Session {
|
||||
/// New Document's starting settings: Letter in Preferences ▸ Units ▸ General.
|
||||
fn default_settings(&self) -> DocSettings {
|
||||
pub(crate) fn default_settings(&self) -> DocSettings {
|
||||
DocSettings { units: self.default_units(), ..DocSettings::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden). With art, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden; edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -306,16 +306,74 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving:
|
||||
})
|
||||
}
|
||||
|
||||
/// `arts` (artboard indices with their art) with each artboard's screen print marks group in its
|
||||
/// own artboard's entry: another artboard's group lying on one of them goes with its own artboard
|
||||
/// when that one is among `arts`, and is left out when it is not. Only the groups on the marks
|
||||
/// layer count; a group whose artboard was deleted stays where it is.
|
||||
/// `held(i, id)` says group `id` stays put for artboard `i`.
|
||||
pub(crate) fn marks_with_owners(
|
||||
d: &vectorcraft_doc::Document,
|
||||
arts: Vec<(usize, Vec<NodeId>)>,
|
||||
held: impl Fn(usize, NodeId) -> bool,
|
||||
) -> Vec<(usize, Vec<NodeId>)> {
|
||||
let owners = super::addons::screen_marks_owners(d);
|
||||
if owners.is_empty() {
|
||||
return arts;
|
||||
}
|
||||
let board = |i: usize| d.artboards.get(i).map(|a| a.id);
|
||||
let owner = |id: NodeId| owners.get(&id).copied().filter(|o| d.artboards.iter().any(|a| a.id == *o));
|
||||
let mut moved: Vec<(u32, NodeId)> = vec![];
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = arts
|
||||
.into_iter()
|
||||
.map(|(i, art)| {
|
||||
let art = art
|
||||
.into_iter()
|
||||
.filter(|id| match owner(*id) {
|
||||
Some(o) if Some(o) != board(i) => {
|
||||
moved.push((o, *id));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
(i, art)
|
||||
})
|
||||
.collect();
|
||||
for (o, id) in moved {
|
||||
if let Some((i, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o))
|
||||
&& !held(*i, id)
|
||||
{
|
||||
art.push(id);
|
||||
}
|
||||
}
|
||||
arts
|
||||
}
|
||||
|
||||
/// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object
|
||||
/// counted once, with the first of them it is on (artboards can overlap).
|
||||
/// counted once, with the first of them it is on (artboards can overlap). With `art`, each
|
||||
/// artboard takes its own eligible screen print marks group, wherever the group lies.
|
||||
pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result<Vec<(usize, Vec<NodeId>)>> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut arts = vec![];
|
||||
for &i in indices {
|
||||
let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
let art: Vec<NodeId> = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
Ok(arts)
|
||||
let d = &s.doc()?.doc;
|
||||
// A move or a cut leaves a group lying on an artboard locked other than its own, as it leaves
|
||||
// other art there, unless locked and hidden art goes too.
|
||||
let held = |i: usize, id: NodeId| moving && !all && d.node(id).is_some_and(|n| d.locked_artboards_except(i).holds(n));
|
||||
if art {
|
||||
for (id, o) in super::addons::screen_marks_copied(d, all) {
|
||||
if let Some((i, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o))
|
||||
&& !held(*i, id)
|
||||
&& seen.insert(id)
|
||||
{
|
||||
own.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(marks_with_owners(d, arts, held))
|
||||
}
|
||||
|
||||
/// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste).
|
||||
@@ -399,7 +457,12 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec
|
||||
if let Some(id) = d.artboards.get(index).map(|a| a.id) {
|
||||
d.copy_artboard_guides(src.id, id, dv);
|
||||
}
|
||||
let to = d.artboards.get(index).map(|a| a.id);
|
||||
let copies = super::edit::copy_above(d, art, |_, _, c| {
|
||||
// A copy of the artboard's screen print marks belongs to the copy.
|
||||
if let Some(to) = to {
|
||||
let _ = super::addons::retag_screen_marks(c, src.id, to);
|
||||
}
|
||||
c.transform(Affine::translate(dv), sc);
|
||||
super::object::keep_pixel_aligned(c, sc);
|
||||
})?;
|
||||
|
||||
@@ -2212,9 +2212,13 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
for p in compounds {
|
||||
// A compound path left empty by an inner one that went is checked again after it.
|
||||
let mut compounds = compounds;
|
||||
while let Some(p) = compounds.pop_first() {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
let up = d.parent_of(p).filter(|u| matches!(d.node(*u).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(p)?;
|
||||
compounds.extend(up);
|
||||
}
|
||||
}
|
||||
super::edit::release_empty_clips(d, clipped);
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! [`fileio::psd_slices`]).
|
||||
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
|
||||
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
|
||||
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
//! - An EMF, WMF, PICT or CGM picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
//! bounded by its art (`crop: "bounding"`).
|
||||
//! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by
|
||||
//! its art: the document an EPS file of ours carries, else what its PostScript draws, else its
|
||||
@@ -377,7 +377,11 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: O
|
||||
));
|
||||
}
|
||||
// Linked images show their files, found from its folder.
|
||||
super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false);
|
||||
let links = super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false);
|
||||
if matches!(format.id, "dxf" | "dwg") {
|
||||
l.warnings.extend(fileio::dxfimport::missing_image_notes(&links.missing));
|
||||
super::links::anchor_missing_relative(&mut l.doc, super::links::LinkBase::file(src.path));
|
||||
}
|
||||
(l.doc, l.warnings)
|
||||
};
|
||||
doc.drop_edit_modes();
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.randomFill",
|
||||
"addon.color.screenMarks",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! File → Print › Advanced, what needs the renderer and the flattener (the PDF writer does the
|
||||
//! rest): Print as Bitmap renders each printed region as one image, and a flattener preset
|
||||
//! rest): Print as Bitmap renders each printed region as one image (at `advanced.bitmapResolution`,
|
||||
//! or the document's raster effects resolution), and a flattener preset
|
||||
//! flattens transparency, both on the document as it prints (only the layers that print,
|
||||
//! overprints discarded or simulated in composite output) before it is laid out on paper.
|
||||
|
||||
@@ -31,7 +32,21 @@ pub(crate) fn flattener(cmd: &str, set: &PrintSettings, saved: &[FlattenerPreset
|
||||
/// `doc` as Print as Bitmap and the flattener preset of `set` print it (from `saved` presets), or
|
||||
/// `None` when neither applies. Print as Bitmap is for composite output.
|
||||
/// `rich_black`: Appearance of Black › Printing / Exporting › Output All Blacks as Rich Black.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[FlattenerPreset], rich_black: bool) -> Result<Option<Document>> {
|
||||
prepare_noting(cmd, doc, set, saved, rich_black, &mut vec![])
|
||||
}
|
||||
|
||||
/// [`prepare`], with the note on an image Print as Bitmap prints below `advanced.bitmapResolution`
|
||||
/// added to `notes`.
|
||||
pub(crate) fn prepare_noting(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
set: &PrintSettings,
|
||||
saved: &[FlattenerPreset],
|
||||
rich_black: bool,
|
||||
notes: &mut Vec<String>,
|
||||
) -> Result<Option<Document>> {
|
||||
let composite = set.output.mode == OutputMode::Composite;
|
||||
let bitmap = set.advanced.print_as_bitmap && composite;
|
||||
let flattener = flattener(cmd, set, saved)?;
|
||||
@@ -40,7 +55,9 @@ pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[F
|
||||
}
|
||||
let printed = vectorcraft_pdf::printed_document(doc, set);
|
||||
if bitmap {
|
||||
return bitmap_document(cmd, &printed, set, rich_black).map(Some);
|
||||
let (out, lowest) = bitmap_document(cmd, &printed, set, rich_black)?;
|
||||
notes.extend(capped_note(set, lowest));
|
||||
return Ok(Some(out));
|
||||
}
|
||||
let Some(mut o) = flattener else { return Ok(None) };
|
||||
// Composite overprints that were discarded or simulated aren't preserved either.
|
||||
@@ -62,12 +79,82 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolution Print as Bitmap renders `doc` at with `set` (ppi): `advanced.bitmapResolution`,
|
||||
/// or the document's raster effects resolution when that is 0 (72 ppi when the stored value isn't a
|
||||
/// number).
|
||||
fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if asked > 0.0 { asked } else { doc.raster_ppi() }
|
||||
}
|
||||
|
||||
/// The pixels per document point Print as Bitmap renders `area` at so that it prints at `ppi` on
|
||||
/// paper when the page scales it by `placed` on each axis (1 = 100%): at most MAX_PIXELS, and
|
||||
/// no side longer than the renderer draws (rounded up to whole pixels when it renders).
|
||||
fn bitmap_scale(area: Rect, ppi: f64, placed: (f64, f64)) -> (f64, f64) {
|
||||
let (w, h) = (area.width() * ppi / 72.0 * placed.0, area.height() * ppi / 72.0 * placed.1);
|
||||
let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0;
|
||||
let limit = 1.0_f64.min((MAX_PIXELS / (w * h).max(1.0)).sqrt()).min(longest / w.max(1.0)).min(longest / h.max(1.0));
|
||||
let (w, h) = (w * limit, h * limit);
|
||||
let rounding = if whole_pixels(w) * whole_pixels(h) > MAX_PIXELS { ((MAX_PIXELS - w - h - 1.0) / (w * h)).sqrt() } else { 1.0 };
|
||||
(w * rounding / area.width(), h * rounding / area.height())
|
||||
}
|
||||
|
||||
/// The whole pixels Print as Bitmap renders `len` pixels of art as: rounded up, at least 1, with
|
||||
/// the rounding error of `len` scaled down and up again left out.
|
||||
fn whole_pixels(len: f64) -> f64 {
|
||||
(len - 1e-6).ceil().max(1.0)
|
||||
}
|
||||
|
||||
/// The horizontal and vertical scales (1 = 100%) the page prints the region `r` of `printed`
|
||||
/// at with `set`, both 1 when it prints on no page.
|
||||
fn placed_scale(printed: &Document, set: &PrintSettings, r: Rect) -> (f64, f64) {
|
||||
vectorcraft_pdf::print_region_scale(printed, set, r).filter(|(x, y)| x.is_finite() && *x > 0.0 && y.is_finite() && *y > 0.0).unwrap_or((1.0, 1.0))
|
||||
}
|
||||
|
||||
/// The note on Print as Bitmap printing below the `advanced.bitmapResolution` of `set`, when the
|
||||
/// `lowest` resolution (ppi) an image prints at is lower. None when the job leaves the resolution
|
||||
/// to the document.
|
||||
fn capped_note(set: &PrintSettings, lowest: Option<f64>) -> Option<String> {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
let lowest = lowest.filter(|l| asked > 0.0 && l.is_finite() && *l < asked - 1e-6)?;
|
||||
Some(format!(
|
||||
"Print as Bitmap prints at {} ppi, not the {asked} ppi bitmapResolution asks for: a page prints as at most 64 million pixels and 32,768 pixels a side",
|
||||
lowest.floor()
|
||||
))
|
||||
}
|
||||
|
||||
/// What [`prepare`] notes on Print as Bitmap for `doc` printed with `set`, without rendering it,
|
||||
/// for the preview: a page with art that prints whose image the pixel limits keep below
|
||||
/// `advanced.bitmapResolution`. The art is judged by its bounds, so a page holding only art that
|
||||
/// draws nothing (fully transparent) is counted, while the print itself leaves its image out.
|
||||
pub(crate) fn bitmap_notes(cmd: &str, doc: &Document, set: &PrintSettings) -> Result<Vec<String>> {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if !(set.advanced.print_as_bitmap && set.output.mode == OutputMode::Composite && asked > 0.0) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let printed = vectorcraft_pdf::printed_document(doc, set);
|
||||
let regions = vectorcraft_pdf::print_regions(&printed, set).map_err(|e| pdf_error(cmd, e))?;
|
||||
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, &printed);
|
||||
let lowest = regions
|
||||
.iter()
|
||||
.map(|(_, r)| (outset(*r, bleed), placed_scale(&printed, set, *r)))
|
||||
.filter(|(area, _)| vectorcraft_pdf::prints_art_in(&printed, *area))
|
||||
.map(|(area, placed)| {
|
||||
let (x, y) = bitmap_scale(area, asked, placed);
|
||||
(x / placed.0).min(y / placed.1) * 72.0
|
||||
})
|
||||
.reduce(f64::min);
|
||||
Ok(capped_note(set, lowest).into_iter().collect())
|
||||
}
|
||||
|
||||
/// `doc` (as it prints) with its art replaced by one image of each printed region (an artboard
|
||||
/// with its bleed, or all the art), at the document's raster effects resolution; regions where
|
||||
/// nothing is drawn get none.
|
||||
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<Document> {
|
||||
/// with its bleed, or all the art), at [`bitmap_ppi`] within [`bitmap_scale`]'s limits; regions
|
||||
/// where nothing is drawn get none. Also the lowest resolution an image prints at (ppi), `None`
|
||||
/// without images.
|
||||
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<(Document, Option<f64>)> {
|
||||
let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?;
|
||||
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, doc);
|
||||
let ppi = bitmap_ppi(doc, set);
|
||||
let mut art = doc.clone();
|
||||
drop_guides(&mut art.layers);
|
||||
let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None };
|
||||
@@ -75,37 +162,34 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b
|
||||
let mut out = doc.clone();
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let mut images = vec![];
|
||||
let mut lowest: Option<f64> = None;
|
||||
for (_, r) in regions {
|
||||
let area = outset(r, bleed);
|
||||
// At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole
|
||||
// pixels below).
|
||||
let side = area.width().max(area.height()).max(1.0);
|
||||
let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0;
|
||||
let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side);
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
let placed = placed_scale(doc, set, r);
|
||||
let scale = bitmap_scale(area, ppi, placed);
|
||||
if !(scale.0.is_finite() && scale.0 > 0.0 && scale.1.is_finite() && scale.1 > 0.0) {
|
||||
continue;
|
||||
}
|
||||
// Whole pixels.
|
||||
let region = Rect::new(
|
||||
area.x0,
|
||||
area.y0,
|
||||
area.x0 + (area.width() * scale).ceil().max(1.0) / scale,
|
||||
area.y0 + (area.height() * scale).ceil().max(1.0) / scale,
|
||||
);
|
||||
let img = renderer.render_region_with(&art, region, scale, &opts);
|
||||
let width = whole_pixels(area.width() * scale.0) as u32;
|
||||
let height = whole_pixels(area.height() * scale.1) as u32;
|
||||
let view = Affine::scale_non_uniform(scale.0, scale.1) * Affine::translate((-area.x0, -area.y0));
|
||||
let img = renderer.render(&art, width, height, view, &opts);
|
||||
if img.pixels.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
|
||||
continue;
|
||||
}
|
||||
let key = unique_key(&out, "print-bitmap");
|
||||
out.images.insert(key.clone(), ImageBlob::new("image/png", img.to_png().map_err(EngineError::Other)?));
|
||||
let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale);
|
||||
let xf = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(1.0 / scale.0, 1.0 / scale.1);
|
||||
let image = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
images.push(Arc::new(Node::new(out.alloc_id(), NodeKind::Image(Box::new(image)))));
|
||||
let printed_ppi = (scale.0 / placed.0).min(scale.1 / placed.1) * 72.0;
|
||||
lowest = Some(lowest.map_or(printed_ppi, |l| l.min(printed_ppi)));
|
||||
}
|
||||
let mut layer = Node::layer(out.alloc_id(), "Bitmap", LayerColor::Preset(0));
|
||||
if let Some(children) = layer.children_mut() {
|
||||
*children = images;
|
||||
}
|
||||
out.layers = vec![Arc::new(layer)];
|
||||
Ok(out)
|
||||
Ok((out, lowest))
|
||||
}
|
||||
|
||||
@@ -1197,6 +1197,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
let plan = SavePlan {
|
||||
mode: SaveMode::Copy,
|
||||
path: st.path.clone(),
|
||||
path_given: false,
|
||||
format: native,
|
||||
options: serde_json::Map::from_iter([("pdfCompatible".into(), json!(false))]),
|
||||
name: format!("{file}{DOC_EXT}"),
|
||||
|
||||
@@ -257,7 +257,12 @@ pub(crate) fn captured(n: &Node) -> Appearance {
|
||||
/// fills, and their stroke when it has strokes.
|
||||
fn override_chars(n: &mut Node, ap: &Appearance) {
|
||||
let NodeKind::Text(t) = &mut n.kind else { return };
|
||||
let (fills, strokes) = (ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill()));
|
||||
override_text_chars(t, ap, true);
|
||||
}
|
||||
|
||||
/// [`override_chars`] for type `t`; with `fill` false its characters keep their fill.
|
||||
pub(crate) fn override_text_chars(t: &mut vectorcraft_doc::TextObject, ap: &Appearance, fill: bool) {
|
||||
let (fills, strokes) = (fill && ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill()));
|
||||
for r in &mut t.runs {
|
||||
if fills {
|
||||
r.style.fill = Paint::None;
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked. With moveArt, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
has_doc,
|
||||
artboard_move
|
||||
),
|
||||
@@ -685,13 +685,8 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !copy {
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
}
|
||||
// Each artboard's art, an object counted once (artboards can overlap).
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = vec![];
|
||||
for &i in &indices {
|
||||
let art = super::panelcmds::artboard_art(s, i, move_art, locked_art, !copy)?;
|
||||
let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
// Each artboard takes its art once and its own eligible screen print marks group.
|
||||
let arts = super::panelcmds::artboards_art(s, &indices, move_art, locked_art, !copy)?;
|
||||
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
|
||||
let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| {
|
||||
|
||||
@@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 41] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -72,6 +72,7 @@ const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("addon.color.screenMarks", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
("edit.cut", "selectedArtboards"),
|
||||
|
||||
@@ -647,7 +647,7 @@ pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec<String> {
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
pub(crate) fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
if path.is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
|
||||
@@ -258,8 +258,9 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with, nor the Artboard tool's selection from the start of the run.
|
||||
// A document whose active artboard the script chose, or whose artboards the script added or
|
||||
// removed, uses its active artboard by id, not the index the run started with, nor the
|
||||
// Artboard tool's selection from the start of the run.
|
||||
let chosen = h.session.borrow().active().and_then(|st| {
|
||||
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
|
||||
Some((st.uid, super::dom::active_artboard(st)))
|
||||
|
||||
@@ -106,6 +106,7 @@ mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
mod paths;
|
||||
mod perspective;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod raster_capture;
|
||||
@@ -124,6 +125,10 @@ pub(super) use colors::of_color as color_data;
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS, REMOVE_ALL_VISITS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use print::postscript_name;
|
||||
#[cfg(test)]
|
||||
pub(crate) use save_open::with_extension;
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -270,7 +275,8 @@ pub(super) struct State {
|
||||
layer_lists: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose its active
|
||||
/// artboard, or the script last added or removed one of its artboards.
|
||||
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
|
||||
/// Each open document's uid and the index of its active artboard when the run started.
|
||||
pub(super) boards_at_start: Vec<(u64, usize)>,
|
||||
@@ -1745,19 +1751,27 @@ fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer {
|
||||
/// left out. The settings stay with the run, which hands the script an object of the
|
||||
/// `DocumentPreset` class.
|
||||
fn new_preset(h: &Host) -> Answer {
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
add_preset(
|
||||
h,
|
||||
vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// A new `DocumentPreset` of the run with the settings `fields`, which `new DocumentPreset()` and
|
||||
/// `app.getPresetSettings` both make.
|
||||
fn add_preset(h: &Host, fields: Vec<(String, Data)>) -> Answer {
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
if presets.len() >= MAX_PRESETS {
|
||||
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
|
||||
}
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
let fields = vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
];
|
||||
hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?;
|
||||
presets.push(fields);
|
||||
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
|
||||
@@ -3483,6 +3497,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
for (name, members) in perspective::enums() {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
@@ -3519,6 +3537,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(perspective::application_members(l));
|
||||
application.extend(preferences::app_members());
|
||||
application.extend(matrix::app_members(l));
|
||||
application.extend(clipboard::app_members(l));
|
||||
@@ -3605,6 +3624,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(perspective::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
|
||||
@@ -1401,7 +1401,10 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn board_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let (b, i) = this_board(h, a)?;
|
||||
let active = active_board_id(h, b.doc);
|
||||
on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?;
|
||||
keep_active_board(h, b.doc.uid, active);
|
||||
follow_active_board(h, b.doc.uid);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1513,6 +1516,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer {
|
||||
if len >= max {
|
||||
return Err(HostError::Range(format!("a document has at most {max} artboards")));
|
||||
}
|
||||
let active = active_board_id(h, doc);
|
||||
let id = super::atomically(h, |h| {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?;
|
||||
@@ -1529,6 +1533,8 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer {
|
||||
st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into()))
|
||||
})
|
||||
})?;
|
||||
keep_active_board(h, doc.uid, active);
|
||||
follow_active_board(h, doc.uid);
|
||||
Ok(board_ref(h, doc.uid, id))
|
||||
}
|
||||
|
||||
@@ -1550,10 +1556,58 @@ fn boards_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
let len = with_doc(h, doc, |_, st| st.doc.artboards.len());
|
||||
let i = board_index_arg(arg(a, 1), len, "index")?;
|
||||
let active = active_board_id(h, doc);
|
||||
on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?;
|
||||
keep_active_board(h, doc.uid, active);
|
||||
follow_active_board(h, doc.uid);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The id and index of the artboard that is active in `doc` now, chosen or only the fallback.
|
||||
fn active_board_id(h: &Host, doc: Doc) -> Option<(u32, usize)> {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let i = active_artboard(st);
|
||||
st.doc.artboards.get(i).map(|ab| (ab.id, i))
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps artboard `id` active in document `uid` by its id when it is still there, as
|
||||
/// `setActiveArtboardIndex` does, so an artboard added or removed before it moves its index
|
||||
/// instead of making another artboard the active one.
|
||||
/// A stored id of an artboard that is gone is replaced as well. In a document made during the run,
|
||||
/// the index the artboard had before the change is recorded for the run's report, as the first
|
||||
/// `setActiveArtboardIndex` records it.
|
||||
fn keep_active_board(h: &Host, uid: u64, active: Option<(u32, usize)>) {
|
||||
let Some((id, index)) = active else { return };
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
let Some(st) = s.document_mut(uid) else { return };
|
||||
if !st.doc.artboards.iter().any(|ab| ab.id == id) {
|
||||
return;
|
||||
}
|
||||
st.active_artboard = Some(id);
|
||||
}
|
||||
if !h.dom.boards_at_start.iter().any(|(u, _)| *u == uid) {
|
||||
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
|
||||
if !made.iter().any(|(u, _)| *u == uid) {
|
||||
made.push((uid, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays
|
||||
/// act on the document's active artboard by id, at the index the run's report gives it, as after
|
||||
/// `setActiveArtboardIndex`, until the document is reverted.
|
||||
fn follow_active_board(h: &Host, uid: u64) {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(u, _)| *u == uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((uid, reverts));
|
||||
}
|
||||
}
|
||||
|
||||
fn boards_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64)))
|
||||
@@ -1572,15 +1626,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
|
||||
}
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = with_doc(h, doc, |_, st| st.reverts);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((doc.uid, reverts));
|
||||
}
|
||||
}
|
||||
follow_active_board(h, doc.uid);
|
||||
// A document made during the run has no index from the start of the run, so the first choice
|
||||
// records one; an artboard inserted before it later still puts it in the report.
|
||||
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
|
||||
|
||||
@@ -719,7 +719,8 @@ thread_local! {
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path,
|
||||
/// image, placed document or visible type that lays out glyphs to clip by.
|
||||
/// image, placed document or visible type that lays out glyphs to clip by, or leave an image first
|
||||
/// in an ordinary group named as a tracing.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -798,13 +799,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
|
||||
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none()
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
// Without `keepEmpty`, clear removes compound paths whose members all go, emptied inner
|
||||
// compound paths included (`emptied_compounds`), but keeps empty groups. A compound
|
||||
// path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none() && matches!(n.kind, NodeKind::Compound { .. }) && !kids.is_empty() && kids.iter().all(|k| going.contains(&k.id)) {
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths, the frames of visible images and placed
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The perspective grid of a document and the New Document settings of a startup preset in the
|
||||
//! script object model, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>
|
||||
//! and <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> list them, with the values of
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/>.
|
||||
//!
|
||||
//! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with
|
||||
//! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them
|
||||
//! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows
|
||||
//! the grid and makes one undo step when the grid's geometry changes. As the Document page
|
||||
//! describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and
|
||||
//! `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already
|
||||
//! hidden.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has
|
||||
//! that name (in any case), and when the preset's grid is not of `gridType`; nothing changes then.
|
||||
//! - A one-point grid takes only the left and the floor plane as its active plane, as the archived
|
||||
//! scripting guide says
|
||||
//! (<https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf>).
|
||||
//! `INVALIDGRIDPLANETYPE` makes no plane active.
|
||||
//! - `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed.
|
||||
//! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new
|
||||
//! `DocumentPreset` with the settings a new document from that preset starts with, which
|
||||
//! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than
|
||||
//! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout
|
||||
//! of more than 100 artboards, and the layout of a grid by column that no row count lays out the
|
||||
//! same. Changing the result changes nothing else. Each result counts toward the run's limit
|
||||
//! of `DocumentPreset` objects, as `new DocumentPreset()` does.
|
||||
//! - `startupPresetsList` is an array of the startup preset names, each of which
|
||||
//! `documents.addDocument` and `getPresetSettings` take: `Print` first, then the other New
|
||||
//! Document profiles, then `Basic CMYK` and `Basic RGB`. Each read gives a new
|
||||
//! array; a script that changes that array does not change the list a later read gives.
|
||||
//! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset
|
||||
//! files are not available yet.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
|
||||
use super::{
|
||||
Answer, Described, MAX_TEXT_BYTES, arg, get, later, method, named, num, on_doc, returns, startup_preset, text, this_doc, typed, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
|
||||
type Result<T> = std::result::Result<T, HostError>;
|
||||
|
||||
/// The `PerspectiveGridType` values, with the grid kind (`perspective.grid.set`'s `kind`) of each.
|
||||
const GRID_TYPES: &[(&str, Option<u8>)] = &[
|
||||
("OnePointPerspectiveGridType", Some(1)),
|
||||
("TwoPointPerspectiveGridType", Some(2)),
|
||||
("ThreePointPerspectiveGridType", Some(3)),
|
||||
("InvalidPerspectiveGridType", None),
|
||||
];
|
||||
|
||||
/// The `PerspectiveGridPlaneType` values, with the plane of each.
|
||||
const PLANE_TYPES: &[(&str, Plane)] = &[
|
||||
("GRIDLEFTPLANETYPE", Plane::Left),
|
||||
("GRIDRIGHTPLANETYPE", Plane::Right),
|
||||
("GRIDFLOORPLANETYPE", Plane::Ground),
|
||||
("INVALIDGRIDPLANETYPE", Plane::None),
|
||||
];
|
||||
|
||||
/// The enumerations this module adds, as `dom::install` defines them.
|
||||
pub(super) fn enums() -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
vec![
|
||||
("PerspectiveGridType", GRID_TYPES.iter().map(|(n, _)| *n).collect()),
|
||||
("PerspectiveGridPlaneType", PLANE_TYPES.iter().map(|(n, _)| *n).collect()),
|
||||
]
|
||||
}
|
||||
|
||||
/// The kind a `PerspectiveGridType` value names (`None`: `InvalidPerspectiveGridType`).
|
||||
fn grid_type(d: &Data) -> Result<Option<u8>> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("PerspectiveGridType.").and_then(|m| GRID_TYPES.iter().find(|(n, _)| *n == m)),
|
||||
_ => None,
|
||||
};
|
||||
found.map(|(_, k)| *k).ok_or_else(|| HostError::Type("gridType must be a PerspectiveGridType value".into()))
|
||||
}
|
||||
|
||||
/// The plane a `PerspectiveGridPlaneType` value names.
|
||||
fn plane_type(d: &Data) -> Result<Plane> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("PerspectiveGridPlaneType.").and_then(|m| PLANE_TYPES.iter().find(|(n, _)| *n == m)),
|
||||
_ => None,
|
||||
};
|
||||
found.map(|(_, p)| *p).ok_or_else(|| HostError::Type("gridPlane must be a PerspectiveGridPlaneType value".into()))
|
||||
}
|
||||
|
||||
/// The document `this` names and its perspective grid, without the objects attached to it.
|
||||
fn grid(h: &Host, a: &[Data]) -> Result<(super::Doc, PerspectiveGrid)> {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok((doc, with_doc(h, doc, |_, st| PerspectiveGrid::current(&st.doc))))
|
||||
}
|
||||
|
||||
/// `showPerspectiveGrid()`: shows the document's grid (its default one when none was defined).
|
||||
fn show_grid(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if !g.visible {
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": true})))?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `hidePerspectiveGrid()`: hides the document's grid. → whether a grid was hidden.
|
||||
fn hide_grid(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if !g.visible {
|
||||
return Ok(Data::Bool(false));
|
||||
}
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": false})))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `getPerspectiveActivePlane()`: the grid's active plane, shown or hidden.
|
||||
fn active_plane(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, g) = grid(h, a)?;
|
||||
let name = PLANE_TYPES.iter().find(|(_, p)| *p == g.plane).map_or("INVALIDGRIDPLANETYPE", |(n, _)| *n);
|
||||
Ok(text(format!("PerspectiveGridPlaneType.{name}")))
|
||||
}
|
||||
|
||||
/// `setActivePlane(gridPlane)`: makes `gridPlane` the grid's active plane.
|
||||
fn set_active_plane(h: &Host, a: &[Data]) -> Answer {
|
||||
let plane = plane_type(arg(a, 1))?;
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if g.kind == 1 && plane == Plane::Right {
|
||||
return Err(HostError::Range("a one-point grid has no right plane to make active".into()));
|
||||
}
|
||||
if g.plane != plane {
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.plane.set", &json!({"plane": plane.id()})))?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `selectPerspectivePreset(gridType, presetName)`: resets the grid to the preset `presetName`,
|
||||
/// which must be a grid of `gridType`.
|
||||
fn select_preset(h: &Host, a: &[Data]) -> Answer {
|
||||
let kind = grid_type(arg(a, 1))?.ok_or_else(|| HostError::Range("InvalidPerspectiveGridType has no presets".into()))?;
|
||||
let Data::String(name) = arg(a, 2) else { return Err(HostError::Type("presetName must be a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the preset's name is too long".into()));
|
||||
}
|
||||
let doc = this_doc(h, a)?;
|
||||
let preset = h.session.borrow().perspective_preset(name);
|
||||
let preset = preset.ok_or_else(|| HostError::Error(format!("no perspective grid preset called {name}")))?;
|
||||
if preset.kind != kind {
|
||||
return Err(HostError::Error(format!("the preset {} is not a grid of that type", preset.name)));
|
||||
}
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.preset", &json!({"name": preset.name})))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The `RulerUnits` value of `u`, for the units `documents.addDocument` takes (`None`: other units,
|
||||
/// which a preset given back to `addDocument` keeps by leaving `units` out).
|
||||
fn units(u: crate::doc::Unit) -> Option<&'static str> {
|
||||
use crate::doc::Unit;
|
||||
Some(match u {
|
||||
Unit::Points => "RulerUnits.Points",
|
||||
Unit::Picas => "RulerUnits.Picas",
|
||||
Unit::Inches => "RulerUnits.Inches",
|
||||
Unit::Millimeters => "RulerUnits.Millimeters",
|
||||
Unit::Centimeters => "RulerUnits.Centimeters",
|
||||
Unit::Pixels => "RulerUnits.Pixels",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `artboardRowsOrCols` as `addDocument` reads it: the rows of a grid filled by column and the
|
||||
/// columns of the other layouts. `None`: a grid by column whose artboards no row count places the
|
||||
/// same.
|
||||
fn rows_or_cols(d: &crate::cmd::newdoc::DocSettings) -> Option<usize> {
|
||||
use crate::cmd::newdoc::ArtboardLayout;
|
||||
let n = d.artboards.max(1) as usize;
|
||||
if d.layout != ArtboardLayout::GridByColumn {
|
||||
return Some(d.grid_columns().max(1));
|
||||
}
|
||||
if d.rows > 0 {
|
||||
return Some((d.rows as usize).min(n));
|
||||
}
|
||||
let rows = n.div_ceil(d.grid_columns().max(1));
|
||||
let by_rows = crate::cmd::newdoc::DocSettings { rows: u32::try_from(rows).ok()?, ..d.clone() };
|
||||
(by_rows.boards() == d.boards()).then_some(rows)
|
||||
}
|
||||
|
||||
/// `app.getPresetSettings(preset)`: a new `DocumentPreset` with the settings a document from the
|
||||
/// startup preset `preset` starts with.
|
||||
fn preset_settings(h: &Host, a: &[Data]) -> Answer {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, PreviewMode};
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("getPresetSettings needs a startup preset's name".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the startup preset's name is too long".into()));
|
||||
}
|
||||
let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?;
|
||||
// The settings `documents.addDocument` starts from: the first built-in preset of the profile's
|
||||
// category, which a saved preset of the same name does not replace, else New Document's
|
||||
// starting settings.
|
||||
let d = {
|
||||
let s = h.session.borrow();
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&s, n)?.into_iter().next());
|
||||
first.unwrap_or_else(|| s.default_settings())
|
||||
};
|
||||
let cmyk = mode.map_or(d.color_mode == crate::doc::ColorMode::Cmyk, |m| m == "cmyk");
|
||||
let layout = match (d.layout, d.right_to_left) {
|
||||
(ArtboardLayout::GridByRow, false) => "GridByRow",
|
||||
(ArtboardLayout::GridByColumn, false) => "GridByCol",
|
||||
(ArtboardLayout::Row, false) => "Row",
|
||||
(ArtboardLayout::Column, _) => "Column",
|
||||
(ArtboardLayout::GridByRow, true) => "RLGridByRow",
|
||||
(ArtboardLayout::GridByColumn, true) => "RLGridByCol",
|
||||
(ArtboardLayout::Row, true) => "RLRow",
|
||||
};
|
||||
let preview = match d.preview_mode {
|
||||
PreviewMode::Default => Some("DefaultPreview"),
|
||||
PreviewMode::Pixel => None,
|
||||
PreviewMode::Overprint => Some("OverprintPreview"),
|
||||
};
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
let mut out = vec![
|
||||
item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))),
|
||||
item("artboardSpacing", num(d.spacing)),
|
||||
item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })),
|
||||
item("height", num(d.height)),
|
||||
item("width", num(d.width)),
|
||||
];
|
||||
if let Some(preview) = preview {
|
||||
out.push(item("previewMode", text(format!("DocumentPreviewMode.{preview}"))));
|
||||
}
|
||||
// The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them
|
||||
// back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row
|
||||
// count lays out the same), so `addDocument` with the same preset keeps the preset's own.
|
||||
if f64::from(d.artboards.max(1)) <= super::MAX_ARTBOARDS {
|
||||
out.push(item("numArtboards", num(f64::from(d.artboards.max(1)))));
|
||||
if let Some(n) = rows_or_cols(&d) {
|
||||
out.push(item("artboardRowsOrCols", num(super::float(n as u64))));
|
||||
}
|
||||
}
|
||||
if let Some(u) = units(d.units) {
|
||||
out.push(item("units", text(u)));
|
||||
}
|
||||
let resolutions = [(72.0, "ScreenResolution"), (150.0, "MediumResolution"), (300.0, "HighResolution")];
|
||||
if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) {
|
||||
out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}"))));
|
||||
}
|
||||
super::add_preset(h, out)
|
||||
}
|
||||
|
||||
/// The startup presets in the order `app.startupPresetsList` gives them: `Print` first, then the
|
||||
/// other New Document profiles, then the presets that give a document of one color mode.
|
||||
const STARTUP_PRESETS: [&str; 9] = ["Print", "Web", "Mobile", "Film & Video", "Art & Illustration", "Branding", "Social", "Basic CMYK", "Basic RGB"];
|
||||
|
||||
/// `app.startupPresetsList`: the names of the startup presets, as a new array.
|
||||
fn startup_presets(_: &Host, _: &[Data]) -> Answer {
|
||||
Ok(Data::Array(STARTUP_PRESETS.into_iter().map(text).collect()))
|
||||
}
|
||||
|
||||
/// The members this module adds to `Document`'s.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
let mut m = named(vec![
|
||||
("showPerspectiveGrid", method(l, show_grid), returns("boolean", &[])),
|
||||
("hidePerspectiveGrid", method(l, hide_grid), returns("boolean", &[])),
|
||||
("getPerspectiveActivePlane", method(l, active_plane), returns("PerspectiveGridPlaneType", &[])),
|
||||
("setActivePlane", method(l, set_active_plane), returns("boolean", &[("gridPlane", "PerspectiveGridPlaneType")])),
|
||||
("selectPerspectivePreset", method(l, select_preset), returns("boolean", &[("gridType", "PerspectiveGridType"), ("presetName", "string")])),
|
||||
]);
|
||||
m.extend(["exportPerspectiveGridPreset", "importPerspectiveGridPreset"].into_iter().map(|n| later(l, "Document", n)));
|
||||
m
|
||||
}
|
||||
|
||||
/// The members this module adds to `Application`'s.
|
||||
pub(super) fn application_members(l: &Link) -> Vec<Described> {
|
||||
let mut m = named(vec![
|
||||
("getPresetSettings", method(l, preset_settings), returns("DocumentPreset", &[("preset", "string")])),
|
||||
("startupPresetsList", get(l, startup_presets), typed("Array")),
|
||||
]);
|
||||
let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"];
|
||||
m.extend(missing.into_iter().map(|n| later(l, "Application", n)));
|
||||
m
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
//! - `print` with `jobOptions.file` writes a file, a `File` the script may write
|
||||
//! ([`super::super::files`]), and `printerName` does not apply. PostScript is written when the
|
||||
//! name ends with `.ps` or `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise.
|
||||
//! The PostScript is level 2 when `postScriptLevel` is not assigned, the default it reads as.
|
||||
//! - `print` without a file prepares a job for the printer `printerName` names, or for the
|
||||
//! system's default printer when it is empty or not assigned ([`super::super::printing`]): a
|
||||
//! print-ready PDF composed when `print` is called, which the run keeps until it ends. A name
|
||||
@@ -36,6 +37,7 @@
|
||||
//! - A property the help pages list that is not mapped accepts the default its help page gives
|
||||
//! and throws an error that says it is not available yet at any other value.
|
||||
//! - `fitToPage` set to true wins over the scale factors and the tiling mode.
|
||||
//! With no scale or tiling assigned, false clears a base fit mode and preserves other base scaling modes.
|
||||
//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range
|
||||
//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange`
|
||||
//! replaces the range of the settings `print` starts from, which prints when those settings
|
||||
@@ -46,6 +48,9 @@
|
||||
//! with another extension.
|
||||
//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the
|
||||
//! settings `print` starts from.
|
||||
//! - `bitmapResolution` is `file.print`'s `advanced.bitmapResolution`: 0 prints at the document's
|
||||
//! raster effects resolution, and 1 to 9600 ppi at that resolution; `print` throws, before
|
||||
//! anything is written, for a value between 0 and 1.
|
||||
//! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard
|
||||
//! the document does not have, also with `printAllArtboards` true; when `printPreset` or
|
||||
//! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is
|
||||
@@ -54,6 +59,7 @@
|
||||
//! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces,
|
||||
//! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked
|
||||
//! name goes to `file.print` without the spaces around it. `PPDName` takes only the empty string.
|
||||
//! Paper `width` and `height` take 0 (not assigned) or 72 to 14,400 pt.
|
||||
//! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects.
|
||||
//! - `app.printerList` lists the printers the frontend listed for the run as `Printer` objects,
|
||||
//! whose `name` is read-only and whose `printerInfo` is not available yet. It throws with no
|
||||
@@ -150,8 +156,8 @@ const PDF_OVERPRINT: &[&str] = &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"];
|
||||
const POSTSCRIPT_IMAGE_COMPRESSION: &[&str] = &["IMAGECOMPRESSIONNONE", "JPEG", "RLE"];
|
||||
const POSTSCRIPT_LEVEL: &[&str] = &["PSLEVEL1", "PSLEVEL2", "PSLEVEL3"];
|
||||
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` comes from
|
||||
/// [`super::save_open::ENUMS`].
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` and `PageMarksTypes`
|
||||
/// come from [`super::save_open::ENUMS`].
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintColorProfile", PRINT_COLOR_PROFILE),
|
||||
("PrintColorIntent", PRINT_COLOR_INTENT),
|
||||
@@ -163,7 +169,6 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintingBounds", PRINTING_BOUNDS),
|
||||
("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE),
|
||||
("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY),
|
||||
("PageMarksTypes", PAGE_MARKS_TYPES),
|
||||
("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION),
|
||||
("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL),
|
||||
];
|
||||
@@ -176,6 +181,8 @@ enum Kind {
|
||||
Number(f64, f64),
|
||||
/// A whole number from the first to the second.
|
||||
Whole(u64, u64),
|
||||
/// A paper side in points: 0 (not assigned) or a custom size from 72 to 14,400.
|
||||
PaperSize,
|
||||
Text,
|
||||
/// A value of the enumeration (its name and members); only the members in the last list are
|
||||
/// available.
|
||||
@@ -209,7 +216,7 @@ impl Start {
|
||||
|
||||
fn matches(self, kind: Kind, d: &Data) -> bool {
|
||||
match (self, d) {
|
||||
(Start::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9,
|
||||
(Start::Num(a), Data::Number(b)) => a == *b,
|
||||
(Start::None, _) => false,
|
||||
_ => self.value(kind) == *d,
|
||||
}
|
||||
@@ -264,7 +271,7 @@ const JOB: Class = Class {
|
||||
name: "PrintJobOptions",
|
||||
fields: &[
|
||||
f("artboardRange", Kind::Text, Start::Text("1-")),
|
||||
kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)),
|
||||
f("bitmapResolution", Kind::Number(0.0, vectorcraft_pdf::MAX_BITMAP_RESOLUTION), Start::Num(0.0)),
|
||||
f("collate", Kind::Bool, Start::Bool(false)),
|
||||
f("copies", Kind::Whole(1, 999), Start::Num(1.0)),
|
||||
f(
|
||||
@@ -355,14 +362,18 @@ const MARKS: Class = Class {
|
||||
const PAPER: Class = Class {
|
||||
name: "PrintPaperOptions",
|
||||
fields: &[
|
||||
f("height", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("height", Kind::PaperSize, Start::Num(0.0)),
|
||||
f("name", Kind::Text, Start::None),
|
||||
kept("offset", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("transverse", Kind::Bool, Start::Bool(false)),
|
||||
f("width", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("width", Kind::PaperSize, Start::Num(0.0)),
|
||||
],
|
||||
};
|
||||
|
||||
/// The custom paper sizes `file.print` takes, in points.
|
||||
const MIN_PAPER: f64 = 72.0;
|
||||
const MAX_PAPER: f64 = 14_400.0;
|
||||
|
||||
const POSTSCRIPT: Class = Class {
|
||||
name: "PrintPostScriptOptions",
|
||||
fields: &[
|
||||
@@ -440,6 +451,14 @@ fn checked(h: &Host, class: &Class, field: &Field, d: &Data) -> std::result::Res
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
},
|
||||
Kind::PaperSize => match d {
|
||||
Data::Number(n) if n.is_finite() => {
|
||||
if *n != 0.0 && !(MIN_PAPER..=MAX_PAPER).contains(n) {
|
||||
return Err(HostError::Range(format!("{what} must be 0 or from {MIN_PAPER} to {MAX_PAPER}")));
|
||||
}
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
},
|
||||
Kind::Whole(lo, hi) => match d {
|
||||
Data::Number(n) => {
|
||||
if !whole(*n).is_some_and(|n| (lo..=hi).contains(&n)) {
|
||||
@@ -529,6 +548,7 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember {
|
||||
/// What a `PrintOptions` asks `file.print` for.
|
||||
#[derive(Default)]
|
||||
struct Job {
|
||||
clear_fit: bool,
|
||||
preset: Option<String>,
|
||||
file: Option<Data>,
|
||||
/// The assigned `printerName`.
|
||||
@@ -545,10 +565,12 @@ struct Job {
|
||||
paper_size: bool,
|
||||
/// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says.
|
||||
source: bool,
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile.
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` or the base settings must name the profile.
|
||||
custom: bool,
|
||||
/// `printArea` is assigned: the artboards print even when the base settings ignore them.
|
||||
print_area: bool,
|
||||
/// `position` is assigned: an untiled job does not use the saved Print Tiling origin.
|
||||
position: bool,
|
||||
/// The groups of `settings`: the top level and each nested object by its key.
|
||||
top: Map<String, Value>,
|
||||
groups: Vec<(&'static str, Map<String, Value>)>,
|
||||
@@ -675,6 +697,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
"printAsBitmap" => {
|
||||
job.group("advanced").insert("printAsBitmap".into(), json!(flag(v)));
|
||||
}
|
||||
"bitmapResolution" => {
|
||||
job.group("advanced").insert("bitmapResolution".into(), json!(number_of(v)));
|
||||
}
|
||||
"file" => job.file = Some(v.clone()),
|
||||
"artboardRange" => {
|
||||
job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty());
|
||||
@@ -683,6 +708,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) {
|
||||
s.insert("range".into(), json!(range));
|
||||
}
|
||||
if job.range.is_none() && value("printAllArtboards").is_none() {
|
||||
s.insert("artboards".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
"printArea" => job.print_area = true,
|
||||
_ => {}
|
||||
@@ -756,11 +784,12 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
Some(t)
|
||||
} else if scaled {
|
||||
Some("custom")
|
||||
} else if fit.is_some() || tiling.is_some() {
|
||||
} else if tiling.is_some() {
|
||||
Some("none")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
job.clear_fit = fit == Some(false) && scaling.is_none();
|
||||
if let Some(scaling) = scaling {
|
||||
job.top.insert("scaling".into(), json!(scaling));
|
||||
}
|
||||
@@ -809,6 +838,7 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
_ => "center",
|
||||
};
|
||||
job.group("placement").insert("origin".into(), json!(origin));
|
||||
job.position = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -874,6 +904,10 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn postscript_name(path: &str, windows: bool) -> bool {
|
||||
super::save_open::filename_for_suffix(path, windows).to_lowercase().ends_with(".ps")
|
||||
}
|
||||
|
||||
/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names,
|
||||
/// with the assigned options over the document's print settings, or without a file the job for a
|
||||
/// printer ([`prepare`]).
|
||||
@@ -890,11 +924,15 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(file) = job.file.take() else { return prepare(h, doc, job) };
|
||||
check_names(h, doc, &mut job)?;
|
||||
let path = file_path(&file, "print")?;
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || postscript_name(path, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
let mut p = print_params(&mut job);
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps";
|
||||
p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" }));
|
||||
// PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`.
|
||||
if postscript {
|
||||
p.insert("level".into(), json!(job.level.unwrap_or(2)));
|
||||
}
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command(h, PRINT, &Value::Object(p)))))?;
|
||||
// What the job lost or how its options apply: one Script Console line each.
|
||||
@@ -995,23 +1033,40 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// each assigned name against the list it must come from, and puts the checked names into the
|
||||
/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name` and no profile in the base settings.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
|
||||
let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
(st.doc.artboards.len(), mode == Some("ignore"))
|
||||
let scaling = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str);
|
||||
let profile = st.doc.print_setup.as_ref().and_then(|v| v.get("color")).and_then(|v| v.get("profile")).and_then(Value::as_str);
|
||||
let tiled = matches!(scaling, Some("tileFull" | "tileImageable"));
|
||||
(st.doc.artboards.len(), mode == Some("ignore"), scaling == Some("fit"), tiled, profile.unwrap_or("").to_string())
|
||||
});
|
||||
if let Some(range) = &job.range {
|
||||
vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut base_ignore = saved_ignore;
|
||||
let mut base_fit = saved_fit;
|
||||
let mut base_tiled = saved_tiled;
|
||||
if let Some(name) = job.preset.take() {
|
||||
let n = plain_name("PrintOptions.printPreset", "print preset", &name)?;
|
||||
let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?;
|
||||
base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore);
|
||||
base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit);
|
||||
base_tiled = preset.scaling.tiles();
|
||||
base_profile.clone_from(&preset.color.profile);
|
||||
job.preset = Some(n.to_string());
|
||||
}
|
||||
if job.clear_fit && base_fit {
|
||||
job.top.insert("scaling".into(), json!("none"));
|
||||
}
|
||||
// A placed Print Tiling origin replaces the placement, so an assigned `position` clears it
|
||||
// for this job when the job does not tile; the saved settings keep it.
|
||||
let tiled = job.top.get("scaling").and_then(Value::as_str).map_or(base_tiled, |s| matches!(s, "tileFull" | "tileImageable"));
|
||||
if job.position && !tiled {
|
||||
job.group("tileOrigin").insert("placed".into(), json!(false));
|
||||
}
|
||||
// An assigned `printArea` prints by artboard when the base settings ignore the artboards: the
|
||||
// assigned `artboardRange` when there is one, otherwise every artboard.
|
||||
if job.print_area && base_ignore && !job.top.contains_key("artboards") {
|
||||
@@ -1025,9 +1080,6 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
}
|
||||
job.group("advanced").insert("flattenerPreset".into(), json!(n));
|
||||
}
|
||||
if job.custom && job.profile.is_none() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.profile.take() {
|
||||
let what = "PrintColorManagementOptions.name";
|
||||
let n = plain_name(what, "color profile", &name)?;
|
||||
@@ -1039,6 +1091,8 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
if !job.source {
|
||||
job.group("color").insert("profile".into(), json!(profile.name));
|
||||
}
|
||||
} else if job.custom && base_profile.trim().is_empty() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.paper.take() {
|
||||
let n = plain_name("PrintPaperOptions.name", "paper", &name)?;
|
||||
@@ -1155,10 +1209,16 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
fn field_info(field: &Field) -> MemberInfo {
|
||||
match field.kind {
|
||||
Kind::Bool => typed("boolean"),
|
||||
// A field with no upper limit, such as `bitmapResolution`, reports no maximum.
|
||||
// A field with no upper limit reports no maximum.
|
||||
Kind::Number(min, max) => MemberInfo { min: Some(min), max: (max < f64::MAX).then_some(max), ..typed("number") },
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") },
|
||||
Kind::PaperSize => MemberInfo {
|
||||
min: Some(0.0),
|
||||
max: Some(MAX_PAPER),
|
||||
description: Some(format!("0 (not assigned) or a custom size from {MIN_PAPER} to {MAX_PAPER} pt")),
|
||||
..typed("number")
|
||||
},
|
||||
Kind::Text => typed("string"),
|
||||
Kind::Choice(name, _, _) | Kind::Child(name) => typed(name),
|
||||
Kind::File => typed("File"),
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte.
|
||||
//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error.
|
||||
//! - Each method sends command warnings to the Script Console with its name as the prefix.
|
||||
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
|
||||
//! commands a script runs never show a dialog, so the level does not change what they do, and it
|
||||
//! never allows a file the script's grants do not.
|
||||
@@ -919,7 +920,7 @@ pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
|
||||
/// a linked image an open could not read. → the command's answer.
|
||||
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
|
||||
let (answer, value) = super::super::command_value(h, id, p)?;
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().take(super::MAX_LISTED).filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
Ok(answer)
|
||||
@@ -963,8 +964,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
let given_options = given(arg(a, 2));
|
||||
// Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options
|
||||
// object of that format's class holds.
|
||||
let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase());
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c));
|
||||
let named_format = save_format_for_name(path, cfg!(windows)).map(|f| f.id);
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == named_format).map(|(c, _)| fresh(c));
|
||||
if let Some(o) = given_options.or(by_extension.as_ref()) {
|
||||
let name = typename(o);
|
||||
let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else {
|
||||
@@ -982,20 +983,38 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
} else if !q.is_empty() {
|
||||
p.insert("options".into(), Value::Object(q));
|
||||
}
|
||||
} else {
|
||||
let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id);
|
||||
}
|
||||
// Without options, the format of the file name as the platform reads it (on Windows, without
|
||||
// trailing dots and spaces), else the document's own.
|
||||
if !p.contains_key("format") {
|
||||
let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format));
|
||||
p.insert("format".into(), json!(format));
|
||||
}
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `path` with the extension of `kind` added, unless its name already ends with one of them.
|
||||
fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String {
|
||||
let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions };
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase();
|
||||
fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> {
|
||||
let name = filename_for_suffix(path, windows);
|
||||
// A name that is only a dot and an extension, such as `.pdf`, picks its format only for the
|
||||
// `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule.
|
||||
match name.rsplit_once('.') {
|
||||
Some(("", extension)) if SAVE_CLASSES.iter().any(|(_, f)| extension.eq_ignore_ascii_case(f)) => {
|
||||
crate::cmd::fileio::format_for_name(&format!("x.{extension}"))
|
||||
}
|
||||
_ => crate::cmd::fileio::format_for_name(name),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn filename_for_suffix(path: &str, windows: bool) -> &str {
|
||||
let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path);
|
||||
if windows { name.trim_end_matches(['.', ' ']) } else { name }
|
||||
}
|
||||
|
||||
pub(crate) fn with_extension(path: &str, extensions: &[&str], windows: bool) -> String {
|
||||
let name = filename_for_suffix(path, windows).to_lowercase();
|
||||
match extensions.first() {
|
||||
Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"),
|
||||
_ => path.to_string(),
|
||||
@@ -1058,10 +1077,10 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
} else {
|
||||
p.insert("useArtboards".into(), json!(false));
|
||||
}
|
||||
let named = with_extension(path, &kind, svgz);
|
||||
let named = with_extension(path, if svgz { &["svgz"] } else { kind.extensions }, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportFile", "document.export", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1110,9 +1129,19 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
// The command opens the given path; a real path that is not valid UTF-8 is still refused.
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
// The document's size is read before any of it is; a placed image keeps its own limit and message.
|
||||
if std::fs::metadata(&real).is_ok_and(|m| m.len() > super::super::files::MAX_OPEN_BYTES) {
|
||||
return Err(refused(super::super::files::OPEN_TOO_LARGE, path));
|
||||
}
|
||||
plain(real)?;
|
||||
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?));
|
||||
let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?;
|
||||
let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || {
|
||||
exactly(h, || warned(h, "app.open", "document.open", &Value::Object(p)))
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
HostError::Error(message) if message == crate::cmd::fileio::READ_TOO_LARGE => refused(super::super::files::OPEN_TOO_LARGE, path),
|
||||
e => e,
|
||||
})?;
|
||||
let index = match &r {
|
||||
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
|
||||
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
@@ -1283,7 +1312,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = super::with_doc(h, doc, |_, st| st.title());
|
||||
let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?;
|
||||
let p = json!({"path": plain(real)?, "format": format});
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.close", "file.saveAs", &p)))?;
|
||||
}
|
||||
_ => return Err(HostError::Error(UNSAVED_CHANGES.into())),
|
||||
}
|
||||
@@ -1340,3 +1369,37 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod save_format_tests {
|
||||
use super::save_format_for_name;
|
||||
|
||||
#[test]
|
||||
fn save_as_selects_the_format_from_windows_filename_aliases() {
|
||||
for extension in ["svg", "svgz", "ai", "eps", "pdf"] {
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
|
||||
assert_eq!(save_format_for_name(&name, true).map(|f| f.id), Some(extension), "{name}");
|
||||
assert!(save_format_for_name(&name, false).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] {
|
||||
assert!(save_format_for_name(name, true).is_none(), "{name}");
|
||||
}
|
||||
// Production passes `cfg!(windows)`; a Windows host still splits this name at the backslash.
|
||||
#[cfg(unix)]
|
||||
assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg"));
|
||||
#[cfg(windows)]
|
||||
assert!(save_format_for_name("proof\\.svg", false).is_none());
|
||||
for windows in [false, true] {
|
||||
assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf"));
|
||||
assert!(save_format_for_name(".svg", windows).is_none());
|
||||
assert!(save_format_for_name("/exports/.png", windows).is_none());
|
||||
assert_eq!(save_format_for_name("/exports/.eps", windows).map(|f| f.id), Some("eps"));
|
||||
assert_eq!(save_format_for_name("drawing.svg", windows).map(|f| f.id), Some("svg"));
|
||||
assert_eq!(save_format_for_name("drawing.svgz", windows).map(|f| f.id), Some("svgz"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,7 +478,7 @@ fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer {
|
||||
for items in exports {
|
||||
let mut p = base.clone();
|
||||
p.extend(items);
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
|
||||
@@ -47,10 +47,12 @@ fn owner_of(h: &Host, d: &Data) -> std::result::Result<Owner, HostError> {
|
||||
}
|
||||
|
||||
/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must
|
||||
/// still be in its document.
|
||||
/// still be in its document. A tracing the run traced again is followed to the object that
|
||||
/// replaced it, which keeps its tags, as its `PluginItem` is.
|
||||
fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = super::tracing::follow(h, doc.uid, id);
|
||||
let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some()));
|
||||
if !alive {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
@@ -111,7 +113,8 @@ fn doc_of_owner(owner: Owner) -> Doc {
|
||||
}
|
||||
|
||||
fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
let [high, low] = id_parts(id);
|
||||
// A tracing traced again keeps the id of the first object of its chain, as its `PluginItem` does.
|
||||
let [high, low] = id_parts(super::tracing::origin(h, doc.uid, id));
|
||||
let [tag_high, tag_low] = id_parts(NodeId(tag));
|
||||
host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low])
|
||||
}
|
||||
@@ -119,7 +122,7 @@ fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
/// `PageItem.tags`.
|
||||
pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let [high, low] = id_parts(item.id);
|
||||
let [high, low] = id_parts(super::tracing::origin(h, item.doc.uid, item.id));
|
||||
Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low]))
|
||||
}
|
||||
|
||||
|
||||
@@ -1539,7 +1539,8 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
|
||||
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does.
|
||||
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does, and
|
||||
/// so does an image the deletion would leave first in an ordinary group named as a tracing.
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = frames_scope(h, a)?;
|
||||
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -1563,7 +1564,7 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
// A clip group named as a tracing, released with an image left first, would become one.
|
||||
// A group named as a tracing, cleared or released with an image left first, would become one.
|
||||
if tracing {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
}
|
||||
|
||||
@@ -108,6 +108,9 @@ pub const MAX_MASK_STEPS: usize = 1 << 24;
|
||||
|
||||
pub(crate) const ACCESS_DENIED: &str = "Script file access denied";
|
||||
pub(crate) const TOO_LARGE: &str = "Script file exceeds 8 MiB";
|
||||
/// The largest document `app.open` reads, checked before the file is read.
|
||||
pub(crate) const MAX_OPEN_BYTES: u64 = 256 << 20;
|
||||
pub(crate) const OPEN_TOO_LARGE: &str = "Script document exceeds 256 MiB";
|
||||
pub(crate) const NOT_OPEN: &str = "Script file is not open";
|
||||
pub(crate) const UNDECODABLE: &str = "Script file cannot be decoded";
|
||||
pub(crate) const NOT_REGULAR: &str = "Script file is not a regular file";
|
||||
@@ -750,7 +753,7 @@ impl Disk {
|
||||
Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED),
|
||||
Err(ScriptRead::Failed(_)) => return Err(READ_FAILED),
|
||||
};
|
||||
if !real.is_file() {
|
||||
if !std::fs::metadata(&real).map_err(|_| READ_FAILED)?.is_file() {
|
||||
return Err(NOT_REGULAR);
|
||||
}
|
||||
Ok(real)
|
||||
|
||||
@@ -2835,7 +2835,12 @@ impl Session {
|
||||
changed_names.push(st.title());
|
||||
continue;
|
||||
};
|
||||
let changed = !st.same_content(&b.doc);
|
||||
// The perspective grid's view state changes without an undo step, as it does outside a
|
||||
// run, when no command in the run recorded an undo step of its own on the working copy.
|
||||
// The working copy starts with no undo steps (`World::working`), so any step it holds now
|
||||
// was recorded in the run.
|
||||
let recorded = !st.history.undo.is_empty();
|
||||
let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc));
|
||||
st.history = std::mem::take(&mut b.history);
|
||||
st.recovery.clone_from(&b.recovery);
|
||||
if changed {
|
||||
|
||||
@@ -442,7 +442,7 @@ impl Session {
|
||||
// parts it left alone keep the interaction's. The pattern lists every field, so a field
|
||||
// added to `PaintDefaults` does not compile until it is handled here. The paints a preview
|
||||
// took its new-art paints over from take the change as well.
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint;
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = &self.paint;
|
||||
for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) {
|
||||
if *fill != paint.fill {
|
||||
start.fill.clone_from(fill);
|
||||
@@ -462,8 +462,9 @@ impl Session {
|
||||
if *blend != paint.blend {
|
||||
start.blend = *blend;
|
||||
}
|
||||
if *style != paint.style {
|
||||
if *style != paint.style || *style_doc != paint.style_doc {
|
||||
start.style.clone_from(style);
|
||||
start.style_doc = *style_doc;
|
||||
}
|
||||
if *inherited != paint.inherited {
|
||||
start.inherited = *inherited;
|
||||
@@ -974,7 +975,7 @@ fn take_changed_paints(
|
||||
left: &vectorcraft_tools::PaintDefaults,
|
||||
now: &vectorcraft_tools::PaintDefaults,
|
||||
) {
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now;
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = now;
|
||||
if left.fill != *fill {
|
||||
target.fill.clone_from(fill);
|
||||
}
|
||||
@@ -993,8 +994,9 @@ fn take_changed_paints(
|
||||
if left.blend != *blend {
|
||||
target.blend = *blend;
|
||||
}
|
||||
if left.style != *style {
|
||||
if left.style != *style || left.style_doc != *style_doc {
|
||||
target.style.clone_from(style);
|
||||
target.style_doc = *style_doc;
|
||||
}
|
||||
if left.inherited != *inherited {
|
||||
target.inherited = *inherited;
|
||||
|
||||
@@ -188,6 +188,7 @@ mod script_dom;
|
||||
mod script_dom_defaults;
|
||||
mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_perspective;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_resources;
|
||||
mod script_dom_tracing;
|
||||
|
||||
@@ -474,3 +474,249 @@ fn set_new_art_refuses_while_new_art_takes_the_selected_look() {
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true}));
|
||||
assert_eq!(s.new_art().stroke().unwrap().width, 7.0);
|
||||
}
|
||||
|
||||
fn new_type(s: &mut Session, p: Value) -> Node {
|
||||
let id = NodeId(run(s, "text.create", p)["id"].as_u64().unwrap());
|
||||
node(s, id)
|
||||
}
|
||||
|
||||
/// The fill of `n`'s first run of characters.
|
||||
fn char_fill(n: &Node) -> Paint {
|
||||
match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.fill.clone(),
|
||||
_ => panic!("{} is not type", n.id.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Type with a second fill and a drop shadow on the object, selected.
|
||||
fn styled_type(s: &mut Session) -> NodeId {
|
||||
let id = NodeId(run(s, "text.create", json!({"x": 20, "y": 60, "text": "RIP", "size": 30}))["id"].as_u64().unwrap());
|
||||
run(s, "appearance.addFill", json!({}));
|
||||
run(s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(s, "effect.apply", json!({"effect": "stylize.dropShadow"}));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects() {
|
||||
let mut s = session();
|
||||
let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let src = styled_type(&mut s);
|
||||
let from = node(&s, src).appearance;
|
||||
assert_eq!(from.effects.len(), 1);
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [src.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "new"}));
|
||||
assert_eq!(n.appearance.effects.len(), 1, "the drop shadow");
|
||||
assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), from.items.iter().filter(|i| i.is_fill()).count());
|
||||
assert_eq!(n.appearance.fill_paint(), from.fill_paint(), "the template keeps its own fill");
|
||||
// Override Character Color: the object's fill shows instead of the characters' own.
|
||||
assert_eq!(char_fill(&n), Paint::None);
|
||||
// Type placed in a group takes it too, and a color given keeps the characters' fill.
|
||||
run(&mut s, "select.set", json!({"ids": [src.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let g = new_type(&mut s, json!({"x": 200, "y": 250, "text": "in", "parent": group, "color": "#00ff00"}));
|
||||
assert_eq!(g.appearance.effects.len(), 1);
|
||||
assert_ne!(char_fill(&g), Paint::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke() {
|
||||
let mut s = session();
|
||||
let plain = new_type(&mut s, json!({"x": 20, "y": 60, "text": "a"}));
|
||||
assert!(plain.appearance.items.is_empty() && plain.appearance.effects.is_empty());
|
||||
// Option on: a styled selection gives new type only its basic paints, so it stays plain.
|
||||
let src = styled_type(&mut s);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "b"}));
|
||||
assert_eq!((n.appearance.items.len(), n.appearance.effects.len(), char_fill(&n)), (0, 0, char_fill(&plain)));
|
||||
// Option off with plain type last selected: its characters' basic look, no fills of the object.
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [n.id.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let m = new_type(&mut s, json!({"x": 200, "y": 250, "text": "c"}));
|
||||
assert_eq!((m.appearance.items.len(), char_fill(&m)), (0, char_fill(&plain)));
|
||||
assert!(node(&s, src).appearance.effects.len() == 1, "the source keeps its look");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_style_clicked_with_nothing_selected_styles_the_next_type() {
|
||||
let mut s = session();
|
||||
fancy(&mut s);
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Fancy"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "styled"}));
|
||||
assert_eq!((n.appearance.items.iter().filter(|i| i.is_fill()).count(), n.appearance.effects.len()), (2, 1));
|
||||
assert_eq!(char_fill(&n), Paint::None);
|
||||
// With Override Character Color off the characters keep their fill under the style's.
|
||||
run(&mut s, "graphicStyle.setOptions", json!({"overrideCharColor": false}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let kept = new_type(&mut s, json!({"x": 200, "y": 250, "text": "kept"}));
|
||||
assert_eq!(kept.appearance.effects.len(), 1);
|
||||
assert_ne!(char_fill(&kept), Paint::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_art_and_type_from_a_knockout_style_stay_linked_to_it() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 20.0);
|
||||
run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true}));
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Knockout"}))["name"].as_str().unwrap().to_string();
|
||||
for (make, p) in
|
||||
[("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))]
|
||||
{
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
run(&mut s, make, p);
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{make}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type() {
|
||||
let mut s = session();
|
||||
let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0);
|
||||
let red = node(&s, src).appearance.fill_paint();
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Plain"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
// The first type is linked to the style, so the next one, taking its look, gets it too.
|
||||
for (y, text) in [(200, "one"), (250, "two")] {
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": y, "text": text}));
|
||||
assert_eq!(n.appearance.fill_paint(), red, "{text}");
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{text}");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with() {
|
||||
let mut s = session();
|
||||
let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 80}));
|
||||
// A placed vertical gradient, top to bottom of the rectangle.
|
||||
let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]);
|
||||
run(&mut s, "paint.setFill", json!({"gradient": {"stops": stops, "start": [50, 0], "end": [50, 80]}}));
|
||||
let name = run(&mut s, "graphicStyle.new", json!({"name": "Vertical"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "object.textWrap.make", json!({"offset": 0}));
|
||||
let style = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == name).unwrap().clone();
|
||||
assert!(style.unit_box && style.appearance.has_placed_gradient());
|
||||
let area = json!({"width": 100, "height": 20, "fit": "autoHeight"});
|
||||
// Drawn behind the wrap object, and placed into a group below it.
|
||||
for p in [
|
||||
json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area}),
|
||||
json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area, "parent": group}),
|
||||
] {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "view.drawMode", json!({"mode": if p.get("parent").is_some() { "normal" } else { "behind" }}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": name}));
|
||||
let n = new_type(&mut s, p.clone());
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(b.height() > 80.0, "the frame grows below the wrap object: {b:?} ({p})");
|
||||
let mut placed = style.appearance.clone();
|
||||
placed.rebase_gradients(vectorcraft_doc::GraphicStyle::UNIT_BOX, b);
|
||||
assert_eq!(*n.appearance, placed, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name() {
|
||||
let mut s = session();
|
||||
fancy(&mut s);
|
||||
run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Shared"}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": "Shared"}));
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
rect(&mut s, 20.0);
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Shared"}));
|
||||
for (make, p) in
|
||||
[("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))]
|
||||
{
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let id = NodeId(run(&mut s, make, p)["id"].as_u64().unwrap());
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.extras().graphic_style, n.isolate), (None, false), "{make}");
|
||||
assert_eq!(n.appearance.effects.len(), 1, "{make} keeps the template's look");
|
||||
}
|
||||
// Back in the document the style came from, new art is linked to it again.
|
||||
s.set_active(0);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "text.create", json!({"x": 200, "y": 200, "text": "k"}));
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Shared".to_string(), true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_in_another_document_takes_a_basic_styles_look_and_transparency() {
|
||||
let mut s = session();
|
||||
let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0);
|
||||
let red = node(&s, src).appearance.fill_paint();
|
||||
run(&mut s, "transparency.set", json!({"opacity": 50, "blend": "multiply"}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Red"}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": "Red"}));
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "k"}));
|
||||
assert_eq!(n.appearance.fill_paint(), red, "the style's fill");
|
||||
assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply), "the style's transparency");
|
||||
assert_eq!(n.extras().graphic_style, None, "no link to a style of another document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_art_and_type_from_a_style_redefined_after_it_was_picked_keep_the_picked_look_unlinked() {
|
||||
let mut s = session();
|
||||
fancy(&mut s);
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Picked"}));
|
||||
let other = painted(&mut s, 120.0, "#00ff00", "#000000", 3.0);
|
||||
run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "graphicStyle.apply", json!({"name": "Picked"}));
|
||||
let picked = s.new_art();
|
||||
let redefine = |s: &mut Session| run(s, "graphicStyle.redefine", json!({"name": "Picked", "id": other.0}));
|
||||
let linked = |s: &mut Session| run(s, "appearance.newArt", json!({}))["graphicStyle"].clone();
|
||||
let make =
|
||||
[("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))];
|
||||
redefine(&mut s);
|
||||
assert_eq!(linked(&mut s), Value::Null);
|
||||
// Undone, the style has the picked look again, and new art links to it.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(linked(&mut s), json!("Picked"));
|
||||
for (cmd, p) in &make {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, cmd, p.clone());
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Picked".to_string(), true)), "{cmd}");
|
||||
}
|
||||
redefine(&mut s);
|
||||
assert_eq!(linked(&mut s), Value::Null);
|
||||
for (cmd, p) in &make {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let id = NodeId(run(&mut s, cmd, p.clone())["id"].as_u64().unwrap());
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.extras().graphic_style, n.isolate, n.opacity), (None, false, 0.5), "{cmd}: the picked transparency, unlinked");
|
||||
assert_eq!((n.appearance.effects.len(), n.appearance.fill_paint()), (1, picked.fill_paint()), "{cmd}: the picked look");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_type_takes_a_selected_look_that_matches_the_redefined_default_style() {
|
||||
let mut s = session();
|
||||
let src = fancy(&mut s);
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "Default Graphic Style", "id": src.0}));
|
||||
run(&mut s, "graphicStyle.breakLink", json!({"ids": [src.0]}));
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [src.0]}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "in"}));
|
||||
assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), 2, "both fills from the selection");
|
||||
assert_eq!(n.appearance.effects.len(), 1, "the drop shadow from the selection");
|
||||
// The same look from paint.default is the document's default, so new type stays plain.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
run(&mut s, "paint.default", json!({}));
|
||||
let d = new_type(&mut s, json!({"x": 200, "y": 260, "text": "df"}));
|
||||
assert!(d.appearance.items.is_empty() && d.appearance.effects.is_empty(), "plain type");
|
||||
assert_ne!(char_fill(&d), Paint::None);
|
||||
}
|
||||
|
||||
@@ -152,6 +152,236 @@ fn print_as_bitmap_prints_all_of_a_long_artboard() {
|
||||
assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}");
|
||||
}
|
||||
|
||||
/// A raster effects resolution that isn't a number prints at the resolution the document reads it
|
||||
/// as (72 ppi), not as an empty page.
|
||||
#[test]
|
||||
fn print_as_bitmap_of_a_resolution_that_is_not_a_number_prints_at_72_ppi() {
|
||||
let (s, _) = session();
|
||||
let saved = s.prefs.flattener_presets.clone();
|
||||
let set = settings(json!({"advanced": {"printAsBitmap": true}}));
|
||||
let widths = |ppi: f64| {
|
||||
let mut d = doc(&s).clone();
|
||||
d.raster_effects_ppi = ppi;
|
||||
let bitmap = crate::cmd::printadvanced::prepare("file.print", &d, &set, &saved, false).unwrap().unwrap();
|
||||
let mut widths = vec![];
|
||||
bitmap.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
widths.push(im.width);
|
||||
}
|
||||
});
|
||||
widths
|
||||
};
|
||||
let at_72 = widths(72.0);
|
||||
assert_eq!(at_72.len(), 1, "{at_72:?}");
|
||||
assert_eq!(widths(f64::NAN), at_72);
|
||||
assert!(widths(144.0)[0] > at_72[0], "the resolution decides the image's size");
|
||||
}
|
||||
|
||||
/// The images `file.print` prints with `settings`: their pixel sizes and their places on the page
|
||||
/// in the print-ready PDF (read back), their pixel sizes in the PostScript file (its image
|
||||
/// dictionaries, each size once), and the warnings of both.
|
||||
struct Printed {
|
||||
pdf: Vec<(u32, u32)>,
|
||||
placed: Vec<Rect>,
|
||||
ps: Vec<(u32, u32)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn printed_images(s: &mut Session, settings: &Value) -> Printed {
|
||||
let warnings = |v: &Value| -> Vec<String> { v["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect() };
|
||||
let v = s.execute("file.print", &json!({ "settings": settings })).unwrap();
|
||||
let back = vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let (mut pdf, mut placed) = (vec![], vec![]);
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
pdf.push((im.width, im.height));
|
||||
placed.push(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))));
|
||||
}
|
||||
});
|
||||
let mut all = warnings(&v);
|
||||
let v = s.execute("file.print", &json!({ "settings": settings, "format": "postscript" })).unwrap();
|
||||
let ps = String::from_utf8_lossy(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).into_owned();
|
||||
let mut sizes = vec![];
|
||||
for part in ps.split("<< /ImageType ").skip(1) {
|
||||
let after = |key: &str| part.split_once(key).and_then(|(_, r)| r.split_whitespace().next()).and_then(|n| n.parse::<u32>().ok());
|
||||
if let (Some(w), Some(h)) = (after("/Width "), after("/Height ")) {
|
||||
sizes.push((w, h));
|
||||
}
|
||||
}
|
||||
sizes.sort_unstable();
|
||||
sizes.dedup();
|
||||
all.extend(warnings(&v));
|
||||
Printed { pdf, placed, ps: sizes, warnings: all }
|
||||
}
|
||||
|
||||
const CAPPED: &str = "Print as Bitmap prints at";
|
||||
|
||||
/// `advanced.bitmapResolution` sets how many pixels Print as Bitmap prints the art with, in a
|
||||
/// print-ready PDF and in PostScript, on the same place of the page; 0 or none keeps the
|
||||
/// document's raster effects resolution.
|
||||
#[test]
|
||||
fn bitmap_resolution_sets_the_printed_image_size() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let mut places = vec![];
|
||||
for (ppi, size) in [(Value::Null, (200, 100)), (json!(0), (200, 100)), (json!(144), (400, 200)), (json!(36), (100, 50)), (json!(1), (3, 2))] {
|
||||
let mut advanced = json!({"printAsBitmap": true});
|
||||
if !ppi.is_null() {
|
||||
advanced["bitmapResolution"] = ppi.clone();
|
||||
}
|
||||
let p = printed_images(&mut s, &json!({ "advanced": advanced }));
|
||||
assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([size].as_slice(), [size].as_slice()), "{ppi}");
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{ppi}: {:?}", p.warnings);
|
||||
// At 1 ppi the image is rounded up to whole pixels past the artboard.
|
||||
if ppi != json!(1) {
|
||||
places.extend(p.placed);
|
||||
}
|
||||
}
|
||||
let first = places[0];
|
||||
for r in &places {
|
||||
let apart = (r.x0 - first.x0).abs() + (r.y0 - first.y0).abs() + (r.width() - first.width()).abs() + (r.height() - first.height()).abs();
|
||||
assert!(apart < 1.0, "the image covers the same part of the page: {r:?} vs {first:?}");
|
||||
}
|
||||
// Art that does not print as a bitmap leaves it unused.
|
||||
let p = printed_images(&mut s, &json!({"advanced": {"bitmapResolution": 144}}));
|
||||
assert!(p.pdf.is_empty(), "{:?}", p.pdf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_as_bitmap_keeps_its_resolution_at_unlinked_print_scales() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let set = json!({
|
||||
"advanced": {"printAsBitmap": true, "bitmapResolution": 144},
|
||||
"scaling": "custom", "scale": {"width": 200, "height": 100, "linked": false}
|
||||
});
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([(800, 200)].as_slice(), [(800, 200)].as_slice()));
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
let [placed] = p.placed[..] else { panic!("one image: {:?}", p.placed) };
|
||||
assert!((placed.width() - 400.0).abs() < 0.01 && (placed.height() - 100.0).abs() < 0.01, "{placed:?}");
|
||||
}
|
||||
|
||||
/// Print as Bitmap prints at `bitmapResolution` on paper: a job printed at 200% renders twice the
|
||||
/// pixels, and so does one that Fit to Page enlarges, so the image keeps its resolution.
|
||||
#[test]
|
||||
fn print_as_bitmap_keeps_its_resolution_at_a_print_scale() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let advanced = json!({"printAsBitmap": true, "bitmapResolution": 144});
|
||||
let p = printed_images(&mut s, &json!({"advanced": advanced, "scaling": "custom", "scale": {"width": 200}}));
|
||||
assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([(800, 400)].as_slice(), [(800, 400)].as_slice()));
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
let fit = printed_images(&mut s, &json!({"advanced": advanced, "scaling": "fit"}));
|
||||
let [(w, _)] = fit.pdf[..] else { panic!("one image: {:?}", fit.pdf) };
|
||||
let [placed] = fit.placed[..] else { panic!("one image: {:?}", fit.placed) };
|
||||
let ppi = f64::from(w) / placed.width() * 72.0;
|
||||
assert!((ppi - 144.0).abs() < 2.0, "{w} pixels across {} pt: {ppi} ppi", placed.width());
|
||||
}
|
||||
|
||||
/// A `bitmapResolution` given to `file.print` applies to that job alone; `print.setup` saves it.
|
||||
#[test]
|
||||
fn a_bitmap_resolution_given_to_file_print_applies_to_that_job() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let undo = s.active().unwrap().history.undo.len();
|
||||
let p = printed_images(&mut s, &json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 144}}));
|
||||
assert_eq!(p.pdf, [(400, 200)]);
|
||||
assert!(doc(&s).print_setup.is_none(), "the saved settings stay as they are");
|
||||
assert_eq!(doc(&s).raster_effects_ppi, 72.0, "and so does the raster effects resolution");
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo, "printing adds no undo step");
|
||||
let v = s.execute("print.setup", &json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": 144}}})).unwrap();
|
||||
assert_eq!(v["settings"]["advanced"]["bitmapResolution"], 144.0);
|
||||
assert_eq!(printed_images(&mut s, &json!({})).pdf, [(400, 200)], "a job without settings prints at the saved one");
|
||||
assert_eq!(printed_images(&mut s, &json!({"advanced": {"bitmapResolution": 0}})).pdf, [(200, 100)], "0 over it: the document's");
|
||||
// A saved 0 is left out of the settings, which read it back as 0.
|
||||
let v = s.execute("print.setup", &json!({"settings": {"advanced": {"bitmapResolution": 0}}})).unwrap();
|
||||
assert!(v["settings"]["advanced"].get("bitmapResolution").is_none(), "{}", v["settings"]["advanced"]);
|
||||
}
|
||||
|
||||
/// A `bitmapResolution` outside 0 and 1–9600 ppi, or that is not a number, is refused by
|
||||
/// `print.setup`, `print.preview` and `file.print` alike, and nothing is saved.
|
||||
#[test]
|
||||
fn a_bitmap_resolution_out_of_range_is_refused() {
|
||||
let (mut s, _) = session();
|
||||
let undo = s.active().unwrap().history.undo.len();
|
||||
for bad in [json!(0.5), json!(-1), json!(-0.001), json!(9600.5), json!(1e300), json!("high"), json!(true), json!([300])] {
|
||||
let p = json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": bad}}});
|
||||
for cmd in ["print.setup", "print.preview", "file.print"] {
|
||||
let e = s.execute(cmd, &p).map(|v| panic!("{cmd} {bad}: {v}")).unwrap_err().to_string();
|
||||
assert!(!bad.is_number() || e.contains("advanced.bitmapResolution must be 1–9600 ppi"), "{cmd} {bad}: {e}");
|
||||
}
|
||||
}
|
||||
assert!(doc(&s).print_setup.is_none());
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo);
|
||||
for ok in [1.0, 9600.0] {
|
||||
s.execute("print.preview", &json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": ok}}})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A page the pixel limits print below the `bitmapResolution` asked for gets a warning that names
|
||||
/// the resolution it prints at, in `file.print`'s PDF and PostScript replies and in
|
||||
/// `print.preview`.
|
||||
#[test]
|
||||
fn a_bitmap_resolution_the_pixel_limits_lower_is_named() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 9000, "height": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 2})).unwrap();
|
||||
let set = json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}});
|
||||
let p = printed_images(&mut s, &set);
|
||||
// 32,766 pixels across 9,000 pt: 262.1 ppi.
|
||||
let note = "Print as Bitmap prints at 262 ppi, not the 600 ppi bitmapResolution asks for";
|
||||
assert_eq!(p.warnings.iter().filter(|w| w.starts_with(note)).count(), 2, "{:?}", p.warnings);
|
||||
let [(w, _)] = p.pdf[..] else { panic!("one image: {:?}", p.pdf) };
|
||||
assert!((32_000..=vectorcraft_render::MAX_RASTER_SIDE).contains(&w), "{w} pixels");
|
||||
assert_eq!(p.ps, p.pdf);
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(note)), "{}", pv["warnings"]);
|
||||
// A resolution that fits, the document's resolution, and output that is not a bitmap: no note.
|
||||
for set in [
|
||||
json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 200}}),
|
||||
json!({"advanced": {"printAsBitmap": true}}),
|
||||
json!({"advanced": {"bitmapResolution": 600}}),
|
||||
json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}, "output": {"mode": "separations"}}),
|
||||
] {
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(!pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{set}: {}", pv["warnings"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard with no art prints no image, so the pixel limits a bitmap of it would meet name no
|
||||
/// lower resolution, also with only art that draws nothing on it in `file.print`; once a background
|
||||
/// color or art that draws is on it, they do.
|
||||
#[test]
|
||||
fn an_empty_artboard_does_not_name_a_lower_bitmap_resolution() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("artboard.new", &json!({"x": 0, "y": 500, "width": 9000, "height": 2})).unwrap();
|
||||
let set = json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}});
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 1, "only the artboard with art prints an image: {:?}", p.pdf);
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(!pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{}", pv["warnings"]);
|
||||
// A background color prints, in file.print and in what print.preview says alike.
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "color": "#336699"})).unwrap();
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 2, "{:?}", p.pdf);
|
||||
assert_eq!(p.warnings.iter().filter(|w| w.starts_with(CAPPED)).count(), 2, "{:?}", p.warnings);
|
||||
let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap();
|
||||
assert!(pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{}", pv["warnings"]);
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "color": null})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 500, "width": 9000, "height": 2})).unwrap()["id"].clone();
|
||||
// Art that draws nothing prints no image either.
|
||||
s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap();
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 1, "{:?}", p.pdf);
|
||||
assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings);
|
||||
s.execute("object.setProps", &json!({"ids": [id], "opacity": 100})).unwrap();
|
||||
let p = printed_images(&mut s, &set);
|
||||
assert_eq!(p.pdf.len(), 2, "{:?}", p.pdf);
|
||||
assert_eq!(p.warnings.iter().filter(|w| w.starts_with(CAPPED)).count(), 2, "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
/// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB
|
||||
/// black when `rich_black` is on.
|
||||
#[test]
|
||||
|
||||
@@ -133,6 +133,118 @@ fn pathless_save_rejection_hides_document_folder() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_file_save_directory_errors_hide_paths_the_caller_did_not_give() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("multi-file-directory-error");
|
||||
let (inside, outside) = (d.join("in"), d.join("kept-out"));
|
||||
for folder in [&inside, &outside] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
let saved = s.execute("document.save", &json!({"path": own, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = saved["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert!(files.len() > 1, "{saved}");
|
||||
let primary = std::fs::read(&own).unwrap();
|
||||
rect(&mut s);
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
|
||||
for target in [&files[0], &files[1]] {
|
||||
let original = std::fs::read(target).unwrap();
|
||||
std::fs::remove_file(target).unwrap();
|
||||
std::fs::create_dir(target).unwrap();
|
||||
let name = std::path::Path::new(target).file_name().unwrap().to_string_lossy();
|
||||
for (roots, params, shown) in [
|
||||
(&write_only, json!({"separateArtboards": true}), name.as_ref()),
|
||||
(&write_only, json!({"path": null, "separateArtboards": true}), name.as_ref()),
|
||||
(&write_only, json!({"path": own, "separateArtboards": true}), target.as_str()),
|
||||
(&both, json!({"separateArtboards": true}), target.as_str()),
|
||||
] {
|
||||
let error = confine(roots.as_ref(), || s.execute("document.save", ¶ms)).unwrap_err().to_string();
|
||||
assert_eq!(error, format!("{shown}: not a file"), "{params}");
|
||||
assert!(std::path::Path::new(target).is_dir());
|
||||
if target != &own {
|
||||
assert_eq!(std::fs::read(&own).unwrap(), primary);
|
||||
}
|
||||
assert!(s.doc().unwrap().is_dirty());
|
||||
}
|
||||
std::fs::remove_dir(target).unwrap();
|
||||
std::fs::write(target, original).unwrap();
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_multi_file_save_never_calls_the_writer() {
|
||||
use crate::cmd::fileio::save_job;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("refused-writer");
|
||||
let inside = d.join("in");
|
||||
let outside = d.join("out");
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": own})).unwrap();
|
||||
let original = std::fs::read(&own).unwrap();
|
||||
let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
for explicit in [false, true] {
|
||||
let p = if explicit { json!({"path": own, "separateArtboards": true}) } else { json!({"separateArtboards": true}) };
|
||||
let plan = save_plan(&s, SaveMode::Save, &p).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let mut calls = 0;
|
||||
let error = confine(roots.as_ref(), || {
|
||||
job.write_unless(
|
||||
|_| None,
|
||||
|_, _| {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(calls, 0);
|
||||
assert!(error.contains("outside the write root"), "{error}");
|
||||
assert_eq!(error.contains(&outside.to_string_lossy().to_string()), explicit, "{error}");
|
||||
assert_eq!(std::fs::read(&own).unwrap(), original);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A save of several files into a folder that may not be read fails as a write there fails, with
|
||||
/// READ_ONLY_LOCATION, and not because the files' real paths could not be compared.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_multi_file_save_into_a_locked_folder_is_read_only() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let d = dir("locked-multi");
|
||||
let locked = d.join("locked");
|
||||
std::fs::create_dir_all(&locked).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let own = path(&locked, "doc.vectorcraft");
|
||||
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
// Where permissions don't hold (root), the folder reads as any other.
|
||||
let enforced = std::fs::read_dir(&locked).is_err();
|
||||
let r = s.execute("document.save", &json!({"path": own, "separateArtboards": true}));
|
||||
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
if enforced {
|
||||
let e = r.unwrap_err();
|
||||
assert!(matches!(e, EngineError::ReadOnlyLocation(_)), "{e}");
|
||||
assert!(std::fs::read_dir(&locked).unwrap().next().is_none());
|
||||
} else {
|
||||
assert!(r.is_ok(), "{r:?}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_path_writes_svg_and_save_writes_it_back() {
|
||||
let d = dir("svg");
|
||||
|
||||
@@ -338,6 +338,45 @@ fn steps_discard_the_chosen_artboard_after_revert() {
|
||||
assert_ne!(now[2], was[2], "playback uses the run's original index after revert");
|
||||
}
|
||||
|
||||
/// An artboard the script removes or inserts moves the active artboard's index; its played steps act
|
||||
/// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does,
|
||||
/// also after an undo puts the artboards back. The artboard that was active stays active, also when
|
||||
/// none was chosen before the run.
|
||||
#[test]
|
||||
fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() {
|
||||
let setup = |active: Option<usize>| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
if let Some(i) = active {
|
||||
make_active(&mut s, i);
|
||||
}
|
||||
(s, id)
|
||||
};
|
||||
let actions = set(&[("Align", vec![json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}})])]);
|
||||
let cases = [
|
||||
(Some(1), "A.remove(0);"),
|
||||
(Some(1), "A[0].remove();"),
|
||||
(Some(1), "A.insert([2000, 500, 2100, 400], 0);"),
|
||||
(Some(1), "A.insert([2000, 500, 2100, 400], 2);"),
|
||||
(Some(1), "A.remove(0); app.undo();"),
|
||||
(None, "A.insert([2000, 500, 2100, 400], 0);"),
|
||||
];
|
||||
for (active, edit) in cases {
|
||||
let (mut s, id) = setup(active);
|
||||
let was = s.active().unwrap().doc.artboards[active.unwrap_or(0)].rect;
|
||||
let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');");
|
||||
let out = log_with(&mut s, &source, &actions);
|
||||
let index = out[0].as_u64().unwrap() as usize;
|
||||
let board = s.active().unwrap().doc.artboards[index].rect;
|
||||
let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
assert_eq!(left, board.x0, "{active:?} {edit}");
|
||||
assert_eq!(board, was, "the artboard active before the edit stays active: {active:?} {edit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
|
||||
@@ -2804,6 +2804,11 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let steps = undo_steps(&s);
|
||||
// The lengths are read inside the run, after the refusal is caught, so a delete that ran before
|
||||
// the refusal shows here even though a failed run would put the tree back.
|
||||
let lengths = "vc.log([d.pageItems.length, d.layers[0].pageItems.length, d.groupItems.length, d.groupItems.length && d.groupItems[0].pageItems.length, \
|
||||
d.compoundPathItems.length]);";
|
||||
let counts = log(&mut s, &format!("var d = app.activeDocument; {lengths}"));
|
||||
for scope in [
|
||||
"app.activeDocument.layers[0].pageItems",
|
||||
"app.activeDocument.layers[0].groupItems",
|
||||
@@ -2815,9 +2820,13 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
"app.activeDocument.groupItems.getByName('locked').pathItems",
|
||||
"app.activeDocument.compoundPathItems[0].pathItems",
|
||||
] {
|
||||
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
|
||||
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("var d = app.activeDocument; try {{ {scope}.removeAll(); vc.log('ok'); }} catch (e) {{ vc.log(e.message); }} {lengths}"),
|
||||
);
|
||||
let err = out[0].as_str().unwrap_or_default();
|
||||
assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}");
|
||||
assert_eq!(out[1..], counts[..], "{scope}: nothing is deleted before the refusal");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}");
|
||||
assert_eq!(undo_steps(&s), steps, "{scope}");
|
||||
let doc = &s.active().unwrap().doc;
|
||||
@@ -5190,6 +5199,38 @@ fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() {
|
||||
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
|
||||
}
|
||||
|
||||
/// Without a chosen artboard, an artboard inserted before the default active one moves it to the
|
||||
/// next index, in an open document and in one the run makes, and the report gives that index.
|
||||
#[test]
|
||||
fn inserting_before_the_default_active_artboard_keeps_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let first = s.active().unwrap().doc.artboards[0].id;
|
||||
let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}]));
|
||||
assert_eq!(s.active().unwrap().active_artboard, Some(first));
|
||||
let r = run(&mut s, "var d = app.documents.add(); var A = d.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());")
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
let list = r["activeArtboards"].as_array().cloned().unwrap_or_default();
|
||||
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
|
||||
}
|
||||
|
||||
/// After the chosen artboard is removed, the artboard active in its place stays active when one is
|
||||
/// inserted before it.
|
||||
#[test]
|
||||
fn inserting_before_the_fallback_after_the_chosen_artboard_is_removed_keeps_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var A = app.activeDocument.artboards; A.add([800, 300, 900, 100]); A.setActiveArtboardIndex(1); A.remove(1);\
|
||||
var was = A[A.getActiveArtboardIndex()].name; A.insert([1000, 300, 1100, 100], 0);\
|
||||
vc.log(A[A.getActiveArtboardIndex()].name == was);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([true]), "{r}");
|
||||
}
|
||||
|
||||
/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard.
|
||||
#[test]
|
||||
fn artboards_insert_returns_nothing() {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! The script object model's perspective grid members and `app.getPresetSettings`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn grid(s: &mut Session) -> Value {
|
||||
s.execute("perspective.grid.get", &json!({})).unwrap()["grid"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_and_hide_change_the_view_without_an_undo_step() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
let out =
|
||||
log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.showPerspectiveGrid()); vc.log(d.showPerspectiveGrid());");
|
||||
assert_eq!(out, vec![json!(false), json!(true), json!(true)]);
|
||||
assert_eq!(grid(&mut s)["visible"], true);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
let out = log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.hidePerspectiveGrid());");
|
||||
assert_eq!(out, vec![json!(true), json!(false)]);
|
||||
assert_eq!(grid(&mut s)["visible"], false);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_view_migrates_legacy_attachments_without_an_undo_step() {
|
||||
use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane};
|
||||
|
||||
for (call, edit) in [("showPerspectiveGrid", false), ("hidePerspectiveGrid", false), ("showPerspectiveGrid", true), ("hidePerspectiveGrid", true)]
|
||||
{
|
||||
let mut s = doc();
|
||||
let made = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let id = NodeId(made["id"].as_u64().unwrap());
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let mut g = PerspectiveGrid::current(d);
|
||||
g.visible = call == "hidePerspectiveGrid";
|
||||
g.attached.insert(id.0.to_string(), Plane::Right);
|
||||
d.unknown.insert(persp::DOC_KEY.into(), serde_json::to_value(&g).unwrap());
|
||||
let before = undo_steps(&s);
|
||||
let draw = if edit { "vc.run('shape.rectangle', {x: 50, y: 50, width: 10, height: 10});" } else { "" };
|
||||
run(&mut s, &format!("app.activeDocument.{call}(); {draw}")).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + usize::from(edit));
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(PerspectiveGrid::current(d).attachment_of(d, id), Some((Plane::Right, 0.0)));
|
||||
assert!(d.node(id).unwrap().extras().perspective.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
run(&mut s, "vc.run('perspective.grid.show', {visible: true}); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap();
|
||||
assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
run(&mut s, "app.activeDocument.hidePerspectiveGrid(); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});").unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(grid(&mut s)["visible"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_view_run_after_an_edit_adds_no_undo_step() {
|
||||
let mut s = doc();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let drawn = s.active().unwrap().doc.node_count();
|
||||
run(&mut s, "app.activeDocument.showPerspectiveGrid(); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap();
|
||||
assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.node_count(), drawn - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
s.execute("perspective.grid.set", &json!({"locked": true})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let mut s = doc();
|
||||
let source = "vc.run('perspective.grid.set', {locked: true}); app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE);";
|
||||
run(&mut s, source).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!((grid(&mut s)["locked"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!grid(&mut s).get("locked").and_then(Value::as_bool).unwrap_or(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_active_plane_round_trips_and_a_failed_run_puts_it_back() {
|
||||
let mut s = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; vc.log(d.getPerspectiveActivePlane());\
|
||||
vc.log(d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE)); vc.log(d.getPerspectiveActivePlane());\
|
||||
d.setActivePlane(PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE); vc.log(d.getPerspectiveActivePlane());",
|
||||
);
|
||||
let expected = ["PerspectiveGridPlaneType.GRIDLEFTPLANETYPE", "PerspectiveGridPlaneType.GRIDFLOORPLANETYPE"];
|
||||
assert_eq!(out[..3], [json!(expected[0]), json!(true), json!(expected[1])]);
|
||||
assert_eq!(out[3], json!("PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE"));
|
||||
assert_eq!(grid(&mut s)["plane"], "none");
|
||||
failure(&mut s, "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE); d.showPerspectiveGrid(); throw 1;");
|
||||
assert_eq!(grid(&mut s)["plane"], "none");
|
||||
assert_eq!(grid(&mut s)["visible"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_plane_or_a_right_plane_on_a_one_point_grid_throws() {
|
||||
let mut s = doc();
|
||||
for bad in ["'left'", "0", "PerspectiveGridType.OnePointPerspectiveGridType", "undefined"] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({bad});"));
|
||||
assert!(e.contains("PerspectiveGridPlaneType"), "{bad}: {e}");
|
||||
}
|
||||
s.execute("perspective.grid.preset", &json!({"kind": 1})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE);");
|
||||
assert!(e.contains("one-point grid"), "{e}");
|
||||
assert_eq!(grid(&mut s)["plane"], "left");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE); vc.log(d.getPerspectiveActivePlane());",
|
||||
);
|
||||
assert_eq!(out, vec![json!("PerspectiveGridPlaneType.GRIDFLOORPLANETYPE")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_perspective_preset_checks_the_type_and_the_name() {
|
||||
let mut s = doc();
|
||||
let one = s.execute("perspective.presets.list", &json!({})).unwrap()["presets"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|p| p["kind"] == 1)
|
||||
.map(|p| p["name"].as_str().unwrap().to_string())
|
||||
.unwrap();
|
||||
let before = undo_steps(&s);
|
||||
for (call, message) in [
|
||||
(format!("PerspectiveGridType.TwoPointPerspectiveGridType, '{one}'"), "not a grid of that type"),
|
||||
(format!("PerspectiveGridType.InvalidPerspectiveGridType, '{one}'"), "has no presets"),
|
||||
("PerspectiveGridType.OnePointPerspectiveGridType, 'No Such Preset'".to_string(), "no perspective grid preset called"),
|
||||
(format!("'one', '{one}'"), "PerspectiveGridType value"),
|
||||
("PerspectiveGridType.OnePointPerspectiveGridType, 7".to_string(), "presetName must be a string"),
|
||||
(format!("PerspectiveGridType.OnePointPerspectiveGridType, '{}'", "x".repeat(5000)), "too long"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({call});"));
|
||||
assert!(e.contains(message), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(grid(&mut s)["kind"], 2);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("vc.log(app.activeDocument.selectPerspectivePreset(PerspectiveGridType.OnePointPerspectiveGridType, '{}'));", one.to_uppercase()),
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
let g = grid(&mut s);
|
||||
assert_eq!((g["kind"].clone(), g["visible"].clone()), (json!(1), json!(true)));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_and_numbers_throw_with_nothing_changed() {
|
||||
let mut s = doc();
|
||||
s.execute("perspective.presets.save", &json!({"name": "Mine"})).unwrap();
|
||||
let before = (undo_steps(&s), grid(&mut s));
|
||||
for name in ["../Mine", "..\\\\Mine", "/Mine", "C:\\\\Mine", "Mine/..", "Mi\\u0000ne", "~/Mine"] {
|
||||
for call in [
|
||||
format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, '{name}');"),
|
||||
format!("app.getPresetSettings('{name}');"),
|
||||
] {
|
||||
let e = failure(&mut s, &call);
|
||||
assert!(e.contains("no perspective grid preset called") || e.contains("no startup preset called"), "{call}: {e}");
|
||||
}
|
||||
}
|
||||
// The script host refuses a number that is not finite before the member runs.
|
||||
for value in ["NaN", "Infinity", "-1e308", "1e308", "2"] {
|
||||
let refused = |e: &str, message: &str| e.contains(message) || e.contains("is not a finite number");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({value}, 'Mine');"));
|
||||
assert!(refused(&e, "PerspectiveGridType value"), "{value}: {e}");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({value});"));
|
||||
assert!(refused(&e, "PerspectiveGridPlaneType value"), "{value}: {e}");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, {value});"));
|
||||
assert!(refused(&e, "presetName must be a string"), "{value}: {e}");
|
||||
}
|
||||
assert_eq!((undo_steps(&s), grid(&mut s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_document_throws_on_every_grid_member() {
|
||||
let mut s = doc();
|
||||
run(&mut s, "#targetengine keep\nvar held = app.activeDocument;").unwrap();
|
||||
let e = failure(&mut s, "#targetengine keep\nheld.showPerspectiveGrid();");
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
let e = failure(&mut s, "var d = app.activeDocument; vc.run('file.close', {}); d.hidePerspectiveGrid();");
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
let e = failure(&mut s, "Document.prototype.getPerspectiveActivePlane.call({});");
|
||||
assert!(e.contains("not a Document"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_gives_a_copy_add_document_takes() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Basic CMYK'); vc.log(p.typename); vc.log(p.colorMode); vc.log(p.width); vc.log(p.height);\
|
||||
vc.log(p.numArtboards); p.width = 100; vc.log(app.getPresetSettings('Basic CMYK').width);\
|
||||
var d = app.documents.addDocument('Basic CMYK', p); vc.log(d.width); vc.log(d.documentColorSpace);\
|
||||
vc.log(app.getPresetSettings(DocumentPresetType.BasicRGB).colorMode);",
|
||||
);
|
||||
let expected = [json!("DocumentPreset"), json!("DocumentColorSpace.CMYK"), json!(612), json!(792), json!(1), json!(612)];
|
||||
assert_eq!(out[..6], expected);
|
||||
assert_eq!(out[6..], [json!(100), json!("DocumentColorSpace.CMYK"), json!("DocumentColorSpace.RGB")]);
|
||||
for (call, message) in [("'No Such Preset'", "no startup preset called"), ("3", "startup preset's name"), ("undefined", "startup preset's name")]
|
||||
{
|
||||
let e = failure(&mut s, &format!("app.getPresetSettings({call});"));
|
||||
assert!(e.contains(message), "{call}: {e}");
|
||||
}
|
||||
let e = failure(&mut s, &format!("app.getPresetSettings('{}');", "x".repeat(5000)));
|
||||
assert!(e.contains("too long"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_of_a_profile_gives_what_add_document_starts_from() {
|
||||
let mut s = Session::new();
|
||||
for preset in ["Video", "Web", "Mobile", "Print", "DocumentPresetType.Video"] {
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.getPresetSettings('{preset}'); var d = app.documents.addDocument('{preset}');\
|
||||
vc.log([p.width, p.height, p.units, p.colorMode]); vc.log([d.width, d.height, d.rulerUnits, d.documentColorSpace]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], out[1], "{preset}");
|
||||
}
|
||||
let out = log(&mut s, "var p = app.getPresetSettings('Video'); vc.log([p.width, p.height]);");
|
||||
assert_ne!(out[0], json!([612, 792]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_given_back_to_add_document_makes_the_same_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": "feet"})).unwrap();
|
||||
let layout = json!({"layout": "gridByColumn", "rows": 3, "spacing": 30});
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": 5, "artboardLayout": layout})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.numArtboards); vc.log(p.units === undefined);\
|
||||
function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\
|
||||
var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\
|
||||
vc.log(boards(a)); vc.log(boards(b)); vc.log(a.rulerUnits === b.rulerUnits);",
|
||||
);
|
||||
// A saved preset with the built-in preset's name changes neither the settings nor the document.
|
||||
assert_eq!(out[..2], [json!(1), json!(true)]);
|
||||
assert_eq!(out[2], out[3]);
|
||||
assert_eq!(out[2].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(out[4], json!(true));
|
||||
for (artboards, layout) in [
|
||||
(6, json!({"layout": "gridByColumn", "columns": 4})),
|
||||
(150, json!({"layout": "gridByRow", "columns": 12})),
|
||||
(7, json!({"layout": "gridByRow", "columns": 3, "rightToLeft": true})),
|
||||
] {
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": artboards, "artboardLayout": layout})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.numArtboards);\
|
||||
function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\
|
||||
vc.log(boards(app.documents.addDocument('Print'))); vc.log(boards(app.documents.addDocument('Print', p)));",
|
||||
);
|
||||
assert_eq!(out[0], json!(1), "{artboards} {layout}");
|
||||
assert_eq!(out[1].as_array().map(Vec::len), Some(1), "{layout}");
|
||||
assert_eq!(out[1], out[2], "{artboards} {layout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_preview_preset_settings_can_be_given_back_to_add_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "previewMode": "pixel"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.previewMode);\
|
||||
var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\
|
||||
vc.log([a.width, a.height, a.documentColorSpace]); vc.log([b.width, b.height, b.documentColorSpace]);",
|
||||
);
|
||||
// The saved preset's Pixel Preview does not replace the built-in preset's preview mode.
|
||||
assert_eq!(out[0], json!("DocumentPreviewMode.DefaultPreview"));
|
||||
assert_eq!(out[1], out[2]);
|
||||
assert_eq!(out[1], json!([612, 792, "DocumentColorSpace.CMYK"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_presets_list_names_presets_add_document_takes() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var l = app.startupPresetsList; vc.log(l); l.push('Mine'); l[0] = 'x'; vc.log(app.startupPresetsList.length === l.length - 1);\
|
||||
vc.log(app.startupPresetsList[0] !== 'x');\
|
||||
for (var i = 0; i < l.length - 1; i++) { var n = app.startupPresetsList[i]; var p = app.getPresetSettings(n);\
|
||||
var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }",
|
||||
);
|
||||
let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
// VectorCraft's own order puts Print first.
|
||||
assert_eq!(names.first(), Some(&"Print"));
|
||||
// Every New Document profile and both Basic presets, each once.
|
||||
let mut sorted = names.clone();
|
||||
sorted.sort_unstable();
|
||||
let mut listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect();
|
||||
listed.sort_unstable();
|
||||
assert_eq!(sorted, listed);
|
||||
assert_eq!(out[1..3], [json!(true), json!(true)]);
|
||||
assert_eq!(out.len(), 3 + names.len());
|
||||
for (name, made) in names.iter().zip(&out[3..]) {
|
||||
assert_eq!(made, &json!([name, true]), "{name}");
|
||||
}
|
||||
assert_eq!(s.documents().len(), names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_not_built_yet_say_so() {
|
||||
let mut s = doc();
|
||||
for (owner, member) in [
|
||||
("app", "saveWorkspace"),
|
||||
("app", "switchWorkspace"),
|
||||
("app", "deleteWorkspace"),
|
||||
("app", "resetWorkspace"),
|
||||
("app", "loadColorSettings"),
|
||||
("app", "showPresets"),
|
||||
("app.activeDocument", "exportPerspectiveGridPreset"),
|
||||
("app.activeDocument", "importPerspectiveGridPreset"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("{owner}.{member}('x');"));
|
||||
assert!(e.contains(&format!("{member} is not available yet")), "{member}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -1659,6 +1659,102 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retrace_keeps_the_tracing_note_and_tags() {
|
||||
let base = folder("retrace-attributes");
|
||||
let (mut s, _) = session(&base, false);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var tags = p.tags, t = tags.add(); t.name = 'job'; t.value = '42';\
|
||||
p.tracing.tracingOptions.threshold = 90; vc.log(p.note); vc.log(p.tags.length); vc.log(p.tags[0].name + '=' + p.tags[0].value);\
|
||||
vc.log(tags.length); vc.log(t.value); vc.log(t === p.tags[0]); vc.log(tags === p.tags);",
|
||||
);
|
||||
assert_eq!(out, [json!("keep me"), json!(1), json!("job=42"), json!(1), json!("42"), json!(true), json!(true)]);
|
||||
// Image Trace › Make on the tracing keeps them too.
|
||||
let id = traces(&s)[0];
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let attrs = d.node(id).and_then(|n| n.extras().attrs.as_deref().cloned()).unwrap_or_default();
|
||||
assert_eq!(attrs.note, "keep me");
|
||||
let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect();
|
||||
assert_eq!(tags, [("job", "42")]);
|
||||
let r = s.execute("imageTrace.makeAndExpand", &json!({"id": id.0})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let group = d.node(id).unwrap();
|
||||
assert!(matches!(group.kind, NodeKind::Group { .. }));
|
||||
let attrs = group.extras().attrs.as_deref().cloned().unwrap_or_default();
|
||||
assert_eq!(attrs.note, "keep me");
|
||||
let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect();
|
||||
assert_eq!(tags, [("job", "42")]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Tracing again moves the tracing's attributes to the new tracing: it copies them once, when it
|
||||
/// reads the tracing out of the document, and not again for the new object.
|
||||
#[test]
|
||||
fn retrace_copies_the_tracing_attributes_once() {
|
||||
let base = folder("retrace-attribute-copies");
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var t = p.tags.add(); t.name = 'job'; t.value = '42';",
|
||||
);
|
||||
let id = traces(&s)[0];
|
||||
let before = vectorcraft_doc::attribute_copies();
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap();
|
||||
assert_eq!(vectorcraft_doc::attribute_copies() - before, 1, "copies of the attributes");
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let note = s.active().unwrap().doc.node(id).and_then(|n| n.extras().attrs.as_deref().map(|a| a.note.clone()));
|
||||
assert_eq!(note.as_deref(), Some("keep me"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an
|
||||
/// ordinary group named as a tracing, before the document changes.
|
||||
#[test]
|
||||
fn path_and_type_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||||
let setup = |bottom: &str| {
|
||||
format!(
|
||||
"var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\
|
||||
var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);"
|
||||
)
|
||||
};
|
||||
for (name, bottom, list) in [
|
||||
("remove-all-trace-name-paths", "d.pathItems.rectangle(10, 10, 20, 20)", "pathItems"),
|
||||
// `edit.clear` also deletes the compound path its members leave empty.
|
||||
(
|
||||
"remove-all-trace-name-compound",
|
||||
"(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\
|
||||
vc.run('object.compoundPath.make'); return d.pageItems[0]; })()",
|
||||
"pathItems",
|
||||
),
|
||||
("remove-all-trace-name-type", "d.textFrames.pointText([10, 10])", "textFrames"),
|
||||
] {
|
||||
let base = folder(name);
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(&mut s, &base, &setup(bottom));
|
||||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\
|
||||
vc.log(m); vc.log(d.pageItems[0].typename);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}");
|
||||
assert!(traces(&s).is_empty(), "{list}");
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}");
|
||||
assert_eq!(undo_steps(&s), steps, "{list}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_the_same_preset_in_bracket_form_does_not_trace_again() {
|
||||
let base = folder("retrace-bracket-preset");
|
||||
|
||||
@@ -10,6 +10,23 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn postscript_suffix_recognizes_windows_filename_aliases() {
|
||||
use crate::script::dom::postscript_name;
|
||||
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}proof.PS{suffix}");
|
||||
assert!(postscript_name(&name, true), "{name}");
|
||||
assert!(!postscript_name(&name, false), "{name}");
|
||||
}
|
||||
}
|
||||
for name in ["proof.pdf", "proof.ps\t", "proof.ps\u{a0}", "folder.ps/proof", "folder.ps\\proof"] {
|
||||
assert!(!postscript_name(name, true), "{name}");
|
||||
}
|
||||
assert!(postscript_name("proof.ps", false));
|
||||
}
|
||||
|
||||
/// A test's folder, removed when the test ends, a failed assertion included.
|
||||
struct Workspace(PathBuf);
|
||||
|
||||
@@ -42,6 +59,20 @@ fn folder(name: &str) -> Workspace {
|
||||
Workspace(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_is_removed_when_its_test_panics() {
|
||||
let base = folder("removed-on-panic");
|
||||
let path = base.to_path_buf();
|
||||
assert!(
|
||||
std::panic::catch_unwind(move || {
|
||||
let _held = base;
|
||||
panic!("a failed assertion");
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a
|
||||
/// 300 × 200 document of two artboards holding a rectangle.
|
||||
fn session(base: &Path) -> Session {
|
||||
@@ -81,6 +112,95 @@ fn pages(path: &Path) -> Vec<(f64, f64)> {
|
||||
info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_blank_assigned_range_clears_the_saved_range() {
|
||||
let base = folder("blank-range");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
|
||||
for (name, range) in [("empty.pdf", ""), ("spaces.pdf", " ")] {
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
o.jobOptions.artboardRange = '{}'; app.activeDocument.print(o);",
|
||||
quoted(&dir.join(name)),
|
||||
range
|
||||
),
|
||||
);
|
||||
assert_eq!(pages(&dir.join(name)).len(), s.active().unwrap().doc.artboards.len());
|
||||
}
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["range"], json!("1"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_uses_the_assigned_file_object_after_its_path_changes() {
|
||||
let base = folder("file-reference");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(), f = new File({}); o.jobOptions.file = f;
|
||||
vc.log(o.jobOptions.file === f); vc.log(f.changePath({}));
|
||||
app.activeDocument.print(o); vc.log(o.jobOptions.file === f);
|
||||
vc.log(f.rename('renamed.pdf')); app.activeDocument.print(o);
|
||||
o.jobOptions.file = null; vc.log(o.jobOptions.file == null);",
|
||||
quoted(&dir.join("old.pdf")),
|
||||
quoted(&dir.join("new.ps"))
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([true, true, true, true, true]));
|
||||
assert!(!dir.join("old.pdf").exists());
|
||||
assert!(!dir.join("new.ps").exists());
|
||||
assert!(std::fs::read(dir.join("renamed.pdf")).unwrap().starts_with(b"%PDF"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_custom_profile_requires_an_assigned_or_base_profile() {
|
||||
let base = folder("custom-profile-required");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = dir.join("custom.pdf");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
let script = format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
o.colorManagementOptions.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; app.activeDocument.print(o);",
|
||||
quoted(&path)
|
||||
);
|
||||
let error = failure(&mut s, &base, &script);
|
||||
assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
s.execute("print.setup", &json!({"settings": {"color": {"profile": "sRGB IEC61966-2.1"}}})).unwrap();
|
||||
logged(&mut s, &base, &script);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%PDF"));
|
||||
let preset_script = script.replace("app.activeDocument.print(o);", "o.printPreset = '[Default]'; app.activeDocument.print(o);");
|
||||
let error = failure(&mut s, &base, &preset_script);
|
||||
assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_dot_ps_file_names_write_postscript() {
|
||||
let base = folder("dot-ps");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
for name in [".ps", ".PS"] {
|
||||
let path = dir.join(name);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&path)),
|
||||
);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%!PS"));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
let base = folder("happy");
|
||||
@@ -108,6 +228,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
j.file = new File(dir + '/c.ps'); doc.print(o);\n\
|
||||
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\
|
||||
doc.print(o);\n\
|
||||
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3; j.file = new File(dir + '/level3.ps');\n\
|
||||
doc.print(o);\n\
|
||||
vc.log([app.printPresetsList[0], app.PPDFileList.length]);"
|
||||
),
|
||||
);
|
||||
@@ -120,9 +242,11 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies");
|
||||
assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4");
|
||||
let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]);
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a .ps name alone prints at PSLEVEL2: {}", &ps[..ps.len().min(200)]);
|
||||
let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]);
|
||||
let ps = std::fs::read_to_string(dir.join("level3.ps")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 3"), "an assigned PSLEVEL3: {}", &ps[..ps.len().min(200)]);
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are");
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step");
|
||||
// The commands stay closed to vc.run, before and after a print.
|
||||
@@ -389,6 +513,92 @@ fn file_print_max_pages_composes_only_what_fits() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_job_file_can_be_read_and_assigned_to_another_job() {
|
||||
let base = folder("file-getter");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = dir.join("proof 100%.pdf");
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var first = new PrintJobOptions(), second = new PrintJobOptions();
|
||||
first.file = new File({}); second.file = first.file;
|
||||
vc.log([second.file instanceof File, second.file.fsName === first.file.fsName]);
|
||||
var o = new PrintOptions(); o.jobOptions = second; app.activeDocument.print(o);",
|
||||
quoted(&path)
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([true, true]));
|
||||
assert!(!pages(&path).is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_scale_assignment_and_reflection_share_the_supported_range() {
|
||||
let base = folder("scale-range");
|
||||
let mut s = session(&base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var c = new PrintCoordinateOptions();
|
||||
var names = ['horizontalScale', 'verticalScale'];
|
||||
for (var i = 0; i < names.length; i++) {
|
||||
var name = names[i], info = c.reflect.find(name);
|
||||
c[name] = info.max;
|
||||
try { c[name] = info.max + 0.01; vc.log('accepted'); }
|
||||
catch (e) { vc.log([e.name, c[name] === info.max, info.max === 10000]); }
|
||||
}",
|
||||
);
|
||||
assert_eq!(out, json!([["RangeError", true, true], ["RangeError", true, true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_fit_preserves_other_base_scaling_modes() {
|
||||
let base = folder("fit-false");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let boxes = |path: &Path| {
|
||||
let mut boxes = Vec::new();
|
||||
vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap().walk(|node| {
|
||||
if let Some(bounds) = node.path_data().and_then(|p| p.bounds()) {
|
||||
boxes.push(bounds);
|
||||
}
|
||||
});
|
||||
boxes
|
||||
};
|
||||
for mode in ["tileFull", "tileImageable", "custom", "fit"] {
|
||||
let settings = json!({"scaling": mode, "scale": {"width": 500, "height": 500}});
|
||||
s.execute("print.setup", &json!({"settings": settings})).unwrap();
|
||||
s.execute("print.presets.save", &json!({"name": "Base", "settings": settings})).unwrap();
|
||||
let override_settings = if mode == "fit" { json!({"scaling": "none"}) } else { json!({}) };
|
||||
let want = s.execute("file.print", &json!({"settings": override_settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
|
||||
for preset in [false, true] {
|
||||
if preset {
|
||||
s.execute("print.setup", &json!({"settings": {"scaling": "none"}})).unwrap();
|
||||
}
|
||||
let out = dir.join(format!("{mode}-{preset}.pdf"));
|
||||
let select = if preset { "o.printPreset = 'Base';" } else { "" };
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
|
||||
{select} o.coordinateOptions.fitToPage = false; app.activeDocument.print(o);",
|
||||
quoted(&out)
|
||||
),
|
||||
);
|
||||
let expected = boxes(&dir.join("want.pdf"));
|
||||
assert!(!expected.is_empty());
|
||||
assert_eq!(boxes(&out), expected, "{mode}, preset: {preset}");
|
||||
assert_eq!(pages(&out).len() as u64, want["pages"].as_u64().unwrap());
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A job past `maxPages` is turned away before its raster effects are flattened.
|
||||
#[test]
|
||||
fn file_print_max_pages_turns_a_job_away_before_raster_effects_are_flattened() {
|
||||
@@ -439,6 +649,9 @@ fn print_options_refuse_bad_values() {
|
||||
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
|
||||
("o.paperOptions.width = 36;", "RangeError", "width must be 0 or from 72 to 14400"),
|
||||
("o.paperOptions.height = 71.9;", "RangeError", "height must be 0 or from 72 to 14400"),
|
||||
("o.paperOptions.width = 72; o.paperOptions.width = 0; o.paperOptions.width = 1;", "RangeError", "width must be 0 or from 72"),
|
||||
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"),
|
||||
@@ -590,6 +803,68 @@ fn one_assigned_scale_factor_keeps_the_saved_other() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The pixel sizes of the images in the PDF at `path`.
|
||||
fn image_sizes(path: &Path) -> Vec<(u32, u32)> {
|
||||
let back = vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap();
|
||||
let mut sizes = vec![];
|
||||
back.walk(|n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
sizes.push((im.width, im.height));
|
||||
}
|
||||
});
|
||||
sizes
|
||||
}
|
||||
|
||||
/// `PrintJobOptions.bitmapResolution` sets the resolution Print as Bitmap prints at, as
|
||||
/// `advanced.bitmapResolution` does; 0 keeps the document's raster effects resolution.
|
||||
#[test]
|
||||
fn bitmap_resolution_sets_the_printed_image_size() {
|
||||
let base = folder("bitmap");
|
||||
let mut s = session(&base);
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap();
|
||||
let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone();
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(), j = o.jobOptions;\n\
|
||||
vc.log(j.bitmapResolution);\n\
|
||||
j.printAsBitmap = true; j.printAllArtboards = false; j.artboardRange = '1';\n\
|
||||
j.bitmapResolution = 144; j.file = new File({}); app.activeDocument.print(o);\n\
|
||||
j.bitmapResolution = 0; j.file = new File({}); app.activeDocument.print(o);\n\
|
||||
vc.log(j.bitmapResolution);",
|
||||
quoted(&dir.join("a.pdf")),
|
||||
quoted(&dir.join("b.pdf"))
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([0, 0]));
|
||||
assert_eq!(image_sizes(&dir.join("a.pdf")), [(600, 400)], "a 300 by 200 pt artboard at 144 ppi");
|
||||
assert_eq!(image_sizes(&dir.join("b.pdf")), [(300, 200)], "at the raster effects resolution, 72 ppi");
|
||||
let settings = json!({"artboards": "range", "range": "1", "advanced": {"printAsBitmap": true, "bitmapResolution": 144}});
|
||||
s.execute("file.print", &json!({"settings": settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
|
||||
assert_eq!(image_sizes(&dir.join("want.pdf")), image_sizes(&dir.join("a.pdf")), "the same image as the command prints");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "the saved settings stay as they are");
|
||||
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
|
||||
for (case, kind, part) in [
|
||||
("j.bitmapResolution = 9601;", "RangeError", "bitmapResolution must be from 0 to 9600"),
|
||||
("j.bitmapResolution = -1;", "RangeError", "bitmapResolution must be from 0 to 9600"),
|
||||
("j.bitmapResolution = NaN;", "TypeError", "bitmapResolution"),
|
||||
("j.bitmapResolution = Infinity;", "TypeError", "bitmapResolution"),
|
||||
("j.bitmapResolution = '300';", "TypeError", "bitmapResolution must be a finite number"),
|
||||
(
|
||||
&format!("{file} j.printAsBitmap = true; j.bitmapResolution = 0.5; app.activeDocument.print(o);"),
|
||||
"",
|
||||
"advanced.bitmapResolution must be 1–9600 ppi",
|
||||
),
|
||||
] {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {case}"));
|
||||
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists(), "nothing printed");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over
|
||||
/// saved settings that ignore the artboards, and two scale factors that differ by any amount print
|
||||
/// unlinked.
|
||||
@@ -614,14 +889,46 @@ fn assigned_job_and_scale_options_apply_over_the_saved_settings() {
|
||||
assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page");
|
||||
assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints");
|
||||
assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards");
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "width": 150})).unwrap();
|
||||
let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';";
|
||||
assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range");
|
||||
let info = vectorcraft_pdf::info(&std::fs::read(dir.join("area-range.pdf")).unwrap(), None).unwrap();
|
||||
let trim = info.pages[0].boxes.iter().find(|(k, _)| *k == vectorcraft_pdf::CropTo::Trim).map(|(_, r)| *r).unwrap();
|
||||
assert_eq!((trim.width().round(), trim.height().round()), (150.0, 200.0), "the page is artboard 2");
|
||||
let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;";
|
||||
assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An assigned `position` places an untiled print even when the saved Print Tiling origin is
|
||||
/// placed; the saved origin stays.
|
||||
#[test]
|
||||
fn an_assigned_position_replaces_a_placed_tile_origin() {
|
||||
let base = folder("position");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let trim = |s: &mut Session, name: &str, body: &str| {
|
||||
let file = quoted(&dir.join(name));
|
||||
logged(
|
||||
s,
|
||||
&base,
|
||||
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"),
|
||||
);
|
||||
let info = vectorcraft_pdf::info(&std::fs::read(dir.join(name)).unwrap(), None).unwrap();
|
||||
let b = info.pages[0].boxes.iter().find(|(k, _)| *k == vectorcraft_pdf::CropTo::Trim).map(|(_, r)| *r).unwrap();
|
||||
[b.x0, b.y0, b.x1, b.y1].map(f64::round)
|
||||
};
|
||||
let top_left = "o.coordinateOptions.position = PrintPosition.TRANSLATETOPLEFT;";
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
|
||||
let plain = trim(&mut s, "plain.pdf", top_left);
|
||||
s.execute("print.setup", &json!({"settings": {"tileOrigin": {"placed": true, "x": 100, "y": 0}}})).unwrap();
|
||||
assert_ne!(trim(&mut s, "placed.pdf", ""), plain, "the placed origin moves the art");
|
||||
assert_eq!(trim(&mut s, "assigned.pdf", top_left), plain, "the assigned position wins");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["tileOrigin"]["placed"], json!(true), "the saved origin stays");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Each option group prints the PostScript `file.print` writes for the settings it maps to, and
|
||||
/// each of those settings changes the file.
|
||||
#[test]
|
||||
@@ -644,7 +951,8 @@ fn option_groups_print_what_their_settings_print() {
|
||||
assert!(text.starts_with("%!PS"), "{}: {}", path.display(), &text[..text.len().min(40)]);
|
||||
text.lines().filter(|l| !l.starts_with("%%CreationDate:")).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
s.execute("file.print", &json!({"format": "postscript", "path": dir.join("plain.ps").to_string_lossy()})).unwrap();
|
||||
// A script prints PostScript at level 2 unless `postScriptLevel` is assigned.
|
||||
s.execute("file.print", &json!({"format": "postscript", "level": 2, "path": dir.join("plain.ps").to_string_lossy()})).unwrap();
|
||||
let plain = undated(&dir.join("plain.ps"));
|
||||
let mut wrong = Vec::new();
|
||||
let cases = [
|
||||
@@ -667,7 +975,7 @@ fn option_groups_print_what_their_settings_print() {
|
||||
];
|
||||
for (i, (body, settings)) in cases.iter().enumerate() {
|
||||
let [want, got] = ["want", "got"].map(|name| dir.join(format!("{name}{i}.ps")));
|
||||
s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": want.to_string_lossy()})).unwrap();
|
||||
s.execute("file.print", &json!({"format": "postscript", "level": 2, "settings": settings, "path": want.to_string_lossy()})).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
|
||||
@@ -10,6 +10,41 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn export_extension_recognizes_windows_filename_aliases() {
|
||||
use crate::script::dom::with_extension;
|
||||
|
||||
for extension in ["svg", "svgz", "jpg", "jpeg", "png"] {
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
|
||||
assert_eq!(with_extension(&name, &[extension], true), name);
|
||||
assert_eq!(with_extension(&name, &[extension], false), format!("{name}.{extension}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(with_extension("drawing.JPEG ", &["jpg", "jpeg"], true), "drawing.JPEG ");
|
||||
assert_eq!(with_extension("drawing.svg ", &["svgz"], true), "drawing.svg .svgz");
|
||||
for name in ["drawing", "drawing.png\t", "drawing.png\u{a0}", "folder.png/drawing", "folder.png\\drawing"] {
|
||||
assert_eq!(with_extension(name, &["png"], true), format!("{name}.png"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_open_refuses_an_oversized_document() {
|
||||
let base = folder("oversized-open");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let input = dir.join("huge.svg");
|
||||
std::fs::File::create(&input).unwrap().set_len(crate::script::files::MAX_OPEN_BYTES + 1).unwrap();
|
||||
let before = s.documents().len();
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&input)));
|
||||
assert!(error.contains(crate::script::files::OPEN_TOO_LARGE), "{error}");
|
||||
assert_eq!(s.documents().len(), before);
|
||||
let out = logged(&mut s, &base, &format!("Folder.userData; var f = new File({}); vc.log([f.open('r'), f.error]);", quoted(&input)));
|
||||
assert_eq!(out, json!([[false, crate::script::files::TOO_LARGE]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_wrappers_report_encoder_warnings_without_changing_their_return_values() {
|
||||
for method in ["exportFile", "saveAs", "exportForScreens"] {
|
||||
@@ -209,6 +244,76 @@ fn quoted(p: &Path) -> String {
|
||||
serde_json::to_string(&p.to_string_lossy()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_description_limits_the_preflight_guarantee() {
|
||||
let params = crate::cmd::find_command("document.save").unwrap().params;
|
||||
assert!(params.contains("failure found before writing leaves every file unchanged"));
|
||||
assert!(params.contains("a later write failure can leave earlier files written"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn svg_save_and_export_refuse_resolved_destination_collisions() {
|
||||
let base = folder("svg-collision");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let pic = base.join("outside/pic.png");
|
||||
std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap();
|
||||
let svg = dir.join("a.svg");
|
||||
let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&svg));
|
||||
logged(&mut s, &base, &format!("Folder.userData; {export}"));
|
||||
s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap();
|
||||
let images: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect();
|
||||
assert_eq!(images.len(), 1);
|
||||
std::fs::remove_file(&images[0]).unwrap();
|
||||
std::os::unix::fs::symlink(&svg, &images[0]).unwrap();
|
||||
for call in [export.clone(), format!("app.activeDocument.saveAs(new File({}));", quoted(&svg))] {
|
||||
std::fs::write(&svg, "original").unwrap();
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; {call}"));
|
||||
assert!(error.contains("resolve to the same file"), "{error}");
|
||||
assert_eq!(std::fs::read(&svg).unwrap(), b"original");
|
||||
assert!(std::fs::symlink_metadata(&images[0]).unwrap().file_type().is_symlink());
|
||||
}
|
||||
// With no primary file yet, the image's link leads nowhere but still names the primary.
|
||||
std::fs::remove_file(&svg).unwrap();
|
||||
let error = s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap_err().to_string();
|
||||
assert!(error.contains("resolve to the same file"), "{error}");
|
||||
assert!(!svg.exists());
|
||||
// A script may not write through a link that leads nowhere at all.
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; {export}"));
|
||||
assert!(error.contains("resolve to the same file") || error.contains("access denied"), "{error}");
|
||||
assert!(!svg.exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn open_template_link_creates_an_untitled_copy() {
|
||||
let base = folder("template-link");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let target = dir.join("drawing.vectorcraft");
|
||||
s.execute("file.saveAs", &json!({"path": target.to_string_lossy()})).unwrap();
|
||||
let link = dir.join("drawing.vctemplate");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let count = s.documents().len();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&link)));
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
assert!(s.active().unwrap().path.is_none());
|
||||
assert_ne!(s.active().unwrap().title(), "drawing.vectorcraft");
|
||||
assert!(!s.active().unwrap().doc.template);
|
||||
let template = dir.join("source.vctemplate");
|
||||
std::fs::write(&template, std::fs::read(&target).unwrap()).unwrap();
|
||||
let document = dir.join("alias.vectorcraft");
|
||||
std::os::unix::fs::symlink(&template, &document).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&document)));
|
||||
assert!(s.active().unwrap().path.is_some());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
let base = folder("happy");
|
||||
@@ -251,6 +356,99 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_selects_the_format_before_resolving_a_link() {
|
||||
let base = folder("save-link-format");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for extension in ["svg", "svgz"] {
|
||||
let target = dir.join(format!("{extension}.vectorcraft"));
|
||||
let link = dir.join(format!("drawing.{extension}"));
|
||||
std::fs::write(&target, "original").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link)));
|
||||
let bytes = std::fs::read(&target).unwrap();
|
||||
if extension == "svgz" {
|
||||
assert!(bytes.starts_with(&[0x1f, 0x8b]));
|
||||
} else {
|
||||
assert!(String::from_utf8(bytes).unwrap().contains("<svg"));
|
||||
}
|
||||
}
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let link = dir.join("drawing");
|
||||
std::fs::write(dir.join("target.svg"), "original").unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("target.svg"), &link).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link)));
|
||||
assert_eq!(s.active().unwrap().format, "vectorcraft");
|
||||
assert!(dir.join("target.svg").is_file());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_sidecar_directories_are_refused_before_any_output_changes() {
|
||||
let base = folder("svg-directory");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let pic = base.join("outside/pic.png");
|
||||
std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap();
|
||||
let svg = dir.join("a.svg");
|
||||
let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&svg));
|
||||
logged(&mut s, &base, &format!("Folder.userData; {export}"));
|
||||
s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap();
|
||||
let images: Vec<PathBuf> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect();
|
||||
assert_eq!(images.len(), 1);
|
||||
let image = &images[0];
|
||||
std::fs::remove_file(image).unwrap();
|
||||
std::fs::create_dir(image).unwrap();
|
||||
for save in [false, true] {
|
||||
std::fs::write(&svg, "original SVG").unwrap();
|
||||
let call = if save { format!("app.activeDocument.saveAs(new File({}));", quoted(&svg)) } else { export.clone() };
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; {call}"));
|
||||
assert!(error.contains("not a file"), "{call}: {error}");
|
||||
assert_eq!(std::fs::read_to_string(&svg).unwrap(), "original SVG");
|
||||
assert!(image.is_dir());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_export_and_open_report_command_warnings_in_the_console() {
|
||||
let base = folder("command-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"app.documents.add(DocumentColorSpace.RGB, 100, 100);
|
||||
vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 50});
|
||||
vc.run('transparency.set', {opacity: 0.5}); app.activeDocument.pageItems[0].name = 'bad\\u0001name';",
|
||||
);
|
||||
for (command, format, method, call) in [
|
||||
("file.saveAs", "eps", "Document.saveAs", "app.activeDocument.saveAs(f);"),
|
||||
("document.export", "svg", "Document.exportFile", "app.activeDocument.exportFile(f, ExportType.SVG);"),
|
||||
] {
|
||||
let path = dir.join(format!("warnings.{format}"));
|
||||
let want = s.execute(command, &json!({"path": path.to_string_lossy(), "format": format})).unwrap();
|
||||
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("{method}: {}", w.as_str().unwrap())).collect();
|
||||
assert!(!warnings.is_empty(), "{command}: {want}");
|
||||
let report = run(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&path))).unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(warnings));
|
||||
}
|
||||
let svg = dir.join("missing-image.svg");
|
||||
std::fs::write(&svg, "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><image href='missing.png' width='50' height='50'/></svg>")
|
||||
.unwrap();
|
||||
let want = s.execute("document.open", &json!({"path": svg.to_string_lossy()})).unwrap();
|
||||
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("app.open: {}", w.as_str().unwrap())).collect();
|
||||
assert!(!warnings.is_empty(), "{want}");
|
||||
let report = run(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&svg))).unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(warnings));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripted_file_writes_log_command_warnings() {
|
||||
for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] {
|
||||
@@ -262,7 +460,7 @@ fn scripted_file_writes_log_command_warnings() {
|
||||
let path = dir.join(format!("output.{extension}"));
|
||||
let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap();
|
||||
assert!(path.is_file(), "{method}");
|
||||
let prefix = format!("{method}: ");
|
||||
let prefix = format!("Document.{method}: ");
|
||||
let lines = out["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")), "{method}: {out}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
@@ -319,7 +517,7 @@ fn export_file_logs_encoder_warnings() {
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
assert!(dir.join("warnings.svg").is_file());
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
let warning = "exportFile: Object names containing invalid XML characters were left out of SVG name attributes";
|
||||
let warning = "Document.exportFile: Object names containing invalid XML characters were left out of SVG name attributes";
|
||||
assert!(lines.iter().any(|line| line.as_str() == Some(warning)), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -338,7 +536,7 @@ fn save_as_logs_the_saves_warnings() {
|
||||
let r = run(&mut s, &base, &text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ") && l.contains("keeps the artwork"));
|
||||
let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("Document.saveAs: ") && l.contains("keeps the artwork"));
|
||||
assert!(warned, "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -359,7 +557,7 @@ fn open_logs_warnings_for_an_unreadable_linked_image() {
|
||||
let r = run(&mut s, &base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["Document"]));
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("open: ") && l.contains("missing.png")), "{lines:?}");
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("app.open: ") && l.contains("missing.png")), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -410,6 +608,27 @@ fn save_as_uses_the_link_name_extension_for_the_encoder() {
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_file_save_refuses_a_directory_before_replacing_the_primary_file() {
|
||||
let base = folder("save-directory");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
let path = dir.join("drawing.vectorcraft");
|
||||
let saved = s.execute("file.saveAs", &json!({"path": path.to_string_lossy(), "format": "vectorcraft", "separateArtboards": true})).unwrap();
|
||||
let files = saved["files"].as_array().unwrap();
|
||||
assert!(files.len() > 1, "{saved}");
|
||||
let primary = std::fs::read(&path).unwrap();
|
||||
let sidecar = files.iter().map(|v| PathBuf::from(v.as_str().unwrap())).find(|p| *p != path).unwrap();
|
||||
std::fs::remove_file(&sidecar).unwrap();
|
||||
std::fs::create_dir(&sidecar).unwrap();
|
||||
let error = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&path)));
|
||||
assert!(error.contains("not a file"), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), primary);
|
||||
assert!(sidecar.is_dir());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_template_preserves_the_document_file_and_saved_state() {
|
||||
let base = folder("templatecopy");
|
||||
@@ -1267,6 +1486,23 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
assert_eq!(s.active().unwrap().path, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logging_files_and_folders_reads_only_enumerable_own_properties() {
|
||||
let base = folder("log-file-folder");
|
||||
let mut s = session(&base);
|
||||
let text = "var f = new File('kept.svg'), d = new Folder('kept');\n\
|
||||
vc.log(f); vc.log(d); vc.log([f, {folder: d}]);\n\
|
||||
File.prototype.inherited = 'omit'; Folder.prototype.inherited = 'omit';\n\
|
||||
Object.defineProperty(f, 'hidden', {value: 'omit', enumerable: false});\n\
|
||||
Object.defineProperty(d, 'hidden', {value: 'omit', enumerable: false});\n\
|
||||
f.label = 'drawing'; d.count = 2;\n\
|
||||
vc.log(f); vc.log(d); vc.log([f, {folder: d}]);";
|
||||
let log = logged(&mut s, &base, text);
|
||||
let nested = json!([{"label": "drawing"}, {"folder": {"count": 2}}]);
|
||||
assert_eq!(log, json!([{}, {}, [{}, {"folder": {}}], {"label": "drawing"}, {"count": 2}, nested]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a
|
||||
/// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its
|
||||
/// own path, so nothing is written or opened at the path the script put there.
|
||||
@@ -1638,7 +1874,7 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() {
|
||||
/// to the Script Console.
|
||||
#[test]
|
||||
fn a_saves_warnings_go_to_the_console() {
|
||||
let base = folder("warnings");
|
||||
let base = folder("pdf-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
@@ -1649,7 +1885,7 @@ fn a_saves_warnings_go_to_the_console() {
|
||||
);
|
||||
let r = run(&mut s, &base, &save).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}");
|
||||
assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("Document.saveAs: "))), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -1989,7 +2225,7 @@ fn save_as_writes_its_warnings_to_the_console() {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap();
|
||||
let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}");
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("Document.saveAs: ")), "{lines:?}");
|
||||
drop(base);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! must load as an error or as a document that then renders and exports, without a panic; nor may
|
||||
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
|
||||
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
|
||||
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! opcodes with random contents) opened or placed, nor binary CGM files (damaged files, elements
|
||||
//! with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
|
||||
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
|
||||
@@ -4158,6 +4159,125 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Binary CGM files: opened and placed ----------
|
||||
|
||||
// The CGM reader waits on craft-libs#5410: everything here is behind the `cgm` feature.
|
||||
|
||||
/// One CGM element, in the long form past 30 bytes, padded to an even length.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
if data.len() < 31 {
|
||||
b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes());
|
||||
} else {
|
||||
b.extend(((class << 12) | (id << 5) | 31).to_be_bytes());
|
||||
b.extend((data.len() as u16).to_be_bytes());
|
||||
}
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A metafile of one picture holding `body`.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_of(body: &[(u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut b = cgm_el(0, 1, b"\x01x");
|
||||
b.extend(cgm_el(1, 1, &be16(&[3])));
|
||||
b.extend(cgm_el(1, 13, b"\x09Helvetica"));
|
||||
b.extend(cgm_el(0, 3, b"\x01p"));
|
||||
b.extend(cgm_el(2, 6, &be16(&[0, 0, 1000, 500])));
|
||||
b.extend(cgm_el(0, 4, &[]));
|
||||
for (class, id, data) in body {
|
||||
b.extend(cgm_el(*class, *id, data));
|
||||
}
|
||||
b.extend(cgm_el(0, 5, &[]));
|
||||
b.extend(cgm_el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
/// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_sample() -> Vec<u8> {
|
||||
cgm_of(&[
|
||||
(5, 34, vec![8, 10, 20, 30, 40, 50, 60]),
|
||||
(5, 3, be16(&[3])),
|
||||
(5, 2, be16(&[2])),
|
||||
(4, 1, be16(&[0, 0, 100, 100, 200, 0])),
|
||||
(4, 2, be16(&[0, 10, 50, 10, 60, 10, 90, 10])),
|
||||
(5, 22, be16(&[1])),
|
||||
(5, 30, be16(&[1])),
|
||||
(4, 7, be16(&[300, 0, 400, 0, 350, 80])),
|
||||
(4, 8, be16(&[0, 200, 1, 100, 200, 1, 100, 300, 3])),
|
||||
(4, 11, be16(&[500, 0, 600, 100])),
|
||||
(4, 12, be16(&[700, 100, 50])),
|
||||
(4, 14, be16(&[800, 0, 850, 50, 900, 0, 0])),
|
||||
(4, 16, be16(&[100, 400, 1, 0, 0, 1, 50, 1])),
|
||||
(4, 19, be16(&[300, 400, 350, 400, 300, 420, 1, 0, 0, 1, 0])),
|
||||
(4, 26, be16(&[2, 0, 0, 10, 20, 30, 20, 40, 0])),
|
||||
(0, 8, vec![]),
|
||||
(4, 1, be16(&[500, 300, 600, 300])),
|
||||
(4, 15, be16(&[600, 350, 0, -1, 0, 1, 50])),
|
||||
(3, 10, vec![]),
|
||||
(0, 9, vec![]),
|
||||
(5, 6, be16(&[3])),
|
||||
(4, 3, be16(&[900, 400, 950, 450])),
|
||||
(3, 5, be16(&[0, 0, 500, 250])),
|
||||
(5, 15, be16(&[40])),
|
||||
(4, 4, [be16(&[100, 100, 0]), b"\x03abc".to_vec()].concat()),
|
||||
(4, 6, [be16(&[1]), b"\x02de".to_vec()].concat()),
|
||||
(4, 9, [be16(&[0, 0, 200, 100, 200, 0, 2, 2, 4, 1]), vec![0x12, 0, 0x34, 0]].concat()),
|
||||
])
|
||||
}
|
||||
|
||||
/// The sample the mutations start from opens with art, type and an image.
|
||||
#[cfg(feature = "cgm")]
|
||||
#[test]
|
||||
fn the_cgm_sample_opens() {
|
||||
let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap();
|
||||
assert_eq!(l.format.id, "cgm");
|
||||
let (mut paths, mut images, mut texts) = (0, 0, 0);
|
||||
l.doc.walk(|n| match n.kind {
|
||||
vectorcraft_doc::NodeKind::Path { .. } => paths += 1,
|
||||
vectorcraft_doc::NodeKind::Image(_) => images += 1,
|
||||
vectorcraft_doc::NodeKind::Text(_) => texts += 1,
|
||||
_ => {}
|
||||
});
|
||||
assert!(paths > 10 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings);
|
||||
}
|
||||
|
||||
/// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the
|
||||
/// low one.
|
||||
#[cfg(feature = "cgm")]
|
||||
const CGM_ELEMENTS: [u16; 44] = [
|
||||
0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306,
|
||||
0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418,
|
||||
0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801,
|
||||
];
|
||||
|
||||
#[cfg(feature = "cgm")]
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
#[test]
|
||||
fn mutated_cgm_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::<u8>()), 0..16)) {
|
||||
let mut bytes = cgm_sample();
|
||||
let n = bytes.len();
|
||||
for &(at, b) in &edits {
|
||||
bytes[at % n] = b;
|
||||
}
|
||||
bytes.truncate(cut);
|
||||
survive_metafile("mutated CGM", "x.cgm", &bytes)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_cgm_elements_never_panic(els in prop::collection::vec((prop::sample::select(CGM_ELEMENTS.to_vec()), arb_body()), 0..32)) {
|
||||
let body: Vec<(u16, u16, Vec<u8>)> = els.into_iter().map(|(e, d)| (e >> 8, e & 0xFF, d)).collect();
|
||||
survive_metafile("CGM elements", "x.cgm", &cgm_of(&body))?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- HP-GL plot files: opened and placed ----------
|
||||
|
||||
/// A plot file with every kind of instruction the reader plays, printer escapes around it.
|
||||
|
||||
@@ -58,10 +58,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
|
||||
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. The perspective
|
||||
/// grid preset files of `Document`, and the workspace methods, `loadColorSettings` and
|
||||
/// `showPresets` of `Application`, throw "not available yet". Reading a preference changes nothing,
|
||||
/// and the matrix functions return new records. `app.copy` and `app.cut` fill VectorCraft's
|
||||
/// clipboard, which the desktop app offers to other apps after the run as Edit › Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "__vcPaletteEvent alert confirm length prompt prototype"),
|
||||
@@ -103,22 +104,22 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
|
||||
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
|
||||
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
|
||||
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
|
||||
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
|
||||
View Views ZOrderMethod",
|
||||
PathPointSelection PathPoints PerspectiveGridPlaneType PerspectiveGridType PlacedItem PlacedItems PluginItem PointType \
|
||||
PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots \
|
||||
StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint \
|
||||
Symbols Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \
|
||||
unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut deleteWorkspace \
|
||||
deleteWorkspace= documents doScript executeMenuCommand getIdentityMatrix getIsFileOpen getPresetSettings \
|
||||
getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix isSingularMatrix loadAction \
|
||||
loadAction= loadColorSettings loadColorSettings= open paste PPDFileList preferences printPresetsList printerList \
|
||||
redo redraw resetWorkspace resetWorkspace= saveWorkspace saveWorkspace= selection selection= selectTool \
|
||||
showColorPicker showPresets showPresets= startupPresetsList switchWorkspace switchWorkspace= textFonts toString \
|
||||
typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
|
||||
),
|
||||
("Preferences.", "prototype"),
|
||||
("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"),
|
||||
@@ -140,10 +141,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
|
||||
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
|
||||
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
|
||||
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace \
|
||||
exportPerspectiveGridPreset exportPerspectiveGridPreset= fullName getPerspectiveActivePlane gradients gradients= \
|
||||
graphicStyles groupItems height hidePerspectiveGrid importPerspectiveGridPreset importPerspectiveGridPreset= \
|
||||
layers name pageItems paragraphStyles parent path pathItems patterns patterns= placedItems rasterItems \
|
||||
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selectPerspectivePreset selection selection= \
|
||||
setActivePlane showPerspectiveGrid spots stories swatchGroups swatches symbolItems symbols tags textFrames \
|
||||
toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -300,6 +304,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||||
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
|
||||
("PerspectiveGridPlaneType.", "GRIDFLOORPLANETYPE GRIDLEFTPLANETYPE GRIDRIGHTPLANETYPE INVALIDGRIDPLANETYPE"),
|
||||
("PerspectiveGridType.", "InvalidPerspectiveGridType OnePointPerspectiveGridType ThreePointPerspectiveGridType TwoPointPerspectiveGridType"),
|
||||
("PointType.", "CORNER SMOOTH"),
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
@@ -401,7 +407,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
// The print option classes and the enumerations of printing.
|
||||
(
|
||||
"",
|
||||
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
"FontSubstitutionPolicy PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
|
||||
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
|
||||
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
|
||||
@@ -464,7 +470,6 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
postScriptLevel= shadingResolution shadingResolution= typename",
|
||||
),
|
||||
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
|
||||
("PageMarksTypes.", "Japanese Roman"),
|
||||
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
|
||||
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
|
||||
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
|
||||
|
||||
@@ -103,7 +103,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
/// The text of the localization object `id` for the current locale: the string value of the first
|
||||
/// of [`Localization::keys`] that the object has as its own data property. No getter runs.
|
||||
pub(crate) fn localized_text(interp: &mut Interp, id: ObjId) -> JsResult<Option<Value>> {
|
||||
if !matches!(interp.object(id)?.class, Class::Ordinary) {
|
||||
if !matches!(interp.object(id)?.class, Class::Ordinary | Class::FsEntry(..)) {
|
||||
return Ok(None);
|
||||
}
|
||||
for k in interp.localization.keys() {
|
||||
@@ -293,11 +293,13 @@ impl Source {
|
||||
Some(Err(*length))
|
||||
}
|
||||
Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)),
|
||||
Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")),
|
||||
Class::Ordinary if o.proto == Some(object_proto) && enumerable => {
|
||||
Class::Ordinary | Class::FsEntry(..) if has_symbols => {
|
||||
return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source"));
|
||||
}
|
||||
Class::Ordinary | Class::FsEntry(..) if o.proto == Some(object_proto) && enumerable => {
|
||||
Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::<Vec<_>>()))
|
||||
}
|
||||
Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
|
||||
Class::Ordinary | Class::FsEntry(..) => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
|
||||
_ => None,
|
||||
};
|
||||
let fixed = shape.as_ref().and(fixed_state(o));
|
||||
@@ -451,3 +453,53 @@ fn function_name(code: &Code) -> String {
|
||||
None => "[anonymous]".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::heap::{OPEN, PropMap};
|
||||
use crate::interp::Abrupt;
|
||||
|
||||
fn source_error(interp: &mut Interp, id: ObjId) -> String {
|
||||
let Err(Abrupt::Throw(error)) = write_source(interp, Value::Object(id)) else { panic!("expected a source error") };
|
||||
let Value::String(message) = interp.get_value(&error, &key("message")).unwrap() else { panic!("expected an error message") };
|
||||
message.to_rust_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_uses_ordinary_properties_and_guards_for_files() {
|
||||
for file in [false, true] {
|
||||
let mut interp = Interp::new(crate::Options { es2015: true, ..crate::Options::default() }, crate::Limits::default());
|
||||
let class = if file {
|
||||
let Value::String(path) = Value::str("native path") else { panic!("expected a string") };
|
||||
let mut slots = PropMap::default();
|
||||
slots.insert(key("__vcError"), Value::str(""));
|
||||
Class::FsEntry(path, Box::new(slots))
|
||||
} else {
|
||||
Class::Ordinary
|
||||
};
|
||||
let mut object = Object::new(class, Some(interp.intrinsics.object_proto));
|
||||
object.props.insert(key("label"), Prop::Data { value: Value::str("public"), flags: OPEN });
|
||||
let id = interp.heap.alloc_object(object);
|
||||
let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") };
|
||||
assert_eq!(source.to_rust_string(), r#"({"label":"public"})"#);
|
||||
interp.object_mut(id).unwrap().props.insert(key("__vcPath"), Prop::Data { value: Value::str("own path"), flags: OPEN });
|
||||
let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") };
|
||||
assert_eq!(source.to_rust_string(), r#"({"label":"public", "__vcPath":"own path"})"#);
|
||||
interp.object_mut(id).unwrap().proto = None;
|
||||
assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT);
|
||||
interp.object_mut(id).unwrap().proto = Some(interp.intrinsics.object_proto);
|
||||
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: 0 });
|
||||
assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT);
|
||||
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: crate::heap::ENUMERABLE });
|
||||
assert_eq!(source_error(&mut interp, id), FIXED_PROPERTY);
|
||||
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: OPEN });
|
||||
interp.object_mut(id).unwrap().extensible = false;
|
||||
assert_eq!(source_error(&mut interp, id), NOT_EXTENSIBLE);
|
||||
interp.object_mut(id).unwrap().extensible = true;
|
||||
let symbol = interp.well_known(|w| &w.iterator).unwrap();
|
||||
interp.define_sym(id, symbol, Prop::Data { value: Value::Bool(true), flags: OPEN }).unwrap();
|
||||
assert_eq!(source_error(&mut interp, id), "toSource: an object with a Symbol property cannot be written as source");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -428,7 +428,7 @@ impl Interp {
|
||||
return Err(self.type_error(&format!("the constructor {name} did not give an object")));
|
||||
}
|
||||
if let Value::Object(o) = &v
|
||||
&& matches!(self.object(*o)?.class, Class::Ordinary)
|
||||
&& matches!(self.object(*o)?.class, Class::Ordinary | Class::FsEntry(..))
|
||||
&& let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))?
|
||||
{
|
||||
self.object_mut(*o)?.proto = Some(proto);
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
//! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the
|
||||
//! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two
|
||||
//! objects for one path are different objects. An object keeps its path in the host's platform
|
||||
//! form in an internal slot that only the classes' own methods set ([`Class::FsEntry`]), so an
|
||||
//! object a script makes with `Object.create(File.prototype)` is not a `File`. It keeps its `error`
|
||||
//! text, the id of the file it has open (or -1), the encoding set before `open` and its line feed
|
||||
//! in properties that are not enumerable; every name the getters give comes from
|
||||
//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open`
|
||||
//! and its line feed in native slots that only the classes' own methods set ([`Class::FsEntry`]),
|
||||
//! so an object a script makes with `Object.create(File.prototype)` is not a `File`; every name the
|
||||
//! getters give comes from
|
||||
//! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's
|
||||
//! `current`.
|
||||
//!
|
||||
@@ -97,7 +97,7 @@ impl Interp {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(match &o.class {
|
||||
Class::FsEntry(s) => Some(crate::Data::Object(vec![(key.to_string(), crate::Data::String(s.to_rust_string()))])),
|
||||
Class::FsEntry(s, _) => Some(crate::Data::Object(vec![(key.to_string(), crate::Data::String(s.to_rust_string()))])),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
@@ -106,7 +106,7 @@ impl Interp {
|
||||
/// The path of `o` when the `File` or `Folder` class made it.
|
||||
fn own_path(i: &Interp, o: ObjId) -> JsResult<Option<Value>> {
|
||||
Ok(match &i.object(o)?.class {
|
||||
Class::FsEntry(s) => Some(Value::String(s.clone())),
|
||||
Class::FsEntry(s, _) => Some(Value::String(s.clone())),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
@@ -116,7 +116,7 @@ fn set_path(i: &mut Interp, o: ObjId, fs: Value) -> JsResult<()> {
|
||||
let Value::String(s) = fs else { return Err(i.type_error("File: the host gave no path")) };
|
||||
i.rooted(&[Value::Object(o), Value::String(s.clone())], |i| i.reserve_heap(string_bytes(s.len())))?;
|
||||
if let Some(ob) = i.heap.object_mut(o)
|
||||
&& let Class::FsEntry(path) = &mut ob.class
|
||||
&& let Class::FsEntry(path, _) = &mut ob.class
|
||||
{
|
||||
*path = s;
|
||||
}
|
||||
@@ -151,28 +151,55 @@ fn message(i: &mut Interp, name: &str) -> JsResult<Value> {
|
||||
}
|
||||
|
||||
/// The field `name` of a record the host gave: its own data property, `undefined` when it has none,
|
||||
/// so that a property a script put on `Object.prototype` is not read as part of it.
|
||||
/// so that a property a script put on `Object.prototype` is not read as part of it. A proxy's traps
|
||||
/// do not run: a proxy has no such property.
|
||||
fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult<Value> {
|
||||
match v.as_object() {
|
||||
Some(o) => slot(i, o, name),
|
||||
Some(o) => Ok(match i.ordinary_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
_ => Value::Undefined,
|
||||
}),
|
||||
None => Ok(Value::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the own data property `name` of `o`, `undefined` when it has none. A proxy's
|
||||
/// traps do not run: a proxy has no such property.
|
||||
/// The native slot `name` of `o`, or `undefined` when it has none.
|
||||
fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
Ok(match i.ordinary_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
Ok(match &i.object(o)?.class {
|
||||
Class::FsEntry(_, fields) => fields.get(&key(name)).cloned().unwrap_or(Value::Undefined),
|
||||
_ => Value::Undefined,
|
||||
})
|
||||
}
|
||||
|
||||
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
|
||||
if let Value::String(s) = &value {
|
||||
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
|
||||
/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype`
|
||||
/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an
|
||||
/// object made with `Object.create(File.prototype)` included.
|
||||
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
|
||||
let Some(c) = &i.files else { return Ok(None) };
|
||||
let o = i.object(id)?;
|
||||
if o.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
i.define(o, key(name), Prop::Data { value, flags: HIDDEN })
|
||||
Ok(match own_path(i, id)? {
|
||||
Some(Value::String(s)) => Some(s.to_rust_string()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
|
||||
let Class::FsEntry(_, fields) = &i.object(o)?.class else {
|
||||
return Err(Abrupt::Internal("File slot on an object without native storage".into()));
|
||||
};
|
||||
let name = key(name);
|
||||
let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) };
|
||||
i.rooted(&[Value::Object(o), value.clone()], |i| {
|
||||
i.reserve_heap(added)?;
|
||||
if let Class::FsEntry(_, fields) = &mut i.object_mut(o)?.class {
|
||||
fields.insert(name, value);
|
||||
i.heap.bytes = i.heap.bytes.saturating_add(added);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// The object `this` and its path, or a `TypeError` naming `what` when it is not a `File` or
|
||||
@@ -245,8 +272,10 @@ fn instance(i: &mut Interp, proto: ObjId, fs: Value) -> JsResult<Value> {
|
||||
let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) };
|
||||
let line_feed = host_value(i, "lineFeed")?;
|
||||
i.rooted(&[fs, line_feed.clone()], |i| {
|
||||
i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?;
|
||||
let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto)));
|
||||
let storage = std::mem::size_of::<crate::heap::PropMap<Value>>();
|
||||
i.reserve_heap(OBJECT_BYTES + storage + string_bytes(path.len()))?;
|
||||
let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone(), Box::default()), Some(proto)));
|
||||
i.heap.bytes = i.heap.bytes.saturating_add(storage);
|
||||
i.rooted(&[Value::Object(o)], |i| {
|
||||
set_slot(i, o, ERROR, Value::str(""))?;
|
||||
set_slot(i, o, HANDLE, Value::Number(-1.0))?;
|
||||
@@ -1426,6 +1455,75 @@ mod tests {
|
||||
assert_eq!(v.unwrap(), JsValue::String("x,/x,2,d/b,1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_folders_localize_their_own_locale_properties() {
|
||||
let mut r = realm();
|
||||
r.add_script_extensions().unwrap();
|
||||
r.localization().set_locale("fr_FR");
|
||||
r.localization().set_enabled(true);
|
||||
let source = "var results = []; var constructors = [File, Folder];
|
||||
for (var n = 0; n < constructors.length; n++) {
|
||||
var C = constructors[n], f = new C('x'), hit = false;
|
||||
C.prototype.fr = 'inherited';
|
||||
results.push(localize(f) === f);
|
||||
f.en = 'English %1';
|
||||
Object.defineProperty(f, 'fr_FR', {get: function () { hit = true; return 'getter'; }, configurable: true});
|
||||
results.push(localize(f, 'text') === 'English text', !hit);
|
||||
f.fr = 'French %1';
|
||||
results.push(localize(f, 'text') === 'French text');
|
||||
results.push(Object.prototype.toString.call(f) === 'French %1');
|
||||
delete C.prototype.fr;
|
||||
}
|
||||
results.every(function (v) { return v; })";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_folders_copy_only_ordinary_own_properties() {
|
||||
let mut r = realm();
|
||||
let copy = HostItem::Function(Rc::new(|a: Vec<Data>| Ok(a.into_iter().next().unwrap_or(Data::Undefined))));
|
||||
r.define_host_object("host", vec![("copy".into(), copy)]).unwrap();
|
||||
let source = "var results = []; var constructors = [File, Folder];
|
||||
for (var n = 0; n < constructors.length; n++) {
|
||||
var C = constructors[n], f = new C('x');
|
||||
results.push(Object.getOwnPropertyNames(f).length === 0, Object.keys(f).length === 0);
|
||||
results.push(JSON.stringify(f) === '{}', typeof f === 'object', f instanceof C);
|
||||
results.push(Object.prototype.toString.call(f) === '[object Object]');
|
||||
f.label = 'public'; f.child = {values: [1, true]}; f.__vcPath = 'ordinary property';
|
||||
var plain = {label: 'public', child: {values: [1, true]}, __vcPath: 'ordinary property'};
|
||||
results.push(JSON.stringify(f) === JSON.stringify(plain));
|
||||
results.push(Object.keys(f).join() === Object.keys(plain).join());
|
||||
results.push(Object.getOwnPropertyNames(f).join() === Object.getOwnPropertyNames(plain).join());
|
||||
results.push(f.fsName === '/x', f.__vcPath === 'ordinary property', f.__vcHandle === undefined);
|
||||
var cloned = host.copy(f);
|
||||
results.push(JSON.stringify(cloned) === JSON.stringify(plain), cloned !== f, cloned.child !== f.child);
|
||||
results.push(Object.getPrototypeOf(cloned) === Object.prototype);
|
||||
}
|
||||
results.every(function (v) { return v; })";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_constructor_assigns_its_prototype_to_a_returned_file() {
|
||||
let mut r = realm();
|
||||
let make = Rc::new(|_: Vec<Data>| Ok(Data::Object(vec![(crate::FILE_REF_KEY.into(), Data::String("/x".into()))])));
|
||||
let copy = Rc::new(|a: Vec<Data>| Ok(a.get(1).cloned().unwrap_or(Data::Undefined)));
|
||||
let class = crate::HostClass {
|
||||
name: "ReturnedFile".into(),
|
||||
parent: None,
|
||||
members: vec![("copy".into(), crate::HostMember::Method(copy))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make),
|
||||
};
|
||||
r.define_host_classes(vec![class], Vec::new()).unwrap();
|
||||
let source = "var f = new ReturnedFile(); f.own = 'kept'; var d = new Folder('x'); d.own = 'folder';
|
||||
f instanceof ReturnedFile && Object.getPrototypeOf(f) === ReturnedFile.prototype &&
|
||||
Object.keys(f).join() === 'own' && JSON.stringify(f) === '{\"own\":\"kept\"}' &&
|
||||
JSON.stringify(f.copy(f)) === '{\"own\":\"kept\"}' && f.copy(d) instanceof Folder && f.copy(d).fsName === d.fsName";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_constructor_picks_the_class_only_without_new() {
|
||||
let mut r = realm();
|
||||
|
||||
@@ -292,9 +292,9 @@ pub(crate) enum Class {
|
||||
ModuleNamespace(Box<ModuleExports>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `File` or `Folder` ([`crate::file_classes`]) and its path in the host's platform form,
|
||||
/// which only the classes' own methods set.
|
||||
FsEntry(Str),
|
||||
/// A `File` or `Folder` ([`crate::file_classes`]): its path in the host's platform form and its
|
||||
/// other native slots, which only the classes' own methods set.
|
||||
FsEntry(Str, Box<PropMap<Value>>),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
/// A promise (ECMA-262 11th edition, section 25.6) and its state.
|
||||
@@ -618,7 +618,7 @@ impl Class {
|
||||
Class::Ordinary
|
||||
| Class::ForIn(_)
|
||||
| Class::Host(_)
|
||||
| Class::FsEntry(_)
|
||||
| Class::FsEntry(..)
|
||||
| Class::Symbol(_)
|
||||
| Class::Iterator(_)
|
||||
| Class::IterRecord(_)
|
||||
@@ -1193,7 +1193,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = PROP_BYTES * exports.bindings.len();
|
||||
}
|
||||
Class::String(s) | Class::FsEntry(s) => strings.add(s),
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
strings.bytes += re.heap_bytes();
|
||||
@@ -1291,8 +1291,22 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = std::mem::size_of::<PropMap<Value>>() + PROP_BYTES * fields.len();
|
||||
}
|
||||
Class::FsEntry(path, fields) => {
|
||||
strings.add(path);
|
||||
for (name, value) in fields.iter() {
|
||||
strings.add_key(name);
|
||||
mark_value(value, work, strings);
|
||||
}
|
||||
extra = std::mem::size_of::<PropMap<Value>>() + PROP_BYTES * fields.len();
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
Class::Host(h) => extra = crate::host_classes::handle_bytes(h.handle.len()),
|
||||
Class::Host(h) => {
|
||||
for (_, file, _) in &h.files {
|
||||
mark_value(file, work, strings);
|
||||
}
|
||||
extra = crate::host_classes::handle_bytes(h.handle.len())
|
||||
+ h.files.iter().map(|(name, _, path)| PROP_BYTES + name.len() + path.len()).sum::<usize>();
|
||||
}
|
||||
Class::Promise(p) => {
|
||||
for v in p.values() {
|
||||
mark_value(&v, work, strings);
|
||||
|
||||
@@ -119,6 +119,16 @@ pub(crate) enum ArgRead {
|
||||
/// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of
|
||||
/// host classes in the result are made from theirs.
|
||||
Hosted,
|
||||
/// A read of a host property whose reflected type is `File`.
|
||||
HostedFileGet,
|
||||
/// An assignment to a host property whose reflected type is `File`.
|
||||
HostedFileSet,
|
||||
}
|
||||
|
||||
impl ArgRead {
|
||||
fn hosted(&self) -> bool {
|
||||
matches!(self, Self::Hosted | Self::HostedFileGet | Self::HostedFileSet)
|
||||
}
|
||||
}
|
||||
|
||||
/// A member of an object the host adds to the global environment.
|
||||
@@ -291,7 +301,7 @@ impl Interp {
|
||||
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
|
||||
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
|
||||
Class::Array { length, .. } => Shape::Array(*length),
|
||||
Class::Ordinary | Class::FsEntry(_) => {
|
||||
Class::Ordinary | Class::FsEntry(..) => {
|
||||
let o = self.object(id)?;
|
||||
if o.props.len() > r.limits.entries {
|
||||
return Err(self.data_error(r, ErrorType::Range, "has too many entries"));
|
||||
@@ -447,9 +457,23 @@ impl Interp {
|
||||
/// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to
|
||||
/// the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
// The receiver and the arguments may be held only here (an `apply` of an array-like): they
|
||||
// stay rooted while the files sync, the host runs and the assigned File is kept.
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(this.clone());
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
let r = self.call_data_rooted(f, name, this, args, how);
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
fn call_data_rooted(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
if how.hosted() {
|
||||
self.sync_host_files()?;
|
||||
}
|
||||
let data = match how {
|
||||
ArgRead::Site => site_data(self.call_site()),
|
||||
ArgRead::Hosted => self.read_args(name, Some(this), args, how)?,
|
||||
how if how.hosted() => self.read_args(name, Some(this), args, how)?,
|
||||
_ => self.read_args(name, None, args, how)?,
|
||||
};
|
||||
// Only the script's own code, in a run that can pause, can wait for a result, and a host
|
||||
@@ -458,12 +482,37 @@ impl Interp {
|
||||
self.can_wait.set(can_wait);
|
||||
let result = f(data);
|
||||
self.can_wait.set(false);
|
||||
if result.is_ok()
|
||||
&& let Some(id) = this.as_object()
|
||||
{
|
||||
if matches!(how, ArgRead::HostedFileSet) {
|
||||
let file = args.first().cloned().unwrap_or(Value::Undefined);
|
||||
self.keep_host_file(id, name.clone(), file)?;
|
||||
} else if matches!(how, ArgRead::HostedFileGet)
|
||||
&& let Class::Host(h) = &self.object(id)?.class
|
||||
&& let Some((_, file, kept)) = h.files.iter().find(|(n, _, _)| n == name)
|
||||
&& let Ok(d) = &result
|
||||
{
|
||||
// The assigned File keeps its identity while the getter still names its file;
|
||||
// otherwise the host changed the property, and the getter's value is given.
|
||||
let (file, kept, d) = (file.clone(), kept.clone(), d.clone());
|
||||
let (same, got) = self.names_file(d, &kept)?;
|
||||
if same {
|
||||
return Ok(file);
|
||||
}
|
||||
self.keep_host_file(id, name.clone(), Value::Undefined)?;
|
||||
return match got {
|
||||
Some(got) => Ok(got),
|
||||
None => Ok(Value::Undefined),
|
||||
};
|
||||
}
|
||||
}
|
||||
match result {
|
||||
Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d),
|
||||
Ok(d) if how.hosted() => self.write_hosted(d),
|
||||
Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)),
|
||||
Err(HostError::Wait) if can_wait => {
|
||||
self.waiting = true;
|
||||
self.waiting_hosted = matches!(how, ArgRead::Hosted);
|
||||
self.waiting_hosted = how.hosted();
|
||||
self.pause.set(true);
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
@@ -472,6 +521,105 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
fn keep_host_file(&mut self, id: ObjId, name: Rc<str>, file: Value) -> JsResult<()> {
|
||||
let path = match file.as_object() {
|
||||
Some(file) => crate::file_classes::file_path(self, file)?,
|
||||
None => None,
|
||||
};
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(()) };
|
||||
let before = h.files.iter().find(|(n, _, _)| n == &name).map_or(0, |(n, _, p)| PROP_BYTES + n.len() + p.len());
|
||||
let after = path.as_ref().map_or(0, |p| PROP_BYTES + name.len() + p.len());
|
||||
if after > before {
|
||||
self.reserve_heap(after - before)?;
|
||||
}
|
||||
self.heap.bytes = self.heap.bytes.saturating_sub(before).saturating_add(after);
|
||||
if let Class::Host(h) = &mut self.object_mut(id)?.class {
|
||||
h.files.retain(|(n, _, _)| n != &name);
|
||||
if let Some(path) = path {
|
||||
h.files.push((name, file, path));
|
||||
}
|
||||
}
|
||||
if after > 0 && !self.host_file_objects.contains(&id) {
|
||||
self.host_file_objects.push(id);
|
||||
} else if after == 0 && matches!(&self.object(id)?.class, Class::Host(h) if h.files.is_empty()) {
|
||||
self.host_file_objects.retain(|&kept| kept != id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the host's value `d` is a File for `path`, compared as the File the script receives
|
||||
/// for it; with the File made to compare it, when one was made.
|
||||
fn names_file(&mut self, d: Data, path: &str) -> JsResult<(bool, Option<Value>)> {
|
||||
if crate::file_ref_path(&d) == Some(path) {
|
||||
return Ok((true, None));
|
||||
}
|
||||
let got = self.write_hosted(d)?;
|
||||
let same = match got.as_object() {
|
||||
Some(g) => crate::file_classes::file_path(self, g)?.as_deref() == Some(path),
|
||||
None => false,
|
||||
};
|
||||
Ok((same, Some(got)))
|
||||
}
|
||||
|
||||
pub(crate) fn sync_host_files(&mut self) -> JsResult<()> {
|
||||
let mut updates = Vec::new();
|
||||
let mut untracked = Vec::new();
|
||||
for id in self.host_file_objects.clone() {
|
||||
self.use_fuel()?;
|
||||
let Some(object) = self.heap.object(id) else { continue };
|
||||
let Class::Host(h) = &object.class else { continue };
|
||||
let class = h.class;
|
||||
for (name, file, previous) in &h.files {
|
||||
let Some(file_id) = file.as_object() else { continue };
|
||||
match crate::file_classes::file_path(self, file_id)? {
|
||||
// An object that is no longer a File (its prototype changed) is not tracked
|
||||
// any more, and the host keeps the path it has.
|
||||
None => untracked.push((id, name.clone())),
|
||||
Some(path) if path != *previous => {
|
||||
if let Some((get, set)) = self.file_accessors(class, name) {
|
||||
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, name) in untracked {
|
||||
self.keep_host_file(id, name, Value::Undefined)?;
|
||||
}
|
||||
for (id, name, file, previous, get, set) in updates {
|
||||
self.use_fuel()?;
|
||||
// A property the host changed since the assignment no longer holds this File: it is
|
||||
// not tracked any more, and the host's value stays.
|
||||
let this = self.read_args(&name, Some(&Value::Object(id)), &[], &ArgRead::Hosted)?;
|
||||
let same = match get(this) {
|
||||
Ok(d) => self.names_file(d, &previous).map(|(same, _)| same),
|
||||
Err(error) => Err(self.host_error(error).unwrap_or_else(|e| e)),
|
||||
};
|
||||
match same {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
self.keep_host_file(id, name, Value::Undefined)?;
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
// A getter that fails stops tracking too, so the error is thrown once.
|
||||
self.keep_host_file(id, name, Value::Undefined)?;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
let data = self.read_args(&name, Some(&Value::Object(id)), std::slice::from_ref(&file), &ArgRead::Hosted)?;
|
||||
if let Err(error) = set(data) {
|
||||
// The host refused the new path: the File is no longer tracked, so the error is
|
||||
// thrown once and a later assignment can replace it.
|
||||
self.keep_host_file(id, name, Value::Undefined)?;
|
||||
return Err(self.host_error(error)?);
|
||||
}
|
||||
self.keep_host_file(id, name, file)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where the innermost frame of the script's code is: its source's tag and the line and column
|
||||
/// of the instruction it is running.
|
||||
fn call_site(&self) -> CallSite {
|
||||
@@ -559,7 +707,7 @@ impl Interp {
|
||||
ancestors: Vec::new(),
|
||||
path: Vec::new(),
|
||||
function: name.clone(),
|
||||
hosted: matches!(how, ArgRead::Hosted),
|
||||
hosted: how.hosted(),
|
||||
};
|
||||
let args = match how {
|
||||
ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args),
|
||||
@@ -575,14 +723,20 @@ impl Interp {
|
||||
}
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
let mark = self.temp_roots.len();
|
||||
if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) {
|
||||
if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen) && !how.hosted() {
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
}
|
||||
let mut read = Ok(());
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
|
||||
let d = match how {
|
||||
ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
|
||||
ArgRead::Data
|
||||
| ArgRead::DataWithin(_)
|
||||
| ArgRead::Frozen
|
||||
| ArgRead::Site
|
||||
| ArgRead::Hosted
|
||||
| ArgRead::HostedFileGet
|
||||
| ArgRead::HostedFileSet => self.read_data(a, &mut reading),
|
||||
ArgRead::Text => self.read_text(a, &mut reading),
|
||||
ArgRead::Each(list) => match list.get(i) {
|
||||
Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined),
|
||||
|
||||
@@ -125,6 +125,8 @@ pub struct HostClass {
|
||||
pub(crate) struct HostObj {
|
||||
pub(crate) class: u32,
|
||||
pub(crate) handle: Rc<[f64]>,
|
||||
/// The assigned File objects and the paths last sent to their setters.
|
||||
pub(crate) files: Vec<(Rc<str>, Value, String)>,
|
||||
}
|
||||
|
||||
/// The estimated bytes an object of a host class holds beyond [`crate::heap::OBJECT_BYTES`] for a
|
||||
@@ -153,6 +155,8 @@ pub(crate) struct Entry {
|
||||
own: Rc<HashMap<Key, bool>>,
|
||||
/// The class's own members as `reflect` lists them.
|
||||
members: Rc<[Reflected]>,
|
||||
/// The getter and setter of each File property the class declares, by `Class.member`.
|
||||
pub(crate) file_setters: Vec<(Rc<str>, HostFunction, HostFunction)>,
|
||||
}
|
||||
|
||||
/// How a script may use a member of a host class.
|
||||
@@ -249,6 +253,20 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
/// The getter and setter of File property `name` (`Class.member`) of `class` or of a class it
|
||||
/// descends from.
|
||||
pub(crate) fn file_accessors(&self, class: u32, name: &str) -> Option<(HostFunction, HostFunction)> {
|
||||
let mut at = Some(class);
|
||||
for _ in 0..=self.host_classes.len() {
|
||||
let entry = self.host_classes.get(at? as usize)?;
|
||||
if let Some((_, get, set)) = entry.file_setters.iter().find(|(n, _, _)| &**n == name) {
|
||||
return Some((get.clone(), set.clone()));
|
||||
}
|
||||
at = entry.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
|
||||
/// class, and the closest of that class and the classes it descends from that declares `k`
|
||||
/// declares it as available.
|
||||
@@ -340,7 +358,7 @@ impl Interp {
|
||||
}
|
||||
let extra = handle_bytes(handle.len());
|
||||
self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?;
|
||||
let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto));
|
||||
let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into(), files: Vec::new() }), Some(proto));
|
||||
o.extensible = false;
|
||||
let id = self.heap.alloc_object(o);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
@@ -414,6 +432,13 @@ impl Interp {
|
||||
if self.host_ref_size(id)?.is_none() {
|
||||
return Ok(Value::Undefined);
|
||||
}
|
||||
// The host reads File properties as the script left them, as it does for a method call. The
|
||||
// receiver may be held only here, so it stays rooted while the files sync.
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(id));
|
||||
let synced = self.sync_host_files();
|
||||
self.temp_roots.truncate(mark);
|
||||
synced?;
|
||||
let args = self.read_index_args(id, k, probe)?;
|
||||
match f(args) {
|
||||
Ok(d) => self.write_hosted(d),
|
||||
@@ -632,6 +657,17 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
|
||||
parent: parent_class,
|
||||
own: Rc::new(own),
|
||||
members,
|
||||
file_setters: class
|
||||
.members
|
||||
.iter()
|
||||
.filter_map(|(name, member)| {
|
||||
let HostMember::Property { get, set } = member else { return None };
|
||||
if !class.info.iter().any(|(n, info)| n == name && info.data_type == "File") {
|
||||
return None;
|
||||
}
|
||||
Some((format!("{}.{name}", class.name).into(), get.clone(), set.clone()))
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
// The host class named `Symbol` keeps the built-in `Symbol` global. Its objects use the host prototype.
|
||||
let global = i.global;
|
||||
@@ -684,9 +720,11 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId
|
||||
let prop = match member {
|
||||
HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE },
|
||||
HostMember::Property { get, set } => {
|
||||
let get = hosted_function(i, get.clone(), &full);
|
||||
let file = class.info.iter().any(|(n, info)| n == name && info.data_type == "File");
|
||||
let get = hosted_function_read(i, get.clone(), &full, if file { ArgRead::HostedFileGet } else { ArgRead::Hosted });
|
||||
i.temp_roots.push(Value::Object(get));
|
||||
Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE }
|
||||
let set = hosted_function_read(i, set.clone(), &full, if file { ArgRead::HostedFileSet } else { ArgRead::Hosted });
|
||||
Prop::Accessor { get: Some(get), set: Some(set), flags: ENUMERABLE }
|
||||
}
|
||||
HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 },
|
||||
HostMember::Unavailable(f) => {
|
||||
@@ -709,6 +747,10 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId
|
||||
}
|
||||
|
||||
fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId {
|
||||
let proto = i.intrinsics.function_proto;
|
||||
i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto)))
|
||||
hosted_function_read(i, f, name, ArgRead::Hosted)
|
||||
}
|
||||
|
||||
fn hosted_function_read(i: &mut Interp, f: HostFunction, name: &str, read: ArgRead) -> ObjId {
|
||||
let proto = i.intrinsics.function_proto;
|
||||
i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read }), Some(proto)))
|
||||
}
|
||||
|
||||