Merge main into fix/retrace-keeps-note-and-tags
@@ -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 |
|
||||
|
||||
@@ -1256,7 +1256,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1418,7 +1418,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1486,7 +1486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1536,7 +1536,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1681,7 +1681,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1689,7 +1689,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2470,7 +2470,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
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=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
@@ -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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
|
||||
# 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -799,6 +799,10 @@ fn main() -> std::process::ExitCode {
|
||||
// window, so eframe's windows are recorded as it makes and drops them (`quit_windows`).
|
||||
#[cfg(target_os = "linux")]
|
||||
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options };
|
||||
// Floating panels and dialogs that draw their own title bar stay borderless on Windows, as the
|
||||
// main window does (`window_frame`, #10797).
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(window_frame::Hooks)), ..options };
|
||||
#[cfg(feature = "wgpu")]
|
||||
let options = {
|
||||
let mut options = options;
|
||||
|
||||
@@ -22,10 +22,20 @@
|
||||
//! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge
|
||||
//! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window
|
||||
//! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878).
|
||||
//!
|
||||
//! Floating panels and dialogs that draw their own title bar (Preferences, a floating Color panel)
|
||||
//! are undecorated winit windows as well, and on the same systems their content was drawn offset
|
||||
//! by the caption and border too (#10797). `Hooks` records those windows as eframe makes them and
|
||||
//! runs the same guard on each one in each of its frames.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
|
||||
/// Run once per frame; a no-op once the window is borderless.
|
||||
pub type WindowFrameFn = Box<dyn FnMut()>;
|
||||
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
pub use platform::Hooks;
|
||||
pub use platform::service;
|
||||
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
@@ -49,6 +59,33 @@ mod platform {
|
||||
Some(Box::new(move || reapply(&hwnd)))
|
||||
}
|
||||
|
||||
/// The undecorated windows of floating panels and dialogs, which [`Hooks`] records.
|
||||
static SECONDARY: std::sync::LazyLock<super::Viewports<HWND>> = std::sync::LazyLock::new(super::Viewports::default);
|
||||
|
||||
/// Keeps the undecorated windows of floating panels and dialogs borderless, as [`service`]
|
||||
/// keeps the main window: the guard runs when eframe makes such a window and before each of its
|
||||
/// frames. Set as [`eframe::NativeOptions::viewport_hooks`].
|
||||
pub struct Hooks;
|
||||
|
||||
impl eframe::ViewportHooks for Hooks {
|
||||
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
|
||||
let hwnd = match window.window_handle().map(|h| h.as_raw()) {
|
||||
Ok(RawWindowHandle::Win32(h)) => find_window(h.hwnd.get()),
|
||||
_ => None,
|
||||
};
|
||||
SECONDARY.created(viewport, window.is_decorated(), hwnd);
|
||||
SECONDARY.with(viewport, reapply);
|
||||
}
|
||||
|
||||
fn window_destroyed(&self, viewport: egui::ViewportId) {
|
||||
SECONDARY.destroyed(viewport);
|
||||
}
|
||||
|
||||
fn raw_input(&self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
SECONDARY.with(raw_input.viewport_id, reapply);
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass of the per-frame guard: the styles winit put back come off again, and a parked
|
||||
/// maximize stays clear of the taskbar.
|
||||
fn reapply(hwnd: &HWND) {
|
||||
@@ -152,6 +189,55 @@ mod platform {
|
||||
}
|
||||
}
|
||||
|
||||
/// The windows of the undecorated floating panels and dialogs, by viewport, while eframe holds
|
||||
/// them. A record holds `None` while [`Viewports::with`] has its window out. Platform-neutral so
|
||||
/// it is tested everywhere.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
struct Viewports<H>(Mutex<HashMap<egui::ViewportId, Option<H>>>);
|
||||
|
||||
impl<H> Default for Viewports<H> {
|
||||
fn default() -> Self {
|
||||
Self(Mutex::new(HashMap::new()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
impl<H> Viewports<H> {
|
||||
/// eframe made `viewport`'s window, with `handle`. It is recorded when it is an undecorated
|
||||
/// window other than the main one, which [`service`] keeps; otherwise any earlier record of the
|
||||
/// viewport is removed, so a window made again with the system title bar is left alone.
|
||||
fn created(&self, viewport: egui::ViewportId, decorated: bool, handle: Option<H>) {
|
||||
let mut windows = self.lock();
|
||||
match handle {
|
||||
Some(handle) if viewport != egui::ViewportId::ROOT && !decorated => windows.insert(viewport, Some(handle)),
|
||||
_ => windows.remove(&viewport),
|
||||
};
|
||||
}
|
||||
|
||||
/// eframe dropped `viewport`'s window.
|
||||
fn destroyed(&self, viewport: egui::ViewportId) {
|
||||
self.lock().remove(&viewport);
|
||||
}
|
||||
|
||||
/// Runs `f` on `viewport`'s recorded window, if any. The window is taken out of its record
|
||||
/// while `f` runs, so window messages that `f` sends and that reach the hooks again do not wait
|
||||
/// on the lock. It goes back only if the record is still there and empty: a window dropped or
|
||||
/// made again for the viewport in the meantime wins.
|
||||
fn with(&self, viewport: egui::ViewportId, f: impl FnOnce(&H)) {
|
||||
let Some(handle) = self.lock().get_mut(&viewport).and_then(Option::take) else {
|
||||
return;
|
||||
};
|
||||
f(&handle);
|
||||
if let Some(slot @ None) = self.lock().get_mut(&viewport) {
|
||||
*slot = Some(handle);
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, Option<H>>> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -260,7 +346,64 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
|
||||
fn viewport(name: &str) -> egui::ViewportId {
|
||||
egui::ViewportId::from_hash_of(name)
|
||||
}
|
||||
|
||||
/// The windows `with` reaches for each viewport, in order.
|
||||
fn reached(windows: &Viewports<u32>, viewports: &[egui::ViewportId]) -> Vec<Option<u32>> {
|
||||
viewports
|
||||
.iter()
|
||||
.map(|&id| {
|
||||
let mut seen = None;
|
||||
windows.with(id, |&h| seen = Some(h));
|
||||
seen
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Floating panels and dialogs with their own title bar are kept borderless (#10797); the main
|
||||
/// window, which `service` keeps, and windows with the system title bar are not recorded.
|
||||
#[test]
|
||||
fn undecorated_floating_windows_are_recorded_until_dropped() {
|
||||
let windows = Viewports::default();
|
||||
let (prefs, color, hang) = (viewport("Preferences"), viewport("Color"), viewport("Not responding"));
|
||||
windows.created(egui::ViewportId::ROOT, false, Some(1));
|
||||
windows.created(prefs, false, Some(7));
|
||||
windows.created(color, false, Some(9));
|
||||
windows.created(hang, true, Some(11));
|
||||
assert_eq!(reached(&windows, &[egui::ViewportId::ROOT, prefs, color, hang]), [None, Some(7), Some(9), None]);
|
||||
// Each frame reaches the window again.
|
||||
assert_eq!(reached(&windows, &[prefs]), [Some(7)]);
|
||||
windows.destroyed(prefs);
|
||||
assert_eq!(reached(&windows, &[prefs, color]), [None, Some(9)]);
|
||||
// A window made again with the system title bar, or without a handle, is left alone.
|
||||
windows.created(color, true, Some(13));
|
||||
assert_eq!(reached(&windows, &[color]), [None]);
|
||||
windows.created(color, false, Some(15));
|
||||
windows.created(color, false, None);
|
||||
assert_eq!(reached(&windows, &[color]), [None]);
|
||||
}
|
||||
|
||||
/// A window dropped or made again while the guard runs on the old one is not brought back.
|
||||
#[test]
|
||||
fn a_window_dropped_or_made_again_during_the_guard_wins() {
|
||||
let windows = Viewports::default();
|
||||
let prefs = viewport("Preferences");
|
||||
windows.created(prefs, false, Some(7));
|
||||
windows.with(prefs, |_| windows.destroyed(prefs));
|
||||
assert_eq!(reached(&windows, &[prefs]), [None]);
|
||||
windows.created(prefs, false, Some(7));
|
||||
windows.with(prefs, |_| windows.created(prefs, false, Some(8)));
|
||||
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
|
||||
// The guard can reach the hooks again for the same viewport without waiting on itself.
|
||||
let mut inner = None;
|
||||
windows.with(prefs, |_| windows.with(prefs, |&h| inner = Some(h)));
|
||||
assert_eq!(inner, None);
|
||||
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() {
|
||||
|
||||
@@ -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 |
@@ -227,6 +227,16 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The path whose anchors the anchor tools edit, in document space: a path's, or the path of
|
||||
/// type on a path outside perspective (Add, Delete and Anchor Point tools, Pen + Alt).
|
||||
pub fn anchor_path(&self) -> Option<std::borrow::Cow<'_, PathData>> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => Some(std::borrow::Cow::Borrowed(path)),
|
||||
NodeKind::Text(t) if self.extras().perspective.is_none() => t.type_path().map(std::borrow::Cow::Owned),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path_data_mut(&mut self) -> Option<&mut PathData> {
|
||||
match &mut self.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
|
||||
@@ -368,18 +368,29 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too.
|
||||
fn overprints_anywhere(n: &Node) -> bool {
|
||||
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too, and with `images` an
|
||||
/// image's color.
|
||||
fn overprints_anywhere(n: &Node, images: bool) -> bool {
|
||||
n.appearance.items.iter().any(|i| i.overprint())
|
||||
|| n.extras().colorize_overprint
|
||||
|| (images && n.extras().colorize_overprint)
|
||||
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c)))
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c, images)))
|
||||
}
|
||||
|
||||
/// Stop every fill and stroke of `a`'s subtree overprinting (characters' too), copying only the
|
||||
/// nodes on the way to them.
|
||||
pub fn clear_overprints(a: &mut Arc<Node>) {
|
||||
if !overprints_anywhere(a) {
|
||||
clear(a, true);
|
||||
}
|
||||
|
||||
/// [`clear_overprints`] for fills, strokes and characters only: the colors of images keep their
|
||||
/// overprint ([`crate::NodeExtras::colorize_overprint`]).
|
||||
pub fn clear_paint_overprints(a: &mut Arc<Node>) {
|
||||
clear(a, false);
|
||||
}
|
||||
|
||||
fn clear(a: &mut Arc<Node>, images: bool) {
|
||||
if !overprints_anywhere(a, images) {
|
||||
return;
|
||||
}
|
||||
let n = Arc::make_mut(a);
|
||||
@@ -392,11 +403,11 @@ pub fn clear_overprints(a: &mut Arc<Node>) {
|
||||
}
|
||||
}
|
||||
// Also the flag an image keeps after its color is removed.
|
||||
if n.extras().colorize_overprint {
|
||||
if images && n.extras().colorize_overprint {
|
||||
n.extras_mut().colorize_overprint = false;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
clear_overprints(c);
|
||||
clear(c, images);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -487,6 +487,16 @@ impl TextObject {
|
||||
true
|
||||
})
|
||||
}
|
||||
/// Replace type on a path's path with `path`, given in document space; the brackets keep their
|
||||
/// fractions of the path. False, changing nothing, for other type, a degenerate `xf` or a path
|
||||
/// that would not be finite.
|
||||
pub fn set_type_path(&mut self, path: &PathData) -> bool {
|
||||
matches!(self.kind, TextKind::OnPath { .. })
|
||||
&& self.reshape_local(|frame, to_text| {
|
||||
*frame = path.transformed(to_text);
|
||||
true
|
||||
})
|
||||
}
|
||||
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
|
||||
/// when `f` succeeds and the result is finite.
|
||||
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod colormgmt;
|
||||
pub mod colortheme;
|
||||
pub mod compositefonts;
|
||||
mod compoundshape;
|
||||
pub mod conceptvector;
|
||||
pub(crate) mod create;
|
||||
mod css;
|
||||
mod cut;
|
||||
@@ -365,6 +366,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(artboardalign::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
v.extend(conceptvector::specs());
|
||||
v.extend(shaper::specs());
|
||||
v.extend(brushsym::specs());
|
||||
v.extend(patterncmds::specs());
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fix All Issues",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}",
|
||||
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}",
|
||||
has_doc,
|
||||
fix
|
||||
),
|
||||
@@ -262,6 +262,13 @@ fn fix(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// With nothing to fix, the document and its undo history stay as they are.
|
||||
if total > 0 {
|
||||
if let Some(guard) = &s.artboard_deletion_guard {
|
||||
let st = s.doc()?;
|
||||
let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard);
|
||||
if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) {
|
||||
return Err(EngineError::Other(guard.message.clone()));
|
||||
}
|
||||
}
|
||||
sel.prune(&d);
|
||||
s.edit("Fix Issues", |doc, selection| {
|
||||
*doc = d;
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
|
||||
//! splits type on a path into point type holding the same text and the plain path it was set on
|
||||
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
|
||||
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its
|
||||
//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
pub mod font_sheet;
|
||||
pub mod numbers;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -76,6 +78,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
numbers::make_numbers
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(font_sheet::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Release Type on a Path's command (the id in [`specs`]).
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font
|
||||
//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a
|
||||
//! filter or a list names), each labeled with its font's name, flowed down columns on the active
|
||||
//! artboard and on new artboards to its right when it fills, as one group made in one undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Shape};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use super::super::super::create::{new_type_para, new_type_style};
|
||||
use super::super::super::panelcmds::artboard_at;
|
||||
use super::super::super::typecmd::refresh_bounds;
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.type.fontSheet";
|
||||
/// The sample text when none is given.
|
||||
pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog";
|
||||
/// Most fonts one sheet sets.
|
||||
pub const MAX_FONTS: usize = 5000;
|
||||
/// Most characters the sample text has.
|
||||
pub const MAX_CHARS: usize = 1000;
|
||||
/// The largest size a label is set at; a smaller sample's label is set at the sample's size.
|
||||
const LABEL_SIZE: f64 = 9.0;
|
||||
/// The space between the artboards the sheet adds, as `artboard.new` leaves it.
|
||||
const ARTBOARD_GAP: f64 = 20.0;
|
||||
/// The page a document without artboards lays the sheet out on (US Letter).
|
||||
const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.type.fontSheet",
|
||||
"Create Font Sheet",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}",
|
||||
has_doc,
|
||||
font_sheet
|
||||
)]
|
||||
}
|
||||
|
||||
/// `key` of `p`: `default` when omitted, else a number in `range`.
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => 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()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters.
|
||||
fn sample_text(p: &Value) -> Result<String> {
|
||||
let text = match p.get("text") {
|
||||
None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()),
|
||||
Some(Value::String(t)) => t.clone(),
|
||||
Some(_) => return Err(bad(COMMAND, "`text` must be a string")),
|
||||
};
|
||||
if text.trim().is_empty() {
|
||||
return Err(bad(COMMAND, "`text` must not be empty"));
|
||||
}
|
||||
// The line and paragraph separators break a line too.
|
||||
if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) {
|
||||
return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters"));
|
||||
}
|
||||
if text.chars().count() > MAX_CHARS {
|
||||
return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// The families the sheet sets, in order: those `families` names, else those the font menus of
|
||||
/// `db` list whose name contains `filter`.
|
||||
fn families(p: &Value, db: &FontDb) -> Result<Vec<String>> {
|
||||
let filter = match p.get("filter") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()),
|
||||
Some(_) => return Err(bad(COMMAND, "`filter` must be a string")),
|
||||
};
|
||||
let listed = match p.get("families") {
|
||||
None | Some(Value::Null) => {
|
||||
let menu = db.menu_family_list();
|
||||
let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str()));
|
||||
let found: Vec<String> = menu.iter().filter(wanted).cloned().collect();
|
||||
if found.is_empty() {
|
||||
return Err(bad(COMMAND, "no font family matches `filter`"));
|
||||
}
|
||||
return Ok(found);
|
||||
}
|
||||
Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")),
|
||||
};
|
||||
if listed.is_empty() {
|
||||
return Err(bad(COMMAND, "`families` must name at least one family"));
|
||||
}
|
||||
let mut out: Vec<String> = Vec::with_capacity(listed.len());
|
||||
for f in listed {
|
||||
let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?;
|
||||
if !db.has_family(f) {
|
||||
return Err(bad(COMMAND, format!("font family `{f}` is not available")));
|
||||
}
|
||||
// The name as the font menus spell it, looked up as the database compares names.
|
||||
let name = match db.composite_font(f) {
|
||||
Some(c) => c.name.clone(),
|
||||
None => db.canonical(f, "").0,
|
||||
};
|
||||
if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) {
|
||||
return Err(bad(COMMAND, format!("`families` names `{name}` twice")));
|
||||
}
|
||||
out.push(name);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The index of the artboard the view has active, else the one the document opened on, else the first.
|
||||
fn active_artboard(st: &crate::DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn font_sheet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
font_sheet_in(s, p, FontDb::global())
|
||||
}
|
||||
|
||||
/// [`font_sheet`] over the fonts of `db`.
|
||||
fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let text = sample_text(p)?;
|
||||
let size = number(p, "size", 12.0, 1.0..=1296.0)?;
|
||||
let columns = number(p, "columns", 2.0, 1.0..=50.0)?;
|
||||
if columns.fract() != 0.0 {
|
||||
return Err(bad(C, "`columns` must be a whole number 1..50"));
|
||||
}
|
||||
let columns = columns as usize;
|
||||
let gap = number(p, "gap", 12.0, 0.0..=1000.0)?;
|
||||
let margin = number(p, "margin", 36.0, 0.0..=1000.0)?;
|
||||
let all_styles = switch_or(p, "allStyles", false, C)?;
|
||||
let labels = switch_or(p, "labels", true, C)?;
|
||||
let new_artboards = switch_or(p, "newArtboards", true, C)?;
|
||||
let families = families(p, db)?;
|
||||
|
||||
// Each entry's font: (family, style); no style for the family's Regular or closest style.
|
||||
let mut fonts: Vec<(String, Option<String>)> = vec![];
|
||||
for f in &families {
|
||||
let styles = if all_styles { db.styles(f) } else { vec![] };
|
||||
if styles.is_empty() {
|
||||
fonts.push((f.clone(), None));
|
||||
} else {
|
||||
fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st))));
|
||||
}
|
||||
if fonts.len() > MAX_FONTS {
|
||||
return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`")));
|
||||
}
|
||||
}
|
||||
|
||||
let label = size.min(LABEL_SIZE);
|
||||
// The artboard named, else `activeArtboard` (a replay of the journal), else the view's active
|
||||
// one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard.
|
||||
let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?;
|
||||
let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let st = s.doc()?;
|
||||
let i = active_artboard(st);
|
||||
if i < st.doc.artboards.len() {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
i
|
||||
}
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let template = d.artboards.get(active).cloned();
|
||||
let page = template.as_ref().map_or(LETTER, |a| a.rect);
|
||||
let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max);
|
||||
let system_layout = d.setup.system_layout;
|
||||
let parent = st.target_parent()?;
|
||||
// An entry's first baseline is at least one line's size below its top, and the entry at least
|
||||
// this tall; the fonts are only laid out when the page has room for that.
|
||||
let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5);
|
||||
let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin);
|
||||
let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64;
|
||||
let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard");
|
||||
if column_w <= 0.0 || inner_h < least_height {
|
||||
return Err(no_room());
|
||||
}
|
||||
|
||||
let label_style = {
|
||||
let mut style = new_type_style(s, &json!({ "size": label }), C)?;
|
||||
style.leading = Some(label * 1.2);
|
||||
style
|
||||
};
|
||||
// Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline.
|
||||
let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len());
|
||||
let mut skipped: Vec<String> = vec![];
|
||||
// The entries whose font lacks a glyph needed by the sample.
|
||||
let mut fallback: Vec<String> = vec![];
|
||||
for (family, style) in fonts {
|
||||
let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?;
|
||||
sample.leading = Some(size * 1.2);
|
||||
let name = match &style {
|
||||
Some(st) => format!("{family} {st}"),
|
||||
None => family.clone(),
|
||||
};
|
||||
// A font that doesn't load is drawn in the fallback font, and a style that doesn't in the
|
||||
// family's closest style: either is left out. A composite font is left out when a part
|
||||
// that sets the sample names a font or style that doesn't load.
|
||||
let composite = db.composite_font(&family).is_some();
|
||||
// Layout picks a font for each character as typed, then draws All Caps type, and the
|
||||
// lowercase letters of Small Caps type, in capitals in that font, so coverage is checked on both.
|
||||
let caps = sample.all_caps || sample.small_caps.is_some();
|
||||
let (loads, covers) = if composite {
|
||||
// Glyph coverage is checked on the characters layout draws, in the sample's numeral system.
|
||||
let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, caps).is_none_or(|c| c.lacking.is_empty());
|
||||
(db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers)
|
||||
} else {
|
||||
let wanted = db.canonical(&family, "").0;
|
||||
match db.face(&sample.font_family, &sample.font_style) {
|
||||
Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => {
|
||||
let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c));
|
||||
let capitals = || text.chars().flat_map(char::to_uppercase).collect::<String>();
|
||||
(true, drawn(&text) && (!caps || drawn(&capitals())))
|
||||
}
|
||||
_ => (false, true),
|
||||
}
|
||||
};
|
||||
if !loads {
|
||||
skipped.push(name);
|
||||
continue;
|
||||
}
|
||||
if !covers {
|
||||
fallback.push(name.clone());
|
||||
}
|
||||
let (first, more) = if labels {
|
||||
(TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample)))
|
||||
} else {
|
||||
(TextRun::new(text.clone(), sample), None)
|
||||
};
|
||||
let t = laid_out(first, more, system_layout);
|
||||
let extent = ink_extent(&t);
|
||||
laid.push((name, t, extent));
|
||||
}
|
||||
if laid.is_empty() {
|
||||
return Err(bad(C, "none of the fonts could be loaded"));
|
||||
}
|
||||
|
||||
// Each page's layout: each entry's first baseline as far below its top as its ink reaches above
|
||||
// it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin.
|
||||
let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max);
|
||||
let pitch = height + gap;
|
||||
if inner_h < height {
|
||||
return Err(no_room());
|
||||
}
|
||||
let rows = (((inner_h + gap) / pitch).floor() as usize).max(1);
|
||||
let per_page = rows * columns;
|
||||
// Where page `k` starts: the active artboard, then to the right of every artboard.
|
||||
let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) };
|
||||
let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len());
|
||||
for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() {
|
||||
let (k, j) = (i / per_page, i % per_page);
|
||||
let (col, row) = (j / rows, j % rows);
|
||||
let x = page_x(k) + margin + col as f64 * (column_w + gap);
|
||||
let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above);
|
||||
// The layout is in text space, so moving the type keeps it.
|
||||
t.xf = Affine::translate((x, baseline));
|
||||
entries.push((name, t));
|
||||
}
|
||||
let count = entries.len();
|
||||
let pages = count.div_ceil(per_page);
|
||||
let boards: Vec<Rect> = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect();
|
||||
let template = template.filter(|_| new_artboards);
|
||||
let (gid, added) = s.edit("Create Font Sheet", |d, sel| {
|
||||
let mut added = vec![];
|
||||
if let Some(template) = template {
|
||||
for rect in boards {
|
||||
let mut a = template.clone();
|
||||
a.id = d.next_artboard_id();
|
||||
a.name = format!("Artboard {}", d.artboards.len() + 1);
|
||||
a.rect = rect;
|
||||
a.locked = false;
|
||||
d.artboards.push(a);
|
||||
added.push(d.artboards.len() - 1);
|
||||
}
|
||||
}
|
||||
let children: Vec<Arc<Node>> = entries
|
||||
.into_iter()
|
||||
.map(|(name, t)| {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.name = Some(name);
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::new(gid, NodeKind::Group { children, clip: false });
|
||||
g.name = Some("Font Sheet".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok((gid, added))
|
||||
})?;
|
||||
let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added });
|
||||
let warnings: Vec<String> = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few.
|
||||
fn fallback_warning(fallback: &[String]) -> Option<String> {
|
||||
const NAMED: usize = 5;
|
||||
let (first, more) = (fallback.iter().take(NAMED).cloned().collect::<Vec<_>>(), fallback.len().saturating_sub(NAMED));
|
||||
match (first.is_empty(), more) {
|
||||
(true, _) => None,
|
||||
(false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))),
|
||||
(false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out.
|
||||
fn laid_out(first: TextRun, more: Option<TextRun>, system_layout: bool) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "", first.style.clone());
|
||||
t.runs = std::iter::once(first).chain(more).collect();
|
||||
// Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge.
|
||||
t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() };
|
||||
t.system_layout = system_layout;
|
||||
t.normalize_paras();
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
t.cached_bounds = Some(layout.bounds);
|
||||
t.cached_baselines = layout.baselines();
|
||||
let mut ink = layout.run_ink_bounds.clone();
|
||||
for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) {
|
||||
if let Some(bounds) = ink.get_mut(run) {
|
||||
let bar = bar.bounding_box();
|
||||
*bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar)));
|
||||
}
|
||||
}
|
||||
t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b))));
|
||||
if t.runs.len() == 2
|
||||
&& let (Some(label), Some(sample)) = (ink[0], ink[1])
|
||||
{
|
||||
let overlap = label.y1 - sample.y0;
|
||||
if overlap > 0.0
|
||||
&& let Some(run) = t.runs.get_mut(1)
|
||||
{
|
||||
run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap);
|
||||
refresh_bounds(&mut t);
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and
|
||||
/// strikethrough bars included; none when nothing draws.
|
||||
fn ink_extent(t: &TextObject) -> (f64, f64) {
|
||||
t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0)))
|
||||
}
|
||||
|
||||
/// The warning a sheet that left fonts out gives, naming the first few.
|
||||
fn skipped_warning(skipped: &[String]) -> Option<String> {
|
||||
const NAMED: usize = 5;
|
||||
let (first, more) = (skipped.iter().take(NAMED).cloned().collect::<Vec<_>>(), skipped.len().saturating_sub(NAMED));
|
||||
match (first.is_empty(), more) {
|
||||
(true, _) => None,
|
||||
(false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))),
|
||||
(false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,636 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS};
|
||||
use crate::Session;
|
||||
|
||||
/// The bundled families, available on every platform.
|
||||
const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"];
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn group(s: &Session, r: &Value) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Each entry of the sheet `g`: its name and its type.
|
||||
fn entries(g: &Node) -> Vec<(String, TextObject)> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()),
|
||||
_ => panic!("a font sheet holds only type"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the first baseline of `t` starts.
|
||||
fn origin(t: &TextObject) -> (f64, f64) {
|
||||
let [.., x, y] = t.xf.as_coeffs();
|
||||
(x, y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let undo = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard");
|
||||
assert_eq!(steps(&s), undo + 1, "one undo step");
|
||||
let g = group(&s, &r);
|
||||
assert_eq!(g.name.as_deref(), Some("Font Sheet"));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected");
|
||||
let e = entries(&g);
|
||||
assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), BUNDLED, "in the order given, each named after its font");
|
||||
for ((name, t), family) in e.iter().zip(BUNDLED) {
|
||||
assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample");
|
||||
let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) };
|
||||
assert_eq!(sample.style.font_family, family);
|
||||
assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt");
|
||||
assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font");
|
||||
}
|
||||
// Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top.
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let (a, b) = (origin(&e[0].1), origin(&e[1].1));
|
||||
assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}");
|
||||
assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_artboard_continues_on_new_artboards_to_the_right() {
|
||||
let mut s = session();
|
||||
let undo = steps(&s);
|
||||
// 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9).
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard");
|
||||
assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect);
|
||||
assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}");
|
||||
assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too");
|
||||
|
||||
// Without new artboards, the page after the first is laid out in the same place with none.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap();
|
||||
assert_eq!(r["artboards"], json!([]));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_picks_families_and_all_styles_lists_each_style() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert!(e.len() >= 2 && names.len() == e.len(), "{names:?}");
|
||||
assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}");
|
||||
assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}");
|
||||
assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone");
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let styles: Vec<String> = vectorcraft_text::FontDb::global().styles("Source Sans 3");
|
||||
assert!(styles.len() > 1, "{styles:?}");
|
||||
assert_eq!(e.len(), styles.len(), "one entry for each style");
|
||||
for ((name, t), style) in e.iter().zip(&styles) {
|
||||
assert_eq!(name, &format!("Source Sans 3 {style}"));
|
||||
assert_eq!(&t.runs[1].style.font_style, style);
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows.
|
||||
#[test]
|
||||
fn columns_share_the_room_inside_the_margin() {
|
||||
let mut s = session();
|
||||
// 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap();
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let e = entries(&group(&s, &r));
|
||||
// The first column fills before the second starts, so all three share it.
|
||||
let xs: Vec<f64> = e.iter().map(|(_, t)| origin(t).0).collect();
|
||||
assert!(!xs.is_empty(), "the sheet has entries");
|
||||
assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}");
|
||||
// One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let step = (500.0 - 24.0) / 3.0 + 12.0;
|
||||
for (i, (_, t)) in e.iter().enumerate() {
|
||||
let (x, y) = origin(t);
|
||||
assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}");
|
||||
}
|
||||
assert_eq!(r["artboards"], json!([]));
|
||||
}
|
||||
|
||||
/// The journal records the active artboard, so a replay in a new session lays the sheet out on the
|
||||
/// same one; an action leaves it out, and a named artboard goes ahead of it.
|
||||
#[test]
|
||||
fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].clone();
|
||||
s.doc_mut().unwrap().active_artboard = Some(second.id);
|
||||
let start = s.journal.len();
|
||||
let params = json!({"families": ["Inter"], "margin": 10});
|
||||
let r = s.execute(COMMAND, ¶ms).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard");
|
||||
let (id, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1)));
|
||||
assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays");
|
||||
|
||||
// A replay in a session whose view has no active artboard uses the recorded one.
|
||||
let mut fresh = session();
|
||||
fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let r = fresh.replay(COMMAND, &recorded).unwrap();
|
||||
let e = entries(&group(&fresh, &r));
|
||||
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard");
|
||||
// A named artboard goes ahead of the recorded one.
|
||||
let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap();
|
||||
let e = entries(&group(&fresh, &r));
|
||||
let first = fresh.doc().unwrap().doc.artboards[0].rect;
|
||||
assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9);
|
||||
assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard");
|
||||
}
|
||||
|
||||
/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column.
|
||||
#[test]
|
||||
fn a_right_to_left_sample_stays_inside_its_column() {
|
||||
let mut s = session();
|
||||
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
// Alone, and under a left-to-right label: each line starts at the column's left edge.
|
||||
for labels in [false, true] {
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
|
||||
for (name, t) in &entries(&group(&s, &r)) {
|
||||
let x = origin(t).0;
|
||||
assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}");
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), t);
|
||||
for line in &layout.lines {
|
||||
let left = x + line.x0;
|
||||
assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variation_selector_does_not_require_a_separate_glyph() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
assert!(face.covers('A'));
|
||||
assert!(!face.covers('\u{fe0f}'));
|
||||
let text = "A\u{fe0f}";
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["fallback"], json!([]));
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 1);
|
||||
assert_eq!(e[0].1.plain_text(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_uses_the_samples_numeral_system() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
assert!(face.covers('1'));
|
||||
assert!(!face.covers('\u{661}'));
|
||||
for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] {
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}}))
|
||||
.unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}");
|
||||
if missing {
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
|
||||
} else {
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
}
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 1);
|
||||
assert_eq!(e[0].1.plain_text(), text);
|
||||
assert_eq!(e[0].1.runs[0].style.digits.id(), digits);
|
||||
}
|
||||
}
|
||||
|
||||
/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase
|
||||
/// letter but not its capital is named in `fallback`, plain and composite fonts alike.
|
||||
#[test]
|
||||
fn coverage_checks_the_capitals_all_caps_draws() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
let lower = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let mut up = c.to_uppercase();
|
||||
face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
|
||||
let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let text = lower.to_string();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!(e[0].1.runs[0].style.all_caps);
|
||||
assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case");
|
||||
// Layout picks the font for the character as typed, so one the font lacks still falls back
|
||||
// when the font has its capitals.
|
||||
let uncased = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let up: String = c.to_uppercase().collect();
|
||||
!face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has every character whose capitals it has"));
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}");
|
||||
}
|
||||
|
||||
/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with
|
||||
/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike.
|
||||
#[test]
|
||||
fn coverage_checks_the_capitals_small_caps_draws() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
let lower = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let mut up = c.to_uppercase();
|
||||
c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
|
||||
let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let text = lower.to_string();
|
||||
let families = json!(["Inter", "CF Sheet Small Caps"]);
|
||||
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 2);
|
||||
assert!(e[0].1.runs[0].style.small_caps.is_some());
|
||||
assert_eq!(r["fallback"], families, "{lower:?}: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
let long = "x".repeat(MAX_CHARS + 1);
|
||||
for bad in [
|
||||
json!({"text": ""}),
|
||||
json!({"text": " "}),
|
||||
json!({"text": "two\nlines"}),
|
||||
json!({"text": "two\u{2028}lines"}),
|
||||
json!({"text": "two\u{2029}paragraphs"}),
|
||||
json!({"text": long}),
|
||||
json!({"text": 5}),
|
||||
json!({"size": 0.5}),
|
||||
json!({"size": "12"}),
|
||||
json!({"columns": 0}),
|
||||
json!({"columns": 1.5}),
|
||||
json!({"gap": -1}),
|
||||
json!({"margin": 2000}),
|
||||
json!({"margin": 300}),
|
||||
json!({"columns": 50, "gap": 1000}),
|
||||
json!({"filter": "no family is called this"}),
|
||||
json!({"filter": 3}),
|
||||
json!({"families": []}),
|
||||
json!({"families": "Inter"}),
|
||||
json!({"families": ["Inter", "inter"]}),
|
||||
json!({"families": ["No Such Family Anywhere"]}),
|
||||
json!({"families": [""]}),
|
||||
json!({"families": ["Inter"], "filter": "Inter"}),
|
||||
json!({"families": ["Inter"], "filter": ""}),
|
||||
json!({"families": ["Inter"], "filter": " "}),
|
||||
json!({"labels": "yes"}),
|
||||
json!({"allStyles": 1}),
|
||||
json!({"newArtboards": "no"}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(steps(&s), before);
|
||||
let layers = &s.doc().unwrap().doc.layers;
|
||||
assert!(!layers.is_empty(), "the document keeps its layers");
|
||||
assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn");
|
||||
}
|
||||
|
||||
/// Fonts left out are named in the warning, the first five of them, with a count of the rest.
|
||||
#[test]
|
||||
fn fonts_left_out_are_named_in_a_warning() {
|
||||
let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::<Vec<_>>();
|
||||
assert_eq!(super::skipped_warning(&[]), None);
|
||||
assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2"));
|
||||
assert_eq!(
|
||||
super::skipped_warning(&names(7)).as_deref(),
|
||||
Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more")
|
||||
);
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "nothing left out: no warning");
|
||||
}
|
||||
|
||||
/// A family the font menus list whose file no longer reads as a font is left out, as is a style
|
||||
/// that would be drawn in another style of its family; the rest of the sheet is made.
|
||||
#[test]
|
||||
fn fonts_that_do_not_load_are_left_out_and_named() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable");
|
||||
let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', "")));
|
||||
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] {
|
||||
let postscript = format!("{}-{style}", family.replace(' ', ""));
|
||||
std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap();
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
// Cataloged while every file reads; then two of them stop reading as fonts.
|
||||
assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half"));
|
||||
assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone"));
|
||||
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] {
|
||||
std::fs::write(file(family, style), b"not a font").unwrap();
|
||||
}
|
||||
let mut s = session();
|
||||
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}");
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Sheet Half Regular"]);
|
||||
// Nothing that loads: an error, with nothing changed.
|
||||
let before = steps(&s);
|
||||
assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err());
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
/// Where the ink of `t` starts and ends down the page.
|
||||
fn ink_rows(t: &TextObject) -> (f64, f64) {
|
||||
let (_, y) = origin(t);
|
||||
let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap();
|
||||
(y + b.y0, y + b.y1)
|
||||
}
|
||||
|
||||
/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as
|
||||
/// its laid-out ink: the first entry stays inside the margin, the second starts below the first,
|
||||
/// and each sample starts below its own label.
|
||||
#[test]
|
||||
fn rows_fit_the_laid_out_ink_of_a_composite_font() {
|
||||
let mut s = session();
|
||||
let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap();
|
||||
let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"});
|
||||
let r = s.execute(COMMAND, &p).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let e = entries(&group(&s, &r));
|
||||
let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1));
|
||||
assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}");
|
||||
assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}");
|
||||
for (name, t) in &e {
|
||||
let mut label = t.clone();
|
||||
label.runs.truncate(1);
|
||||
let mut sample = t.clone();
|
||||
sample.runs.remove(0);
|
||||
let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y);
|
||||
let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1;
|
||||
let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0;
|
||||
assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font named in other letter case, accented letters included, is found by its own name.
|
||||
#[test]
|
||||
fn a_composite_font_named_in_other_case_is_set() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}");
|
||||
assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet");
|
||||
let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string();
|
||||
assert!(twice.contains("twice"), "{twice}");
|
||||
}
|
||||
|
||||
/// A composite font whose part setting the sample names a font that doesn't load is left out and
|
||||
/// named, as a family that doesn't load is.
|
||||
#[test]
|
||||
fn a_composite_font_with_a_missing_part_is_left_out() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}");
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_font_with_an_unavailable_part_style_is_left_out() {
|
||||
let mut s = session();
|
||||
let font = json!({
|
||||
"name": "CF Sheet Missing Style",
|
||||
"parts": {
|
||||
"kanji": {"font": "Source Sans 3"},
|
||||
"roman": {"font": "Inter", "style": "No Such Sheet Style"}
|
||||
}
|
||||
});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap();
|
||||
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style);
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"]));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc, before.0);
|
||||
assert_eq!(steps(&s), before.1);
|
||||
}
|
||||
|
||||
/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is
|
||||
/// named in `fallback`, as a plain font is.
|
||||
#[test]
|
||||
fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap();
|
||||
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact);
|
||||
assert!(!coverage.lacking.is_empty());
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
|
||||
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}");
|
||||
// A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system.
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}}))
|
||||
.unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_without_overlap_need_no_additional_layouts() {
|
||||
use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread};
|
||||
|
||||
let mut counts = vec![];
|
||||
for labels in [false, true] {
|
||||
let mut s = session();
|
||||
let before = layouts_on_this_thread();
|
||||
let ink_before = ink_work_on_this_thread();
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap();
|
||||
let ink_after = ink_work_on_this_thread();
|
||||
counts.push(layouts_on_this_thread() - before);
|
||||
assert_eq!(r["count"], BUNDLED.len());
|
||||
let mut outlines = 0;
|
||||
for (_, t) in entries(&group(&s, &r)) {
|
||||
assert!(t.cached_ink.unwrap().1.is_some());
|
||||
assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 });
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64;
|
||||
assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
|
||||
}
|
||||
assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once");
|
||||
assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry");
|
||||
}
|
||||
assert!(counts[0] > 0);
|
||||
assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() {
|
||||
use vectorcraft_doc::{CharStyle, TextRun};
|
||||
|
||||
for text in ["Hamburg", " "] {
|
||||
for labels in [false, true] {
|
||||
let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() };
|
||||
let sample = TextRun::new(text, style.clone());
|
||||
let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) };
|
||||
let t = super::laid_out(first, more, false);
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t);
|
||||
assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars");
|
||||
let ink = t.cached_ink.unwrap().1;
|
||||
assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
|
||||
let ink = ink.unwrap();
|
||||
for (_, bar) in bars {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&bar);
|
||||
assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"artboards": 3})).unwrap();
|
||||
let state = s.doc().unwrap();
|
||||
let document = (state.uid, state.reverts);
|
||||
let artboard = state.doc.artboards[1].id;
|
||||
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for params in [json!({"index": 0}), json!({"indices": [1, 0]})] {
|
||||
let error = s.execute("artboard.delete", ¶ms).unwrap_err();
|
||||
assert_eq!(error.to_string(), "The artboard is in use.");
|
||||
assert_eq!(s.doc().unwrap().doc, before.0);
|
||||
assert_eq!(steps(&s), before.1);
|
||||
}
|
||||
s.execute("file.new", &json!({"artboards": 2})).unwrap();
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected");
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
s.doc_mut().unwrap().reverts += 1;
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected");
|
||||
}
|
||||
|
||||
/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too.
|
||||
#[test]
|
||||
fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"artboards": 3})).unwrap();
|
||||
let state = s.doc().unwrap();
|
||||
let document = (state.uid, state.reverts);
|
||||
let artboard = state.doc.artboards[1].id;
|
||||
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for (command, params) in [
|
||||
("artboard.cut", json!({"index": 1})),
|
||||
("artboard.deleteEmpty", json!({})),
|
||||
("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})),
|
||||
] {
|
||||
let error = s.execute(command, ¶ms).unwrap_err();
|
||||
assert_eq!(error.to_string(), "The artboard is in use.", "{command}");
|
||||
assert_eq!(s.doc().unwrap().doc, before.0, "{command}");
|
||||
assert_eq!(steps(&s), before.1, "{command}");
|
||||
}
|
||||
s.execute("artboard.cut", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_a_document() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_layer_takes_no_sheet() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err());
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() {
|
||||
let mut s = session();
|
||||
let editable = s.doc().unwrap().doc.layers[0].id;
|
||||
let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
|
||||
let gid = NodeId(r["id"].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid));
|
||||
assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked");
|
||||
assert!(!holds(locked));
|
||||
}
|
||||
@@ -0,0 +1,830 @@
|
||||
//! Concept to Vector (`conceptVector.*`): vector variations of one selected image, made by a
|
||||
//! provider ([`crate::concept_vector`]), compared, and inserted beside the image.
|
||||
//!
|
||||
//! `conceptVector.generate` asks the named provider for one variation per style and keeps them as a
|
||||
//! job of this session; it changes nothing in the document. `conceptVector.insert` puts the chosen
|
||||
//! variations to the right of the image as one undo step. A job is kept until it is canceled, its
|
||||
//! document closes, or [`KEEP_JOBS`] newer ones replace it; it is never saved.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::buildcmds::TRACE_NAME;
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::shape_node;
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_id, cmd, has_doc, text_param};
|
||||
use crate::concept_vector::{self as cv, MAX_STYLES, Output, Provider, ProviderError, Request, Variation};
|
||||
|
||||
/// The most jobs a session keeps; a new one drops the oldest.
|
||||
pub const KEEP_JOBS: usize = 4;
|
||||
|
||||
/// The gap, in points, between the image and the first inserted variation, and between variations.
|
||||
pub const GAP: f64 = 24.0;
|
||||
|
||||
/// A job's variations, or that it was canceled.
|
||||
#[derive(Clone)]
|
||||
enum Outcome {
|
||||
Done(Arc<Vec<Variation>>),
|
||||
Canceled,
|
||||
}
|
||||
|
||||
/// What `conceptVector.generate` made, and what it was made of.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Job {
|
||||
id: u64,
|
||||
/// The document ([`crate::DocState::uid`]) and the object (an image or an Image Trace object).
|
||||
doc: u64,
|
||||
source: NodeId,
|
||||
image: ImageObject,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
provider: String,
|
||||
outcome: Outcome,
|
||||
}
|
||||
|
||||
/// The session's providers and jobs.
|
||||
pub(crate) struct ConceptState {
|
||||
pub(crate) registry: cv::Registry,
|
||||
jobs: VecDeque<Job>,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Default for ConceptState {
|
||||
fn default() -> Self {
|
||||
Self { registry: cv::Registry::default(), jobs: VecDeque::new(), next: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The Concept to Vector providers this session calls by id.
|
||||
pub fn concept_providers(&self) -> &cv::Registry {
|
||||
&self.concept.registry
|
||||
}
|
||||
|
||||
/// The providers, to register another ([`cv::Registry::register`]).
|
||||
pub fn concept_providers_mut(&mut self) -> &mut cv::Registry {
|
||||
&mut self.concept.registry
|
||||
}
|
||||
|
||||
/// Job `job`'s variations and the size in pixels of the image they were made of; `None` for a
|
||||
/// job this session does not keep, or one that was canceled.
|
||||
pub fn concept_variations(&self, job: u64) -> Option<(&[Variation], (u32, u32))> {
|
||||
let j = self.concept.jobs.iter().find(|j| j.id == job)?;
|
||||
match &j.outcome {
|
||||
Outcome::Done(v) => Some((v.as_slice(), (j.image.width, j.image.height))),
|
||||
Outcome::Canceled => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The document ([`crate::DocState::uid`]) job `job` was made in; `None` for a job this session
|
||||
/// does not keep.
|
||||
pub fn concept_job_doc(&self, job: u64) -> Option<u64> {
|
||||
self.concept.jobs.iter().find(|j| j.id == job).map(|j| j.doc)
|
||||
}
|
||||
|
||||
/// The jobs, for a batch to put back when a step fails. Job numbers are not reused.
|
||||
pub(crate) fn concept_jobs_snapshot(&self) -> VecDeque<Job> {
|
||||
self.concept.jobs.clone()
|
||||
}
|
||||
|
||||
/// Puts back the jobs that [`Self::concept_jobs_snapshot`] took.
|
||||
pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque<Job>) {
|
||||
self.concept.jobs = jobs;
|
||||
}
|
||||
|
||||
/// Exchanges the jobs with `jobs`: a script works on a copy of them, which becomes the
|
||||
/// session's only when the script ends without an error.
|
||||
pub(crate) fn swap_concept_jobs(&mut self, jobs: &mut VecDeque<Job>) {
|
||||
std::mem::swap(&mut self.concept.jobs, jobs);
|
||||
}
|
||||
|
||||
/// The number the next job gets.
|
||||
pub(crate) fn next_concept_job(&self) -> u64 {
|
||||
self.concept.next
|
||||
}
|
||||
|
||||
/// Takes in what the app did to the jobs while a script ran, `others` being the jobs as the app
|
||||
/// left them: a job canceled there is canceled here too, and the jobs numbered `from` or higher
|
||||
/// that this session does not keep (those the app made) are added. Then keeps the
|
||||
/// [`KEEP_JOBS`] newest of open documents.
|
||||
pub(crate) fn merge_concept_jobs(&mut self, others: VecDeque<Job>, from: u64) {
|
||||
for j in others {
|
||||
match self.concept.jobs.iter_mut().find(|k| k.id == j.id) {
|
||||
Some(k) if matches!(j.outcome, Outcome::Canceled) => k.outcome = Outcome::Canceled,
|
||||
Some(_) => {}
|
||||
None if j.id >= from => self.concept.jobs.push_back(j),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
self.concept.jobs.make_contiguous().sort_by_key(|j| j.id);
|
||||
self.prune_concept_jobs();
|
||||
while self.concept.jobs.len() > KEEP_JOBS {
|
||||
self.concept.jobs.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the jobs of document `doc` (its `uid`), when it closes.
|
||||
pub(crate) fn forget_concept_jobs(&mut self, doc: u64) {
|
||||
self.concept.jobs.retain(|j| j.doc != doc);
|
||||
}
|
||||
|
||||
/// Drops the jobs whose document is closed.
|
||||
/// In a batch, nothing is dropped until the batch ends without an error.
|
||||
pub(crate) fn prune_concept_jobs(&mut self) {
|
||||
if self.batch_stash.is_some() {
|
||||
return;
|
||||
}
|
||||
let open: Vec<u64> = self.documents().iter().map(|d| d.uid).collect();
|
||||
self.concept.jobs.retain(|j| open.contains(&j.doc));
|
||||
}
|
||||
}
|
||||
|
||||
/// The image `n` shows: its own, or the source image of an Image Trace object that wasn't expanded.
|
||||
fn shown_image(n: &Node) -> Option<&ImageObject> {
|
||||
match &shown_image_node(n)?.kind {
|
||||
NodeKind::Image(i) => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The image object [`shown_image`] reads: `n` itself, or the first member of its Image Trace object.
|
||||
fn shown_image_node(n: &Node) -> Option<&Node> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(_) => Some(n),
|
||||
NodeKind::Group { clip: false, .. } if n.name.as_deref() == Some(TRACE_NAME) => {
|
||||
n.children()?.first().map(|i| &**i).filter(|i| matches!(i.kind, NodeKind::Image(_)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a group whose members are made or placed from data it holds (a graph, an Objects on
|
||||
/// Path, Shaper, dimension, flare or Live Paint group, a compound shape, a plug-in's generated
|
||||
/// art), so that a member added to it would be placed again, replaced or combined with the others?
|
||||
fn generated(n: &Node) -> bool {
|
||||
let e = n.extras();
|
||||
e.generated.is_some()
|
||||
|| e.graph.is_some()
|
||||
|| e.objects_on_path.is_some()
|
||||
|| e.shaper.is_some()
|
||||
|| e.dimension.is_some()
|
||||
|| e.flare.is_some()
|
||||
|| e.compound_shape
|
||||
|| vectorcraft_tools::builder::is_live_paint(n)
|
||||
}
|
||||
|
||||
const NO_SOURCE: &str = "select one image or an unexpanded Image Trace object";
|
||||
|
||||
const LOCKED: &str = "the image is locked or hidden";
|
||||
|
||||
/// The object `id` names, else the one selected: an image or an unexpanded Image Trace object,
|
||||
/// shown and unlocked with every layer and group around it, and not on a locked artboard → it, its
|
||||
/// image and the image's bytes.
|
||||
fn source(s: &Session, c: &str, p: &Value) -> Result<(NodeId, ImageObject, Arc<Vec<u8>>)> {
|
||||
let id = match p.get("id").filter(|v| !v.is_null()) {
|
||||
Some(v) => checked_id(s, v, c)?,
|
||||
None => match selected_roots(s)?.as_slice() {
|
||||
[one] => *one,
|
||||
_ => return Err(bad(c, NO_SOURCE)),
|
||||
},
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let image = shown_image(n).ok_or_else(|| bad(c, NO_SOURCE))?;
|
||||
if !d.is_editable(id) {
|
||||
return Err(bad(c, LOCKED));
|
||||
}
|
||||
let blob = d.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
|
||||
Ok((id, image.clone(), Arc::clone(&blob.bytes)))
|
||||
}
|
||||
|
||||
/// A generation prepared from the session, which runs without it ([`ConceptRun::run`]), on any
|
||||
/// thread, and is kept as a job with [`ConceptRun::finish`].
|
||||
pub struct ConceptRun {
|
||||
provider: Arc<dyn Provider>,
|
||||
/// The provider's id, as it was registered.
|
||||
provider_id: &'static str,
|
||||
request: Request,
|
||||
doc: u64,
|
||||
source: NodeId,
|
||||
image: ImageObject,
|
||||
}
|
||||
|
||||
impl ConceptRun {
|
||||
/// What `conceptVector.generate` with params `p` makes in the active document, checked as the
|
||||
/// command checks it.
|
||||
pub fn prepare(s: &Session, p: &Value) -> Result<ConceptRun> {
|
||||
const C: &str = "conceptVector.generate";
|
||||
let name = text_param(p, "provider", C)?.ok_or_else(|| bad(C, "missing `provider` (see conceptVector.providers)"))?;
|
||||
let found =
|
||||
s.concept.registry.get(name).ok_or_else(|| bad(C, format!("no Concept to Vector provider `{name}` (see conceptVector.providers)")))?;
|
||||
let (caps, pid, provider) = (&found.capabilities, found.id, Arc::clone(&found.provider));
|
||||
let styles_error = || bad(C, format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)"));
|
||||
// The count is checked before any id is copied or scanned for repeats.
|
||||
let styles: Vec<String> = match p.get("styles") {
|
||||
Some(Value::Array(a)) if (1..=MAX_STYLES).contains(&a.len()) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<_>>().ok_or_else(styles_error)?
|
||||
}
|
||||
_ => return Err(styles_error()),
|
||||
};
|
||||
let known = |id: &String| caps.styles.iter().any(|st| st.id == id);
|
||||
let unique = styles.iter().enumerate().all(|(i, id)| !styles.get(..i).unwrap_or_default().contains(id));
|
||||
if !unique || !styles.iter().all(known) {
|
||||
return Err(styles_error());
|
||||
}
|
||||
let prompt = text_param(p, "prompt", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
// Results are vector paths, inserted as vector art, whatever else a provider makes.
|
||||
let output = match text_param(p, "output", C)? {
|
||||
None | Some("vector") => Output::Vector,
|
||||
Some(_) => return Err(bad(C, "`output` must be \"vector\"")),
|
||||
};
|
||||
if !caps.image_input {
|
||||
return Err(bad(C, format!("`{pid}` does not take an image")));
|
||||
}
|
||||
if !caps.vector_output {
|
||||
return Err(bad(C, format!("`{pid}` does not make vector art")));
|
||||
}
|
||||
if prompt.is_some() && !caps.prompt {
|
||||
return Err(bad(C, format!("`{pid}` takes no prompt")));
|
||||
}
|
||||
let detail = match p.get("detail") {
|
||||
None => 50,
|
||||
Some(v) => v.as_u64().filter(|d| *d <= 100).ok_or_else(|| bad(C, "`detail` must be a whole number from 0 to 100"))? as u8,
|
||||
};
|
||||
let (source, image, bytes) = source(s, C, p)?;
|
||||
let request = Request { image: bytes, width: image.width, height: image.height, prompt, styles, detail, output };
|
||||
Ok(ConceptRun { provider, provider_id: pid, request, doc: s.doc()?.uid, source, image })
|
||||
}
|
||||
|
||||
/// The document it was prepared in ([`crate::DocState::uid`]).
|
||||
pub fn doc(&self) -> u64 {
|
||||
self.doc
|
||||
}
|
||||
|
||||
/// The image or Image Trace object it makes variations of.
|
||||
pub fn source(&self) -> NodeId {
|
||||
self.source
|
||||
}
|
||||
|
||||
/// Asks the provider for the variations and checks them ([`cv::check_result`]), telling `steps`
|
||||
/// how far it has got; it touches no document. A panic in the provider is an error.
|
||||
pub fn run(&self, steps: cv::Steps) -> std::result::Result<Vec<Variation>, ProviderError> {
|
||||
let made = crate::guard::catch_panic(|| self.provider.generate(&self.request, steps)).map_err(ProviderError::Internal)??;
|
||||
cv::check_result(&self.request, &made)?;
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
/// How many styles it makes.
|
||||
pub fn style_count(&self) -> usize {
|
||||
self.request.styles.len()
|
||||
}
|
||||
|
||||
/// Does the next part of the run kept in `run`, for a caller with no thread for
|
||||
/// [`ConceptRun::run`] (the web build), which can run other work, or stop, between the parts
|
||||
/// → whether every style is made ([`PartRun::made`]). A provider that makes parts
|
||||
/// ([`cv::Provider::parts`]) does one of its own; the others make one style alone, and the
|
||||
/// styles made so far are checked together ([`cv::check_result`]) after each one, so the
|
||||
/// totals stop the run as soon as they are passed. A panic in the provider is an error.
|
||||
pub fn run_part(&self, run: &mut PartRun, steps: cv::Steps) -> std::result::Result<bool, ProviderError> {
|
||||
let guard = ProviderError::Internal;
|
||||
if run.parts.is_none() {
|
||||
run.parts = Some(crate::guard::catch_panic(|| self.provider.parts(&self.request)).map_err(guard)?);
|
||||
}
|
||||
if let Some(Some(parts)) = &mut run.parts {
|
||||
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
|
||||
if !steps(run.done as u64, self.style_count() as u64) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
let Some(made) = crate::guard::catch_panic(|| parts.step()).map_err(guard)?? else {
|
||||
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
|
||||
return Ok(false);
|
||||
};
|
||||
cv::check_result(&self.request, &made)?;
|
||||
run.made = made;
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(style) = self.request.styles.get(run.made.len()) else { return Ok(true) };
|
||||
let one = Request { styles: vec![style.clone()], ..self.request.clone() };
|
||||
let next = crate::guard::catch_panic(|| self.provider.generate(&one, steps)).map_err(guard)??;
|
||||
cv::check_result(&one, &next)?;
|
||||
// A style that takes the totals past their limits is dropped, so `run` keeps only the
|
||||
// styles that passed.
|
||||
let kept = run.made.len();
|
||||
run.made.extend(next);
|
||||
let so_far = Request { styles: self.request.styles.get(..run.made.len()).unwrap_or_default().to_vec(), ..one };
|
||||
if let Err(e) = cv::check_result(&so_far, &run.made) {
|
||||
run.made.truncate(kept);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(run.made.len() == self.request.styles.len())
|
||||
}
|
||||
|
||||
/// Keeps `variations` as a new job of `s` → the job, as `conceptVector.results` gives it;
|
||||
/// `None`, keeping nothing, when the document it was prepared in has closed.
|
||||
pub fn finish(self, s: &mut Session, variations: Vec<Variation>) -> Option<Value> {
|
||||
s.prune_concept_jobs();
|
||||
if !s.documents().iter().any(|d| d.uid == self.doc) {
|
||||
return None;
|
||||
}
|
||||
let id = s.concept.next;
|
||||
s.concept.next += 1;
|
||||
let job = Job {
|
||||
id,
|
||||
doc: self.doc,
|
||||
source: self.source,
|
||||
image: self.image,
|
||||
bytes: self.request.image,
|
||||
provider: self.provider_id.to_string(),
|
||||
outcome: Outcome::Done(Arc::new(variations)),
|
||||
};
|
||||
let out = job_json(&s.concept.registry, &job);
|
||||
s.concept.jobs.push_back(job);
|
||||
while s.concept.jobs.len() > KEEP_JOBS {
|
||||
s.concept.jobs.pop_front();
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a run made a part at a time ([`ConceptRun::run_part`]) has got.
|
||||
#[derive(Default)]
|
||||
pub struct PartRun {
|
||||
/// The provider's parts, once asked for (`None` inside: it makes one style at a time).
|
||||
parts: Option<Option<Box<dyn cv::Parts>>>,
|
||||
/// The styles the provider's parts had made when last asked, inside the panic guard.
|
||||
done: usize,
|
||||
made: Vec<Variation>,
|
||||
}
|
||||
|
||||
impl PartRun {
|
||||
/// The styles made so far.
|
||||
pub fn styles_done(&self) -> usize {
|
||||
if self.made.is_empty() { self.done } else { self.made.len() }
|
||||
}
|
||||
|
||||
/// The variations made: all of them once [`ConceptRun::run_part`] has said so.
|
||||
pub fn made(self) -> Vec<Variation> {
|
||||
self.made
|
||||
}
|
||||
}
|
||||
|
||||
/// `e` as the engine's error.
|
||||
pub fn provider_error(e: ProviderError) -> EngineError {
|
||||
match e {
|
||||
ProviderError::Canceled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The English name of style `style` of provider `provider`, else the id.
|
||||
fn style_label(registry: &cv::Registry, provider: &str, style: &str) -> String {
|
||||
let caps = registry.get(provider).map(|p| &p.capabilities);
|
||||
caps.and_then(|c| c.styles.iter().find(|s| s.id == style).map(|s| s.label.to_string())).unwrap_or_else(|| style.to_string())
|
||||
}
|
||||
|
||||
/// Where `style` comes in the styles `provider` lists; after them when it lists no such style.
|
||||
fn style_rank(registry: &cv::Registry, provider: &str, style: &str) -> usize {
|
||||
let caps = registry.get(provider).map(|p| &p.capabilities);
|
||||
caps.and_then(|c| c.styles.iter().position(|s| s.id == style)).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// Where `image`'s pixels lie in the document.
|
||||
fn image_rect(image: &ImageObject) -> Option<Rect> {
|
||||
let r = Rect::new(0.0, 0.0, f64::from(image.width.max(1)), f64::from(image.height.max(1)));
|
||||
let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| image.xf * kurbo::Point::new(x, y));
|
||||
let mut out = Rect::from_points(pts[0], pts[0]);
|
||||
for q in &pts[1..] {
|
||||
out = out.union_pt(*q);
|
||||
}
|
||||
[out.x0, out.y0, out.x1, out.y1].iter().all(|v| v.is_finite()).then_some(out)
|
||||
}
|
||||
|
||||
fn job_json(registry: &cv::Registry, j: &Job) -> Value {
|
||||
let (state, variations) = match &j.outcome {
|
||||
Outcome::Done(v) => ("done", v.as_slice()),
|
||||
Outcome::Canceled => ("canceled", &[][..]),
|
||||
};
|
||||
let variations: Vec<Value> = variations
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let bounds = v.paths.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b));
|
||||
json!({
|
||||
"style": v.style,
|
||||
"label": style_label(registry, &j.provider, &v.style),
|
||||
"paths": v.paths.len(),
|
||||
"anchors": v.anchors(),
|
||||
"bounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]),
|
||||
"warnings": v.warnings,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "job": j.id, "provider": j.provider, "source": j.source.0, "state": state, "variations": variations })
|
||||
}
|
||||
|
||||
/// The `job` param of command `c`.
|
||||
fn job_param(c: &str, p: &Value) -> Result<u64> {
|
||||
p.get("job").and_then(Value::as_u64).ok_or_else(|| bad(c, "`job` must be a job number from conceptVector.generate"))
|
||||
}
|
||||
|
||||
/// The error of command `c` for a job the session does not keep.
|
||||
fn no_job(c: &str, job: u64) -> EngineError {
|
||||
bad(c, format!("no Concept to Vector job {job}: it was never made, or was dropped (see conceptVector.results)"))
|
||||
}
|
||||
|
||||
/// The index of job `job` among those `s` keeps.
|
||||
fn job_index(s: &mut Session, c: &str, job: u64) -> Result<usize> {
|
||||
s.prune_concept_jobs();
|
||||
s.concept.jobs.iter().position(|j| j.id == job).ok_or_else(|| no_job(c, job))
|
||||
}
|
||||
|
||||
fn providers(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list: Vec<Value> = s
|
||||
.concept
|
||||
.registry
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let c = &p.capabilities;
|
||||
json!({
|
||||
"id": p.id,
|
||||
"name": p.name,
|
||||
"available": true,
|
||||
"offline": c.offline,
|
||||
"imageInput": c.image_input,
|
||||
"vectorOutput": c.vector_output,
|
||||
"prompt": c.prompt,
|
||||
"rasterOutput": c.raster_output,
|
||||
"maxStyles": MAX_STYLES,
|
||||
"styles": c.styles,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let selected = s.concept.registry.iter().next().map(|p| p.id);
|
||||
Ok(json!({ "providers": list, "selected": selected }))
|
||||
}
|
||||
|
||||
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let run = ConceptRun::prepare(s, p)?;
|
||||
// A script's run stops when the script is asked to stop, and keeps no job.
|
||||
let stop = s.script_in_run.then(|| s.script_interrupt());
|
||||
let stopped = || stop.as_ref().is_some_and(|i| i.is_set());
|
||||
let made = run.run(&|_, _| !stopped()).map_err(provider_error)?;
|
||||
if stopped() {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
run.finish(s, made).ok_or(EngineError::NoDocument)
|
||||
}
|
||||
|
||||
fn results(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.results";
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
|
||||
Ok(job_json(&s.concept.registry, j))
|
||||
}
|
||||
|
||||
/// The error of an insert or cancel played from recorded steps: a job lives only in this session,
|
||||
/// and a job number from another one may name other results.
|
||||
const REPLAYED: &str = "Concept to Vector jobs are not saved, so a recorded insert or cancel does not play again: generate again";
|
||||
|
||||
fn cancel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.cancel";
|
||||
if s.replaying() {
|
||||
return Err(bad(C, REPLAYED));
|
||||
}
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
if let Some(j) = s.concept.jobs.get_mut(at) {
|
||||
j.outcome = Outcome::Canceled;
|
||||
}
|
||||
Ok(json!({ "job": job, "state": "canceled" }))
|
||||
}
|
||||
|
||||
/// The appearance of variation path `p`, its widths scaled by `unit` (points per pixel).
|
||||
fn appearance_of(p: &cv::VectorPath, unit: f64) -> Appearance {
|
||||
let solid = |c: [u8; 3]| Paint::solid(Color::rgb8(c[0], c[1], c[2]));
|
||||
let mut items = vec![];
|
||||
if let Some(c) = p.fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(solid(c))));
|
||||
}
|
||||
if let Some((c, w)) = p.stroke {
|
||||
let cap = if p.square_caps { LineCap::Square } else { LineCap::Round };
|
||||
items.push(AppearanceItem::Stroke(StrokeLayer { cap, join: LineJoin::Round, ..StrokeLayer::new(solid(c), w * unit) }));
|
||||
}
|
||||
Appearance { items, ..Default::default() }
|
||||
}
|
||||
|
||||
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "conceptVector.insert";
|
||||
if s.replaying() {
|
||||
return Err(bad(C, REPLAYED));
|
||||
}
|
||||
let job = job_param(C, p)?;
|
||||
let at = job_index(s, C, job)?;
|
||||
let list_error = || bad(C, format!("`variations` must list different style ids of job {job}"));
|
||||
let listed = match p.get("variations") {
|
||||
Some(Value::Array(a)) if !a.is_empty() => a,
|
||||
_ => return Err(list_error()),
|
||||
};
|
||||
let stale = || bad(C, format!("job {job} no longer applies: its document, image or image placement changed, so generate again"));
|
||||
let (doc, source, image, bytes, picked, label_of) = {
|
||||
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
|
||||
let Outcome::Done(all) = &j.outcome else { return Err(bad(C, format!("job {job} has no results to insert: it was canceled"))) };
|
||||
// The count is checked before the ids are read or scanned for repeats.
|
||||
if listed.len() > all.len() {
|
||||
return Err(list_error());
|
||||
}
|
||||
let chosen: Vec<&str> = listed.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(list_error)?;
|
||||
let unique = chosen.iter().enumerate().all(|(i, id)| !chosen.get(..i).unwrap_or_default().contains(id));
|
||||
let mut picked: Vec<Variation> = all.iter().filter(|v| chosen.contains(&v.style.as_str())).cloned().collect();
|
||||
if !unique || picked.len() != chosen.len() {
|
||||
return Err(list_error());
|
||||
}
|
||||
// In the provider's order, whatever order they were listed or generated in.
|
||||
picked.sort_by_key(|v| style_rank(&s.concept.registry, &j.provider, &v.style));
|
||||
let labels: Vec<String> = picked.iter().map(|v| style_label(&s.concept.registry, &j.provider, &v.style)).collect();
|
||||
(j.doc, j.source, j.image.clone(), Arc::clone(&j.bytes), picked, labels)
|
||||
};
|
||||
// The same document, the same object showing the same pixels where they were.
|
||||
let st = s.doc()?;
|
||||
let now = st.doc.node(source).and_then(shown_image);
|
||||
let same_pixels = || st.doc.images.get(&image.key).is_some_and(|b| Arc::ptr_eq(&b.bytes, &bytes) || *b.bytes == *bytes);
|
||||
let current = st.uid == doc && now.is_some_and(|i| i.key == image.key && i.xf == image.xf && i.width == image.width && i.height == image.height);
|
||||
if !current || !same_pixels() {
|
||||
return Err(stale());
|
||||
}
|
||||
if !st.doc.is_editable(source) {
|
||||
return Err(bad(C, LOCKED));
|
||||
}
|
||||
// The results go above the outermost group around the image that clips or masks it, so that
|
||||
// it hides none of them, and above the outermost envelope, blend, repeat or other live object,
|
||||
// the outermost group whose members it makes or places ([`generated`]), and the outermost
|
||||
// group with effects or fills and strokes of its own, so that its content and the place its
|
||||
// effects measure from stay as they are. A layer that clips or masks its art, or has effects,
|
||||
// fills or strokes of its own, leaves them nowhere to go. An effect that moves or reshapes
|
||||
// the image, its own or a group's around it, shows it away from its placement, which the
|
||||
// results are placed by.
|
||||
let ancestry = st.doc.ancestry(source).ok_or_else(stale)?;
|
||||
let moves = |id: &NodeId| st.doc.node(*id).is_some_and(|n| !n.is_layer() && vectorcraft_render::effects::has_geometry(&n.appearance.effects));
|
||||
if ancestry.iter().any(moves) {
|
||||
return Err(bad(C, "the image or a group around it has effects that move or reshape it, so the results would not go beside it"));
|
||||
}
|
||||
// A distorted image ([`Node::image_quad`]) is drawn at its corners, not by its transform.
|
||||
if st.doc.node(source).and_then(shown_image_node).is_some_and(Node::is_distorted_image) {
|
||||
return Err(bad(C, "the image is distorted, so the results would not go beside it"));
|
||||
}
|
||||
let mut anchor = source;
|
||||
for &id in ancestry.iter().rev().skip(1) {
|
||||
let n = st.doc.node(id).ok_or_else(stale)?;
|
||||
let masked = n.extras().mask.as_ref().is_some_and(|m| !m.disabled);
|
||||
if matches!(n.kind, NodeKind::Layer { clip: true, .. }) {
|
||||
return Err(bad(C, "the image is on a layer with a clipping mask, which would hide the results"));
|
||||
}
|
||||
if n.is_layer() && masked {
|
||||
return Err(bad(C, "the image is on a layer with an opacity mask, which would hide the results"));
|
||||
}
|
||||
let styled = !n.appearance.items.is_empty() || !n.appearance.effects.is_empty();
|
||||
if n.is_layer() && !n.appearance.effects.is_empty() {
|
||||
return Err(bad(C, "the image is on a layer with effects of its own, which would apply to the results"));
|
||||
}
|
||||
// A layer's fills and strokes paint over its members, the results included.
|
||||
if n.is_layer() && !n.appearance.items.is_empty() {
|
||||
return Err(bad(C, "the image is on a layer with fills or strokes of its own, which would apply to the results"));
|
||||
}
|
||||
let live = !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || generated(n);
|
||||
if !n.is_layer() && (masked || live || styled || matches!(n.kind, NodeKind::Group { clip: true, .. })) {
|
||||
anchor = id;
|
||||
}
|
||||
}
|
||||
let src = image_rect(&image).ok_or_else(stale)?;
|
||||
// A variation with no paths adds nothing: it is left out, and with none left nothing changes.
|
||||
let (picked, label_of): (Vec<Variation>, Vec<String>) = picked.into_iter().zip(label_of).filter(|(v, _)| !v.paths.is_empty()).unzip();
|
||||
if picked.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let unit = image.xf.determinant().abs().sqrt();
|
||||
// Each chosen variation's box over the image: the image's box and the variation's painted
|
||||
// bounds, which may reach past it. A square cap's corner lies half the width along the path
|
||||
// and half across it from the end, so up to √2 times half the width past it on an axis.
|
||||
let boxes: Vec<Rect> = picked
|
||||
.iter()
|
||||
.map(|v| {
|
||||
v.paths
|
||||
.iter()
|
||||
.filter_map(|vp| {
|
||||
let reach = if vp.square_caps { std::f64::consts::SQRT_2 } else { 1.0 };
|
||||
let half = vp.stroke.map_or(0.0, |(_, w)| w * unit / 2.0 * reach);
|
||||
vp.path.transformed(image.xf).bounds().map(|b| b.inflate(half, half))
|
||||
})
|
||||
.fold(src, |a, b| a.union(b))
|
||||
})
|
||||
.collect();
|
||||
// How far each variation's box is moved past the first's: each box starts GAP to the right of
|
||||
// the one before it (`width + GAP` further right for boxes the image's size).
|
||||
let mut offsets = Vec::with_capacity(boxes.len());
|
||||
let mut next = 0.0;
|
||||
for (k, b) in boxes.iter().enumerate() {
|
||||
if let Some(prev) = k.checked_sub(1).and_then(|j| boxes.get(j)) {
|
||||
next += prev.x1 - b.x0 + GAP;
|
||||
}
|
||||
offsets.push(next);
|
||||
}
|
||||
// The first box's left edge, which may lie left of the image's where its variation paints there.
|
||||
let first = boxes.first().map_or(src.x0, |b| b.x0);
|
||||
// The boxes with the first one's left edge moved to `x0`, the others after it.
|
||||
let row = |x0: f64| -> Vec<Rect> {
|
||||
boxes
|
||||
.iter()
|
||||
.zip(&offsets)
|
||||
.map(|(b, off)| {
|
||||
let dx = x0 + off - first;
|
||||
Rect::new(b.x0 + dx, b.y0, b.x1 + dx, b.y1)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The painted bounds of every visible object (the source's too: an Image Trace object's traced
|
||||
// art and effects can reach past the image), and the image's own box. A layer or group that
|
||||
// paints nothing of its own is measured by its members (an opacity mask only hides them); one
|
||||
// that clips, by its members after the clipping path, cut to what it paints.
|
||||
let mut obstacles: Vec<Rect> = vec![src];
|
||||
// One lookup of the symbols for the whole walk, so each symbol's art is measured once.
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let mut stack: Vec<(&Arc<Node>, Option<Rect>)> = st.doc.layers.iter().map(|l| (l, None)).collect();
|
||||
while let Some((node, within)) = stack.pop() {
|
||||
if !node.visible {
|
||||
continue;
|
||||
}
|
||||
let cut = |b: Rect| match within {
|
||||
Some(w) => Some(b.intersect(w)).filter(|i| i.width() > 0.0 && i.height() > 0.0),
|
||||
None => Some(b),
|
||||
};
|
||||
let painted = || vectorcraft_render::painted_bounds_with(&symbols, node).and_then(cut);
|
||||
if node.id == source {
|
||||
obstacles.extend(painted());
|
||||
continue;
|
||||
}
|
||||
let clips = matches!(node.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
let by_members = (node.is_layer() || matches!(node.kind, NodeKind::Group { .. }))
|
||||
&& node.appearance.items.is_empty()
|
||||
&& node.appearance.effects.is_empty();
|
||||
if by_members {
|
||||
// A clipping path paints its fills and strokes when they are set (`Node::clip_paint`),
|
||||
// its strokes outside the clip too, whether or not it is shown.
|
||||
if clips && let Some(path) = node.children().into_iter().flatten().next() {
|
||||
let paint = path.clip_paint();
|
||||
for part in [paint.fill, paint.stroke].into_iter().flatten() {
|
||||
if let Some(b) = vectorcraft_render::painted_bounds_with(&symbols, &part).and_then(cut) {
|
||||
obstacles.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
let within = if clips {
|
||||
// Nothing of a clipping group shows outside what it paints.
|
||||
let Some(shown) = painted() else { continue };
|
||||
Some(shown)
|
||||
} else {
|
||||
within
|
||||
};
|
||||
stack.extend(node.children().into_iter().flatten().skip(usize::from(clips)).map(|c| (c, within)));
|
||||
} else if let Some(b) = painted() {
|
||||
obstacles.push(b);
|
||||
}
|
||||
}
|
||||
let placed = place_row(&row, src.x1 + GAP, &obstacles);
|
||||
let room = || bad(C, "there is no room for the results to the right of the image");
|
||||
let Some(x0) = placed.filter(|x0| x0.is_finite()) else {
|
||||
return Err(room());
|
||||
};
|
||||
let right = row(x0).iter().map(|r| r.x1).fold(f64::NEG_INFINITY, f64::max);
|
||||
if right > crate::MAX_COORD {
|
||||
return Err(room());
|
||||
}
|
||||
let ids = s.edit("Concept to Vector", |d, sel| {
|
||||
let mut groups = vec![];
|
||||
for ((v, label), off) in picked.into_iter().zip(label_of).zip(&offsets) {
|
||||
let dx = x0 + off - first;
|
||||
let xf = Affine::translate((dx, 0.0)) * image.xf;
|
||||
let mut members = Vec::with_capacity(v.paths.len());
|
||||
for vp in &v.paths {
|
||||
let path = vp.path.transformed(xf);
|
||||
if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().any(|c| c.abs() > crate::MAX_COORD)) {
|
||||
return Err(room());
|
||||
}
|
||||
let mut node = shape_node(d, path, None);
|
||||
node.appearance = appearance_of(vp, unit).into();
|
||||
members.push(Arc::new(node));
|
||||
}
|
||||
let mut g = Node::group(d.alloc_id(), members);
|
||||
g.name = Some(label);
|
||||
groups.push(g);
|
||||
}
|
||||
let ids: Vec<NodeId> = groups.iter().map(|g| g.id).collect();
|
||||
d.insert_beside(vec![(anchor, groups)], false)?;
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`place_row`] has looked at an object on this thread.
|
||||
pub(crate) static LOOKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Where the left edge of the row's first box goes, from `start` rightward, so that no box meets
|
||||
/// one of `obstacles`: a box in the way moves GAP past the rightmost object it meets. `row(x0)`
|
||||
/// gives the boxes with the first one's left edge at `x0`. `None` when the moves run out.
|
||||
pub(crate) fn place_row(row: &dyn Fn(f64) -> Vec<Rect>, start: f64, obstacles: &[Rect]) -> Option<f64> {
|
||||
// Each box's objects: those level with it, by their left edges. The row only moves right, so
|
||||
// each object joins its box's list once, when the box's right edge passes its left edge, and
|
||||
// stays: of those joined, only the rightmost right edge matters, and the box meets that object
|
||||
// exactly when the edge is right of the box's left edge.
|
||||
let lanes: Vec<Vec<Rect>> = row(start)
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut lane: Vec<Rect> = obstacles.iter().filter(|o| o.y0 < b.y1 && b.y0 < o.y1).copied().collect();
|
||||
lane.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
lane
|
||||
})
|
||||
.collect();
|
||||
let mut joined = vec![0usize; lanes.len()];
|
||||
let mut reach = vec![f64::NEG_INFINITY; lanes.len()];
|
||||
let mut x0 = start;
|
||||
// Each move takes a box past every object joined to it, so another move of that box needs a
|
||||
// new object to join.
|
||||
for _ in 0..=lanes.iter().map(Vec::len).sum::<usize>() {
|
||||
let mut shift = None;
|
||||
for ((r, lane), (j, far)) in row(x0).iter().zip(&lanes).zip(joined.iter_mut().zip(reach.iter_mut())) {
|
||||
while let Some(o) = lane.get(*j).filter(|o| o.x0 < r.x1) {
|
||||
#[cfg(test)]
|
||||
LOOKS.with(|n| n.set(n.get() + 1));
|
||||
*far = far.max(o.x1);
|
||||
*j += 1;
|
||||
}
|
||||
// The first box in the way, moved past the rightmost object it meets.
|
||||
if shift.is_none() && *far > r.x0 {
|
||||
shift = Some(*far + GAP - r.x0);
|
||||
}
|
||||
}
|
||||
match shift {
|
||||
None => return Some(x0),
|
||||
Some(by) => x0 += by,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "conceptVector.providers",
|
||||
"Concept to Vector Providers",
|
||||
[],
|
||||
None,
|
||||
"{} → {providers: [{id, name, available, offline, imageInput, vectorOutput, prompt, rasterOutput, maxStyles: 8, styles: [{id, label}]}], selected: the id the panel uses} the providers conceptVector.generate can call by id; the built-in offline.traceStyles makes its styles with Image Trace on this computer (outline, inkLines, flatColor, detailedColor, grayTones), takes no prompt and makes vector art only",
|
||||
always,
|
||||
providers
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.generate",
|
||||
"Generate Concept to Vector Styles",
|
||||
[],
|
||||
None,
|
||||
"{id?: image or unexpanded Image Trace object (default: the one selected object), provider: id (conceptVector.providers; no other provider is used in its place), styles: [style id…] (1 to 8 different ids of that provider), detail?: 0-100 (50: how much of the image's detail each style keeps), prompt?: text (an error for a provider without prompts unless empty), output?: \"vector\" (the only output; any other value is an error)} one variation of the image for each style, kept by this session as a job and not put in the document; a provider that takes no image, makes no vector art or takes no prompt when one is given is refused with that reason; an object that is locked or hidden, itself or by a layer or group around it, or on a locked artboard, is refused → {job, provider, source: id, state: \"done\", variations: [{style, label, paths, anchors, bounds: [x0,y0,x1,y1] in the image's pixels, warnings: [text…]}]}",
|
||||
has_doc,
|
||||
generate
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.results",
|
||||
"Concept to Vector Results",
|
||||
[],
|
||||
None,
|
||||
"{job} a job conceptVector.generate made, as it returned it, or with state \"canceled\" and no variations; the session keeps the 4 newest jobs, until their document closes → {job, provider, source, state, variations}",
|
||||
has_doc,
|
||||
results
|
||||
),
|
||||
cmd!(
|
||||
query "conceptVector.cancel",
|
||||
"Cancel Concept to Vector Job",
|
||||
[],
|
||||
None,
|
||||
"{job} drop a job's variations, so that it can't be inserted; canceling it again does the same; an error when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved → {job, state: \"canceled\"}",
|
||||
has_doc,
|
||||
cancel
|
||||
),
|
||||
cmd!(
|
||||
"conceptVector.insert",
|
||||
"Insert Concept to Vector Styles",
|
||||
[],
|
||||
None,
|
||||
"{job, variations: [style id…] (different styles of the job)} put a group of each chosen variation, named after its style and in the provider's order, in a row to the right of the job's image, each the image's size with 24 pt between them, moved further right past other visible art in their way, where a variation reaches past its box too (the next one then starts 24 pt past what it paints); the groups go above the outermost clip group or opacity-masked group around the image, and above the outermost envelope, blend, repeat or other live object, the outermost group whose members it makes or places (a graph, an Objects on Path, Shaper, dimension, flare or Live Paint group, a compound shape) and the outermost group with effects or fills and strokes of its own around it; the image and other art stay as they are; one undo step; a variation with no paths is left out, and when every chosen one has none nothing changes (no undo step, ids []); an error when the job's document is not the active one, the object, its image or its placement changed, the object is now locked or hidden, or it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or it or a group around it has effects that move or reshape it, or its image is distorted (Perspective Distort or Free Distort), and when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved →{ids: the groups, selected}",
|
||||
has_doc,
|
||||
insert
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -33,6 +33,6 @@ mod smooth;
|
||||
|
||||
pub(super) use anchors::{following_anchors, remove_anchors_of};
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
|
||||
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
pub(super) use freehand::freehand_brushed;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound};
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, with_anchor_path, within_input_bound};
|
||||
use super::{
|
||||
Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2,
|
||||
add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or,
|
||||
@@ -111,6 +111,24 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let curvature = switch_or(p, "curvature", false, C)?;
|
||||
let removed = s.edit("Delete Anchor Point", |d, sel| {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
// Type on a path keeps its path: the anchor goes only while two or more stay.
|
||||
with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
if curvature {
|
||||
vectorcraft_tools::draw2::curvature_remove(sp, ai);
|
||||
} else {
|
||||
po::remove_anchors(sp, &[ai]);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
return Ok(false);
|
||||
}
|
||||
let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
@@ -254,23 +272,24 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
s.edit("Convert Anchor Point", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if smooth && target.is_none() {
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if smooth && target.is_none() {
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
// Without a handle position the anchor curves as the Curvature tool curves a point; one
|
||||
// with no direction to take stays as it is.
|
||||
vectorcraft_tools::draw2::curvature_smooth(sp, ai);
|
||||
return Ok(());
|
||||
}
|
||||
// Without a handle position the anchor curves as the Curvature tool curves a point; one
|
||||
// with no direction to take stays as it is.
|
||||
vectorcraft_tools::draw2::curvature_smooth(sp, ai);
|
||||
return Ok(());
|
||||
}
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
match target {
|
||||
Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t),
|
||||
_ => a.retract(),
|
||||
}
|
||||
Ok(())
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
match target {
|
||||
Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t),
|
||||
_ => a.retract(),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -287,13 +306,14 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let perpendicular = switch_or(p, "perpendicular", false, C)?;
|
||||
s.edit("Reshape", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) };
|
||||
if !bent {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(())
|
||||
with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) };
|
||||
if !bent {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points)",
|
||||
"{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least",
|
||||
has_doc,
|
||||
remove_anchor
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)",
|
||||
"{id (a path, or type on a path), subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)",
|
||||
has_doc,
|
||||
convert_anchor
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reshape Segment",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does",
|
||||
"{id (a path, or type on a path), subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does",
|
||||
has_doc,
|
||||
reshape_segment
|
||||
),
|
||||
|
||||
@@ -308,6 +308,29 @@ pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` on the anchors the anchor tools edit on `id` ([`Node::anchor_path`]): a path's, as
|
||||
/// [`path_mut`] gives them, or type on a path's path in document space. The type keeps the edited
|
||||
/// path and lays out again; an edit that leaves a subpath with fewer than two anchors, or a path
|
||||
/// that is not finite or reaches past the canvas, is an error and changes nothing.
|
||||
pub(in super::super) fn with_anchor_path<R>(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result<R>) -> Result<R> {
|
||||
if !matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
return f(path_mut(d, id)?);
|
||||
}
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut path = n.anchor_path().map(std::borrow::Cow::into_owned).ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?;
|
||||
let r = f(&mut path)?;
|
||||
let within = path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD));
|
||||
if path.subpaths.is_empty() || path.subpaths.iter().any(|sp| sp.anchors.len() < 2) || !within {
|
||||
return Err(EngineError::Other(format!("type on a path keeps at least two anchors on its path, within the canvas (object {id})")));
|
||||
}
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::NoNode(id)) };
|
||||
if !t.set_type_path(&path) {
|
||||
return Err(EngineError::Other(format!("the path of object {id} would not be finite")));
|
||||
}
|
||||
crate::cmd::typecmd::refresh_bounds(t);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> {
|
||||
match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)),
|
||||
|
||||
@@ -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")))]
|
||||
|
||||
@@ -289,6 +289,31 @@ thread_local! {
|
||||
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn regular_write_target(path: &str) -> Result<()> {
|
||||
if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
@@ -299,27 +324,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 +781,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
|
||||
|
||||
@@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The active artboard the app passes, for the steps that act on it.
|
||||
let artboard = p.get("artboard").and_then(Value::as_u64);
|
||||
// What an error rolls back besides the documents: session-level state a step may change
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group, the
|
||||
// Concept to Vector jobs).
|
||||
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
|
||||
// would otherwise run inside it and take its baseline as theirs (#1697).
|
||||
if s.active().is_some() && !s.previewing {
|
||||
@@ -24,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
let (clipboard_copied, copies) = (s.clipboard_copied, s.copies);
|
||||
let concept_jobs = s.concept_jobs_snapshot();
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
@@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(results) => {
|
||||
s.notify_text_tool("batch.end");
|
||||
s.batch_steps = Some(grouped);
|
||||
s.prune_concept_jobs();
|
||||
results
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -59,6 +62,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
(s.clipboard_copied, s.copies) = (clipboard_copied, copies);
|
||||
s.pending_paint = None;
|
||||
s.restore_concept_jobs(concept_jobs);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,10 +308,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool {
|
||||
|
||||
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
|
||||
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
|
||||
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
|
||||
/// type as text?
|
||||
/// trim boxes by default, with its type as text?
|
||||
fn reads_layers_alone(opts: &LoadOptions) -> bool {
|
||||
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
reads_editing_copy(opts)
|
||||
&& !opts.explicit_crop_box
|
||||
&& opts.crop == vectorcraft_pdf::CropTo::Crop
|
||||
&& opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
|
||||
@@ -475,8 +477,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// The file is read and checked once, for the document it carries, its pages, the
|
||||
// editor's copy and its File Info.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
|
||||
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
|
||||
let editing = (opts.pages.is_none() && opts.native)
|
||||
// Restore the preserved document when opening all pages at their original size.
|
||||
let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box)
|
||||
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
|
||||
.flatten()
|
||||
.map(|e| (e.intact, move || Some(e.data)));
|
||||
@@ -524,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let alone = (r.only_text || empty)
|
||||
let alone = (!opts.explicit_crop_box && (r.only_text || empty))
|
||||
.then(copy_alone)
|
||||
.flatten()
|
||||
.and_then(|read| read.ok())
|
||||
|
||||
@@ -173,7 +173,13 @@ impl LoadOptions {
|
||||
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
|
||||
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
|
||||
pub fn is_partial(&self) -> bool {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
self.pages.is_some()
|
||||
|| self.crop != CropTo::default()
|
||||
|| self.explicit_crop_box
|
||||
|| self.password.is_some()
|
||||
|| !self.layers
|
||||
|| !self.native
|
||||
|| self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
|
||||
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
|
||||
/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box.
|
||||
#[test]
|
||||
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
|
||||
@@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
|
||||
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
|
||||
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap();
|
||||
let cropped = &s.doc().unwrap().doc;
|
||||
assert!(cropped.artboards[0].rect.width() > board.width());
|
||||
let placed = &cropped.layers[0].children().unwrap()[0];
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one is an error",
|
||||
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one, or the one an open Create Font Sheet dialog uses, is an error",
|
||||
has_doc,
|
||||
artboard_delete
|
||||
),
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Empty Artboards",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)",
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go); an error, with nothing deleted, when one of them is the artboard an open Create Font Sheet dialog uses → {deleted: [index…]} (the indices before deleting)",
|
||||
has_empty_artboards,
|
||||
artboard_delete_empty
|
||||
),
|
||||
@@ -1225,11 +1225,25 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?;
|
||||
refuse_guarded(s, &indices)?;
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The session's artboard deletion guard's message when deleting artboards `indices` of the
|
||||
/// active document would delete the artboard it protects.
|
||||
pub(crate) fn refuse_guarded(s: &Session, indices: &[usize]) -> Result<()> {
|
||||
let Some(guard) = &s.artboard_deletion_guard else { return Ok(()) };
|
||||
let state = s.doc()?;
|
||||
if (state.uid, state.reverts) == guard.document
|
||||
&& indices.iter().any(|&index| state.doc.artboards.get(index).is_some_and(|a| a.id == guard.artboard))
|
||||
{
|
||||
return Err(EngineError::Other(guard.message.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be
|
||||
/// left. The other artboards keep their order, no later artboard takes a deleted one's id, and
|
||||
/// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides,
|
||||
@@ -1306,6 +1320,7 @@ fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if indices.is_empty() {
|
||||
return Err(EngineError::Other("no empty artboards to delete".into()));
|
||||
}
|
||||
refuse_guarded(s, &indices)?;
|
||||
s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
Ok(json!({ "deleted": indices }))
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, or a locked one; 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); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -366,6 +366,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
|
||||
return Err(EngineError::Other("a document needs at least one artboard".into()));
|
||||
}
|
||||
if cut {
|
||||
super::layer::refuse_guarded(s, &indices)?;
|
||||
refuse_locked(&st.doc, &indices)?;
|
||||
}
|
||||
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
"{id (a path, or type on a path), subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
|
||||
"{id (a path, or type on a path), subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
|
||||
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)",
|
||||
has_doc,
|
||||
insert_anchor
|
||||
),
|
||||
@@ -719,39 +719,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let old_point = a.p;
|
||||
let old_handle = if out { a.h_out } else { a.h_in };
|
||||
if let Some(to) = at {
|
||||
a.translate(to - a.p);
|
||||
}
|
||||
let handle = if out { a.h_out } else { a.h_in };
|
||||
let kind_changes = independent && a.kind != AnchorKind::Corner;
|
||||
// Ordinary decimal moves can round `at - old_point` differently from the handle's
|
||||
// translation. Within that calculation's roundoff, place the selected point exactly
|
||||
// without realigning the other stored Smooth handle. Real edits still use set_handle.
|
||||
let translation_roundoff = at.is_some_and(|to| {
|
||||
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
|
||||
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
|
||||
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
|
||||
};
|
||||
to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
|
||||
});
|
||||
if !kind_changes && (handle == pos || translation_roundoff) {
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
super::draw2::with_anchor_path(d, id, |path| {
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let old_point = a.p;
|
||||
let old_handle = if out { a.h_out } else { a.h_in };
|
||||
if let Some(to) = at {
|
||||
a.translate(to - a.p);
|
||||
}
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (pos - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
Ok(())
|
||||
let handle = if out { a.h_out } else { a.h_in };
|
||||
let kind_changes = independent && a.kind != AnchorKind::Corner;
|
||||
// Ordinary decimal moves can round `at - old_point` differently from the handle's
|
||||
// translation. Within that calculation's roundoff, place the selected point exactly
|
||||
// without realigning the other stored Smooth handle. Real edits still use set_handle.
|
||||
let translation_roundoff = at.is_some_and(|to| {
|
||||
let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| {
|
||||
let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0);
|
||||
(actual - requested).abs() <= 4.0 * f64::EPSILON * scale
|
||||
};
|
||||
to != old_point
|
||||
&& matches(handle.x, pos.x, old_point.x, old_handle.x, to.x)
|
||||
&& matches(handle.y, pos.y, old_point.y, old_handle.y, to.y)
|
||||
});
|
||||
if !kind_changes && (handle == pos || translation_roundoff) {
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
}
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (pos - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -852,22 +855,26 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| {
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
|
||||
let unchanged = s.doc()?.doc.node(id).and_then(Node::anchor_path).is_some_and(|pd| {
|
||||
pd.subpaths.get(si).is_some_and(|sp| {
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos))
|
||||
})
|
||||
})
|
||||
});
|
||||
if unchanged {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let pull_out = sp.has_segment(ai, !out);
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.link_handle(out, pos, pull_out);
|
||||
Ok(())
|
||||
super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let pull_out = sp.has_segment(ai, !out);
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.link_handle(out, pos, pull_out);
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -958,6 +965,13 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Move", |d, sel| {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
return super::draw2::with_anchor_path(d, id, |path| {
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p);
|
||||
let before = corner_sources(d, id);
|
||||
let moved = BTreeSet::from([(si, ai)]);
|
||||
@@ -975,24 +989,25 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it.
|
||||
/// Busy while a script runs, as [`Session::edit`] is.
|
||||
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path, or type
|
||||
/// on a path ([`Node::anchor_path`], in document space), that has it. Busy while a script runs, as
|
||||
/// [`Session::edit`] is.
|
||||
fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anchor>> {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
|
||||
Ok(d.node(id).and_then(Node::anchor_path).and_then(|path| path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).copied()))
|
||||
}
|
||||
|
||||
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
|
||||
/// incoming side; false when the path, subpath or anchor is not there.
|
||||
/// Whether anchor `ai` of subpath `si` of path `id` (or of type on a path's path) has a segment on
|
||||
/// its outgoing (`out`) or incoming side; false when the path, subpath or anchor is not there.
|
||||
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
|
||||
Ok(d.node(id).and_then(Node::anchor_path).is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, out))))
|
||||
}
|
||||
|
||||
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -2614,12 +2629,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
|
||||
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
|
||||
let idx = s.edit("Add Anchor Point", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
let idx = super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(sp.insert_anchor(seg, t))
|
||||
})?;
|
||||
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
|
||||
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
if select_anchor || !sel.contains(id) {
|
||||
sel.clear();
|
||||
}
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
if sel.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
sel.key_anchor = None;
|
||||
}
|
||||
sel.add(id);
|
||||
return Ok(idx);
|
||||
}
|
||||
let idx = sp.insert_anchor(seg, t);
|
||||
renumber_after_insert(sel, id, si, idx);
|
||||
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
|
||||
// the point added shows and can be edited at once (#4237). `selectAnchor` does the same
|
||||
|
||||
@@ -895,6 +895,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
|
||||
(&["Object"], "Perspective"),
|
||||
(&["Object"], "Live Paint"),
|
||||
(&["Object"], "Image Trace"),
|
||||
(&["Object"], "Concept to Vector…"),
|
||||
(&["Object"], "Text Wrap"),
|
||||
(&["Object"], "Clipping Mask"),
|
||||
(&["Object"], "Compound Path"),
|
||||
|
||||
@@ -762,13 +762,20 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
|
||||
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
|
||||
/// report where it is on disk, edit text once per match with no limit on the matches in one call,
|
||||
/// or hand an image to a Concept to Vector provider and its results.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
"addon.pen.nextSegment",
|
||||
"addon.type.fontSheet",
|
||||
"addon.type.numbers",
|
||||
"color.contrast",
|
||||
"conceptVector.cancel",
|
||||
"conceptVector.generate",
|
||||
"conceptVector.insert",
|
||||
"conceptVector.providers",
|
||||
"conceptVector.results",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
"object.blend.createSpine",
|
||||
|
||||
@@ -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,81 @@ 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.
|
||||
fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if asked > 0.0 { asked } else { doc.raster_effects_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 +161,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;
|
||||
|
||||
@@ -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); 39] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -70,6 +70,7 @@ const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
("artboard.distribute", "activeArtboard"),
|
||||
("artboard.distributeSpacing", "selectedArtboards"),
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Concept to Vector providers: what makes vector variations of a selected image.
|
||||
//!
|
||||
//! A provider ([`Provider`]) takes one image's encoded pixels and up to [`MAX_STYLES`] of its own
|
||||
//! style ids ([`Request`]), and returns one [`Variation`] per style, in the order asked, as paths
|
||||
//! in the image's pixel space with explicit paints. It sees nothing else of the session or the
|
||||
//! document. The session keeps the providers in a [`Registry`] and calls one only by its id: an
|
||||
//! unknown or incapable provider is an error, never a substitute.
|
||||
//!
|
||||
//! The host checks every result again ([`check_result`]) before it keeps it, whatever provider
|
||||
//! made it: the number and order of the variations, finite coordinates and widths within bounds,
|
||||
//! and the totals [`MAX_ANCHORS`] and [`MAX_PATHS`] across all styles.
|
||||
//!
|
||||
//! The one built-in provider ([`offline::ID`]) makes its styles with Image Trace, on this
|
||||
//! computer: it takes no prompt and makes vector art only.
|
||||
|
||||
pub mod offline;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
/// The most styles one request may ask for.
|
||||
pub const MAX_STYLES: usize = 8;
|
||||
|
||||
/// The most anchor points all the variations of one request may hold together.
|
||||
pub const MAX_ANCHORS: usize = 1_000_000;
|
||||
|
||||
/// The most paths all the variations of one request may hold together, each subpath of a compound
|
||||
/// path counted as one.
|
||||
pub const MAX_PATHS: usize = 250_000;
|
||||
|
||||
/// The most warnings a variation may carry, and the most characters in each.
|
||||
pub const MAX_WARNINGS: usize = 16;
|
||||
const MAX_WARNING_CHARS: usize = 500;
|
||||
|
||||
/// One of a provider's styles: its stable id and its English name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct Style {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
/// What a provider takes and makes.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Capabilities {
|
||||
/// It takes an image as its input.
|
||||
pub image_input: bool,
|
||||
/// It makes editable vector paths.
|
||||
pub vector_output: bool,
|
||||
/// It takes a text prompt.
|
||||
pub prompt: bool,
|
||||
/// It makes raster images.
|
||||
pub raster_output: bool,
|
||||
/// It runs on this computer without a network.
|
||||
pub offline: bool,
|
||||
/// Its styles, in the order it lists them.
|
||||
pub styles: Vec<Style>,
|
||||
}
|
||||
|
||||
/// The kind of result a request asks for. `conceptVector.generate` asks only for
|
||||
/// [`Output::Vector`]: a [`Variation`] holds vector paths.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Output {
|
||||
Vector,
|
||||
Raster,
|
||||
}
|
||||
|
||||
/// One request: the encoded pixels of an image, and how to make its variations.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Request {
|
||||
/// The image's encoded bytes (PNG, JPEG, WebP or GIF), as the document holds them.
|
||||
pub image: Arc<Vec<u8>>,
|
||||
/// The image's size in pixels: the space the variations' paths are in.
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The prompt, trimmed; `None` when there is none.
|
||||
pub prompt: Option<String>,
|
||||
/// The provider's style ids, 1 to [`MAX_STYLES`] of them, each once.
|
||||
pub styles: Vec<String>,
|
||||
/// How much of the image's detail to keep, 0 (least) to 100 (most).
|
||||
pub detail: u8,
|
||||
pub output: Output,
|
||||
}
|
||||
|
||||
/// One path of a variation, in the image's pixel space (`(0, 0)` top left, `(width, height)` bottom
|
||||
/// right).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VectorPath {
|
||||
pub path: PathData,
|
||||
/// The fill color (sRGB), if it is filled.
|
||||
pub fill: Option<[u8; 3]>,
|
||||
/// The stroke color (sRGB) and width in pixels, if it is stroked.
|
||||
pub stroke: Option<([u8; 3], f64)>,
|
||||
/// Stroked: the stroke's ends are square (cut straight half the width past the path's end);
|
||||
/// otherwise round.
|
||||
pub square_caps: bool,
|
||||
}
|
||||
|
||||
/// The variation a provider made for one style.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Variation {
|
||||
/// The style id it was made for.
|
||||
pub style: String,
|
||||
/// Its paths, bottom-most first.
|
||||
pub paths: Vec<VectorPath>,
|
||||
/// Notes for the person who asked (a scaled-down image, nothing traced).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
/// Its anchor points, every path counted.
|
||||
pub fn anchors(&self) -> usize {
|
||||
self.paths.iter().map(|p| p.path.anchor_count()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a provider made nothing.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
pub enum ProviderError {
|
||||
/// The image or the request cannot be used.
|
||||
#[error("{0}")]
|
||||
InvalidInput(String),
|
||||
/// The provider does not do what the request asks.
|
||||
#[error("{0}")]
|
||||
Unsupported(String),
|
||||
/// The provider cannot run now.
|
||||
#[error("{0}")]
|
||||
Unavailable(String),
|
||||
/// The caller stopped it.
|
||||
#[error("cancelled; nothing was changed")]
|
||||
Canceled,
|
||||
/// The results would pass a limit.
|
||||
#[error("the results would have more than {0} anchor points: lower Detail or choose fewer styles")]
|
||||
ResourceLimit(usize),
|
||||
/// The provider's results do not match the request, or are out of bounds.
|
||||
#[error("the provider's results do not match the request or are malformed")]
|
||||
InvalidResult,
|
||||
/// The provider stopped on a fault of its own.
|
||||
#[error("the provider stopped with an internal error: {0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
/// How far a provider has got: `steps(done, total)`; it stops with [`ProviderError::Canceled`]
|
||||
/// once this answers `false`.
|
||||
pub type Steps<'a> = &'a (dyn Fn(u64, u64) -> bool + Sync);
|
||||
|
||||
/// Something that makes vector variations of an image.
|
||||
pub trait Provider: Send + Sync {
|
||||
/// Its stable id, such as `offline.traceStyles`.
|
||||
fn id(&self) -> &'static str;
|
||||
/// Its English name.
|
||||
fn name(&self) -> &'static str;
|
||||
fn capabilities(&self) -> Capabilities;
|
||||
/// One variation for each of `request.styles`, in that order. A style's variation depends only
|
||||
/// on the image, the prompt, the detail and that style, not on the other styles asked for: a
|
||||
/// caller with no thread to wait on asks for one style at a time when [`Provider::parts`] gives
|
||||
/// `None` (`ConceptRun::run_part`, which the web build uses).
|
||||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError>;
|
||||
/// What [`Provider::generate`] makes, made a part at a time ([`Parts`]), for a caller with no
|
||||
/// thread to wait on; `None` (the default) when it makes no parts smaller than one style.
|
||||
fn parts(&self, _request: &Request) -> Option<Box<dyn Parts>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A request's variations made a part at a time: each call of [`Parts::step`] does a part and
|
||||
/// returns, so that the caller can run other work, or stop, between parts.
|
||||
pub trait Parts: Send {
|
||||
/// Does the next part → the variations once the last part is done, `None` before it.
|
||||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError>;
|
||||
/// The styles made so far.
|
||||
fn styles_done(&self) -> usize;
|
||||
}
|
||||
|
||||
/// The providers a session can call, by id.
|
||||
#[derive(Clone)]
|
||||
pub struct Registry {
|
||||
providers: Vec<Registered>,
|
||||
}
|
||||
|
||||
/// A provider in a [`Registry`], with the id, name and capabilities it gave when it was
|
||||
/// registered.
|
||||
#[derive(Clone)]
|
||||
pub struct Registered {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
pub capabilities: Capabilities,
|
||||
pub provider: Arc<dyn Provider>,
|
||||
}
|
||||
|
||||
impl Default for Registry {
|
||||
/// The built-in provider only.
|
||||
fn default() -> Self {
|
||||
let p = offline::TraceStyles;
|
||||
Self { providers: vec![Registered { id: p.id(), name: p.name(), capabilities: p.capabilities(), provider: Arc::new(p) }] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// A registry with no provider.
|
||||
pub fn empty() -> Self {
|
||||
Self { providers: vec![] }
|
||||
}
|
||||
|
||||
/// Add `provider`, reading its id, name and capabilities once; an error when one with its id
|
||||
/// is registered already, or when the provider panics while giving them.
|
||||
pub fn register(&mut self, provider: Arc<dyn Provider>) -> Result<(), String> {
|
||||
let (id, name, capabilities) = crate::guard::catch_panic(|| (provider.id(), provider.name(), provider.capabilities()))
|
||||
.map_err(|e| ProviderError::Internal(e).to_string())?;
|
||||
if self.get(id).is_some() {
|
||||
return Err(format!("a provider with the id `{id}` is registered already"));
|
||||
}
|
||||
self.providers.push(Registered { id, name, capabilities, provider });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The provider `id` (exactly so spelled).
|
||||
pub fn get(&self, id: &str) -> Option<&Registered> {
|
||||
self.providers.iter().find(|p| p.id == id)
|
||||
}
|
||||
|
||||
/// The providers in the order they were registered.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Registered> {
|
||||
self.providers.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` is a finite point within `limit` of the image's pixel space.
|
||||
fn within(p: Point, limit: f64, size: (f64, f64)) -> bool {
|
||||
p.x.is_finite() && p.y.is_finite() && p.x >= -limit && p.y >= -limit && p.x <= size.0 + limit && p.y <= size.1 + limit
|
||||
}
|
||||
|
||||
/// Checks the variations a provider returned for `request`: one per style in the order asked, at
|
||||
/// most [`MAX_PATHS`] paths (each subpath of a compound path counted as one) and [`MAX_ANCHORS`]
|
||||
/// anchors together, each path with a fill or a stroke and with subpaths that each have an anchor,
|
||||
/// every anchor and handle finite and within one image side of the image, every
|
||||
/// stroke width finite, over 0 and at most the image's larger side, and at most [`MAX_WARNINGS`]
|
||||
/// warnings of at most 500 characters on each variation.
|
||||
pub fn check_result(request: &Request, variations: &[Variation]) -> Result<(), ProviderError> {
|
||||
if variations.len() != request.styles.len() || variations.iter().zip(&request.styles).any(|(v, s)| v.style != *s) {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
let size = (f64::from(request.width.max(1)), f64::from(request.height.max(1)));
|
||||
let side = size.0.max(size.1);
|
||||
let (mut paths, mut anchors) = (0usize, 0usize);
|
||||
for v in variations {
|
||||
// Each subpath of a compound path becomes an object of its own when it is inserted.
|
||||
paths = v.paths.iter().fold(paths, |n, p| n.saturating_add(p.path.subpaths.len().max(1)));
|
||||
anchors += v.anchors();
|
||||
if anchors > MAX_ANCHORS {
|
||||
return Err(ProviderError::ResourceLimit(MAX_ANCHORS));
|
||||
}
|
||||
if paths > MAX_PATHS || v.warnings.len() > MAX_WARNINGS || v.warnings.iter().any(|w| w.chars().count() > MAX_WARNING_CHARS) {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
for p in &v.paths {
|
||||
let width_ok = p.stroke.is_none_or(|(_, w)| w.is_finite() && w > 0.0 && w <= side);
|
||||
let painted = p.fill.is_some() || p.stroke.is_some();
|
||||
let points_ok = p.path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].into_iter().all(|q| within(q, side, size)));
|
||||
let no_empty_subpath = !p.path.subpaths.is_empty() && p.path.subpaths.iter().all(|sp| !sp.anchors.is_empty());
|
||||
if !width_ok || !painted || !no_empty_subpath || !points_ok {
|
||||
return Err(ProviderError::InvalidResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
//! The built-in provider: Concept to Vector styles made with Image Trace on this computer.
|
||||
//!
|
||||
//! Each style is a fixed set of Image Trace settings of VectorCraft's own, and Detail (0 to 100)
|
||||
//! moves its Paths, Noise and color count within that style's range. The image is decoded once and
|
||||
//! traced once per style; an image over [`MAX_PIXELS`] is scaled down first, aspect kept, and
|
||||
//! each variation says so. The paths are mapped back to the image's own pixel size.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::kurbo::common::solve_cubic;
|
||||
use vectorcraft_geom::{Affine, Anchor, CubicBez, ParamCurve, PathData, Point, SubPath};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
use super::{Capabilities, MAX_ANCHORS, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath};
|
||||
|
||||
/// The built-in provider's id.
|
||||
pub const ID: &str = "offline.traceStyles";
|
||||
|
||||
/// The most pixels the built-in provider traces an image at (16 megapixels).
|
||||
pub const MAX_PIXELS: u64 = 16 << 20;
|
||||
|
||||
/// The built-in provider's styles, in the order it lists them.
|
||||
pub const STYLES: [Style; 5] = [
|
||||
Style { id: "outline", label: "Outline" },
|
||||
Style { id: "inkLines", label: "Ink Lines" },
|
||||
Style { id: "flatColor", label: "Flat Color" },
|
||||
Style { id: "detailedColor", label: "Detailed Color" },
|
||||
Style { id: "grayTones", label: "Gray Tones" },
|
||||
];
|
||||
|
||||
/// Concept to Vector styles made with Image Trace ([`ID`]).
|
||||
pub struct TraceStyles;
|
||||
|
||||
/// `lo` at Detail 0 to `hi` at Detail 100.
|
||||
fn between(lo: f64, hi: f64, t: f64) -> f64 {
|
||||
lo + (hi - lo) * t
|
||||
}
|
||||
|
||||
/// The trace settings of style `id` at Detail `detail` (0 to 100); `None` for an id that isn't one
|
||||
/// of [`STYLES`].
|
||||
pub fn style_params(id: &str, detail: u8) -> Option<tr::TraceParams> {
|
||||
let t = f64::from(detail.min(100)) / 100.0;
|
||||
let noise = |lo: f64, hi: f64| between(hi, lo, t).round().max(1.0) as u32;
|
||||
let count = |lo: f64, hi: f64| between(lo, hi, t).round() as u32;
|
||||
let base = tr::TraceParams { shapes: false, gradients: false, auto_grouping: false, ..tr::TraceParams::default() };
|
||||
Some(match id {
|
||||
// Black stroked lines only: thin lines as center lines, wider areas as outlines.
|
||||
"outline" => {
|
||||
tr::TraceParams { fills: false, strokes: true, ignore_white: true, paths: between(50.0, 90.0, t), noise: noise(4.0, 40.0), ..base }
|
||||
}
|
||||
// Black filled ink on no background, the straight runs straightened.
|
||||
"inkLines" => tr::TraceParams {
|
||||
ignore_white: true,
|
||||
snap_curves_to_lines: true,
|
||||
paths: between(50.0, 95.0, t),
|
||||
corners: 80.0,
|
||||
noise: noise(4.0, 30.0),
|
||||
..base
|
||||
},
|
||||
// A few flat colors, abutting.
|
||||
"flatColor" => tr::TraceParams {
|
||||
mode: tr::Mode::Color,
|
||||
colors: count(3.0, 8.0),
|
||||
paths: between(40.0, 80.0, t),
|
||||
corners: 60.0,
|
||||
noise: noise(8.0, 40.0),
|
||||
snap_curves_to_lines: true,
|
||||
..base
|
||||
},
|
||||
// Many colors, stacked so no hairline gaps show.
|
||||
"detailedColor" => tr::TraceParams {
|
||||
mode: tr::Mode::Color,
|
||||
colors: count(12.0, 32.0),
|
||||
paths: between(70.0, 95.0, t),
|
||||
corners: 40.0,
|
||||
noise: noise(2.0, 12.0),
|
||||
method: tr::Method::Overlapping,
|
||||
..base
|
||||
},
|
||||
// Grays, stacked.
|
||||
"grayTones" => tr::TraceParams {
|
||||
mode: tr::Mode::Grayscale,
|
||||
colors: count(4.0, 12.0),
|
||||
paths: between(55.0, 90.0, t),
|
||||
corners: 50.0,
|
||||
noise: noise(4.0, 20.0),
|
||||
method: tr::Method::Overlapping,
|
||||
..base
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `img` box-filtered down to at most [`MAX_PIXELS`], aspect kept; `img` itself when it fits.
|
||||
fn fit(img: tr::Raster) -> tr::Raster {
|
||||
fit_within(img, MAX_PIXELS)
|
||||
}
|
||||
|
||||
/// `img` box-filtered down to at most `max` pixels (at least 1), aspect kept as far as a side of
|
||||
/// at least one pixel allows; `img` itself when it fits.
|
||||
pub(super) fn fit_within(img: tr::Raster, max: u64) -> tr::Raster {
|
||||
let (w, h) = (u64::from(img.width), u64::from(img.height));
|
||||
let max = max.max(1);
|
||||
if w * h <= max || w == 0 || h == 0 {
|
||||
return img;
|
||||
}
|
||||
let k = (max as f64 / (w * h) as f64).sqrt();
|
||||
// A side that rounds down to one pixel leaves the other side the whole budget, no more.
|
||||
let nh = ((h as f64 * k).floor() as u64).clamp(1, h.min(max));
|
||||
let nw = ((w as f64 * k).floor() as u64).clamp(1, w.min(max / nh)) as u32;
|
||||
let nh = nh as u32;
|
||||
let mut rgba = Vec::with_capacity(nw as usize * nh as usize * 4);
|
||||
for y in 0..nh {
|
||||
let (y0, y1) = (u64::from(y) * h / u64::from(nh), (u64::from(y + 1) * h / u64::from(nh)).max(u64::from(y) * h / u64::from(nh) + 1));
|
||||
for x in 0..nw {
|
||||
let (x0, x1) = (u64::from(x) * w / u64::from(nw), (u64::from(x + 1) * w / u64::from(nw)).max(u64::from(x) * w / u64::from(nw) + 1));
|
||||
// Each pixel's color is weighted by its alpha. A box with nothing opaque in it is clear black.
|
||||
let mut sum = [0u64; 4];
|
||||
for sy in y0..y1.min(h) {
|
||||
for sx in x0..x1.min(w) {
|
||||
let [r, g, b, a] = img.pixel(sx as u32, sy as u32).map(u64::from);
|
||||
sum = [sum[0] + r * a, sum[1] + g * a, sum[2] + b * a, sum[3] + a];
|
||||
}
|
||||
}
|
||||
let n = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
|
||||
let alpha = sum[3];
|
||||
let color = |s: u64| s.checked_div(alpha).map_or(0, |c| c.min(255) as u8);
|
||||
rgba.extend([color(sum[0]), color(sum[1]), color(sum[2]), (alpha / n) as u8]);
|
||||
}
|
||||
}
|
||||
tr::Raster { width: nw, height: nh, rgba }
|
||||
}
|
||||
|
||||
impl super::Provider for TraceStyles {
|
||||
fn id(&self) -> &'static str {
|
||||
ID
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Offline Image Trace Styles"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles: STYLES.to_vec() }
|
||||
}
|
||||
|
||||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError> {
|
||||
let params = checked(request)?;
|
||||
let total = params.len() as u64;
|
||||
if !steps(0, total) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
let image = Decoded::new(request)?;
|
||||
let mut left = MAX_ANCHORS;
|
||||
let mut out = Vec::with_capacity(params.len());
|
||||
for (i, (style, p)) in request.styles.iter().zip(¶ms).enumerate() {
|
||||
let go_on = |_: u64, _: u64| steps(i as u64, total);
|
||||
let res = tr::trace_watched(&image.raster, p, left, &go_on).map_err(trace_error)?;
|
||||
left = left.saturating_sub(res.anchor_count());
|
||||
out.push(image.variation(style, p, res));
|
||||
}
|
||||
if !steps(total, total) {
|
||||
return Err(ProviderError::Canceled);
|
||||
}
|
||||
Ok(with_seams(out))
|
||||
}
|
||||
|
||||
/// The image decoded in the first part; then for each style, its color layers found in one
|
||||
/// part and each layer traced in a part of its own ([`tr::TraceSteps`]), or all of them in
|
||||
/// one part where the style stacks them (Overlapping with Fills).
|
||||
fn parts(&self, request: &Request) -> Option<Box<dyn Parts>> {
|
||||
Some(Box::new(TraceParts { request: request.clone(), image: None, trace: None, left: MAX_ANCHORS, out: vec![], ended: false }))
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace settings of each of `request`'s styles; an error for a prompt, an output other than
|
||||
/// vector art, or a style that isn't one of [`STYLES`]. The host refuses these first; a direct
|
||||
/// caller gets the same answer.
|
||||
fn checked(request: &Request) -> Result<Vec<tr::TraceParams>, ProviderError> {
|
||||
let pid = ID;
|
||||
if request.prompt.is_some() || request.output != Output::Vector {
|
||||
return Err(ProviderError::Unsupported(format!("`{pid}` takes no prompt and makes vector art only")));
|
||||
}
|
||||
request
|
||||
.styles
|
||||
.iter()
|
||||
.map(|s| style_params(s, request.detail))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| ProviderError::InvalidInput(format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")))
|
||||
}
|
||||
|
||||
fn trace_error(e: tr::TraceError) -> ProviderError {
|
||||
match e {
|
||||
tr::TraceError::Cancelled => ProviderError::Canceled,
|
||||
tr::TraceError::TooComplex { .. } => ProviderError::ResourceLimit(MAX_ANCHORS),
|
||||
e => ProviderError::InvalidInput(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A request's image decoded for tracing, with what maps its traced paths back.
|
||||
struct Decoded {
|
||||
raster: Arc<tr::Raster>,
|
||||
/// The decoded raster's pixels → the image's own pixel space.
|
||||
back: Affine,
|
||||
unit: f64,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Decoded {
|
||||
/// `request`'s image decoded, scaled down to at most [`MAX_PIXELS`].
|
||||
fn new(request: &Request) -> Result<Self, ProviderError> {
|
||||
let raster = fit(tr::Raster::decode_to_fit(&request.image).map_err(|e| ProviderError::InvalidInput(e.to_string()))?);
|
||||
let mut warnings = vec![];
|
||||
let (iw, ih) = (request.width.max(1), request.height.max(1));
|
||||
if u64::from(raster.width) * u64::from(raster.height) < u64::from(iw) * u64::from(ih) {
|
||||
warnings.push(format!("The image was traced at {} × {} pixels, scaled down from {iw} × {ih}.", raster.width, raster.height));
|
||||
}
|
||||
let back = Affine::scale_non_uniform(f64::from(iw) / f64::from(raster.width.max(1)), f64::from(ih) / f64::from(raster.height.max(1)));
|
||||
let unit = back.determinant().abs().sqrt();
|
||||
Ok(Self { raster: Arc::new(raster), back, unit, warnings })
|
||||
}
|
||||
|
||||
/// The variation of `style` that the trace `res` of this image, made with `params`, makes, and
|
||||
/// the seam fills of an Abutting trace with fills ([`tr::seam_fills`]) trimmed inside the
|
||||
/// image ([`within_image`]) and outlined in raster pixels before mapping them back, for
|
||||
/// [`with_seams`] to lay under its paths.
|
||||
fn variation(&self, style: &str, params: &tr::TraceParams, res: tr::TraceResult) -> Made {
|
||||
let size = (self.raster.width, self.raster.height);
|
||||
let seams = tr::seam_fills(&res.paths, params, size).map_or_else(Vec::new, |s| {
|
||||
s.strokes
|
||||
.into_iter()
|
||||
.map(|tp| {
|
||||
let mut tp = within_image(tp, size);
|
||||
if let Some(width) = tp.stroke.take() {
|
||||
tp.path = vectorcraft_pathops::outline_stroke(
|
||||
&tp.path,
|
||||
width,
|
||||
vectorcraft_pathops::Cap::Butt,
|
||||
vectorcraft_pathops::Join::Round,
|
||||
4.0,
|
||||
);
|
||||
}
|
||||
tp
|
||||
})
|
||||
.filter(|tp| !tp.path.subpaths.is_empty())
|
||||
.map(|tp| self.vector_path(tp))
|
||||
.collect()
|
||||
});
|
||||
let paths = res.paths.into_iter().map(|tp| self.vector_path(tp)).collect();
|
||||
Made { variation: Variation { style: style.to_string(), paths, warnings: self.warnings.clone() }, seams }
|
||||
}
|
||||
|
||||
/// Traced path `tp` in the image's own pixels.
|
||||
fn vector_path(&self, tp: tr::TracedPath) -> VectorPath {
|
||||
let path = tp.path.transformed(self.back);
|
||||
match tp.stroke {
|
||||
Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps },
|
||||
None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A variation made, and the outlined seam fills to lay under its paths.
|
||||
pub(super) struct Made {
|
||||
pub(super) variation: Variation,
|
||||
pub(super) seams: Vec<VectorPath>,
|
||||
}
|
||||
|
||||
/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`].
|
||||
fn with_seams(made: Vec<Made>) -> Vec<Variation> {
|
||||
with_seams_within(made, MAX_ANCHORS, MAX_PATHS)
|
||||
}
|
||||
|
||||
/// The variations `made`, each with its seam fills under its paths, in order, while they fit in
|
||||
/// the `max_anchors` anchors and `max_paths` paths (each subpath counted as one) left once every
|
||||
/// variation is counted: the traced paths of every style come first, and a style whose seam fills
|
||||
/// do not fit goes without them.
|
||||
pub(super) fn with_seams_within(made: Vec<Made>, max_anchors: usize, max_paths: usize) -> Vec<Variation> {
|
||||
let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::<usize>();
|
||||
let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::<usize>();
|
||||
let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::<usize>();
|
||||
made.into_iter()
|
||||
.map(|Made { mut variation, seams }| {
|
||||
let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::<usize>(), subpaths(&seams));
|
||||
if !seams.is_empty() && anchors.saturating_add(more_anchors) <= max_anchors && paths.saturating_add(more_paths) <= max_paths {
|
||||
anchors += more_anchors;
|
||||
paths += more_paths;
|
||||
variation.paths.splice(0..0, seams);
|
||||
}
|
||||
variation
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Seam stroke `tp` of a `size` raster trimmed to half its width inside the raster's border,
|
||||
/// so that its outline with butt caps and round joins stays inside the image. The pieces left form
|
||||
/// open runs; a closed subpath left whole stays closed.
|
||||
fn within_image(mut tp: tr::TracedPath, size: (u32, u32)) -> tr::TracedPath {
|
||||
let half = tp.stroke.unwrap_or_default() / 2.0;
|
||||
let (w, h) = (f64::from(size.0), f64::from(size.1));
|
||||
let mut runs: Vec<SubPath> = vec![];
|
||||
if !half.is_finite() || half < 0.0 || half * 2.0 > w || half * 2.0 > h {
|
||||
tp.path = PathData::new(runs);
|
||||
return tp;
|
||||
}
|
||||
let inside = |p: Point| p.x >= half && p.y >= half && p.x <= w - half && p.y <= h - half;
|
||||
let clamp = |p: Point| Point::new(p.x.clamp(half, w - half), p.y.clamp(half, h - half));
|
||||
for sp in &tp.path.subpaths {
|
||||
let count = sp.segment_count();
|
||||
let mut pieces = vec![];
|
||||
for k in 0..count {
|
||||
let c = sp.segment(k);
|
||||
let mut cuts = vec![0.0, 1.0];
|
||||
if ![c.p0, c.p1, c.p2, c.p3].into_iter().all(inside) {
|
||||
for (p0, p1, p2, p3, side) in [
|
||||
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, half),
|
||||
(c.p0.x, c.p1.x, c.p2.x, c.p3.x, w - half),
|
||||
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, half),
|
||||
(c.p0.y, c.p1.y, c.p2.y, c.p3.y, h - half),
|
||||
] {
|
||||
// Intersections with the sides' supporting lines also cover corner crossings.
|
||||
cuts.extend(
|
||||
solve_cubic(p0 - side, 3.0 * (p1 - p0), 3.0 * (p0 - 2.0 * p1 + p2), p3 - p0 + 3.0 * (p1 - p2))
|
||||
.into_iter()
|
||||
.filter(|&t| t > 0.0 && t < 1.0),
|
||||
);
|
||||
}
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
cuts.dedup();
|
||||
}
|
||||
for pair in cuts.windows(2) {
|
||||
let (t0, t1) = (pair[0], pair[1]);
|
||||
pieces.push((k, t0, t1, inside(c.eval(t0 + (t1 - t0) / 2.0))));
|
||||
}
|
||||
}
|
||||
if pieces.iter().all(|&(_, _, _, kept)| kept) {
|
||||
if count > 0 {
|
||||
runs.push(sp.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Start after a piece left out, so that a run across a closed subpath's first anchor
|
||||
// stays one run.
|
||||
let start = if sp.closed { pieces.iter().position(|&(_, _, _, kept)| !kept).map_or(0, |k| k + 1) } else { 0 };
|
||||
let mut run: Vec<Anchor> = vec![];
|
||||
for j in 0..pieces.len() {
|
||||
let (k, t0, t1, kept) = pieces[(start + j) % pieces.len()];
|
||||
if kept {
|
||||
let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % sp.anchors.len())) else { continue };
|
||||
let c = sp.segment(k);
|
||||
let mut c = if t0 == 0.0 && t1 == 1.0 { c } else { c.subsegment(t0..t1) };
|
||||
// Remove roundoff at the cut endpoints without constraining the curve's handles.
|
||||
c.p0 = clamp(c.p0);
|
||||
c.p3 = clamp(c.p3);
|
||||
if sp.segment_is_line(k) {
|
||||
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
|
||||
}
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = c.p1;
|
||||
} else {
|
||||
let a = if t0 == 0.0 { a } else { Anchor::corner(c.p0) };
|
||||
run.push(Anchor { p: c.p0, h_in: c.p0, h_out: c.p1, ..a });
|
||||
}
|
||||
let b = if t1 == 1.0 { b } else { Anchor::corner(c.p3) };
|
||||
run.push(Anchor { p: c.p3, h_in: c.p2, h_out: c.p3, ..b });
|
||||
} else if !run.is_empty() {
|
||||
runs.push(open_run(std::mem::take(&mut run)));
|
||||
}
|
||||
}
|
||||
if !run.is_empty() {
|
||||
runs.push(open_run(run));
|
||||
}
|
||||
}
|
||||
tp.path = PathData::new(runs);
|
||||
tp
|
||||
}
|
||||
|
||||
/// An open run of anchors: the last one has no handle out.
|
||||
fn open_run(mut run: Vec<Anchor>) -> SubPath {
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = last.p;
|
||||
}
|
||||
SubPath::new(run, false)
|
||||
}
|
||||
|
||||
/// [`TraceStyles`]' variations made a part at a time.
|
||||
struct TraceParts {
|
||||
request: Request,
|
||||
image: Option<Decoded>,
|
||||
/// The trace of the style after those in `out`, once started.
|
||||
trace: Option<tr::TraceSteps>,
|
||||
/// The anchor points the styles not made yet may have.
|
||||
left: usize,
|
||||
out: Vec<Made>,
|
||||
/// The variations or an error have been given.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
impl Parts for TraceParts {
|
||||
/// After the variations or an error, each call gives `None`.
|
||||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||||
if self.ended {
|
||||
return Ok(None);
|
||||
}
|
||||
let part = self.next_part();
|
||||
self.ended = !matches!(part, Ok(None));
|
||||
part
|
||||
}
|
||||
|
||||
fn styles_done(&self) -> usize {
|
||||
self.out.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl TraceParts {
|
||||
fn next_part(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||||
let Some(image) = &self.image else {
|
||||
checked(&self.request)?;
|
||||
self.image = Some(Decoded::new(&self.request)?);
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(with_seams(std::mem::take(&mut self.out)))) };
|
||||
let trace = match &mut self.trace {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||||
self.trace.insert(tr::TraceSteps::new(Arc::clone(&image.raster), params, self.left))
|
||||
}
|
||||
};
|
||||
let Some(res) = trace.step().map_err(trace_error)? else { return Ok(None) };
|
||||
self.trace = None;
|
||||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||||
self.left = self.left.saturating_sub(res.anchor_count());
|
||||
self.out.push(image.variation(style, ¶ms, res));
|
||||
if self.out.len() < self.request.styles.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(with_seams(std::mem::take(&mut self.out))))
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod cmd;
|
||||
pub mod concept_vector;
|
||||
pub mod file_access;
|
||||
pub mod guard;
|
||||
pub mod inspect;
|
||||
@@ -58,6 +59,12 @@ pub use vectorcraft_tools as tools;
|
||||
pub use vectorcraft_doc::MAX_COORD;
|
||||
const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap");
|
||||
|
||||
pub struct ArtboardDeletionGuard {
|
||||
pub document: (u64, u64),
|
||||
pub artboard: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// The maximum number of newest swatch renames a session keeps until they are taken.
|
||||
pub(crate) const MAX_SWATCH_RENAMES: usize = 64;
|
||||
|
||||
@@ -67,6 +74,7 @@ pub struct Session {
|
||||
pub prefs: Prefs,
|
||||
/// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences.
|
||||
pub caps_lock: bool,
|
||||
pub artboard_deletion_guard: Option<ArtboardDeletionGuard>,
|
||||
/// Fill/stroke for new art (the toolbar proxy).
|
||||
pub paint: PaintDefaults,
|
||||
/// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles.
|
||||
@@ -352,6 +360,9 @@ pub struct Session {
|
||||
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
|
||||
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
|
||||
pub(crate) trace_hand_off: Option<cmd::Traced>,
|
||||
/// The Concept to Vector providers and the jobs made with them ([`cmd::conceptvector`]); not
|
||||
/// saved.
|
||||
pub(crate) concept: cmd::conceptvector::ConceptState,
|
||||
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
|
||||
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
|
||||
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
|
||||
|
||||
@@ -124,6 +124,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};
|
||||
|
||||
@@ -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.
|
||||
@@ -997,21 +1035,38 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// 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`.
|
||||
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)
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -501,6 +501,9 @@ struct World {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: Journal,
|
||||
/// The Concept to Vector jobs, and the number of the first job made after the run started.
|
||||
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
|
||||
concept_from: u64,
|
||||
/// The preferences when the run started.
|
||||
start_prefs: crate::Prefs,
|
||||
/// The Caps Lock state when the run started.
|
||||
@@ -631,6 +634,8 @@ impl World {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: Journal::default(),
|
||||
concept_jobs: s.concept_jobs_snapshot(),
|
||||
concept_from: s.next_concept_job(),
|
||||
start_prefs: s.prefs.clone(),
|
||||
start_caps_lock: s.caps_lock,
|
||||
}
|
||||
@@ -655,6 +660,7 @@ impl World {
|
||||
swap(&mut self.pending_paint, &mut s.pending_paint);
|
||||
self.choices.swap(s);
|
||||
swap(&mut self.journal, &mut s.journal);
|
||||
s.swap_concept_jobs(&mut self.concept_jobs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -696,6 +702,7 @@ pub(crate) struct Savepoint {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: usize,
|
||||
concept_jobs: std::collections::VecDeque<cmd::conceptvector::Job>,
|
||||
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
|
||||
plugin_events: u64,
|
||||
}
|
||||
@@ -732,6 +739,7 @@ impl Savepoint {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: s.journal.len(),
|
||||
concept_jobs: s.concept_jobs_snapshot(),
|
||||
plugin_events: s.plugin_events_mark(),
|
||||
}
|
||||
}
|
||||
@@ -787,6 +795,7 @@ impl Savepoint {
|
||||
s.pending_paint = self.pending_paint;
|
||||
self.choices.put(s);
|
||||
s.journal.truncate(self.journal);
|
||||
s.restore_concept_jobs(self.concept_jobs);
|
||||
// The documents the command opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(self.plugin_events);
|
||||
s.sync_front_profiles();
|
||||
@@ -2842,6 +2851,9 @@ impl Session {
|
||||
for st in start.iter().filter(|b| !job.start_uids.contains(&b.uid)) {
|
||||
self.docs.push(st.clone());
|
||||
}
|
||||
// So do the Concept to Vector jobs the app made while the run went on.
|
||||
let others = std::mem::take(&mut job.world.concept_jobs);
|
||||
self.merge_concept_jobs(others, job.world.concept_from);
|
||||
// A document the script closed is gone now, with its recovery copy.
|
||||
for b in start.iter().filter(|b| job.start_uids.contains(&b.uid) && !self.docs.iter().any(|d| d.uid == b.uid)) {
|
||||
cmd::recovery::forget_closed(self, b);
|
||||
|
||||
@@ -51,6 +51,7 @@ impl Session {
|
||||
active: None,
|
||||
prefs: Prefs::default(),
|
||||
caps_lock: false,
|
||||
artboard_deletion_guard: None,
|
||||
paint: PaintDefaults::default(),
|
||||
fill_active: true,
|
||||
clipboard: Clipboard::default(),
|
||||
@@ -149,6 +150,7 @@ impl Session {
|
||||
place_queue_loads: 0,
|
||||
image_hand_off: None,
|
||||
trace_hand_off: None,
|
||||
concept: Default::default(),
|
||||
retype_hand_off: None,
|
||||
place_cursor_requests: false,
|
||||
package_hand_off: None,
|
||||
@@ -567,6 +569,10 @@ impl Session {
|
||||
// Closed (saved or discarded): nothing left to recover.
|
||||
let uid = self.docs[index].uid;
|
||||
cmd::recovery::forget(self, uid);
|
||||
// In a batch, the jobs are dropped when the batch ends without an error.
|
||||
if self.batch_stash.is_none() {
|
||||
self.forget_concept_jobs(uid);
|
||||
}
|
||||
let old = self.docs.remove(index);
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -211,6 +211,33 @@ fn exclude_makes_compound() {
|
||||
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_over_work_budget_preserves_art_and_selection() {
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap();
|
||||
let cutter = NodeId(line["id"].as_u64().unwrap());
|
||||
// The existing pathops work-budget fixture uses 1,500 overlapping lines.
|
||||
// Put them in one open path so the setup only makes two document objects.
|
||||
let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false);
|
||||
s.edit("complex cutter", |d, _| {
|
||||
let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") };
|
||||
*path = PathData::new(vec![line; 1_500]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("too many segments or pieces"), "{error}");
|
||||
let state = s.doc().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored");
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_produces_group_of_faces() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -519,3 +519,138 @@ fn type_on_a_path_made_with_the_type_tool_has_brackets_at_once() {
|
||||
assert!(ink(&s, id).y0 > 299.0, "{tool}: below the path");
|
||||
}
|
||||
}
|
||||
|
||||
/// Press and release `tool` at `p`.
|
||||
fn click(s: &mut Session, tool: &str, p: Point) {
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool(tool, v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
|
||||
}
|
||||
assert!(!s.in_interaction());
|
||||
}
|
||||
|
||||
/// Type along "M100 300 L300 300 L500 300" turned a quarter turn, so a document-space edit isn't
|
||||
/// the path's own, and selected; with its path in document space.
|
||||
fn turned_path_type(s: &mut Session) -> NodeId {
|
||||
let id = path_type(s, "M100 300 L300 300 L500 300", [100.0, 310.0], "Reshaped type");
|
||||
s.execute("object.transform", &json!({"ids": [id.0], "matrix": [0, 1, -1, 0, 600, 0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn type_path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
|
||||
text(s, id).type_path().unwrap()
|
||||
}
|
||||
|
||||
fn close(a: Point, b: Point) -> bool {
|
||||
near(a.x, b.x) && near(a.y, b.y)
|
||||
}
|
||||
|
||||
/// #10862: the Anchor Point tool drags handles out of an anchor of selected type on a path's path,
|
||||
/// in document space through the type's transform, as one undo step, and the type reflows.
|
||||
#[test]
|
||||
fn anchor_point_tool_pulls_handles_out_of_type_on_a_path() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
let middle = type_path(&s, id).subpaths[0].anchors[1].p;
|
||||
let (glyphs, n) = (origins(&s, id), undo_len(&s));
|
||||
let to = middle + vectorcraft_geom::Vec2::new(40.0, 0.0);
|
||||
drag(&mut s, "anchorPoint", middle, to, Mods::default());
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(close(a.p, middle) && close(a.h_out, to) && close(a.h_in, middle - (to - middle)), "{a:?}");
|
||||
assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth);
|
||||
assert_ne!(origins(&s, id), glyphs, "the type reflows along the curved path");
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!type_path(&s, id).subpaths[0].anchors[1].has_out());
|
||||
}
|
||||
|
||||
/// #10862: the rest of the Anchor Point tool's gestures on type on a path's path: a click makes a
|
||||
/// smooth anchor a corner, a handle drag moves that handle alone, Shift at the press moves the
|
||||
/// anchor, and a segment drag bends the segment.
|
||||
#[test]
|
||||
fn anchor_point_tool_reshapes_type_on_a_path() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
let [first, middle, last] = [0, 1, 2].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
|
||||
let up = vectorcraft_geom::Vec2::new(40.0, 0.0);
|
||||
drag(&mut s, "anchorPoint", middle, middle + up, Mods::default());
|
||||
// A handle end, dragged, moves alone and makes the anchor a corner.
|
||||
let handle = middle + vectorcraft_geom::Vec2::new(40.0, 30.0);
|
||||
drag(&mut s, "anchorPoint", middle + up, handle, Mods::default());
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(close(a.h_out, handle) && close(a.h_in, middle - up) && a.kind == vectorcraft_geom::AnchorKind::Corner, "{a:?}");
|
||||
// A click on the anchor takes its handles back.
|
||||
click(&mut s, "anchorPoint", middle);
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(!a.has_in() && !a.has_out(), "{a:?}");
|
||||
// Shift at the press moves the anchor.
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
drag(&mut s, "anchorPoint", middle, middle + up, shift);
|
||||
assert!(close(type_path(&s, id).subpaths[0].anchors[1].p, middle + up));
|
||||
// A drag on the first segment bends it; its anchors stay.
|
||||
let on_segment = first.midpoint(middle + up);
|
||||
drag(&mut s, "anchorPoint", on_segment, on_segment + vectorcraft_geom::Vec2::new(0.0, 30.0), Mods::default());
|
||||
let sp = &type_path(&s, id).subpaths[0];
|
||||
assert!(close(sp.anchors[0].p, first) && close(sp.anchors[2].p, last));
|
||||
assert!(sp.anchors[0].has_out() && sp.anchors[1].has_in(), "the segment curves: {sp:?}");
|
||||
}
|
||||
|
||||
/// #10862: the Add and Delete Anchor Point tools add an anchor to type on a path's path and delete
|
||||
/// one, and Pen + Alt pulls handles out of one; Delete leaves the path two anchors at least, and
|
||||
/// Scissors does not cut the type.
|
||||
#[test]
|
||||
fn add_delete_and_pen_alt_edit_type_on_a_path() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
let [first, middle] = [0, 1].map(|i| type_path(&s, id).subpaths[0].anchors[i].p);
|
||||
let quarter = first.midpoint(middle);
|
||||
click(&mut s, "addAnchor", quarter);
|
||||
let sp = type_path(&s, id).subpaths[0].clone();
|
||||
assert_eq!(sp.anchors.len(), 4);
|
||||
assert!(close(sp.anchors[1].p, quarter), "{sp:?}");
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let to = quarter + vectorcraft_geom::Vec2::new(0.0, 25.0);
|
||||
drag(&mut s, "pen", quarter, to, alt);
|
||||
let a = type_path(&s, id).subpaths[0].anchors[1];
|
||||
assert!(close(a.p, quarter) && close(a.h_out, to) && a.kind == vectorcraft_geom::AnchorKind::Smooth, "{a:?}");
|
||||
// The Pen's Auto Add/Delete adds an anchor on a segment and deletes it again.
|
||||
let last = type_path(&s, id).subpaths[0].anchors[3].p;
|
||||
let three_quarters = middle.midpoint(last);
|
||||
click(&mut s, "pen", three_quarters);
|
||||
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 5);
|
||||
click(&mut s, "pen", three_quarters);
|
||||
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 4);
|
||||
click(&mut s, "deleteAnchor", quarter);
|
||||
click(&mut s, "deleteAnchor", middle);
|
||||
assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 2);
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": 0}));
|
||||
assert!(r.is_err(), "type on a path keeps two anchors: {r:?}");
|
||||
assert_eq!((type_path(&s, id).subpaths[0].anchors.len(), undo_len(&s)), (2, n));
|
||||
let end = type_path(&s, id).subpaths[0].anchors[1].p;
|
||||
click(&mut s, "scissors", first.midpoint(end));
|
||||
assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. }));
|
||||
assert_eq!(undo_len(&s), n, "Scissors leaves the type whole");
|
||||
}
|
||||
|
||||
/// #10862: `path.insertAnchor` on type on a path, unselected or with `selectAnchor`, leaves the type
|
||||
/// selected whole with no direct-selected anchors, so `path.moveAnchors` (the arrow keys) moves
|
||||
/// the type instead of failing on an anchor that is not a path's.
|
||||
#[test]
|
||||
fn an_anchor_added_to_type_on_a_path_leaves_it_selected_whole() {
|
||||
let mut s = session();
|
||||
let id = turned_path_type(&mut s);
|
||||
for select_anchor in [false, true] {
|
||||
if !select_anchor {
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
}
|
||||
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5, "selectAnchor": select_anchor})).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.contains(id) && sel.partial(id).is_none() && !sel.anchors.contains_key(&id), "selectAnchor {select_anchor}");
|
||||
let before = type_path(&s, id).subpaths[0].anchors[0].p;
|
||||
s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
assert!(close(type_path(&s, id).subpaths[0].anchors[0].p, before + vectorcraft_geom::Vec2::new(10.0, 0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +152,211 @@ 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:?}");
|
||||
}
|
||||
|
||||
/// 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");
|
||||
|
||||
@@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
fn write(path: &Path, bytes: &[u8]) {
|
||||
|
||||
@@ -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.
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ impl AsRef<Path> for Folder {
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
|
||||
fn folder(name: &str) -> Folder {
|
||||
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
|
||||
let base = std::fs::canonicalize(&*guard).unwrap();
|
||||
let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap());
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
Folder { _guard: guard, path: base }
|
||||
}
|
||||
|
||||
@@ -401,7 +401,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 +464,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"),
|
||||
|
||||
@@ -279,11 +279,35 @@ enum FrameKind {
|
||||
/// Point type: the matrix carries the layout (its anchor at the origin of its lines) onto the
|
||||
/// canvas.
|
||||
Point([f64; 6]),
|
||||
/// Area type flowed inside a path: its cubic segments on the canvas, four points each, and the
|
||||
/// Area Type Options the frame keeps.
|
||||
Area(Vec<[f64; 8]>, AreaFrame),
|
||||
/// Type on a path, from `start` to `end` (segment index and the place in that segment).
|
||||
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame },
|
||||
/// Area type flowed inside a path: its cubic segments on the canvas, four points each, the Area
|
||||
/// Type Options the frame keeps, and the frame's matrix (the segments are already on the
|
||||
/// canvas; the matrix turns and scales the lines inside them).
|
||||
Area(Vec<[f64; 8]>, AreaFrame, [f64; 6]),
|
||||
/// Type on a path, from `start` to `end` (segment index and the place in that segment), its
|
||||
/// segments on the canvas, and the frame's matrix.
|
||||
OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame, matrix: [f64; 6] },
|
||||
}
|
||||
|
||||
/// The matrix of a frame that keeps none: its frame and layout are already on the canvas.
|
||||
const NO_MATRIX: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// Segment `s` (four points) carried onto the canvas by the frame matrix `m`.
|
||||
fn on_canvas(m: &[f64; 6], s: &[f64; 8]) -> [f64; 8] {
|
||||
let [a, b, c, d, e, f] = *m;
|
||||
let mut out = *s;
|
||||
for [x, y] in out.as_chunks_mut::<2>().0 {
|
||||
(*x, *y) = (a * *x + c * *y + e, b * *x + d * *y + f);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The scale of the frame matrix `m` and its turn (the matrix without its scale or its move), or
|
||||
/// `None` for a matrix that mirrors, has no size or isn't finite.
|
||||
fn turn_of(m: &[f64; 6]) -> Option<(f64, Affine)> {
|
||||
let [a, b, c, d, ..] = *m;
|
||||
let det = a * d - b * c;
|
||||
let scale = det.abs().sqrt();
|
||||
(scale.is_finite() && scale > 1e-6 && det > 0.0).then(|| (scale, Affine::new([a / scale, b / scale, c / scale, d / scale, 0.0, 0.0])))
|
||||
}
|
||||
|
||||
/// The Type on a Path Options a frame of type on a path keeps at key 11. Each stays at its default
|
||||
@@ -732,19 +756,21 @@ impl Texts {
|
||||
fn frame(&self, i: usize) -> Option<FrameKind> {
|
||||
let f = self.frames.get(i)?.get("0")?;
|
||||
let carries = f.get("2")?;
|
||||
// Key 2, the frame's matrix: it carries the frame's segments and its layout onto the canvas.
|
||||
// Type that is neither turned nor scaled has none (Illustrator 24 leaves it out): its frame
|
||||
// and layout are already where they go on the canvas.
|
||||
let matrix: [f64; 6] = match carries.get("2") {
|
||||
None => NO_MATRIX,
|
||||
Some(m) => m.nums()?.try_into().ok()?,
|
||||
};
|
||||
let segments = || -> Option<Vec<[f64; 8]>> {
|
||||
let n = f.get("1")?.get("0")?.nums()?;
|
||||
let (chunks, rest) = n.as_chunks::<8>();
|
||||
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.to_vec())
|
||||
(rest.is_empty() && !chunks.is_empty() && chunks.len() <= MAX_SEGMENTS).then(|| chunks.iter().map(|s| on_canvas(&matrix, s)).collect())
|
||||
};
|
||||
match carries.get("0").and_then(Val::num).unwrap_or(0.0) as i64 {
|
||||
// Point type that is neither turned nor scaled has no matrix (Illustrator 24 leaves it out):
|
||||
// its layout is already where it goes on the canvas.
|
||||
0 => Some(FrameKind::Point(match carries.get("2") {
|
||||
None => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
Some(m) => m.nums()?.try_into().ok()?,
|
||||
})),
|
||||
1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries))),
|
||||
0 => Some(FrameKind::Point(matrix)),
|
||||
1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries), matrix)),
|
||||
2 => {
|
||||
let range = carries.get("6").and_then(Val::nums).unwrap_or_default();
|
||||
let segments = segments()?;
|
||||
@@ -760,7 +786,7 @@ impl Texts {
|
||||
let start = finite(range.first()).unwrap_or(0.0).clamp(0.0, n);
|
||||
(start, finite(range.get(1)).unwrap_or(n).clamp(start, n))
|
||||
};
|
||||
Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries) })
|
||||
Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries), matrix })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
@@ -1219,11 +1245,11 @@ impl Story {
|
||||
frame == 0 && matches!(self.frames.first(), Some(FrameKind::Point(_))) && self.is_blank()
|
||||
}
|
||||
|
||||
/// The point frame's matrix (the first frame's, when it is one), else the identity.
|
||||
/// The first frame's matrix, which carries its layout onto the canvas, else the identity.
|
||||
fn matrix(&self) -> [f64; 6] {
|
||||
match self.frames.first() {
|
||||
Some(FrameKind::Point(m)) => *m,
|
||||
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
Some(FrameKind::Point(m) | FrameKind::Area(_, _, m) | FrameKind::OnPath { matrix: m, .. }) => *m,
|
||||
None => NO_MATRIX,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1256,7 +1282,7 @@ impl Story {
|
||||
let size = self.runs.iter().map(|(_, s)| s.size).fold(0.0, f64::max) * art_scale(to_doc);
|
||||
let bounds = |segments: &[[f64; 8]]| path_of(segments, template, to_doc).bounds();
|
||||
let r = match self.frames.first()? {
|
||||
FrameKind::Area(s, _) => bounds(s)?,
|
||||
FrameKind::Area(s, ..) => bounds(s)?,
|
||||
FrameKind::OnPath { segments, .. } => bounds(segments)?.inflate(size * 1.5, size * 1.5),
|
||||
FrameKind::Point(m) => {
|
||||
let longest = self.text.split(['\r', '\x03']).map(|l| l.chars().count()).max().unwrap_or(0) as f64;
|
||||
@@ -1312,23 +1338,34 @@ impl Story {
|
||||
let threaded = frame > 0;
|
||||
let (scale, xf, kind) = match kind {
|
||||
FrameKind::Point(m) => {
|
||||
let [a, b, c, d, ..] = *m;
|
||||
let scale = (a * d - b * c).abs().sqrt();
|
||||
if !(scale.is_finite() && scale > 1e-6 && a * d - b * c > 0.0) || threaded {
|
||||
return None;
|
||||
}
|
||||
let (scale, turn) = turn_of(m).filter(|_| !threaded)?;
|
||||
let (x, y) = self.place(template);
|
||||
let at = to_doc * Point::new(x, y);
|
||||
(scale, Affine::new([a / scale, b / scale, c / scale, d / scale, at.x, at.y]), TextKind::Point)
|
||||
(scale, Affine::translate(at.to_vec2()) * turn, TextKind::Point)
|
||||
}
|
||||
FrameKind::Area(s, _) => (1.0, Affine::IDENTITY, TextKind::Area { frame: path_of(s, template, to_doc) }),
|
||||
FrameKind::OnPath { segments, start, end, options } => {
|
||||
// Turned area type keeps its turn: its lines run along the turned frame, which is kept
|
||||
// in the text's own space (the frame on the canvas turned back).
|
||||
FrameKind::Area(s, _, m) => {
|
||||
let (scale, turn) = turn_of(m)?;
|
||||
(scale, turn, TextKind::Area { frame: path_of(s, template, to_doc).transformed(turn.inverse()) })
|
||||
}
|
||||
// The glyphs follow the path's tangent and grow by one scale: a frame matrix that also
|
||||
// stretches or slants them isn't made from the text document (the page draws that type).
|
||||
FrameKind::OnPath { segments, start, end, options, matrix } => {
|
||||
let (scale, _) = turn_of(matrix).filter(|(_, turn)| {
|
||||
let [a, b, c, d, ..] = turn.as_coeffs();
|
||||
(a - d).abs() < 1e-6 && (b + c).abs() < 1e-6
|
||||
})?;
|
||||
let n = segments.len() as f64;
|
||||
// A closed path keeps its end bracket wherever it is (the same place as the start: a
|
||||
// full turn, see `TextKind::path_span`); an open one's end at its end is none, unless
|
||||
// a flip makes it the place the type starts.
|
||||
let end = (closed(segments) || options.flip || *end < n - 0.02).then(|| length_fraction(segments, *end));
|
||||
(1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end })
|
||||
(
|
||||
scale,
|
||||
Affine::IDENTITY,
|
||||
TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end },
|
||||
)
|
||||
}
|
||||
};
|
||||
// A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the
|
||||
@@ -1389,7 +1426,7 @@ impl Story {
|
||||
}
|
||||
// Each frame of a thread keeps its own options.
|
||||
match self.frames.get(frame) {
|
||||
Some(FrameKind::Area(_, options)) => options.apply(&mut t.area, scale),
|
||||
Some(FrameKind::Area(_, options, _)) => options.apply(&mut t.area, scale),
|
||||
Some(FrameKind::OnPath { options, .. }) => {
|
||||
t.path_effect = options.effect;
|
||||
t.path_align = options.align;
|
||||
@@ -1450,7 +1487,7 @@ impl Story {
|
||||
pub(super) fn place_first_line(&self, node: &mut Node, frame: usize, template: (f64, f64), to_doc: Affine) -> bool {
|
||||
// Closer than this (points of the document) and the line is where the file has it.
|
||||
const SAME: f64 = 0.5;
|
||||
if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }))) {
|
||||
if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }, _))) {
|
||||
return false;
|
||||
}
|
||||
let NodeKind::Text(t) = &mut node.kind else { return false };
|
||||
@@ -1458,7 +1495,8 @@ impl Story {
|
||||
return false;
|
||||
}
|
||||
let Some((_, (x, y))) = self.line_starts(template).into_iter().next() else { return false };
|
||||
let at = to_doc * Point::new(x, y);
|
||||
// In the text's own space, where its lines are laid out (turned area type's is turned).
|
||||
let at = t.xf.inverse() * (to_doc * Point::new(x, y));
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// A frame too short for the line lays nothing out: as the line needs it (see `fit_first_line`).
|
||||
let mut probe = TextObject::clone(t);
|
||||
@@ -2229,7 +2267,7 @@ mod tests {
|
||||
for frame in [
|
||||
FrameKind::Point([0.0, 1.0, -1.0, 0.0, 30.0, 40.0]),
|
||||
FrameKind::Point([2.0, 0.0, 0.0, 2.0, -7.0, 3.0]),
|
||||
FrameKind::Area(area_segments(), AreaFrame::default()),
|
||||
FrameKind::Area(area_segments(), AreaFrame::default(), NO_MATRIX),
|
||||
] {
|
||||
let mut st = story("type", &[0.0], &Para::default());
|
||||
st.frames = vec![frame.clone()];
|
||||
@@ -2987,12 +3025,12 @@ mod tests {
|
||||
let mut s = story("one\rtwo\rthree\r", &[0.0, 15.6, 31.2], &Para::default());
|
||||
// A point-type frame (the helper's) isn't fitted.
|
||||
assert!(!s.fit_last_lines(&mut t));
|
||||
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default())];
|
||||
s.frames = vec![FrameKind::Area(vec![], AreaFrame::default(), NO_MATRIX)];
|
||||
assert!(s.fit_last_lines(&mut t));
|
||||
assert_eq!(vectorcraft_text::layout(db, &t).lines.len(), 3);
|
||||
// A story threaded through two frames: its lines are the first frame's alone.
|
||||
let mut t = area(third.baseline - 20.0 + third.descent / 2.0);
|
||||
s.frames.push(FrameKind::Area(vec![], AreaFrame::default()));
|
||||
s.frames.push(FrameKind::Area(vec![], AreaFrame::default(), NO_MATRIX));
|
||||
assert!(!s.fit_last_lines(&mut t));
|
||||
}
|
||||
|
||||
@@ -3017,7 +3055,7 @@ mod tests {
|
||||
(placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline)
|
||||
};
|
||||
let mut s = story("Heading\r", &[], &Para::default());
|
||||
s.frames = vec![FrameKind::Area(frame, AreaFrame::default())];
|
||||
s.frames = vec![FrameKind::Area(frame, AreaFrame::default(), NO_MATRIX)];
|
||||
// Where this lays the line out on its own: the file agrees, and nothing changes.
|
||||
s.lines = vec![(10.0, 20.0)];
|
||||
let (_, Some(own), _) = first(&s) else { panic!("a line") };
|
||||
@@ -3030,6 +3068,32 @@ mod tests {
|
||||
assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_area_type_s_first_line_is_compared_in_its_own_space() {
|
||||
// GUARDS: the file's first line was compared with the layout where it is on the page, not
|
||||
// in the turned type's own space: turned area type whose line is where the file has it got
|
||||
// a fixed first baseline it doesn't keep.
|
||||
let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]));
|
||||
let first = |s: &Story| {
|
||||
let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap();
|
||||
let placed = s.place_first_line(&mut node, 0, template, to_doc);
|
||||
let NodeKind::Text(t) = node.kind else { panic!("area type") };
|
||||
let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
(placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline)
|
||||
};
|
||||
let mut s = story("Heading\r", &[], &Para::default());
|
||||
// A quarter turn round the canvas's origin: the frame's own space is the text document's.
|
||||
s.frames = vec![area_frame("/2 [ 0 1 -1 0 0 0 ]")];
|
||||
s.lines = vec![(10.0, 20.0)];
|
||||
let (_, Some(own), _) = first(&s) else { panic!("a line") };
|
||||
s.lines = vec![(10.0, own)];
|
||||
assert_eq!(first(&s), (false, Some(own), vectorcraft_doc::FirstBaseline::Ascent));
|
||||
s.lines = vec![(10.0, own - 3.0)];
|
||||
let (placed, at, fb) = first(&s);
|
||||
assert!(placed && fb == vectorcraft_doc::FirstBaseline::Fixed, "{fb:?}");
|
||||
assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0);
|
||||
}
|
||||
|
||||
/// A text document's area frame, the rectangle 10, 20 to 210, 120 of the canvas, whose frame
|
||||
/// data has `options` besides its kind, written by hand.
|
||||
fn area_frame(options: &str) -> FrameKind {
|
||||
@@ -3065,6 +3129,91 @@ mod tests {
|
||||
t.area
|
||||
}
|
||||
|
||||
/// The text object a story in the area frame [`area_frame`] makes with `options` comes in as,
|
||||
/// or `None`.
|
||||
fn area_type(options: &str) -> Option<TextObject> {
|
||||
let mut s = story("Some area type\r", &[], &Para::default());
|
||||
s.frames = vec![area_frame(options)];
|
||||
let to_doc = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
|
||||
match s.node(NodeId(0), 0, (CANVAS_CENTRE, -CANVAS_CENTRE), to_doc)?.kind {
|
||||
NodeKind::Text(t) => Some(*t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Width and height of the area frame of `t`, in its own space.
|
||||
fn own_frame_size(t: &TextObject) -> (f64, f64) {
|
||||
let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { panic!("area type") };
|
||||
let r = frame.bounds().unwrap();
|
||||
(r.width(), r.height())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_area_type_comes_in_turned_with_its_lines_along_its_frame() {
|
||||
// GUARDS: area type's frame matrix was left out: a frame turned a quarter came in unturned,
|
||||
// its lines across the page where the file runs them down it.
|
||||
let plain = area_type("").unwrap();
|
||||
let turned = area_type("/2 [ 0 1 -1 0 300 0 ]").unwrap();
|
||||
let (w, h) = own_frame_size(&plain);
|
||||
assert!(w > h, "{w} by {h}");
|
||||
// On the page the frame stands on its end ...
|
||||
let page = turned.bounds().unwrap();
|
||||
assert!((page.width() - h).abs() < 1e-6 && (page.height() - w).abs() < 1e-6, "{page:?}");
|
||||
// ... and in the text's own space, where its lines run, it is as wide as the unturned one.
|
||||
let (tw, th) = own_frame_size(&turned);
|
||||
assert!((tw - w).abs() < 1e-6 && (th - h).abs() < 1e-6, "{tw} by {th}");
|
||||
let along = turned.xf * Point::new(1.0, 0.0) - turned.xf * Point::ZERO;
|
||||
assert!(along.x.abs() < 1e-9 && (along.y.abs() - 1.0).abs() < 1e-9, "{along:?}");
|
||||
// A turn alone leaves the type's size as it is.
|
||||
assert_eq!(turned.runs[0].style.size, plain.runs[0].style.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scaled_area_frame_scales_its_type_and_a_mirrored_one_isnt_made() {
|
||||
// GUARDS: area type's frame matrix was left out: a frame scaled up came in at its unscaled
|
||||
// size, and a mirrored one unmirrored.
|
||||
let plain = area_type("").unwrap();
|
||||
let double = area_type("/2 [ 2 0 0 2 0 0 ]").unwrap();
|
||||
assert_eq!(double.runs[0].style.size, plain.runs[0].style.size * 2.0);
|
||||
let ((w, h), (dw, dh)) = (own_frame_size(&plain), own_frame_size(&double));
|
||||
assert!((dw - 2.0 * w).abs() < 1e-6 && (dh - 2.0 * h).abs() < 1e-6, "{dw} by {dh}");
|
||||
// Mirrored type isn't made from the text document, as point type isn't.
|
||||
assert!(area_type("/2 [ -1 0 0 1 0 0 ]").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_on_a_turned_path_runs_along_the_path_where_the_canvas_has_it() {
|
||||
// GUARDS: type on a path's frame matrix was left out: the path of a frame turned a quarter
|
||||
// came in unturned.
|
||||
let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]];
|
||||
let path = |options: &str| {
|
||||
let (t, _) = on_path("type", on_path_frame_with(&open, [0.0, 2.0], options).unwrap());
|
||||
let vectorcraft_doc::TextKind::OnPath { path, .. } = &t.kind else { panic!("type on a path") };
|
||||
path.bounds().unwrap()
|
||||
};
|
||||
let plain = path("");
|
||||
assert!(plain.width() > 100.0 && plain.height() < 1e-6, "{plain:?}");
|
||||
let turned = path("/2 [ 0 1 -1 0 0 0 ]");
|
||||
assert!(turned.width() < 1e-6 && (turned.height() - plain.width()).abs() < 1e-6, "{turned:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_on_a_stretched_path_is_left_to_the_page() {
|
||||
// GUARDS: a frame matrix that stretched the path four times and the type not at all came
|
||||
// in with glyphs twice as wide and twice as tall.
|
||||
let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]];
|
||||
let made = |options: &str| {
|
||||
let mut st = story("type", &[0.0], &Para::default());
|
||||
st.frames = vec![on_path_frame_with(&open, [0.0, 2.0], options).unwrap()];
|
||||
st.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY)
|
||||
};
|
||||
assert!(made("/2 [ 4 0 0 1 0 0 ]").is_none());
|
||||
assert!(made("/2 [ 1 0.5 0 1 0 0 ]").is_none());
|
||||
// A uniform scale and a turn are still made.
|
||||
assert!(made("/2 [ 2 0 0 2 0 0 ]").is_some());
|
||||
assert!(made("/2 [ 0 2 -2 0 0 0 ]").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_frame_options_are_read() {
|
||||
// GUARDS: area type came in with one row, one column and the 18 pt gutter whatever its frame kept.
|
||||
@@ -3152,7 +3301,7 @@ mod tests {
|
||||
#[test]
|
||||
fn area_frame_without_options_comes_in_as_before() {
|
||||
assert_eq!(area_of(vec![area_frame("")], 0, 1.0), vectorcraft_doc::AreaOptions::default());
|
||||
assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default()));
|
||||
assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default(), NO_MATRIX));
|
||||
}
|
||||
|
||||
/// The segments [`area_frame`] writes.
|
||||
@@ -3199,7 +3348,7 @@ mod tests {
|
||||
(placed, l.baselines().first().map(|b| b.0.x), t.area.first_baseline)
|
||||
};
|
||||
let mut s = story("§§\r", &[], &Para::default());
|
||||
s.frames = vec![FrameKind::Area(frame, AreaFrame::default())];
|
||||
s.frames = vec![FrameKind::Area(frame, AreaFrame::default(), NO_MATRIX)];
|
||||
s.vertical = true;
|
||||
s.anchor = (210.0, 20.0);
|
||||
s.lines = vec![(0.0, 0.0)];
|
||||
|
||||
@@ -38,7 +38,9 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option<Rec
|
||||
let size = text.runs.iter().map(|r| r.style.size).fold(0.0, f64::max);
|
||||
match &mut text.kind {
|
||||
TextKind::Area { frame } => {
|
||||
*frame = path.clone();
|
||||
// The object's path is on the page; turned area type keeps its frame in its own
|
||||
// (turned) space.
|
||||
*frame = path.transformed(text.xf.inverse());
|
||||
*region = path.bounds();
|
||||
}
|
||||
TextKind::OnPath { path: on, .. } => {
|
||||
@@ -738,4 +740,25 @@ mod tests {
|
||||
assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true));
|
||||
assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0);
|
||||
}
|
||||
|
||||
/// The object's own path frames turned area type where the path is on the page: the frame is
|
||||
/// kept in the type's turned space.
|
||||
#[test]
|
||||
fn an_object_s_path_frames_turned_area_type_where_the_path_is() {
|
||||
// GUARDS: the path replaced the frame as it is on the page, and the type's turn then turned
|
||||
// it a second time.
|
||||
let mut node = text(1, "Turned");
|
||||
let NodeKind::Text(t) = &mut node.kind else { panic!("type") };
|
||||
t.xf = Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
|
||||
t.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)) };
|
||||
let on_page = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 220.0));
|
||||
let info = SlotInfo { story: Some(0), frame: 0, shown: true, art_path: Some(on_page.clone()), look: None, group: None };
|
||||
let mut region = None;
|
||||
frame_text_from_art(&info, &mut node, &mut region);
|
||||
let NodeKind::Text(t) = &node.kind else { panic!("type") };
|
||||
let (drawn, want) = (t.bounds().unwrap(), on_page.bounds().unwrap());
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
assert!(near(drawn.x0, want.x0) && near(drawn.y0, want.y0) && near(drawn.x1, want.x1) && near(drawn.y1, want.y1), "{drawn:?} {want:?}");
|
||||
assert_eq!(region, Some(want));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,95 @@ 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();
|
||||
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 };
|
||||
if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous)
|
||||
&& let Some((get, set)) = self.file_accessors(class, name)
|
||||
{
|
||||
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
|
||||
}
|
||||
}
|
||||
}
|
||||
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 +697,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 +713,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)))
|
||||
}
|
||||
|
||||
@@ -1577,3 +1577,108 @@ proptest::proptest! {
|
||||
proptest::prop_assert!(matches!(out.as_str(), "ok" | "RangeError" | "TypeError"), "{}", out);
|
||||
}
|
||||
}
|
||||
|
||||
/// A realm whose global `it` is a `Child` that inherits the File property `file` from `Base`. The
|
||||
/// setter records each path it is given and refuses one containing `bad`; `clear()` sets the
|
||||
/// property to null and `touch()` does nothing.
|
||||
fn file_property_realm() -> (Realm, Rc<RefCell<Vec<String>>>) {
|
||||
file_property_realm_indexed(false)
|
||||
}
|
||||
|
||||
/// [`file_property_realm`], with an indexer on `Child` when `indexed` that gives the last path the
|
||||
/// setter was given when it is called.
|
||||
fn file_property_realm_indexed(indexed: bool) -> (Realm, Rc<RefCell<Vec<String>>>) {
|
||||
let mut r = realm(10_000_000);
|
||||
let parse: HostFunction = Rc::new(|a| {
|
||||
let fs = match a.first() {
|
||||
Some(Data::String(s)) => s.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let name = fs.trim_start_matches('/').to_string();
|
||||
let fields = [("fs", fs.clone()), ("uri", fs), ("name", name.clone()), ("display", name), ("path", "/".into()), ("parent", "/".into())];
|
||||
Ok(Data::Object(fields.into_iter().map(|(k, v)| (k.to_string(), Data::String(v))).collect()))
|
||||
});
|
||||
let messages = ["notOpen", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into()))));
|
||||
r.define_file_classes(vec![
|
||||
("text".into(), HostItem::Object(messages.to_vec())),
|
||||
("current".into(), HostItem::Function(Rc::new(|_| Ok(Data::String("/".into()))))),
|
||||
("parse".into(), HostItem::Function(parse)),
|
||||
])
|
||||
.unwrap();
|
||||
let stored = Rc::new(RefCell::new(Data::Null));
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let (get_stored, set_stored, clear_stored) = (stored.clone(), stored.clone(), stored);
|
||||
let log = seen.clone();
|
||||
let get: HostFunction = Rc::new(move |_| Ok(get_stored.borrow().clone()));
|
||||
let set: HostFunction = Rc::new(move |args| {
|
||||
let path = args.last().and_then(file_ref_path).unwrap_or("?").to_string();
|
||||
if path.contains("bad") {
|
||||
return Err(HostError::Error(format!("{path} is refused")));
|
||||
}
|
||||
log.borrow_mut().push(path.clone());
|
||||
*set_stored.borrow_mut() = file_ref(&path);
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
let clear: HostFunction = Rc::new(move |_| {
|
||||
*clear_stored.borrow_mut() = Data::Null;
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
let info = MemberInfo { data_type: "File".into(), ..MemberInfo::default() };
|
||||
let base = HostClass {
|
||||
name: "Base".into(),
|
||||
parent: None,
|
||||
members: vec![
|
||||
("file".into(), HostMember::Property { get, set }),
|
||||
("clear".into(), HostMember::Method(clear)),
|
||||
("touch".into(), HostMember::Method(Rc::new(|_| Ok(Data::Undefined)))),
|
||||
],
|
||||
info: vec![("file".into(), info)],
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let last = seen.clone();
|
||||
let index: Option<HostFunction> =
|
||||
indexed.then(|| -> HostFunction { Rc::new(move |_| Ok(last.borrow().last().map_or(Data::Null, |p| Data::String(p.clone())))) });
|
||||
let child = HostClass { name: "Child".into(), parent: Some("Base".into()), members: vec![], info: Vec::new(), index, construct: None };
|
||||
r.define_host_classes(vec![base, child], vec![("it".into(), host_ref("Child", &[1.0]))]).unwrap();
|
||||
(r, seen)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_file_property_follows_its_files_new_path() {
|
||||
let (mut r, seen) = file_property_realm();
|
||||
r.run("var f = new File('/a'); it.file = f; f.changePath('/b'); it.touch();").unwrap();
|
||||
assert_eq!(*seen.borrow(), ["/a", "/b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_indexed_read_follows_a_file_propertys_new_path() {
|
||||
let (mut r, seen) = file_property_realm_indexed(true);
|
||||
assert_eq!(r.run("var f = new File('/a'); it.file = f; f.changePath('/b'); it[0]").unwrap(), JsValue::String("/b".into()));
|
||||
assert_eq!(*seen.borrow(), ["/a", "/b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_getter_gives_its_own_value_once_the_host_changes_a_file_property() {
|
||||
let (mut r, _) = file_property_realm();
|
||||
let source = "var f = new File('/a'); it.file = f; var same = it.file === f; it.clear(); [same, it.file === null].join('|')";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_change_does_not_restore_a_property_the_host_cleared() {
|
||||
let (mut r, seen) = file_property_realm();
|
||||
let source = "var f = new File('/a'); it.file = f; it.clear(); f.changePath('/b'); it.touch(); it.file === null";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
assert_eq!(*seen.borrow(), ["/a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_path_change_is_thrown_once() {
|
||||
let (mut r, seen) = file_property_realm();
|
||||
let source = "var f = new File('/a'); it.file = f; f.changePath('/bad'); var first = 'none'; try { it.touch(); } catch (e) { first = e.message; }\n\
|
||||
it.touch(); it.file = new File('/good'); first";
|
||||
let JsValue::String(first) = r.run(source).unwrap() else { panic!("not a string") };
|
||||
assert!(first.contains("refused"), "{first}");
|
||||
assert_eq!(*seen.borrow(), ["/a", "/good"]);
|
||||
}
|
||||
|
||||
@@ -399,6 +399,8 @@ pub(crate) struct Interp {
|
||||
/// the same one give the same object. It is not a root: an object that was collected is dropped
|
||||
/// after each collection.
|
||||
pub(crate) host_objects: crate::host_classes::Made,
|
||||
/// Host objects with assigned Files stay reachable until the next script run.
|
||||
pub(crate) host_file_objects: Vec<ObjId>,
|
||||
/// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the
|
||||
/// operators take no object as a measurement.
|
||||
pub(crate) unit_values: Option<crate::unit_value::Classes>,
|
||||
@@ -822,6 +824,7 @@ impl Interp {
|
||||
host_classes: Vec::new(),
|
||||
write_hosted: false,
|
||||
host_objects: crate::host_classes::Made::default(),
|
||||
host_file_objects: Vec::new(),
|
||||
unit_values: None,
|
||||
date_host: crate::date_builtins::DateHost::default(),
|
||||
held: Rc::default(),
|
||||
@@ -1110,6 +1113,7 @@ impl Interp {
|
||||
roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects));
|
||||
roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects));
|
||||
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
|
||||
roots.objects.extend(self.host_file_objects.iter().copied());
|
||||
roots.values.extend(self.symbols.root_values());
|
||||
roots.objects.extend(self.symbols.root_objects());
|
||||
roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object));
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::bytecode::CodeKind;
|
||||
use crate::heap::{Func, HIDDEN, Object, Prop, key};
|
||||
use crate::heap::{Class, Func, HIDDEN, Object, Prop, key};
|
||||
use crate::interp::{Abrupt, CompileError, Interp};
|
||||
use crate::module::{LinkFail, ModuleLimits, ModuleLoader};
|
||||
use crate::value::Value;
|
||||
@@ -865,6 +865,11 @@ impl Realm {
|
||||
pub fn reset_folder_current(&mut self) -> Result<(), RunError> {
|
||||
self.interp.last_thrown = Value::Undefined;
|
||||
self.interp.last_error = Value::Null;
|
||||
for id in std::mem::take(&mut self.interp.host_file_objects) {
|
||||
if let Class::Host(host) = &mut self.interp.object_mut(id).map_err(|_| internal_error("missing host file object"))?.class {
|
||||
host.files.clear();
|
||||
}
|
||||
}
|
||||
match crate::file_classes::reset_current(&mut self.interp) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
|
||||
@@ -720,7 +720,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.taskBar.actions",
|
||||
"Bar Actions",
|
||||
"",
|
||||
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
|
||||
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"conceptToVector\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
|
||||
),
|
||||
(
|
||||
"window.taskBar.resetActions",
|
||||
@@ -1038,6 +1038,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector",
|
||||
"Concept to Vector…",
|
||||
"",
|
||||
"{} open the Concept to Vector panel for the selected image or unexpanded Image Trace object; an error when the selection is not one such object, unlocked and shown (engine: conceptVector.generate / conceptVector.insert)",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector.generate",
|
||||
"Generate Concept to Vector Styles",
|
||||
"",
|
||||
"{} make the styles ticked in the Concept to Vector panel of the selected image or unexpanded Image Trace object, with the panel's Detail (the panel's Generate; engine: conceptVector.generate), and show them in the panel; off the UI thread in the app unless VECTORCRAFT_SYNC_OPEN is set, one part a frame on the web; a run going is canceled first, and the new one starts once its thread has ended → {running: true} while they are made, else {running: false, job}",
|
||||
),
|
||||
(
|
||||
"ui.conceptVector.cancel",
|
||||
"Cancel Concept to Vector",
|
||||
"",
|
||||
"{} stop the styles the Concept to Vector panel is making off the UI thread (the panel's Cancel; on the web, before the next part): nothing is kept or shown → {canceled: 0 or 1}",
|
||||
),
|
||||
(
|
||||
"ui.recolorUndo",
|
||||
"Undo Changes",
|
||||
@@ -1555,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit
|
||||
//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after
|
||||
//! another, each starting where the last one ended, with the same pen and clip, join into one
|
||||
//! path. Other strokes stay apart, each with its own caps and its own dashes.
|
||||
//! path. Other strokes stay apart, each with its own caps and its own dashes. A path that is
|
||||
//! only filled comes in with every figure closed.
|
||||
//! - A path filled with a pattern or hatched brush is filled with the average color of the
|
||||
//! brush's tile.
|
||||
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
|
||||
@@ -309,11 +310,14 @@ impl Mapper {
|
||||
st
|
||||
}
|
||||
|
||||
/// A path node painted with `fill` and `stroke`; None when neither shows.
|
||||
/// A path node painted with `fill` and `stroke`; None when neither shows. A path that is only
|
||||
/// filled has every figure closed, as a fill closes it: a figure a file fills without closing
|
||||
/// it (FILLPATH without CLOSEFIGURE) comes in as a closed path.
|
||||
fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option<Node> {
|
||||
if bp.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bp = if stroke.is_none() { closed_figures(&bp) } else { bp };
|
||||
let mut items = vec![];
|
||||
if let Some(c) = fill.filter(|c| c[3] > 0) {
|
||||
let mut f = FillLayer::new(color(c));
|
||||
@@ -793,6 +797,29 @@ impl Mapper {
|
||||
}
|
||||
}
|
||||
|
||||
/// `bp` with every figure that has a segment and no close closed.
|
||||
fn closed_figures(bp: &BezPath) -> BezPath {
|
||||
let mut out = BezPath::new();
|
||||
let mut open = false;
|
||||
for el in bp.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(_) => {
|
||||
if open {
|
||||
out.close_path();
|
||||
}
|
||||
open = false;
|
||||
}
|
||||
PathEl::ClosePath => open = false,
|
||||
PathEl::LineTo(_) | PathEl::QuadTo(..) | PathEl::CurveTo(..) => open = true,
|
||||
}
|
||||
out.push(*el);
|
||||
}
|
||||
if open {
|
||||
out.close_path();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where a line `lead + span` long (along the baseline) starts from the reference point, as
|
||||
/// `align` puts it, and `lead` on from there: where its first character starts.
|
||||
fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
|
||||
|
||||
@@ -1560,3 +1560,51 @@ fn emf_without_a_frame_is_read_at_its_device_resolution() {
|
||||
let p = paths(&back.document);
|
||||
assert!(near(p[0].geometric_bounds().unwrap(), Rect::new(10.0 * mm, 5.0 * mm, 20.0 * mm, 7.5 * mm), 0.01), "{:?}", p[0].geometric_bounds());
|
||||
}
|
||||
|
||||
/// Whether each subpath of each path in `bytes` is closed, in order.
|
||||
fn closed_subpaths(bytes: &[u8]) -> Vec<Vec<bool>> {
|
||||
paths(&import(bytes).unwrap().document)
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().map(|s| s.closed).collect(),
|
||||
_ => panic!("a path"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filled_ellipses_and_filled_path_figures_come_in_closed() {
|
||||
// A green brush in slot 1, selected; a null pen.
|
||||
let brush = vec![(39, le(&[1, 0, 0x00_ff_00, 0])), (37, le(&[1])), (37, le(&[0x8000_0008u32 as i32]))];
|
||||
// EMR_ELLIPSE.
|
||||
let ellipse = [brush.clone(), vec![(42, le(&[1000, 1000, 2000, 1500]))]].concat();
|
||||
assert_eq!(closed_subpaths(&hand_emf(5000, 3000, &ellipse)), vec![vec![true]]);
|
||||
// EmfPlusFillEllipse with an inline green color, in a dual file.
|
||||
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
|
||||
let fill = [le(&[0xFF00_FF00u32 as i32]), le_f32(&[1000.0, 1000.0, 1000.0, 500.0])].concat();
|
||||
let comment = emf_plus(&[(0x4001, 1, header), (0x400E, 0x8000, fill), (0x4002, 0, vec![])]);
|
||||
assert_eq!(closed_subpaths(&hand_emf(5000, 3000, &[(70, comment)])), vec![vec![true]]);
|
||||
// BEGINPATH, two figures of MOVETOEX and POLYBEZIERTO16 (half an ellipse each) without
|
||||
// CLOSEFIGURE, ENDPATH, then `paint`.
|
||||
let bracket = |paint: u32, pen: bool| {
|
||||
let mut r = brush.clone();
|
||||
if pen {
|
||||
r.push((37, le(&[0x8000_0007u32 as i32])));
|
||||
}
|
||||
r.push((59, vec![]));
|
||||
for x in [1000, 3000] {
|
||||
let half: [i16; 12] = [x + 1000, 1500, x + 200, 1500, x, 1400, x, 1250, x, 1100, x + 200, 1000];
|
||||
r.push((27, le(&[i32::from(x) + 1000, 1250])));
|
||||
let mut body = le(&[0, 0, 0, 0, 6]);
|
||||
body.extend(half.iter().flat_map(|v| v.to_le_bytes()));
|
||||
r.push((88, body));
|
||||
}
|
||||
r.push((60, vec![]));
|
||||
r.push((paint, le(&[0, 0, 0, 0])));
|
||||
closed_subpaths(&hand_emf(5000, 3000, &r))
|
||||
};
|
||||
// FILLPATH: a fill closes every open figure.
|
||||
assert_eq!(bracket(62, false), vec![vec![true, true]]);
|
||||
// STROKEPATH: a stroke leaves them open.
|
||||
assert_eq!(bracket(64, true), vec![vec![false, false]]);
|
||||
}
|
||||
|
||||
@@ -42,8 +42,8 @@ pub(crate) use cid::replacement;
|
||||
#[cfg(test)]
|
||||
pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical};
|
||||
pub use entry::{
|
||||
INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE,
|
||||
holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note,
|
||||
CONFLICTING_GLYPHS_NOTE, INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE,
|
||||
UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::cid::{CidText, FontInfo, comparable, font_chars, identify_glyph, matching_face, replacement, unify_radical};
|
||||
use super::entry::{
|
||||
MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS, UNMATCHED_GLYPHS_NOTE,
|
||||
UNNAMED_CHARACTERS_NOTE, max_objects,
|
||||
CONFLICTING_GLYPHS_NOTE, MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS,
|
||||
UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, max_objects,
|
||||
};
|
||||
use super::reshaped;
|
||||
use super::state::{
|
||||
@@ -83,6 +83,7 @@ impl<'p> Builder<'p> {
|
||||
cmyk_keys: HashSet::new(),
|
||||
intent_cmyk: None,
|
||||
separation_paints: HashMap::new(),
|
||||
fill_overprint: (false, 0),
|
||||
opaque: HashSet::new(),
|
||||
warnings: vec![],
|
||||
fonts: HashMap::new(),
|
||||
@@ -155,6 +156,7 @@ impl<'p> Builder<'p> {
|
||||
self.stack = vec![Frame::new(FrameKind::Root)];
|
||||
self.root_groups.clear();
|
||||
self.blend = BlendMode::Normal;
|
||||
self.fill_overprint = (false, 0);
|
||||
self.glyphs = None;
|
||||
self.type3_run = None;
|
||||
self.text = None;
|
||||
@@ -182,6 +184,21 @@ impl<'p> Builder<'p> {
|
||||
self.scan.overprints && self.scan.paints.get(self.paint_at - 1).copied().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the image the interpreter draws now, colorized by `paint`, overprints: its fill
|
||||
/// overprint, as the interpreter reported it for this image. Off in a nested reading, as for
|
||||
/// paths. A process color (one without a swatch) overprinting in mode 0 is reported as paths
|
||||
/// are ([`OVERPRINT_ZERO_MODE`]).
|
||||
pub(super) fn image_overprint(&mut self, paint: &Paint) -> bool {
|
||||
let (on, mode) = self.fill_overprint;
|
||||
if !on || self.nested > 0 {
|
||||
return false;
|
||||
}
|
||||
if mode == 0 && matches!(paint, Paint::Solid { swatch: None, .. }) {
|
||||
self.warn(OVERPRINT_ZERO_MODE);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// What the interpreter draws now, as the page's walk counts it: the path whose turn comes
|
||||
/// next, or the `text` before it. `None` in a nested reading, which the walk doesn't follow.
|
||||
pub(super) fn walked(&self, text: bool) -> Option<Walked> {
|
||||
@@ -207,9 +224,10 @@ impl<'p> Builder<'p> {
|
||||
pub(super) fn end_page(&mut self) -> Vec<(Option<usize>, Vec<Arc<Node>>)> {
|
||||
let mut children = self.close_frames();
|
||||
// The interpreter drew another number of paths than the file was read to paint: which
|
||||
// of them overprint can't be trusted.
|
||||
// of them overprint can't be trusted. An image's overprint comes from the interpreter
|
||||
// itself, so it stays.
|
||||
if self.scan.overprints && self.paint_at != self.scan.paints.len() {
|
||||
children.iter_mut().for_each(vectorcraft_doc::overprint::clear_overprints);
|
||||
children.iter_mut().for_each(vectorcraft_doc::overprint::clear_paint_overprints);
|
||||
self.warn(OVERPRINT_UNREAD);
|
||||
}
|
||||
let groups = std::mem::take(&mut self.root_groups);
|
||||
@@ -801,7 +819,13 @@ impl<'p> Builder<'p> {
|
||||
// A line with a glyph the file's font can't keep (another glyph for the same character)
|
||||
// is kept as outlines too, so each glyph draws as the file does.
|
||||
let conflict = line_conflict && !glyphs.is_empty() && !line_type3;
|
||||
if conflict || (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)) {
|
||||
// The warning names why: the glyph conflict, else type that reshapes as it is set.
|
||||
let note = if conflict {
|
||||
Some(CONFLICTING_GLYPHS_NOTE)
|
||||
} else {
|
||||
(checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)).then_some(RESHAPED_TEXT_NOTE)
|
||||
};
|
||||
if let Some(note) = note {
|
||||
outlined = true;
|
||||
if self.mask.is_some() {
|
||||
self.flush_glyphs();
|
||||
@@ -834,7 +858,7 @@ impl<'p> Builder<'p> {
|
||||
self.flush_masked();
|
||||
}
|
||||
}
|
||||
self.warn(RESHAPED_TEXT_NOTE);
|
||||
self.warn(note);
|
||||
} else {
|
||||
let mut n = Node::new(self.id(), NodeKind::Text(Box::new(t)));
|
||||
n.opacity = opacity;
|
||||
@@ -1114,7 +1138,8 @@ impl<'p> Builder<'p> {
|
||||
}
|
||||
|
||||
/// An image of key `key` (its blob made by `make` the first time), placed by `xf`, with opacity
|
||||
/// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image).
|
||||
/// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image), which
|
||||
/// overprints when the interpreter says the image does ([`Self::image_overprint`]).
|
||||
pub(super) fn add_image_masked(
|
||||
&mut self,
|
||||
key: u128,
|
||||
@@ -1123,6 +1148,7 @@ impl<'p> Builder<'p> {
|
||||
mask: Option<OpacityMask>,
|
||||
colorize: Option<Paint>,
|
||||
) {
|
||||
let overprint = colorize.as_ref().is_some_and(|p| self.image_overprint(p));
|
||||
let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() {
|
||||
v
|
||||
} else {
|
||||
@@ -1143,6 +1169,7 @@ impl<'p> Builder<'p> {
|
||||
);
|
||||
n.extras_mut().mask = mask.map(Box::new);
|
||||
n.extras_mut().colorize = colorize.map(Box::new);
|
||||
n.extras_mut().colorize_overprint = overprint;
|
||||
self.push_node(n);
|
||||
}
|
||||
|
||||
@@ -1616,14 +1643,15 @@ fn visual_glyph_text(text: String) -> String {
|
||||
order.iter().filter_map(|&i| chars.get(i)).collect()
|
||||
}
|
||||
|
||||
/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or
|
||||
/// through children that don't isolate. In an isolated group an overprinting object is drawn on
|
||||
/// the group's empty backdrop, so it covers the inks of the art below the group that it does not
|
||||
/// paint; without isolation it leaves them.
|
||||
/// Whether a visible fill or stroke among `children` overprints, characters' and colorized
|
||||
/// images' too, directly or through children that don't isolate. In an isolated group an
|
||||
/// overprinting object is drawn on the group's empty backdrop, so it covers the inks of the art
|
||||
/// below the group that it does not paint; without isolation it leaves them.
|
||||
fn children_overprint(children: &[Arc<Node>]) -> bool {
|
||||
children.iter().any(|c| {
|
||||
c.visible
|
||||
&& (c.appearance.items.iter().any(|i| i.visible() && i.overprint())
|
||||
&& (c.colorize_overprints()
|
||||
|| c.appearance.items.iter().any(|i| i.visible() && i.overprint())
|
||||
|| matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
|| (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch))))
|
||||
})
|
||||
|
||||
@@ -31,6 +31,10 @@ impl<'a> Device<'a> for Builder<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_overprint(&mut self, fill: bool, _stroke: bool, mode: u8) {
|
||||
self.fill_overprint = (fill, mode);
|
||||
}
|
||||
|
||||
fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &craft::pdf::interpret::Paint<'a>, draw_mode: &PathDrawMode) {
|
||||
self.flush_glyphs();
|
||||
self.flush_type3();
|
||||
|
||||
@@ -180,16 +180,24 @@ pub const UNMATCHED_GLYPHS_NOTE: &str = "text whose glyphs differ from the insta
|
||||
pub const RESHAPED_TEXT_NOTE: &str =
|
||||
"text that would not look as it does in the file if set as type (a script whose letters join) was kept as outlines";
|
||||
|
||||
/// Warning: type in a font the file carries that draws a character with a different glyph than
|
||||
/// the rest of the file does in that font (an alternate letter) was kept as outlines: the font kept
|
||||
/// with the document has one glyph per character ([`crate::import_fonts`]).
|
||||
pub const CONFLICTING_GLYPHS_NOTE: &str =
|
||||
"text that uses a different glyph for a character than the rest of its font (such as an alternate letter) was kept as outlines";
|
||||
|
||||
/// The end of the warning that glyphs whose characters the file doesn't name were kept as
|
||||
/// outlines, after "text in" and the font's name.
|
||||
pub const UNNAMED_CHARACTERS_NOTE: &str = "whose characters the file doesn't name (U+FFFD) was kept as outlines";
|
||||
|
||||
/// Is `note` one of the warnings that glyphs were kept as outlines ([`OUTLINED_TEXT_NOTE`],
|
||||
/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`UNNAMED_CHARACTERS_NOTE`])?
|
||||
/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`CONFLICTING_GLYPHS_NOTE`],
|
||||
/// [`UNNAMED_CHARACTERS_NOTE`])?
|
||||
pub fn is_outlines_note(note: &str) -> bool {
|
||||
note == OUTLINED_TEXT_NOTE
|
||||
|| note == UNMATCHED_GLYPHS_NOTE
|
||||
|| note == RESHAPED_TEXT_NOTE
|
||||
|| note == CONFLICTING_GLYPHS_NOTE
|
||||
|| note.starts_with("text in ") && note.ends_with(UNNAMED_CHARACTERS_NOTE)
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +144,9 @@ pub(super) struct Builder<'p> {
|
||||
/// Images in a Separation space, by key: the paint of their ink, or `None` when they open in
|
||||
/// RGB (an ink that can't be told, tints that can't be read).
|
||||
pub(super) separation_paints: HashMap<u128, Option<Paint>>,
|
||||
/// The fill overprint (`/op`) and overprint mode (`/OPM`) the interpreter reported last. It
|
||||
/// reports them before each image it draws, and an image paints with the fill's overprint.
|
||||
pub(super) fill_overprint: (bool, u8),
|
||||
/// Mask keys of CMYK images whose mask turned out to hide nothing.
|
||||
pub(super) opaque: HashSet<u128>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
|
||||
@@ -79,8 +79,8 @@ pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_w
|
||||
pub use export::{check_page_sizes, export, export_with_report, page_areas};
|
||||
pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template};
|
||||
pub use import::{
|
||||
INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE,
|
||||
holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note,
|
||||
CONFLICTING_GLYPHS_NOTE, INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE,
|
||||
UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note,
|
||||
};
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub use import::{form_content_of, function_evaluations_of, imports_of};
|
||||
|
||||
@@ -443,6 +443,18 @@ pub fn print_regions(doc: &Document, set: &PrintSettings) -> Result<Vec<(Option<
|
||||
layout::regions(&printed_document(doc, set), set)
|
||||
}
|
||||
|
||||
/// The scale `set` prints the region `r` of `printed` (a document as [`printed_document`] gives
|
||||
/// it, `r` one of [`print_regions`]) at on paper (1 = 100%): its horizontal and vertical scales,
|
||||
/// with Fit to Page worked out for that region. `None` when it prints on no page.
|
||||
pub fn print_region_scale(printed: &Document, set: &PrintSettings, r: kurbo::Rect) -> Option<(f64, f64)> {
|
||||
layout::region_scale(printed, set, r)
|
||||
}
|
||||
|
||||
/// Is there art that prints in `r` of `printed`, a document as [`printed_document`] gives it?
|
||||
pub fn prints_art_in(printed: &Document, r: kurbo::Rect) -> bool {
|
||||
layout::has_art(printed, r)
|
||||
}
|
||||
|
||||
impl<'a> Job<'a> {
|
||||
fn new(doc: &'a Document, set: &PrintSettings, postscript: bool) -> Result<Self, PdfError> {
|
||||
set.check()?;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
use kurbo::{Affine, Rect, Vec2};
|
||||
use serde::Serialize;
|
||||
use vectorcraft_doc::marks::outset;
|
||||
use vectorcraft_doc::marks::{PrinterMarks, outset};
|
||||
use vectorcraft_doc::range::parse_range;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes};
|
||||
|
||||
@@ -96,7 +96,7 @@ fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) {
|
||||
|
||||
/// Is there art that prints in `r`? The box of a symbol instance whose art holds brushed strokes
|
||||
/// grows by as far as their brush art can paint ([`SymbolBoxes::with_brush_art`]).
|
||||
fn has_art(doc: &Document, r: Rect) -> bool {
|
||||
pub(crate) fn has_art(doc: &Document, r: Rect) -> bool {
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut any = false;
|
||||
for l in &doc.layers {
|
||||
@@ -183,6 +183,56 @@ fn turns(set: &PrintSettings, (w, h): (f64, f64), flipped: bool) -> (Affine, (f6
|
||||
(v, (w, h))
|
||||
}
|
||||
|
||||
/// The bleed at scale `s` and how far it and the marks reach around the artboard,
|
||||
/// `[top, bottom, left, right]` each.
|
||||
fn reach_around(marks: &PrinterMarks, bleed: [f64; 4], s: (f64, f64)) -> ([f64; 4], [f64; 4]) {
|
||||
let b = scaled(bleed, s);
|
||||
let reach = marks.reach(b);
|
||||
(b, std::array::from_fn::<f64, 4, _>(|i| b[i].max(reach[i])))
|
||||
}
|
||||
|
||||
/// The horizontal and vertical scale `set` prints the artboard `r` at on `imageable` (1 = 100%);
|
||||
/// `None` when Fit to Page finds no scale at which it fits with its bleed and marks.
|
||||
fn print_scale(set: &PrintSettings, marks: &PrinterMarks, bleed: [f64; 4], imageable: Rect, r: Rect) -> Option<(f64, f64)> {
|
||||
match set.scaling {
|
||||
PrintScaling::None => Some((1.0, 1.0)),
|
||||
PrintScaling::Fit => {
|
||||
// The largest scale whose artboard with its bleed and marks fits: the marks reach
|
||||
// further when a larger scale grows the bleed.
|
||||
let fit = |s: f64| {
|
||||
let (_, most) = reach_around(marks, bleed, (s, s));
|
||||
((imageable.width() - most[2] - most[3]) / r.width()).min((imageable.height() - most[0] - most[1]) / r.height())
|
||||
};
|
||||
let first = fit(1.0);
|
||||
let s = if first <= 1.0 { first } else { fit(first) };
|
||||
(s.is_finite() && s > 0.0).then_some((s, s))
|
||||
}
|
||||
_ => Some((set.scale.width / 100.0, set.scale.height / 100.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scale `set` prints the region `r` of `doc` at (1 = 100%), as [`layout`] works it out,
|
||||
/// without laying out its pages: the horizontal and vertical scales. `None` for a
|
||||
/// region with no area, a margin that leaves no imageable area, or art that doesn't fit.
|
||||
pub(crate) fn region_scale(doc: &Document, set: &PrintSettings, r: Rect) -> Option<(f64, f64)> {
|
||||
if !(r.width() > 0.0 && r.height() > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (pw, ph) = set.paper();
|
||||
let landscape = match set.auto_rotate {
|
||||
true => (r.width() > r.height()) != (pw > ph),
|
||||
false => set.orientation.landscape(),
|
||||
};
|
||||
let paper = if landscape { (ph, pw) } else { (pw, ph) };
|
||||
let m = set.margin;
|
||||
let imageable = Rect::new(m, m, paper.0 - m, paper.1 - m);
|
||||
if imageable.width() < 1.0 || imageable.height() < 1.0 {
|
||||
return None;
|
||||
}
|
||||
let marks = crate::printer_marks(&set.marks);
|
||||
print_scale(set, &marks, crate::page_bleed(&set.bleed, doc), imageable, r)
|
||||
}
|
||||
|
||||
fn too_many_pages() -> PdfError {
|
||||
PdfError::BadSetting(format!("the job would print more than {} pages", super::MAX_PAGES))
|
||||
}
|
||||
@@ -222,31 +272,10 @@ pub(crate) fn layout(
|
||||
if imageable.width() < 1.0 || imageable.height() < 1.0 {
|
||||
return Err(PdfError::BadSetting(format!("margin: a {m} pt margin leaves no imageable area on the paper")));
|
||||
}
|
||||
// How far the bleed and marks reach around the artboard at scale `s`, `[top, bottom, left, right]`.
|
||||
let around = |s: (f64, f64)| {
|
||||
let b = scaled(bleed, s);
|
||||
let reach = marks.reach(b);
|
||||
(b, std::array::from_fn::<f64, 4, _>(|i| b[i].max(reach[i])))
|
||||
let Some(scale) = print_scale(set, &marks, bleed, imageable, r) else {
|
||||
return Err(PdfError::BadSetting(format!("{what} doesn't fit the paper with its bleed and marks")));
|
||||
};
|
||||
let scale = match set.scaling {
|
||||
PrintScaling::None => (1.0, 1.0),
|
||||
PrintScaling::Fit => {
|
||||
// The largest scale whose artboard with its bleed and marks fits: the marks reach
|
||||
// further when a larger scale grows the bleed.
|
||||
let fit = |s: f64| {
|
||||
let (_, most) = around((s, s));
|
||||
((imageable.width() - most[2] - most[3]) / r.width()).min((imageable.height() - most[0] - most[1]) / r.height())
|
||||
};
|
||||
let first = fit(1.0);
|
||||
let s = if first <= 1.0 { first } else { fit(first) };
|
||||
if !(s.is_finite() && s > 0.0) {
|
||||
return Err(PdfError::BadSetting(format!("{what} doesn't fit the paper with its bleed and marks")));
|
||||
}
|
||||
(s, s)
|
||||
}
|
||||
_ => (set.scale.width / 100.0, set.scale.height / 100.0),
|
||||
};
|
||||
let (bleed_s, most) = around(scale);
|
||||
let (bleed_s, most) = reach_around(&marks, bleed, scale);
|
||||
let size = (r.width() * scale.0, r.height() * scale.1);
|
||||
let extent = (most[2] + size.0 + most[3], most[0] + size.1 + most[1]);
|
||||
let flipped = !set.auto_rotate && orientation.flipped();
|
||||
|
||||
@@ -560,9 +560,13 @@ choice! {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PrintAdvanced {
|
||||
/// Composite pages print as one image each of the art, at the document's raster effects
|
||||
/// resolution (the app renders them before printing).
|
||||
/// Composite pages print as one image each of the art, at [`Self::bitmap_resolution`] (the
|
||||
/// app renders them before printing).
|
||||
pub print_as_bitmap: bool,
|
||||
/// The resolution Print as Bitmap renders at (ppi, 1–[`MAX_BITMAP_RESOLUTION`]); 0: the
|
||||
/// document's raster effects resolution. Other output leaves it unused.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub bitmap_resolution: f64,
|
||||
pub overprints: PrintOverprints,
|
||||
/// The transparency flattener preset transparency is flattened with (a built-in or saved
|
||||
/// one, by name; the app flattens before printing). Empty: transparency prints live.
|
||||
@@ -583,9 +587,17 @@ pub struct TileOrigin {
|
||||
pub y: f64,
|
||||
}
|
||||
|
||||
/// Whether `v` is 0 (a field left at its default is not written).
|
||||
fn is_zero(v: &f64) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
|
||||
/// Most copies of a job.
|
||||
pub const MAX_COPIES: u32 = 999;
|
||||
|
||||
/// The highest [`PrintAdvanced::bitmap_resolution`] (ppi).
|
||||
pub const MAX_BITMAP_RESOLUTION: f64 = 9600.0;
|
||||
|
||||
impl PrintSettings {
|
||||
/// Refuse values out of range (ranges and tile overlap are checked against the document when
|
||||
/// it prints).
|
||||
@@ -613,6 +625,9 @@ impl PrintSettings {
|
||||
self.marks.check()?;
|
||||
self.bleed.check()?;
|
||||
within("graphics.flatness", self.graphics.flatness, 0.2, 100.0, "")?;
|
||||
if self.advanced.bitmap_resolution != 0.0 {
|
||||
within("advanced.bitmapResolution", self.advanced.bitmap_resolution, 1.0, MAX_BITMAP_RESOLUTION, " ppi")?;
|
||||
}
|
||||
let profile = self.color.profile.trim();
|
||||
if !profile.is_empty() && cms::profile(profile).is_none_or(|p| p.kind == ProfileKind::Gray) {
|
||||
return Err(PdfError::BadSetting(format!("color.profile: no RGB or CMYK profile is called “{profile}”")));
|
||||
|
||||
@@ -275,6 +275,16 @@ fn two_glyphs_for_one_character_both_survive_import() {
|
||||
close(&glyph_ink(db, &imported), "imported");
|
||||
}
|
||||
|
||||
/// The line kept as outlines for its other glyph of `a` is Latin type: the warning names the glyph
|
||||
/// conflict, not a script whose letters join, and is one of the warnings on outlines (which a `.ai`
|
||||
/// read from its layers drops when no outlines are left).
|
||||
#[test]
|
||||
fn a_line_kept_as_outlines_for_another_glyph_names_the_glyph_conflict() {
|
||||
let warnings = import(&two_glyphs_pdf()).warnings;
|
||||
assert!(warnings.iter().any(|w| w == CONFLICTING_GLYPHS_NOTE && is_outlines_note(w)), "{warnings:?}");
|
||||
assert!(warnings.iter().all(|w| !is_outlines_note(w) || w == CONFLICTING_GLYPHS_NOTE), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps:
|
||||
/// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that
|
||||
/// type as outlines with the license warning instead of embedding the font again.
|
||||
|
||||
@@ -134,3 +134,118 @@ fn hidden_optional_content_and_pattern_cells_dont_shift_the_count() {
|
||||
assert!(about_overprint(&r).is_empty(), "layers {layers}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// A 2 × 1 image in the spot ink `Spot1` (a Separation space): it opens colorized by the ink.
|
||||
const SPOT_IMAGE: &str = "<< /Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace [/Separation /Spot1 /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>] /BitsPerComponent 8 /Filter /ASCIIHexDecode /Length 5 >>\nstream\nFF00>\nendstream";
|
||||
|
||||
/// An 8 × 1 image mask: it opens colorized by the color that paints it.
|
||||
const MASK: &str = "<< /Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode /Length 3 >>\nstream\nC3>\nendstream";
|
||||
|
||||
/// A page drawing `image` as `/Im1` with `content`, then the `extra` objects after it.
|
||||
fn open_image(content: &str, image: &str, extra: &[&str]) -> ImportReport {
|
||||
let mut objects = vec![image];
|
||||
objects.extend_from_slice(extra);
|
||||
open(content, &format!("{SPOT} /XObject << /Im1 {} 0 R /X0 {} 0 R >>", first_extra(1), first_extra(1) + 1), &objects)
|
||||
}
|
||||
|
||||
/// Each colorized image in paint order: whether its color overprints.
|
||||
fn image_overprints(d: &Document) -> Vec<bool> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n: &Node| {
|
||||
if matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.is_some() {
|
||||
out.push(n.colorize_overprints());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// One placement of `/Im1`, `i` steps down the page.
|
||||
fn draw(i: u32) -> String {
|
||||
format!("q 80 0 0 10 10 {} cm /Im1 Do Q", 10 + 20 * i)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_image_overprints_as_its_fill_does() {
|
||||
// `/op` is the fill's; `/OP` alone is both; a stroke's `/OP` beside `/op false` is not the image's.
|
||||
let content = format!("/On gs {} /Off gs {} /Stroke gs {} /Both gs {}", draw(0), draw(1), draw(2), draw(3));
|
||||
let r = open_image(&content, SPOT_IMAGE, &[]);
|
||||
assert_eq!(image_overprints(&r.document), [true, false, false, true], "{:?}", r.warnings);
|
||||
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
|
||||
// Written with its overprint and read again, each keeps it.
|
||||
let back = import_with_report(&export(&r.document, &PdfOptions::uncompressed()).unwrap(), &ImportOptions::default()).unwrap();
|
||||
assert_eq!(image_overprints(&back.document), [true, false, false, true], "{:?}", back.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_mask_overprints_as_its_fill_does() {
|
||||
let r = open_image(&format!("/CS0 cs 1 scn /On gs {} /Off gs {}", draw(0), draw(1)), MASK, &[]);
|
||||
assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings);
|
||||
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
|
||||
// Overprint mode 0 changes nothing for a spot color; a process color's zero tints would knock out.
|
||||
let r = open_image(&format!("/Zero gs /CS0 cs 1 scn {}", draw(0)), MASK, &[]);
|
||||
assert_eq!(image_overprints(&r.document), [true]);
|
||||
assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings);
|
||||
let r = open_image(&format!("/Zero gs 0 0 0 1 k {}", draw(0)), MASK, &[]);
|
||||
assert_eq!(image_overprints(&r.document), [true]);
|
||||
assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings);
|
||||
assert!(about_overprint(&r)[0].contains("/OPM 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_in_a_form_overprints_as_the_form_sets_it() {
|
||||
// The page's state, then the form's own.
|
||||
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400]", &format!("{} /Off gs {}", draw(0), draw(1)));
|
||||
let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]);
|
||||
assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_isolated_form_holding_only_an_overprinting_image_stays_isolated() {
|
||||
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400] /Group << /S /Transparency /I true >>", &draw(0));
|
||||
let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]);
|
||||
let mut groups = vec![];
|
||||
r.document.walk(|n: &Node| {
|
||||
if matches!(n.kind, NodeKind::Group { .. }) {
|
||||
groups.push(n.isolate);
|
||||
}
|
||||
});
|
||||
assert_eq!(image_overprints(&r.document), [true]);
|
||||
assert!(groups.contains(&true), "{groups:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_in_a_pattern_cell_knocks_out_as_the_cells_paths_do() {
|
||||
let (x, cell) = (first_extra(1), first_extra(1) + 1);
|
||||
let cell_stream = stream(
|
||||
&format!(
|
||||
"/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {ON} /XObject << /Im1 {x} 0 R >> >>"
|
||||
),
|
||||
"/On gs 0 0 1 rg 0 0 5 5 re f q 10 0 0 10 0 0 cm /Im1 Do Q",
|
||||
);
|
||||
let r = open("/On gs /Pattern cs /P0 scn 0 0 100 100 re f", &format!("/Pattern << /P0 {cell} 0 R >>"), &[SPOT_IMAGE, &cell_stream]);
|
||||
let mut art = vec![];
|
||||
for p in r.document.patterns.iter() {
|
||||
for a in &p.art {
|
||||
a.walk(&mut |n: &Node| {
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
art.push(n.colorize_overprints());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
assert_eq!(art, [false], "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_keeps_its_overprint_on_a_page_whose_paths_cant_be_counted() {
|
||||
// The paths' overprint is dropped (see above); the image's comes from the interpreter.
|
||||
let content = format!("0 0 1 rg /Sh0 sh /On gs 10 10 50 50 re f {}", draw(4));
|
||||
let page = PdfPage {
|
||||
resources: format!("{ON} /Shading << /Sh0 << /ShadingType 99 >> >> /XObject << /Im1 {} 0 R >>", first_extra(1)),
|
||||
..PdfPage::new(400.0, 400.0, &content)
|
||||
};
|
||||
let r = import_with_report(&pdf_with(&[page], &[SPOT_IMAGE], None), &ImportOptions::default()).unwrap();
|
||||
assert_eq!(overprints(&r.document), [(Some(false), None)]);
|
||||
assert_eq!(image_overprints(&r.document), [true]);
|
||||
assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
@@ -537,7 +537,9 @@ impl Chain {
|
||||
|
||||
/// The index that ends the chain is of the member `name`, which a string literal in brackets
|
||||
/// named: `[]` becomes `.name` when one of [`catalog::DOM_DOCUMENTS`] reads that member as a
|
||||
/// property (`app['activeDocument']`, `app['documents'][0]`). Any other name keeps the index.
|
||||
/// property (`app['activeDocument']`, `app['documents'][0]`), and when `name` is a member every
|
||||
/// collection inherits or one the collection lists (`app.documents['length']`), so the index is
|
||||
/// not read as a lookup by name. Any other name keeps the index.
|
||||
fn name_index(&mut self, name: &str, cap: usize) {
|
||||
let Some(base) = self.path.strip_suffix("[]").filter(|_| !self.cut) else { return };
|
||||
let property = |d: &&str| {
|
||||
@@ -546,8 +548,11 @@ impl Chain {
|
||||
.and_then(|m| m.strip_prefix(name))
|
||||
.is_some_and(|rest| rest.is_empty() || rest.starts_with('.') || rest.starts_with('['))
|
||||
};
|
||||
let collection = base.rsplit('.').next().unwrap_or(base);
|
||||
let member = catalog::OBJECT_PROTOTYPE_MEMBERS.contains(&name)
|
||||
|| catalog::DOM_COLLECTIONS.iter().any(|(c, members)| collection == *c && members.contains(&name));
|
||||
let ident = !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$');
|
||||
if !ident || !catalog::DOM_DOCUMENTS.iter().any(property) {
|
||||
if !ident || !(member || catalog::DOM_DOCUMENTS.iter().any(property)) {
|
||||
return;
|
||||
}
|
||||
self.path.truncate(self.path.len() - 2);
|
||||
|
||||
@@ -110,6 +110,34 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[
|
||||
"app.open()",
|
||||
];
|
||||
|
||||
// Every collection inherits these Object.prototype members (ECMA-262 3rd edition, section 15.2.4).
|
||||
pub(crate) const OBJECT_PROTOTYPE_MEMBERS: &[&str] =
|
||||
&["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable"];
|
||||
|
||||
// Each collection lists the members a string key names instead of looking up an item.
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ and the corresponding collection
|
||||
// pages list these properties and methods.
|
||||
pub(crate) const DOM_COLLECTIONS: &[(&str, &[&str])] = &[
|
||||
("artboards", &["add", "getActiveArtboardIndex", "getByName", "insert", "length", "parent", "remove", "setActiveArtboardIndex", "typename"]),
|
||||
("characterStyles", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("documents", &["add", "addDocument", "addDocumentNoUI", "getByName", "index", "length", "parent", "typename"]),
|
||||
("groupItems", &["add", "createFromFile", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("layers", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("pageItems", &["getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("paragraphStyles", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
(
|
||||
"pathItems",
|
||||
&["add", "ellipse", "getByName", "index", "length", "parent", "polygon", "rectangle", "removeAll", "roundedRectangle", "star", "typename"],
|
||||
),
|
||||
("pathPoints", &["add", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("stories", &["index", "length", "parent", "typename"]),
|
||||
("swatches", &["add", "getByName", "getSelected", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("symbols", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("tags", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]),
|
||||
("textFrames", &["add", "areaText", "getByName", "index", "length", "parent", "pathText", "pointText", "removeAll", "typename"]),
|
||||
("views", &["index", "length", "parent", "typename"]),
|
||||
];
|
||||
|
||||
// The save option of `Document.close` that saves the document to its own file:
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions).
|
||||
|
||||
@@ -67,10 +67,17 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[
|
||||
("file.objects", "var f = new File(path);", "var f = new Filer(path);"),
|
||||
("file.places", "var t = Folder.temp;", "var t = cache.temp;"),
|
||||
("file.read", "var f = new File(p); f.open('r');", "var f = new File(p);"),
|
||||
("file.read", "app.open(f);", "var f = app.open;"),
|
||||
("file.read", "app.open(f);", "cache.app.open(f);"),
|
||||
("file.read", "app.open(f);", "var app = cache; app.open(f);"),
|
||||
("file.read", "app['open'](f);", "var f = app['open'];"),
|
||||
("file.read", "app['open'](f);", "cache.app['open'](f);"),
|
||||
("file.read", "app['open'](f);", "var app = cache; app['open'](f);"),
|
||||
("file.read", "var f = new File(p); var s = f.read();", "var s = cache.read();"),
|
||||
("file.read", "var all = folder.getFiles();", "var all = folder.files;"),
|
||||
("file.read", "var s = File(p).read();", "var s = Cache(p).read();"),
|
||||
("file.write", "var f = new File(p); f.open('w');", "var f = new File(p); f.open('r');"),
|
||||
("file.write", "var app = new File(p); app.open('w');", "var app = new File(p); app.open('r');"),
|
||||
("file.write", "var f = File.saveDialog(); f.write(s);", "var f = picker(); f.write(s);"),
|
||||
("file.write", "new File(p).remove();", "new Thing(p).remove();"),
|
||||
("file.write", "var a = new File(p); var b = a; b.remove();", "var a = new File(p); var b = a.parent; b.remove();"),
|
||||
@@ -560,6 +567,7 @@ fn save_as_and_export_file_write_a_file() {
|
||||
"d.saveAs(f);\n",
|
||||
"app.activeDocument.exportFile(f, ExportType.PNG24);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2][..]));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
@@ -748,6 +756,74 @@ fn print_writes_a_file() {
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
}
|
||||
|
||||
/// A document reached with its member names in brackets prints to a file as one reached with dots
|
||||
/// does, and so does one a collection looks up by its name; a bracketed name that is not a
|
||||
/// document's member, and a computed one, do not. The report shows a member named in brackets
|
||||
/// after a dot.
|
||||
#[test]
|
||||
fn print_on_bracketed_document_chains_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
|
||||
"app['activeDocument'].print(o);\n",
|
||||
"app[\"activeDocument\"][\"print\"](o);\n",
|
||||
"app[\"documents\"][0].print(o);\n",
|
||||
"app.documents['Draft'].print(o);\n",
|
||||
"app['preferences'].print(o);\n",
|
||||
"app[key].print(o);\n",
|
||||
"app['open'](new File(p));\n",
|
||||
"var d = app['activeDocument']; d.print(o);\n",
|
||||
"app.documents['getByName']('Draft').print(o);\n",
|
||||
"app['documents']['length'].print(o);\n",
|
||||
"var grouped = (app['activeDocument']); grouped.print(o);\n",
|
||||
"var scoped = app['activeDocument']; function f(scoped) {} scoped.print(o);\n",
|
||||
"var caught = app['activeDocument']; try {} catch (caught) {} caught.print(o);\n",
|
||||
"function later() { future.print(o); } var future = app['activeDocument'];\n",
|
||||
"app.documents['removeAll'].print(o);\n",
|
||||
"app['documents']['remove'].print(o);\n",
|
||||
"app.documents['addDocumentNoUI']('Print').print(o);\n",
|
||||
"app.documents['index'](0).print(o);\n",
|
||||
"app.documents['parent'].print(o); app.documents['typename'].print(o);\n",
|
||||
"app['documents']['toString'].print(o);\n",
|
||||
));
|
||||
let lines = &[2, 3, 4, 5, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[8][..]));
|
||||
assert!(r.members.iter().any(|m| m.name == "app.activeDocument.print()"));
|
||||
}
|
||||
|
||||
/// The document `app.open` returns prints to a file when `open` is named in brackets too, and the
|
||||
/// call reads the opened file.
|
||||
#[test]
|
||||
fn print_on_a_document_app_open_returns_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
|
||||
"app['open'](new File(p)).print(o);\n",
|
||||
"app.open(new File(p))['print'](o);\n",
|
||||
"app[\"open\"](new File(p))[\"print\"](o);\n",
|
||||
));
|
||||
let lines = &[2, 3, 4][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(lines));
|
||||
}
|
||||
|
||||
/// A bracketed document chain keeps its member names across scans and included files.
|
||||
#[test]
|
||||
fn print_on_bracketed_document_chains_in_included_files_writes_a_file() {
|
||||
for order in [["doc.jsxinc", "alias.jsxinc"], ["alias.jsxinc", "doc.jsxinc"]] {
|
||||
let mut m = mem(&[("doc.jsxinc", "var doc = app['activeDocument'];\n"), ("alias.jsxinc", "var alias = doc;\n")]);
|
||||
let main = format!("#include '{}'\n#include '{}'\ndoc.print(o);\nalias.print(o);\n", order[0], order[1]);
|
||||
let r = check("main.jsx", main.as_bytes(), Some(&mut m), &Limits::default());
|
||||
let lines = &[3, 4][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines), "{order:?}");
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)], "{order:?}");
|
||||
let mut members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect();
|
||||
members.sort_unstable();
|
||||
assert_eq!(members, ["app.activeDocument", "app.activeDocument.print()"], "{order:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A string literal in brackets that names `activeDocument` or `documents` reads that property, so the
|
||||
/// `print` of the document it gives writes a file; any other name in the brackets, a name that is not
|
||||
/// a property's, and a computed name do not give a document.
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use vectorcraft_doc::text::CompositeClasses;
|
||||
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, TextObject, TextRun};
|
||||
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, Digits, TextObject, TextRun};
|
||||
|
||||
use super::face::FALLBACK_FAMILY;
|
||||
use super::{Arc, FontDb, FontFace, FontMatch};
|
||||
@@ -242,6 +242,24 @@ impl FontDb {
|
||||
/// match, and the characters (neither whitespace nor control characters, sorted, each once)
|
||||
/// that their part's face lacks. `None` when `name` is no composite font.
|
||||
pub fn composite_coverage(&self, name: &str, texts: &[&str]) -> Option<CompositeCoverage> {
|
||||
self.coverage_of(name, texts, None)
|
||||
}
|
||||
|
||||
/// [`FontDb::composite_coverage`] of the characters layout draws in numeral system `digits`:
|
||||
/// each grapheme cluster's part is chosen by its own first character, and the part's face is
|
||||
/// checked for the cluster's drawn characters ([`crate::drawn_chars`]).
|
||||
pub fn composite_drawn_coverage(&self, name: &str, texts: &[&str], digits: Digits) -> Option<CompositeCoverage> {
|
||||
self.coverage_of(name, texts, Some((digits, false)))
|
||||
}
|
||||
|
||||
/// [`FontDb::composite_drawn_coverage`] of type set in All Caps when `all_caps` is on: each
|
||||
/// cluster's part is still chosen by its own first character, and the part's face is also
|
||||
/// checked for the capitals layout draws.
|
||||
pub fn composite_cased_coverage(&self, name: &str, texts: &[&str], digits: Digits, all_caps: bool) -> Option<CompositeCoverage> {
|
||||
self.coverage_of(name, texts, Some((digits, all_caps)))
|
||||
}
|
||||
|
||||
fn coverage_of(&self, name: &str, texts: &[&str], digits: Option<(Digits, bool)>) -> Option<CompositeCoverage> {
|
||||
let f = self.composite_font(name)?;
|
||||
let rank = |m: FontMatch| match m {
|
||||
FontMatch::Exact => 0,
|
||||
@@ -272,7 +290,18 @@ impl FontDb {
|
||||
if worst.as_ref().is_none_or(|(w, _)| rank(m) > rank(*w)) {
|
||||
worst = Some((m, found.as_ref().map(|(face, _)| face.clone())));
|
||||
}
|
||||
lacking.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c))));
|
||||
match digits {
|
||||
Some((d, caps)) => {
|
||||
let missing = |c: &char| !found.as_ref().is_some_and(|(face, _)| face.covers(*c));
|
||||
lacking.extend(crate::drawn_chars(g, d).filter(missing));
|
||||
if caps {
|
||||
let upper: String = g.chars().flat_map(char::to_uppercase).collect();
|
||||
lacking.extend(crate::drawn_chars(&upper, d).filter(missing));
|
||||
}
|
||||
}
|
||||
None => lacking
|
||||
.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))),
|
||||
}
|
||||
}
|
||||
lacking.sort_unstable();
|
||||
lacking.dedup();
|
||||
|
||||
@@ -99,6 +99,8 @@ pub fn fit_source_lines(db: &FontDb, t: &mut TextObject, lines: usize) -> bool {
|
||||
/// own underline and strikeout metrics through the glyph's transform (so the size, baseline shift
|
||||
/// and scaling follow) → (run, bar in text space). Type on a path and vertical type have none yet.
|
||||
pub fn decorations(layout: &TextLayout, db: &FontDb, t: &TextObject) -> Vec<(usize, BezPath)> {
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
crate::test_fonts::count_decorations();
|
||||
let mut out = vec![];
|
||||
if layout.on_path || layout.vertical {
|
||||
return out;
|
||||
@@ -449,6 +451,14 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
|
||||
let original = |run: &mut usize| *run = from.get(*run).copied().unwrap_or(*run);
|
||||
l.glyphs.iter_mut().chain(l.ruby.iter_mut()).for_each(|g| original(&mut g.run));
|
||||
l.inlines.iter_mut().for_each(|i| original(&mut i.run));
|
||||
let mut ink: Vec<Option<Rect>> = vec![None; t.runs.len()];
|
||||
for (mut run, bounds) in std::mem::take(&mut l.run_ink_bounds).into_iter().enumerate() {
|
||||
original(&mut run);
|
||||
if let (Some(ink), Some(bounds)) = (ink.get_mut(run), bounds) {
|
||||
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
|
||||
}
|
||||
}
|
||||
l.run_ink_bounds = ink;
|
||||
l
|
||||
}
|
||||
|
||||
@@ -572,6 +582,6 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T
|
||||
cx.out.line_xf = line_xf;
|
||||
}
|
||||
keep_lone_ligature_carets(&mut cx.out.glyphs);
|
||||
finish_bounds(&mut cx.out);
|
||||
finish_bounds(&mut cx.out, t.runs.len());
|
||||
cx.out
|
||||
}
|
||||
|
||||