Merge main into feat/scripts-api-d10-print-options

This commit is contained in:
dotCooCoo committed 2026-12-05 06:19:46 -08:00
commit 9706d36bc6
204 files changed
+10807 -868

No files matched your search

+7
View File
@@ -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 |
Generated
+91 -91
View File
@@ -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",
+41 -41
View File
@@ -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" }
+1 -1
View File
@@ -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 }
+4
View File
@@ -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;
+144 -1
View File
@@ -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() {
+1
View File
@@ -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

+1
View File
@@ -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

+1
View File
@@ -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

+1
View File
@@ -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

+1
View File
@@ -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

+1
View File
@@ -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

+1
View File
@@ -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

+10
View File
@@ -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),
+18 -7
View File
@@ -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);
}
}
+10
View File
@@ -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 {
+2
View File
@@ -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());
+8 -1
View File
@@ -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;
+6 -1
View File
@@ -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, &params).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", &params).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, &params).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));
}
+830
View File
@@ -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
),
]
}
+36 -7
View File
@@ -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);
+1 -1
View File
@@ -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;
+44 -24
View File
@@ -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()
}
+3 -3
View File
@@ -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
),
+23
View File
@@ -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)),
+5 -1
View File
@@ -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);
}
};
+44 -36
View File
@@ -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
@@ -115,43 +116,28 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
/// 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.
/// 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<()> {
// Files that exist are compared by their real paths. A file a write would create is also
// compared with every other destination by `target_key`.
let mut exact = std::collections::HashSet::new();
let mut folded: std::collections::HashMap<std::path::PathBuf, bool> = std::collections::HashMap::new();
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 exists = std::fs::symlink_metadata(&real).is_ok();
let same_new_file = match folded.insert(target_key(real.clone(), FOLD_CASE), exists) {
Some(other_exists) => !(exists && other_exists),
None => false,
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 !exact.insert(real) || same_new_file {
if !targets.insert(key) {
return Err(EngineError::Other("output destinations resolve to the same file".into()));
}
}
Ok(())
}
/// Whether file names ignore letter case: Windows and macOS file systems do by default, so `A.png`
/// and `a.png` name one file there. Files that already exist are compared by their real paths, so a
/// case-sensitive folder's `A.png` and `a.png` stay two files.
#[cfg(not(target_arch = "wasm32"))]
const FOLD_CASE: bool = cfg!(any(windows, target_os = "macos"));
/// `real` as compared with the other destinations: in lowercase when `fold_case`.
#[cfg(not(target_arch = "wasm32"))]
fn target_key(real: std::path::PathBuf, fold_case: bool) -> std::path::PathBuf {
if fold_case { std::path::PathBuf::from(real.to_string_lossy().to_lowercase()) } else { real }
}
/// 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"))]
@@ -184,18 +170,6 @@ fn dangling_target(path: &str) -> Option<std::path::PathBuf> {
.or_else(|| std::path::absolute(&at).ok())
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod case_tests {
use std::path::PathBuf;
#[test]
fn names_that_differ_only_in_case_are_the_same_file_where_case_is_ignored() {
let key = |p: &str, fold| super::target_key(PathBuf::from(p), fold);
assert_eq!(key("/out/Out.png", true), key("/out/out.png", true), "one file where case is ignored");
assert_ne!(key("/out/Out.png", false), key("/out/out.png", false), "two files where case counts");
}
}
/// `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) {
@@ -227,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);
}
}
+8 -6
View File
@@ -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())
+7 -1
View File
@@ -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
+5 -11
View File
@@ -1098,20 +1098,14 @@ impl SaveJob {
}
super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
}
// An existing destination that is a folder or a read-only file is refused before any file
// is written too.
// An existing destination that is a read-only file is refused before any file is written too.
#[cfg(not(target_arch = "wasm32"))]
if files.len() > 1 {
for (p, _) in &files {
let Ok(meta) = std::fs::metadata(p) else { continue };
let refused = if meta.is_dir() {
crate::EngineError::Other(format!("{p}: is a folder, not a file"))
} else if meta.is_file() && meta.permissions().readonly() {
super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))
} else {
continue;
};
return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused });
if std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().readonly()) {
let refused = super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied));
return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused });
}
}
}
for (i, (p, bytes)) in files.iter().enumerate() {
+1 -1
View File
@@ -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);
}
+17 -2
View File
@@ -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 }))
}
+84 -18
View File
@@ -273,6 +273,12 @@ fn unplace_all(mut ap: Appearance) -> Appearance {
ap
}
/// The fills, strokes and effects new art takes from graphic style `g`, placed gradients relative
/// to the unit box.
fn style_look(g: &GraphicStyle) -> Appearance {
if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) }
}
/// How a new object looks ([`Session::new_art_look`]): its appearance and transparency and the
/// graphic style it is linked to.
pub(crate) struct NewArt {
@@ -280,6 +286,8 @@ pub(crate) struct NewArt {
opacity: f32,
blend: BlendMode,
style: Option<String>,
/// Taken from a graphic style, linked to it or not (a style from another document is not).
styled: bool,
/// From the template: placed gradients are relative to the unit box.
unit_box: bool,
}
@@ -287,24 +295,47 @@ pub(crate) struct NewArt {
impl NewArt {
/// A plain look: `appearance`, full opacity, no link.
pub(crate) fn plain(appearance: Appearance) -> Self {
Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, unit_box: false }
Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, styled: false, unit_box: false }
}
/// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and
/// it links to the style (type keeps its own transparency).
/// it links to the style, taking its isolate and knockout too (type keeps its own transparency
/// unless the look is a graphic style's). A look that no longer matches the style's definition
/// (the style was redefined after it was picked) is given unlinked ([`NewArt::linked_style`]).
pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) {
self.place(n);
if matches!(n.kind, NodeKind::Text(_)) && !self.styled {
return;
}
(n.opacity, n.blend) = (self.opacity, self.blend);
let style = self.linked_style(d);
if let Some(g) = style.and_then(|i| d.graphic_styles.get(i)) {
(n.isolate, n.knockout) = (g.isolate, g.knockout);
}
n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i));
}
/// The index in `d` of the graphic style this look links to: its style, while the style's
/// fills, strokes, effects, opacity and blend mode are still the ones this look has.
pub(crate) fn linked_style(&self, d: &Document) -> Option<usize> {
let i = d.graphic_style_index(self.style.as_deref()?)?;
let g = d.graphic_styles.get(i)?;
((g.opacity, g.blend) == (self.opacity, self.blend) && style_look(g).approx_eq(&self.appearance)).then_some(i)
}
/// Give `n` this look's appearance, its placed gradients relative to `n`'s bounds now.
pub(crate) fn place(&self, n: &mut Node) {
n.appearance = self.appearance.clone().into();
if self.unit_box
&& n.appearance.has_placed_gradient()
if self.places_gradients()
&& let Some(b) = n.geometric_bounds()
{
n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b);
}
if matches!(n.kind, NodeKind::Text(_)) {
return;
}
(n.opacity, n.blend) = (self.opacity, self.blend);
n.extras_mut().graphic_style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)).map(|i| d.graphic_style_id(i));
}
/// Does this look place gradients on the bounds of the object it is given to?
pub(crate) fn places_gradients(&self) -> bool {
self.unit_box && self.appearance.has_placed_gradient()
}
}
@@ -332,7 +363,32 @@ impl Session {
st.width = width;
}
let (opacity, blend, style) = self.new_art_transparency();
NewArt { appearance, opacity, blend, style: style.map(str::to_string), unit_box: true }
NewArt { appearance, opacity, blend, style: style.map(str::to_string), styled: self.new_art_styled(), unit_box: true }
}
/// The look of new type (`text.create`): the template's fills, strokes and effects when it is
/// more than one plain fill and stroke or comes from a graphic style (of this document or
/// another), else none of its own, so the characters' fill and stroke show. The document's own
/// default look (its redefined Default Graphic Style, which [`reset`] gives new art) leaves type
/// plain as the shipped default does; the same look taken from the selection does not. The
/// template is not repainted with the fill and stroke proxies.
pub(crate) fn new_type_look(&self) -> NewArt {
let plain = || NewArt::plain(Appearance::default());
let Some(t) = self.template() else { return plain() };
let styled = self.new_art_styled();
let default_look =
|| !self.paint.inherited && self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t));
if !styled && (t.is_basic() || default_look()) {
return plain();
}
let (opacity, blend, style) = self.new_art_transparency();
NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), styled, unit_box: true }
}
/// Does the next object drawn take its look from a graphic style, in this document or the one
/// the style was taken from?
fn new_art_styled(&self) -> bool {
!self.basic_only() && self.paint.style.is_some()
}
/// The appearance of the next object drawn (the Appearance panel shows it with nothing
@@ -341,9 +397,16 @@ impl Session {
self.new_art_look(self.paint.fill.clone(), self.paint.stroke.clone(), self.paint.stroke_width).appearance
}
/// The opacity, blend mode and graphic style (name) of the next object drawn.
/// The opacity, blend mode and graphic style (name) of the next object drawn. The style is
/// left out in a document other than the one it was taken from, so new art there is not
/// linked to a style of the same name.
pub fn new_art_transparency(&self) -> (f32, BlendMode, Option<&str>) {
if self.basic_only() { (1.0, BlendMode::Normal, None) } else { (self.paint.opacity, self.paint.blend, self.paint.style.as_deref()) }
if self.basic_only() {
return (1.0, BlendMode::Normal, None);
}
let here = self.active().map(|st| st.uid);
let style = self.paint.style.as_deref().filter(|_| self.paint.style_doc.is_some() && self.paint.style_doc == here);
(self.paint.opacity, self.paint.blend, style)
}
/// The stroke of the next object drawn (the Stroke panel shows it with nothing selected).
@@ -378,7 +441,7 @@ impl Session {
/// A graphic style clicked with nothing selected: new art takes it (`add`: its fills, strokes
/// and effects on top of the template's, unlinked).
pub(crate) fn new_art_style(&mut self, g: &GraphicStyle, add: bool) {
let ap = if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) };
let ap = style_look(g);
if add {
let t = self.new_art_template_mut();
t.items.extend(ap.items);
@@ -390,14 +453,16 @@ impl Session {
}
/// Make `ap` (placed gradients relative to the unit box) and this transparency the template,
/// and its top fill, stroke and weight the proxies.
/// and its top fill, stroke and weight the proxies. `style` is a graphic style of the
/// document in front.
fn take_new_art(&mut self, ap: Appearance, opacity: f32, blend: BlendMode, style: Option<String>, inherited: bool) {
let style_doc = style.as_ref().and_then(|_| self.active().map(|st| st.uid));
let p = &mut self.paint;
(p.fill, p.stroke) = (unplaced(&ap.fill_paint()), unplaced(&ap.stroke_paint()));
if let Some(st) = ap.stroke() {
p.stroke_width = st.width;
}
(p.appearance, p.opacity, p.blend, p.style, p.inherited) = (Some(ap), opacity, blend, style, inherited);
(p.appearance, p.opacity, p.blend, p.style, p.style_doc, p.inherited) = (Some(ap), opacity, blend, style, style_doc, inherited);
}
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
@@ -522,7 +587,9 @@ fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
}
fn describe(s: &mut Session, _: &Value) -> Result<Value> {
let (opacity, blend, style) = s.new_art_transparency();
let (opacity, blend, _) = s.new_art_transparency();
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let style = s.doc().ok().and_then(|st| look.linked_style(&st.doc)).and_then(|i| s.doc().ok()?.doc.graphic_styles.get(i)).map(|g| g.name.clone());
Ok(json!({
"basic": s.prefs.new_art_basic,
"appearance": s.new_art(),
@@ -540,8 +607,7 @@ pub(crate) fn reset(s: &mut Session) {
s.paint = PaintDefaults::default();
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
if let Some(g) = style {
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
s.take_new_art(style_look(&g), 1.0, BlendMode::Normal, None, false);
}
}
+2 -1
View File
@@ -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));
+86 -56
View File
@@ -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> {
@@ -2610,12 +2625,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
+1
View File
@@ -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",
+12 -3
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or pre Line truncated
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at bitmapResolution, or lower for a page larger than 64 Mpx or 32,768 px a side, with a warning when bitmapResolution was given), bitmapResolution: 0 (ppi Print as Bitmap prints at on paper, so a print scale above 100% renders more pixels, 1–9600; 0: the document's raster effects resolution; other output leaves it unused), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {pla Line truncated
has_doc,
setup
),
@@ -138,6 +138,12 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
let set = preset_or_saved(C, s, doc, p)?;
super::printadvanced::flattener(C, &set, &s.prefs.flattener_presets)?;
let mut pv = vectorcraft_pdf::preview(doc, &set).map_err(|e| pdf_error(C, e))?;
if set.advanced.print_as_bitmap && set.advanced.bitmap_resolution > 0.0 {
// Print as Bitmap renders placed documents' art and the artboards' background colors too.
let (full, _) = super::place::document::full_documents(doc);
let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(C, e))?;
pv.setting_notes.extend(super::printadvanced::bitmap_notes(C, &filled, &set)?);
}
pv.warnings.extend(type_warnings(doc, set.print_layers, &areas(&pv)));
// What the job loses comes first, then the notes on the options.
let settings = std::mem::take(&mut pv.setting_notes);
@@ -275,7 +281,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
let tile_images =
postscript && !bitmap && flattener.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
let mut bitmap_notes = vec![];
let prepared =
super::printadvanced::prepare_noting(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich", &mut bitmap_notes)?;
let path = str_param(p, "path");
// The type is read before raster effects and Print as Bitmap turn it into images.
let which = set.print_layers;
@@ -293,10 +301,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
// What the job loses comes first, then the notes on the options.
r.warnings.extend(typed);
r.warnings.extend(r.setting_notes);
r.warnings.extend(bitmap_notes);
return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings }));
}
// What the job loses, then the notes on the options: a reply lists them in that order.
let (mut warnings, mut setting_notes) = (vec![], vec![]);
let (mut warnings, mut setting_notes) = (vec![], bitmap_notes);
if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) {
warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string());
}
+103 -20
View File
@@ -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))
}
+6 -1
View File
@@ -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;
+2 -1
View File
@@ -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"),
+269
View File
@@ -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(())
}
+440
View File
@@ -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(&params).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, &params, res));
if self.out.len() < self.request.styles.len() {
return Ok(None);
}
Ok(Some(with_seams(std::mem::take(&mut self.out))))
}
}
File diff suppressed because it is too large. Load diff
+11
View File
@@ -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>,
+8 -2
View File
@@ -48,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
@@ -268,7 +271,7 @@ const JOB: Class = Class {
name: "PrintJobOptions",
fields: &[
f("artboardRange", Kind::Text, Start::Text("1-")),
kept("bitmapResolution", Kind::Number(0.0, 1_000_000_000.0), 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(
@@ -694,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());
@@ -1203,7 +1209,7 @@ 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") },
@@ -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)
})
+12
View File
@@ -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);
+6
View File
@@ -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);
+6 -4
View File
@@ -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;
+246
View File
@@ -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);
}
+28 -1
View File
@@ -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();
+135
View File
@@ -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)));
}
}
+205
View File
@@ -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]
+1 -1
View File
@@ -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]) {
+62 -1
View File
@@ -690,7 +690,6 @@ fn options_that_are_not_available_throw() {
("o.flattenerOptions.rasterizationResolution = NaN;", "PrintFlattenerOptions.rasterizationResolution"),
("o.pageMarksOptions.bleedOffsetRect = [0, 0, 0, 0];", "PrintPageMarksOptions.bleedOffsetRect is not available yet"),
("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"),
("j.bitmapResolution = 0.0000000005;", "PrintJobOptions.bitmapResolution is not available yet"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"),
("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"),
(
@@ -804,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.
@@ -43,7 +43,6 @@ fn app_open_refuses_an_oversized_document() {
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]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
+1 -1
View File
@@ -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 }
}
+185 -36
View File
@@ -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)];
+24 -1
View File
@@ -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));
}
}
+17 -16
View File
@@ -111,21 +111,6 @@ fn own_path(i: &Interp, o: ObjId) -> JsResult<Option<Value>> {
})
}
/// 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);
}
Ok(match own_path(i, id)? {
Some(Value::String(s)) => Some(s.to_rust_string()),
_ => None,
})
}
/// Sets the path of the `File` or `Folder` `o` to `fs`, a path the host gave.
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")) };
@@ -166,7 +151,8 @@ 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) => Ok(match i.ordinary_own_property(o, &key(name))? {
@@ -185,6 +171,21 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
})
}
/// 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);
}
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()));
+1 -1
View File
@@ -561,7 +561,7 @@ impl Interp {
Ok((same, Some(got)))
}
fn sync_host_files(&mut self) -> JsResult<()> {
pub(crate) fn sync_host_files(&mut self) -> JsResult<()> {
let mut updates = Vec::new();
let mut untracked = Vec::new();
for id in self.host_file_objects.clone() {
+7
View File
@@ -432,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),
+17 -1
View File
@@ -1582,6 +1582,12 @@ proptest::proptest! {
/// 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() {
@@ -1630,7 +1636,10 @@ fn file_property_realm() -> (Realm, Rc<RefCell<Vec<String>>>) {
index: None,
construct: None,
};
let child = HostClass { name: "Child".into(), parent: Some("Base".into()), members: vec![], info: Vec::new(), 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)
}
@@ -1642,6 +1651,13 @@ fn an_inherited_file_property_follows_its_files_new_path() {
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();
+20 -2
View File
@@ -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",
+29 -2
View File
@@ -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 {
+48
View File
@@ -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]]);
}
+2 -2
View File
@@ -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};
+40 -12
View File
@@ -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))))
})
+4
View File
@@ -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();
+9 -1
View File
@@ -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)
}
+3
View File
@@ -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>,
+2 -2
View File
@@ -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};
+12
View File
@@ -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()?;
+55 -26
View File
@@ -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();
+17 -2
View File
@@ -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}”")));
+10
View File
@@ -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.
+115
View File
@@ -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);
}
+31 -2
View File
@@ -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();
+11 -1
View File
@@ -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
}
+10 -2
View File
@@ -402,9 +402,17 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool {
!needs_vertical_form || g.gid != g.face.glyph_for(g.ch)
}
pub(super) fn finish_bounds(out: &mut TextLayout) {
pub(super) fn finish_bounds(out: &mut TextLayout, runs: usize) {
let xf = out.line_xf;
let mut b: Option<Rect> = out.ink_bounds();
let mut ink: Vec<Option<Rect>> = vec![None; runs];
let mut b: Option<Rect> = None;
out.for_each_ink(|run, bounds| {
b = Some(b.map_or(bounds, |b| b.union(bounds)));
if let Some(ink) = ink.get_mut(run) {
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
}
});
out.run_ink_bounds = ink;
let mut add = |r: Rect| b = Some(b.map_or(r, |b| b.union(r)));
if !out.on_path {
for l in &out.lines {
+30 -8
View File
@@ -60,7 +60,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
pub use shape::{aki_space, drawn_chars, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
pub use vectorcraft_doc::TextObject;
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
@@ -388,6 +388,9 @@ pub struct TextLayout {
pub lines: Vec<LineInfo>,
/// Ink/advance bounds in text space.
pub bounds: Rect,
/// Ink bounds per text run when layout completed, excluding decorations. These bounds do
/// not update when glyph geometry changes; [`Self::ink_bounds`] measures the current geometry.
pub run_ink_bounds: Vec<Option<Rect>>,
/// True if area text did not fit its frame (the red overflow "+" marker), or on-path text ran
/// past the end of the path.
pub overflow: bool,
@@ -422,6 +425,7 @@ impl Default for TextLayout {
ruby: Vec::new(),
lines: Vec::new(),
bounds: Rect::ZERO,
run_ink_bounds: Vec::new(),
overflow: false,
on_path: false,
frames: Vec::new(),
@@ -477,16 +481,34 @@ impl TextLayout {
/// inline graphics included, without the lines' em boxes that [`Self::bounds`] also covers.
/// What Align to Glyph Bounds aligns. `None` when nothing draws (only spaces, or no text).
pub fn ink_bounds(&self) -> Option<Rect> {
let outlined = |g: &PositionedGlyph| (!g.outline.elements().is_empty()).then(|| g.outline.bounding_box());
let glyphs = self.glyphs.iter().flat_map(|g| {
let mut bounds: Option<Rect> = None;
self.for_each_ink(|_, ink| bounds = Some(bounds.map_or(ink, |bounds| bounds.union(ink))));
bounds
}
fn for_each_ink(&self, mut add: impl FnMut(usize, Rect)) {
let outlined = |g: &PositionedGlyph| {
(!g.outline.elements().is_empty()).then(|| {
#[cfg(any(test, feature = "test-fonts"))]
test_fonts::count_ink_outline();
g.outline.bounding_box()
})
};
for g in &self.glyphs {
let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect()));
let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b));
[outlined(g), image, colour]
});
for ink in [outlined(g), image, colour].into_iter().flatten() {
add(g.run, ink);
}
}
// Ruby is covered by its line's ascent, but its ink can overhang sideways past the line.
let ruby = self.ruby.iter().map(outlined);
let inlines = self.inlines.iter().map(|i| Some(i.bounds));
glyphs.chain(ruby).chain(inlines).flatten().reduce(|a, b| a.union(b))
for g in &self.ruby {
if let Some(ink) = outlined(g) {
add(g.run, ink);
}
}
for inline in &self.inlines {
add(inline.run, inline.bounds);
}
}
/// The box of [`Self::ink_bounds`]' ink with text space mapped by `m`: the glyph and ruby
/// outlines are mapped point by point, so a rotated or sheared `m` gives the outlines' own
+3 -3
View File
@@ -1382,11 +1382,11 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
&& ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking)
}
/// The characters of a grapheme cluster that need a glyph of their own, in the numeral system
/// The characters of the text that need a glyph of their own, in the numeral system
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
/// variation selectors.
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
craft::font_catalog::drawable_characters(cluster, move |c| digits.map(c))
pub fn drawn_chars(text: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
craft::font_catalog::drawable_characters(text, move |c| digits.map(c))
}
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
+14
View File
@@ -29,6 +29,20 @@ pub(crate) fn keeps_shape_plans() -> bool {
std::thread_local! {
/// How many layouts this thread has started ([`layouts_on_this_thread`]).
static LAYOUTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static INK_OUTLINES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static DECORATIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
pub(crate) fn count_ink_outline() {
INK_OUTLINES.with(|n| n.set(n.get() + 1));
}
pub(crate) fn count_decorations() {
DECORATIONS.with(|n| n.set(n.get() + 1));
}
pub fn ink_work_on_this_thread() -> (u64, u64) {
(INK_OUTLINES.with(std::cell::Cell::get), DECORATIONS.with(std::cell::Cell::get))
}
pub(crate) fn count_layout() {
+3
View File
@@ -25,6 +25,8 @@ pub struct PaintDefaults {
pub blend: vectorcraft_color::BlendMode,
/// The graphic style the template came from (by name): new art is linked to it.
pub style: Option<String>,
/// The document `style` is in (its session id): new art in another document is not linked.
pub style_doc: Option<u64>,
/// The template is the last selection's appearance (New Art Has Basic Appearance off): with
/// the option on again, new art takes only its basic fill and stroke.
pub inherited: bool,
@@ -41,6 +43,7 @@ impl Default for PaintDefaults {
opacity: 1.0,
blend: Default::default(),
style: None,
style_doc: None,
inherited: false,
}
}
+1 -1
View File
@@ -483,7 +483,7 @@ shown_when = [
"The Smooth tool, and the Pencil or Blob Brush where Alt gives the Smooth tool, when no path is selected that the Smooth tool can act on: a drag changes nothing.",
]
hotspot = "The centre."
designer = false
look = "A ring crossed by a diagonal bar."
[[cursor]]
id = "Busy"
+17
View File
@@ -834,6 +834,23 @@ fn type_path_handles(cx: &ToolContext) -> Vec<Overlay> {
out
}
/// The anchors and direction handles of selected, editable type on a path's path, for the tools
/// that edit them besides Direct Selection (the Anchor Point, Add and Delete Anchor Point tools and
/// the Pen, #10862): the canvas draws only a path's own.
pub(crate) fn type_path_overlays(cx: &ToolContext) -> Vec<Overlay> {
let editable = cx.doc.editable();
let mut out = vec![];
for &id in &cx.selection.objects {
let Some(path) = cx.doc.node(id).filter(|n| is_path_type(n) && editable(id)).and_then(editable_path) else { continue };
let color = cx.doc.layer_color(id);
out.extend(path.anchors().map(|(_, _, a)| Overlay::Anchor { p: a.p, color, filled: false, size: 5.0 }));
}
if !out.is_empty() {
out.extend(type_path_handles(cx));
}
out
}
/// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and
/// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path,
/// subpath, anchor, is_out).
+52 -7
View File
@@ -377,7 +377,18 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect
/// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]).
pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec<NodeId> {
let mut v: Vec<NodeId> = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect();
candidates(cx, false)
}
/// [`candidate_paths`], with selected type on a path outside perspective among the selected ones:
/// the objects whose anchors the Add, Delete and Anchor Point tools edit (#10862).
pub(crate) fn anchor_owners(cx: &ToolContext) -> Vec<NodeId> {
candidates(cx, true)
}
fn candidates(cx: &ToolContext, path_type: bool) -> Vec<NodeId> {
let picks = |n: &vectorcraft_doc::Node| n.path_data().is_some() || (path_type && crate::select::is_path_type(n));
let mut v: Vec<NodeId> = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(picks)).collect();
let mut rest = vec![];
walk_pickable(cx, |n| {
if let NodeKind::Path { guide: false, .. } = &n.kind {
@@ -407,9 +418,28 @@ pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = No
.filter(move |&id| editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// [`editable_paths`] with selected type on a path outside perspective: the objects the Pen's Auto
/// Add/Delete adds anchors to and deletes them from (#10862).
pub(crate) fn editable_anchor_owners<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
let editable = cx.doc.editable();
cx.selection.objects.iter().copied().filter(move |&id| {
editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. }) || crate::select::is_path_type(n))
})
}
/// The paths whose anchors show with the Pen: the selected ones, and those inside selected groups
/// and compound paths (not guides, nor locked or hidden ones). Pen + Alt converts their anchors.
/// and compound paths (not guides, nor locked or hidden ones).
pub(crate) fn shown_paths(cx: &ToolContext) -> Vec<NodeId> {
shown(cx, false)
}
/// [`shown_paths`] with selected type on a path outside perspective, as the Anchor Point tool the
/// Pen lends takes it ([`anchor_owners`]): the objects whose anchors Pen + Alt converts (#10862).
pub(crate) fn shown_anchor_owners(cx: &ToolContext) -> Vec<NodeId> {
shown(cx, true)
}
fn shown(cx: &ToolContext, path_type: bool) -> Vec<NodeId> {
fn inside(n: &vectorcraft_doc::Node, v: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Path { guide: false, .. } => v.push(n.id),
@@ -424,7 +454,11 @@ pub(crate) fn shown_paths(cx: &ToolContext) -> Vec<NodeId> {
}
let mut v = vec![];
for n in cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)) {
inside(n, &mut v);
if path_type && crate::select::is_path_type(n) {
v.push(n.id);
} else {
inside(n, &mut v);
}
}
let editable = cx.doc.editable();
v.retain(|id| editable(*id));
@@ -436,11 +470,17 @@ pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId
anchor_in(cx, candidate_paths(cx), p, tol)
}
/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor).
/// [`hit_anchor`] on the [`anchor_owners`], selected type on a path's path included.
pub(crate) fn hit_owner_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
anchor_in(cx, anchor_owners(cx), p, tol)
}
/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). Type on
/// a path among `ids` offers its path's anchors ([`vectorcraft_doc::Node::anchor_path`]).
pub(crate) fn anchor_in(cx: &ToolContext, ids: impl IntoIterator<Item = NodeId>, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
let mut best: Option<((NodeId, usize, usize), f64)> = None;
for id in ids {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue };
for (si, ai, a) in pd.anchors() {
let d = a.p.distance(p);
if d <= tol && best.is_none_or(|b| d < b.1 - 1e-9) {
@@ -459,11 +499,16 @@ pub(crate) fn hit_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeI
segment_in(cx, candidate_paths(cx), p, tol)
}
/// [`hit_segment`] on the [`anchor_owners`], selected type on a path's path included.
pub(crate) fn hit_owner_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> {
segment_in(cx, anchor_owners(cx), p, tol)
}
/// Nearest point within `tol` on a segment of the first of `ids` that passes there: (path,
/// subpath, segment, t).
/// subpath, segment, t). Type on a path among `ids` offers its path's segments.
pub(crate) fn segment_in(cx: &ToolContext, ids: impl IntoIterator<Item = NodeId>, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> {
for id in ids {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue };
if let Some((si, seg, t, _, d)) = pd.nearest(p)
&& d <= tol
{
+21 -16
View File
@@ -14,12 +14,14 @@
//! follow the same conversions (#2544).
//! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add,
//! as the Add Anchor Point tool does).
//! Add, Delete and Anchor Point edit the path of selected type on a path outside perspective as
//! they edit a path's (#10862); Delete leaves it two anchors at least, and Scissors does not cut it.
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{ParamCurve, Point};
use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor};
use super::{FEEDBACK, hit_anchor, hit_owner_anchor, hit_owner_segment, hit_segment, insert_anchor, remove_anchor};
use crate::direct::hit_handle;
use crate::guides::{DrawSnap, HandleSnap};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -276,14 +278,14 @@ impl AnchorTool {
}
fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
}
/// Where anchor `ai` is in the document a preview edits: the document as the interaction
/// began, since each preview runs on that, otherwise the document `cx` shows.
fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
let d = cx.interaction_doc.unwrap_or(cx.doc);
d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
d.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
}
/// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned
@@ -342,9 +344,9 @@ impl AnchorTool {
let (point, tol) = (cx.point_tol(), cx.pick_tol());
let mut target = if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
State::Handle { id, si, ai, out, start: p, began: false }
} else if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
} else if let Some((id, si, ai)) = hit_owner_anchor(cx, p, point) {
State::Convert { id, si, ai, start: p, began: false }
} else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) {
} else if let Some((id, si, seg, t)) = hit_owner_segment(cx, p, tol) {
State::Reshape { id, si, seg, t, start: p, began: false, spine: false }
} else {
State::Idle
@@ -402,12 +404,10 @@ impl AnchorTool {
/// instead of converting it. Any other press is kept.
fn moving(cx: &ToolContext, st: State) -> State {
match st {
State::Convert { id, si, ai, start, .. } => {
match cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) {
Some(from) => State::Move { id, si, ai, from, start, began: false },
None => st,
}
}
State::Convert { id, si, ai, start, .. } => match Self::anchor_pos(cx, id, si, ai) {
Some(from) => State::Move { id, si, ai, from, start, began: false },
None => st,
},
State::SpineConvert { id, ai, start, .. } => {
match crate::direct::spines(cx)
.into_iter()
@@ -471,11 +471,11 @@ impl AnchorTool {
}
fn add(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
hit_owner_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect()
}
fn delete(cx: &ToolContext, p: Point) -> Vec<Action> {
hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
hit_owner_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
}
}
@@ -708,8 +708,8 @@ impl Tool for AnchorTool {
let has_handles = cx
.doc
.node(id)
.and_then(|n| n.path_data())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
.and_then(|n| n.anchor_path())
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied())
.is_some_and(|a| a.has_in() || a.has_out());
if has_handles {
vec![Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": "corner"}))]
@@ -743,7 +743,8 @@ impl Tool for AnchorTool {
)]
}
State::Handle { id, si, ai, out, began: false, .. } => {
let Some(a) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) else {
let Some(a) = cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied())
else {
return vec![];
};
vec![Action::Exec(
@@ -780,6 +781,10 @@ impl Tool for AnchorTool {
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = if self.id == "anchorPoint" { Self::spine_overlays(cx) } else { vec![] };
if self.id != "scissors" {
// These tools edit selected type on a path's path, whose anchors the canvas leaves out.
out.extend(crate::direct::type_path_overlays(cx));
}
if matches!(self.state, State::Handle { .. }) {
out.extend(self.guides.iter().cloned());
}
+56
View File
@@ -672,6 +672,62 @@ fn anchor_tools_leave_out_shaper_sources_and_art_outside_isolation() {
assert_eq!(picked(Some(rect), "deleteAnchor", 100.0, 100.0), Some(rect));
}
/// #10862: selected type on a path's path takes the Anchor Point, Add and Delete Anchor Point tools
/// as a path does; Scissors leaves it alone, and type that is not selected is not picked.
#[test]
fn anchor_tools_edit_selected_type_on_a_path() {
let (d, text) = doc_with_path_type();
let p = paint();
let mut s = Selection::default();
s.add(text);
let names = |a: &[Action]| -> Vec<(String, u64)> {
a.iter()
.filter_map(|x| match x {
Action::Preview(c, v) | Action::Exec(c, v) => Some((c.clone(), v["id"].as_u64()?)),
_ => None,
})
.collect()
};
let gesture = |sel: &Selection, tool: &str, from: (f64, f64), to: (f64, f64)| {
let cx = cx(&d, sel, &p);
let mut t = AnchorTool::new(tool);
let mut out = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1));
if from != to {
out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)));
}
out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)));
names(&out)
};
let convert = gesture(&s, "anchorPoint", (400.0, 300.0), (420.0, 260.0));
assert!(convert.contains(&("path.convertAnchor".into(), text.0)), "{convert:?}");
assert_eq!(gesture(&s, "addAnchor", (250.0, 300.0), (250.0, 300.0)), vec![("path.insertAnchor".to_string(), text.0)]);
assert_eq!(gesture(&s, "deleteAnchor", (400.0, 300.0), (400.0, 300.0)), vec![("path.removeAnchor".to_string(), text.0)]);
assert!(gesture(&s, "scissors", (250.0, 300.0), (250.0, 300.0)).is_empty(), "Scissors does not cut type");
let none = Selection::default();
assert!(gesture(&none, "anchorPoint", (400.0, 300.0), (420.0, 260.0)).is_empty(), "type that is not selected");
}
/// #10862: the anchors of selected type on a path's path show with the tools that edit them (the
/// canvas draws only a path's own), not with Scissors, and not when the type is not selected.
#[test]
fn anchor_tools_show_the_anchors_of_selected_type_on_a_path() {
let (d, text) = doc_with_path_type();
let p = paint();
let mut s = Selection::default();
s.add(text);
let anchors =
|o: Vec<Overlay>| -> Vec<Point> { o.into_iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(p) } else { None }).collect() };
let ends = [Point::new(100.0, 300.0), Point::new(400.0, 300.0)];
let selected = cx(&d, &s, &p);
for tool in ["anchorPoint", "addAnchor", "deleteAnchor"] {
assert_eq!(anchors(AnchorTool::new(tool).overlays(&selected)), ends, "{tool}");
}
assert_eq!(anchors(crate::pen::PenTool::default().overlays(&selected)), ends, "pen");
assert!(anchors(AnchorTool::new("scissors").overlays(&selected)).is_empty());
let none = Selection::default();
assert!(anchors(AnchorTool::new("anchorPoint").overlays(&cx(&d, &none, &p))).is_empty());
}
#[test]
fn anchor_point_drag_pulls_handles_click_converts() {
let (d, id) = doc_with_rect();
+1 -1
View File
@@ -171,7 +171,7 @@ mod tests {
(TYPE, &["editing"]),
(&["puppetWarp"], &["pins", "selected"]),
// With nothing queued, `current` (0) is no file's index either.
(&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]),
(&["place"], &["count", "total", "current", "sourceIndex", "name", "width", "height", "names"]),
];
let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k));
// Tools that `create` makes and the catalog doesn't list.
+14 -12
View File
@@ -36,7 +36,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{Anchor, BezPath, Point, Vec2};
use crate::direct::hit_handle;
use crate::draw2::{AnchorTool, editable_paths, shown_paths};
use crate::draw2::{AnchorTool, editable_anchor_owners, shown_anchor_owners, shown_paths};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -225,21 +225,21 @@ fn pick_endpoint(first: Option<Point>, last: Point, p: Point, tol: f64, tie: End
(None, None) => None,
}
}
/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's
/// gesture, within its tolerance.
/// Alt held over a handle end, an anchor or a segment of a selected path, or of selected type on a
/// path's path: the Anchor Point tool's gesture, within its tolerance.
fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
let point = cx.point_tol();
m.alt
&& (hit_handle(cx, p, point).is_some()
|| crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, crate::draw2::shown_paths(cx), p, cx.pick_tol()).is_some())
|| crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some()
|| crate::draw2::segment_in(cx, shown_anchor_owners(cx), p, cx.pick_tol()).is_some())
}
/// The cursor where [`alt_converts`]: Alt lends the Anchor Point tool, so its caret over a handle
/// end or an anchor, the Reshape Segment cursor over a segment.
fn alt_cursor(cx: &ToolContext, p: Point) -> Cursor {
let point = cx.point_tol();
if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() {
if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() {
Cursor::AnchorPoint
} else {
Cursor::ReshapeSegment
@@ -526,7 +526,8 @@ impl Tool for PenTool {
if let Some(t) = &self.convert {
return t.overlays(cx);
}
let mut o = vec![];
// Pen + Alt and Auto Add/Delete edit selected type on a path's path, so its anchors show.
let mut o = crate::direct::type_path_overlays(cx);
// The rubber band preference hides only the preview segment; Measurement Labels decides the readout.
if self.drag.is_none()
&& self.handle.is_none()
@@ -752,15 +753,16 @@ pub(crate) fn continue_from(cx: &ToolContext, id: NodeId, si: usize, at_first: b
out
}
/// Auto Add/Delete: what a click at `p` does to a selected path. On one of its anchors it deletes
/// it; else, where one of its segments passes within `tol`, it adds an anchor. None when the
/// preference turns it off, Shift is held, or no selected path is there.
/// Auto Add/Delete: what a click at `p` does to a selected path, or to selected type on a path's
/// path. On one of its anchors it deletes it; else, where one of its segments passes within `tol`,
/// it adds an anchor. None when the preference turns it off, Shift is held, or no selected path is
/// there.
fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option<Action> {
if !cx.auto_add_delete || m.shift {
return None;
}
let anchor = crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).map(crate::draw2::remove_anchor);
anchor.or_else(|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).map(crate::draw2::insert_anchor))
let anchor = crate::draw2::anchor_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::remove_anchor);
anchor.or_else(|| crate::draw2::segment_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::insert_anchor))
}
/// A click on a selected blend's spine: delete the point under `p` when no key object sits on it
+32 -1
View File
@@ -32,6 +32,8 @@ struct Entry {
#[derive(Default)]
pub struct PlaceTool {
entries: Vec<Entry>,
/// How many files the last load held, before any was placed or discarded.
total: usize,
current: usize,
/// The tool to return to when the last file is placed or discarded.
prev: Option<String>,
@@ -67,6 +69,7 @@ impl PlaceTool {
}
if self.entries.is_empty() {
self.current = 0;
self.total = 0;
return vec![Action::SwitchTool(self.prev.clone().unwrap_or_else(|| "selection".into()))];
}
self.current %= self.entries.len();
@@ -153,11 +156,13 @@ impl Tool for PlaceTool {
Cursor::Crosshair
}
/// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data).
/// `{count, total, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data);
/// `total` is how many files the load held.
fn options(&self) -> Value {
let e = self.entry();
json!({
"count": self.entries.len(),
"total": self.total,
"current": self.current,
"sourceIndex": e.map(|e| e.source_index),
"name": e.map(|e| &e.name),
@@ -187,6 +192,7 @@ impl Tool for PlaceTool {
})
})
.collect();
self.total = entries.len();
self.entries = entries;
self.current = 0;
self.drag = None;
@@ -233,6 +239,7 @@ impl Tool for PlaceTool {
/// Switching tools discards what the cursor holds.
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.entries.clear();
self.total = 0;
self.drag = None;
vec![]
}
@@ -399,6 +406,30 @@ mod tests {
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]);
}
#[test]
fn the_total_is_the_size_of_the_load_until_the_cursor_empties() {
let (d, _) = doc_with_rect();
let (s, p) = (Default::default(), paint());
let c = cx(&d, &s, &p);
let counts = |t: &PlaceTool| (t.options()["count"].clone(), t.options()["total"].clone());
let mut t = loaded(3);
assert_eq!(counts(&t), (json!(3), json!(3)));
t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0));
assert_eq!(counts(&t), (json!(2), json!(3)), "a placed file leaves the total");
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(1), json!(3)), "a discarded file leaves the total");
// A new load replaces the total, and an empty cursor has none.
let mut t = loaded(3);
t.set_option("queue", &json!({"entries": [{"params": {"path": "g.png"}, "name": "g.png", "width": 4.0, "height": 2.0}]}));
assert_eq!(counts(&t), (json!(1), json!(1)));
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(0), json!(0)));
let mut t = loaded(2);
t.deactivate(&c);
assert_eq!(counts(&t), (json!(0), json!(0)));
}
#[test]
fn source_indices_survive_removal_in_cursor_requests() {
let (d, _) = doc_with_rect();
+1 -1
View File
@@ -88,7 +88,7 @@ use layers::parallel_map_at_most;
#[cfg(test)]
pub(crate) use layers::shift_probe;
pub use params::{Method, Mode, PRESET_NAMES, Palette, TraceParams, enhanced_preset, preset, presets};
pub use pipeline::{TraceResult, TracedPath, trace, trace_watched, trace_within};
pub use pipeline::{TraceResult, TraceSteps, TracedPath, trace, trace_watched, trace_within};
#[cfg(test)]
use pipeline::{clear_background, label_extents};
#[cfg(test)]
+259 -75
View File
@@ -1,3 +1,4 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use super::layers::{Layers, parallel_map_at_most};
@@ -177,21 +178,255 @@ pub fn trace_watched(
max_anchors: usize,
steps: &(dyn Fn(u64, u64) -> bool + Sync),
) -> Result<TraceResult, TraceError> {
let (w, h) = (img.width as usize, img.height as usize);
if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) {
if !traceable(img) {
return Ok(TraceResult::default());
}
let mut out = trace_paths(img, params, max_anchors, steps)?;
let out = trace_paths(img, params, max_anchors, steps)?;
Ok(grouped(out, img, params))
}
/// Whether `img` has pixels, as many as its size says.
fn traceable(img: &Raster) -> bool {
let (w, h) = (img.width as usize, img.height as usize);
w > 0 && h > 0 && w.checked_mul(h).and_then(|n| n.checked_mul(4)) == Some(img.rgba.len())
}
/// `out` with Auto Grouping's parents (see [`TraceResult::parents`]) when `params` asks for them.
fn grouped(mut out: TraceResult, img: &Raster, params: &TraceParams) -> TraceResult {
if params.auto_grouping {
// Abutting areas cannot overlap; stacked layers, Logo's shapes and stroked lines can.
let stacked = params.method == Method::Overlapping || params.mode == Mode::Logo || params.strokes;
out.parents = group::parents(&out.paths, img.width as usize, img.height as usize, stacked);
}
Ok(out)
out
}
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<TraceResult, TraceError> {
let (w, h) = (img.width as usize, img.height as usize);
/// How far a trace has got: see [`trace_watched`].
type Steps<'s> = &'s (dyn Fn(u64, u64) -> bool + Sync);
fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<TraceResult, TraceError> {
let p = match prepare(Source::Borrowed(img), params, max_anchors, steps)? {
Begun::Done(out) => return Ok(out),
Begun::Layers(p) => p,
};
if p.stacks() {
let paths = p.job(0).stacked(&p.layers, p.largest(), steps)?;
return Ok((*p).finish_stacked(paths));
}
let traced = {
let job = p.job(0);
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
// of its components, the stack that fills them, its edges): as many layers at a time as fit
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
let at_a_time = ((512 << 20) / (p.largest() * 10)).max(1);
let total = p.layers.len() as u64;
if !steps(0, total) {
return Err(TraceError::Cancelled);
}
// Once stopped, the layers not started yet are skipped.
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
let traced = parallel_map_at_most(at_a_time, &p.layers, |&(r, ci)| {
if stopped.load(Ordering::Relaxed) {
return None;
}
let paths = job.layer(r, ci);
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
stopped.store(true, Ordering::Relaxed);
}
paths
});
if stopped.load(Ordering::Relaxed) {
return Err(TraceError::Cancelled);
}
traced
};
(*p).finish(traced)
}
/// The image a trace works from: borrowed for the length of one call, or shared, for a trace
/// made a part at a time ([`TraceSteps`]).
enum Source<'a> {
Borrowed(&'a Raster),
Shared(Arc<Raster>),
}
impl std::ops::Deref for Source<'_> {
type Target = Raster;
fn deref(&self) -> &Raster {
match self {
Source::Borrowed(img) => img,
Source::Shared(img) => img,
}
}
}
/// A trace with its color layers found and ordered, none of them traced yet.
struct Prepared<'a> {
src: Source<'a>,
/// A copy with a JPEG's block edges (see `deblock`) or a photo's noise (see `smooth`) smoothed
/// away, traced in its place.
smoothed: Option<Raster>,
params: TraceParams,
q: Quantized,
/// Ignore Color, background only: `q.labels` with the background [`TRANSPARENT`].
cleared: Option<Vec<u16>>,
rank: Vec<usize>,
left_out: Vec<bool>,
boxes: Vec<Option<PixelBox>>,
gradients: Vec<Option<TracedGradient>>,
bw_tones: [f64; 2],
/// The layers to trace, bottom first: `(rank, palette entry)`.
layers: Vec<(usize, usize)>,
keep_unmatched: Vec<String>,
keep_ignored: bool,
max_anchors: usize,
}
/// What preparing a trace gives: the whole result (Logo mode), or its layers to trace.
enum Begun<'a> {
Done(TraceResult),
Layers(Box<Prepared<'a>>),
}
impl Prepared<'_> {
/// What tracing one of the layers needs, with `anchors` anchor points made so far.
fn job(&self, anchors: usize) -> Layers<'_> {
Layers {
q: &self.q,
traced: self.cleared.as_deref().unwrap_or(&self.q.labels),
rank: &self.rank,
params: &self.params,
img: self.smoothed.as_ref().unwrap_or(&*self.src),
left_out: self.left_out.clone(),
boxes: self.boxes.clone(),
gradients: &self.gradients,
bw_tones: self.bw_tones,
style: self.params.outline_style(),
w: self.src.width as usize,
h: self.src.height as usize,
anchors: AtomicUsize::new(anchors),
max_anchors: self.max_anchors,
}
}
/// Whether the layers are traced together: Overlapping with Fills fills each shape whole and
/// traces what it encloses again above it (see `Layers::stacked`). Lines (Create Strokes) and
/// outlines (no Fills) are traced a layer at a time.
fn stacks(&self) -> bool {
self.params.method == Method::Overlapping && self.params.fills && !self.params.strokes
}
/// The pixel count of the largest layer's box (at least 1).
fn largest(&self) -> usize {
self.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1)
}
/// The result of `paths`, the layers traced together ([`Prepared::stacks`]).
fn finish_stacked(self, paths: Vec<TracedPath>) -> TraceResult {
let mut out = TraceResult { paths, keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
// The colors used, bottom layer first.
for &(_, ci) in &self.layers {
if let Some(&color) = self.q.palette.get(ci)
&& !out.palette.contains(&color)
&& out.paths.iter().any(|p| p.color == color)
{
out.palette.push(color);
}
}
out
}
/// The result of `traced`, the paths of each of [`Prepared::layers`] in order (`None` for a
/// layer that passed the anchor maximum).
fn finish(self, traced: Vec<Option<Vec<TracedPath>>>) -> Result<TraceResult, TraceError> {
let mut out = TraceResult { keep_unmatched: self.keep_unmatched, keep_ignored: self.keep_ignored, ..TraceResult::default() };
for (paths, &(_, ci)) in traced.into_iter().zip(&self.layers) {
let paths = paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?;
// A layer with no paths adds no color to the palette.
if paths.is_empty() {
continue;
}
out.paths.extend(paths);
let color = self.q.palette[ci];
if !out.palette.contains(&color) {
out.palette.push(color);
}
}
Ok(out)
}
}
/// A trace made a part at a time, for a caller with no thread to trace on that must let other
/// work run between the parts (the web build). The first [`TraceSteps::step`] finds the color
/// layers and each later one traces one layer, bottom first, one at a time (Overlapping with
/// Fills, without Create Strokes, traces all of them in the second step, as its layers are traced
/// together); the result is the one [`trace_within`] gives.
pub struct TraceSteps {
img: Arc<Raster>,
params: TraceParams,
max_anchors: usize,
state: StepState,
}
enum StepState {
Start,
/// The layers found, the paths of those traced so far, and their anchor points.
Layers(Box<Prepared<'static>>, Vec<Option<Vec<TracedPath>>>, usize),
Finished,
}
impl TraceSteps {
/// A trace of `img` with `params` that gives up with [`TraceError::TooComplex`] once the paths
/// have more than `max_anchors` anchor points; nothing is done until [`TraceSteps::step`].
pub fn new(img: Arc<Raster>, params: TraceParams, max_anchors: usize) -> Self {
Self { img, params, max_anchors, state: StepState::Start }
}
/// Does the next part → the result once the last part is done, `None` before it. After the
/// result or an error, each call gives `None`.
pub fn step(&mut self) -> Result<Option<TraceResult>, TraceError> {
let (prepared, mut traced, anchors) = match std::mem::replace(&mut self.state, StepState::Finished) {
StepState::Finished => return Ok(None),
StepState::Start => {
if !traceable(&self.img) {
return Ok(Some(TraceResult::default()));
}
match prepare(Source::Shared(Arc::clone(&self.img)), &self.params, self.max_anchors, &|_, _| true)? {
Begun::Done(out) => return Ok(Some(grouped(out, &self.img, &self.params))),
Begun::Layers(p) if p.layers.is_empty() => return (*p).finish(vec![]).map(|out| Some(grouped(out, &self.img, &self.params))),
Begun::Layers(p) => {
let traced = Vec::with_capacity(p.layers.len());
self.state = StepState::Layers(p, traced, 0);
return Ok(None);
}
}
}
StepState::Layers(p, traced, anchors) => (p, traced, anchors),
};
if prepared.stacks() {
let paths = prepared.job(0).stacked(&prepared.layers, prepared.largest(), &|_, _| true)?;
return Ok(Some(grouped((*prepared).finish_stacked(paths), &self.img, &self.params)));
}
// With every layer traced already the result is finished below.
let mut anchors = anchors;
if let Some(&(r, ci)) = prepared.layers.get(traced.len()) {
let job = prepared.job(anchors);
let paths = job.layer(r, ci);
anchors = job.anchors.load(Ordering::Relaxed);
traced.push(Some(paths.ok_or(TraceError::TooComplex { max: self.max_anchors })?));
}
if traced.len() < prepared.layers.len() {
self.state = StepState::Layers(prepared, traced, anchors);
return Ok(None);
}
(*prepared).finish(traced).map(|out| Some(grouped(out, &self.img, &self.params)))
}
}
/// Finds the color layers of `src` traced with `params` and the order they stack in, telling
/// `steps(0, 0)` after each stage; Logo mode traces the whole image at once.
fn prepare<'a>(src: Source<'a>, params: &TraceParams, max_anchors: usize, steps: Steps) -> Result<Begun<'a>, TraceError> {
let (w, h) = (src.width as usize, src.height as usize);
// The colors Keep Colors traces (checked in every mode).
let listed = params
.keep_colors
@@ -202,7 +437,7 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
let go_on = || if steps(0, 0) { Ok(()) } else { Err(TraceError::Cancelled) };
if params.mode == Mode::Logo {
go_on()?;
return logo::trace_logo(img, params, max_anchors);
return logo::trace_logo(&src, params, max_anchors).map(Begun::Done);
}
// The colour Ignore Color leaves out, if not white.
let ignore = match &params.ignore_color {
@@ -218,12 +453,12 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
// A photo is traced from a copy with its noise smoothed away (see `smooth`); the deblocked copy is
// dropped once it is smoothed.
let photo = |img: &Raster| params.mode != Mode::BlackAndWhite && quantize::continuous_tone(img);
let prepared = match deblock::deblocked(img, strength) {
let smoothed = match deblock::deblocked(&src, strength) {
Some(deblocked) if photo(&deblocked) => Some(smooth::smoothed(&deblocked)),
Some(deblocked) => Some(deblocked),
None => photo(img).then(|| smooth::smoothed(img)),
None => photo(&src).then(|| smooth::smoothed(&src)),
};
let img = prepared.as_ref().unwrap_or(img);
let img = smoothed.as_ref().unwrap_or(&*src);
go_on()?;
// Gradients are found first and kept out of the palette: no colour is spent on bands of them.
// Grayscale finds them in the image's grays (as its flat colours are), so their stops are gray.
@@ -337,75 +572,24 @@ fn trace_paths(img: &Raster, params: &TraceParams, max_anchors: usize, steps: &(
.collect();
// Every layer is left out although a listed color matches one: Ignore Color left those out.
let keep_ignored = !listed.is_empty() && layers.is_empty() && order.iter().any(|&ci| is_kept(q.palette[ci], &listed));
let job = Layers {
q: &q,
traced: cleared.as_deref().unwrap_or(&q.labels),
rank: &rank,
let tones = bw_tones(img, &q);
let params = params.clone();
Ok(Begun::Layers(Box::new(Prepared {
src,
smoothed,
params,
img,
q,
cleared,
rank,
left_out,
boxes,
gradients: &gradients,
bw_tones: bw_tones(img, &q),
style: params.outline_style(),
w,
h,
anchors: AtomicUsize::new(0),
gradients,
bw_tones: tones,
layers,
keep_unmatched,
keep_ignored,
max_anchors,
};
let mut out = TraceResult { keep_unmatched, keep_ignored, ..TraceResult::default() };
// A layer takes about ten bytes a pixel of its box while it is traced (its mask, the labels
// of its components, the stack that fills them, its edges): as many layers at a time as fit
// in half a gigabyte, so that a large image is not traced at the cost of gigabytes.
let largest = job.boxes.iter().flatten().map(|b| (b.2 - b.0) * (b.3 - b.1)).max().unwrap_or(1).max(1);
let at_a_time = ((512 << 20) / (largest * 10)).max(1);
// Overlapping with Fills: each shape is filled whole, and what it encloses is traced again above it (see
// `Layers::stacked`). Lines (Create Strokes) and outlines (no Fills) are stacked as they always were.
if params.method == Method::Overlapping && params.fills && !params.strokes {
out.paths = job.stacked(&layers, largest, steps)?;
// The colors used, bottom layer first.
for &(_, ci) in &layers {
if let Some(&color) = q.palette.get(ci)
&& !out.palette.contains(&color)
&& out.paths.iter().any(|p| p.color == color)
{
out.palette.push(color);
}
}
return Ok(out);
}
let total = layers.len() as u64;
if !steps(0, total) {
return Err(TraceError::Cancelled);
}
// Once stopped, the layers not started yet are skipped.
let (done, stopped) = (AtomicU64::new(0), AtomicBool::new(false));
let traced = parallel_map_at_most(at_a_time, &layers, |&(r, ci)| {
if stopped.load(Ordering::Relaxed) {
return None;
}
let paths = job.layer(r, ci);
if !steps(done.fetch_add(1, Ordering::Relaxed) + 1, total) {
stopped.store(true, Ordering::Relaxed);
}
paths
});
if stopped.load(Ordering::Relaxed) {
return Err(TraceError::Cancelled);
}
for (paths, &(_, ci)) in traced.into_iter().zip(&layers) {
let paths = paths.ok_or(TraceError::TooComplex { max: max_anchors })?;
// A layer with no paths adds no color to the palette.
if paths.is_empty() {
continue;
}
out.paths.extend(paths);
let color = q.palette[ci];
if !out.palette.contains(&color) {
out.palette.push(color);
}
}
Ok(out)
})))
}
/// The luminance of white and of black in a Black and White quantisation: what its lightest
+46
View File
@@ -1086,6 +1086,52 @@ fn a_watched_trace_counts_its_layers_and_stops_when_told() {
assert!(matches!(trace_watched(&img, &p, usize::MAX, &|done, _| done == 0), Err(TraceError::Cancelled)));
}
/// A trace made a part at a time finds its layers in the first part and traces one layer a part
/// after it (all of them in the second part for Overlapping with Fills, which stacks them), and
/// gives what one call gives, Auto Grouping, Logo mode and the anchor budget included.
#[test]
fn a_trace_made_a_part_at_a_time_matches_one_made_at_once() {
fn parts(img: &Raster, p: &TraceParams, max: usize) -> (usize, Result<TraceResult, TraceError>) {
let mut s = TraceSteps::new(std::sync::Arc::new(img.clone()), p.clone(), max);
let mut n = 0;
loop {
n += 1;
assert!(n < 1000, "the parts never end");
match s.step() {
Ok(None) => {}
Ok(Some(r)) => return (n, Ok(r)),
Err(e) => return (n, Err(e)),
}
}
}
let img = stripes(120, 8);
let overlapping =
TraceParams { mode: Mode::Color, colors: 16, noise: 1, method: Method::Overlapping, auto_grouping: true, ..TraceParams::default() };
// Overlapping with Fills traces its layers together: one part finds them, the next traces them.
for (p, layered) in [
(TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() }, true),
(TraceParams { strokes: true, ..overlapping.clone() }, true),
(overlapping, false),
] {
let at_once = trace_within(&img, &p, usize::MAX).unwrap();
let (n, made) = parts(&img, &p, usize::MAX);
assert_eq!(made.unwrap(), at_once, "{p:?}");
assert!(at_once.palette.len() > 1, "{} colors", at_once.palette.len());
assert!(if layered { n > 2 } else { n == 2 }, "{n} parts for {} colors, {p:?}", at_once.palette.len());
}
let logo = TraceParams { mode: Mode::Logo, ..TraceParams::default() };
let round = disc(64, 32.0, 32.0, 20.0);
let (n, made) = parts(&round, &logo, usize::MAX);
assert_eq!((n, made.unwrap()), (1, trace_within(&round, &logo, usize::MAX).unwrap()), "Logo mode is one part");
let p = TraceParams { mode: Mode::Color, colors: 16, noise: 1, ..TraceParams::default() };
let anchors = trace(&img, &p).anchor_count();
assert!(matches!(parts(&img, &p, anchors / 2).1, Err(TraceError::TooComplex { max }) if max == anchors / 2));
assert_eq!(parts(&img, &p, anchors).1.unwrap(), trace(&img, &p));
let mut done = TraceSteps::new(std::sync::Arc::new(Raster::from_fn(0, 0, |_, _| WHITE)), p, usize::MAX);
assert_eq!(done.step().unwrap(), Some(TraceResult::default()), "an empty image");
assert_eq!(done.step().unwrap(), None, "nothing after the result");
}
/// Layers traced in parallel come out in the same order every time: bottom (largest) first.
#[test]
fn parallel_layers_keep_their_order() {
+10 -10
View File
@@ -89,16 +89,16 @@ pub fn menu() -> Vec<Node> {
]
}
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None };
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None, pin_opening_artboard: false };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None, pin_opening_artboard: false };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None, pin_opening_artboard: false };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None, pin_opening_artboard: false };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None, pin_opening_artboard: false };
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None, pin_opening_artboard: false };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None, pin_opening_artboard: false };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None, pin_opening_artboard: false };
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None, pin_opening_artboard: false };
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None, pin_opening_artboard: false };
/// The dialog over `rows`, titled by the heading of `command`.
fn dialog<'a>(command: &str, rows: Vec<Param>) -> ParamDialog<'a> {
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff. Show more