diff --git a/ASSETS.md b/ASSETS.md index 03f33d9a6e..a74a9a29a4 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -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 | diff --git a/Cargo.lock b/Cargo.lock index b878d75456..af882877fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index a48e3c1330..73e26d5375 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 4db9a1dac2..62605759eb 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -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 } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index d772397ce3..63135d00e5 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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; diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index e69806ac29..ba5d3d298d 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -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; +#[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> = 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(Mutex>>); + +impl Default for Viewports { + fn default() -> Self { + Self(Mutex::new(HashMap::new())) + } +} + +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +impl Viewports { + /// 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) { + 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>> { + 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, viewports: &[egui::ViewportId]) -> Vec> { + 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() { diff --git a/assets/cursors/cursor-move.svg b/assets/cursors/cursor-move.svg new file mode 100644 index 0000000000..ee3c16ed90 --- /dev/null +++ b/assets/cursors/cursor-move.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-not-allowed.svg b/assets/cursors/cursor-not-allowed.svg new file mode 100644 index 0000000000..83a8556cd0 --- /dev/null +++ b/assets/cursors/cursor-not-allowed.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-h.svg b/assets/cursors/cursor-resize-h.svg new file mode 100644 index 0000000000..361da7e098 --- /dev/null +++ b/assets/cursors/cursor-resize-h.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-nesw.svg b/assets/cursors/cursor-resize-nesw.svg new file mode 100644 index 0000000000..0f37741f94 --- /dev/null +++ b/assets/cursors/cursor-resize-nesw.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-nwse.svg b/assets/cursors/cursor-resize-nwse.svg new file mode 100644 index 0000000000..d143d581da --- /dev/null +++ b/assets/cursors/cursor-resize-nwse.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-v.svg b/assets/cursors/cursor-resize-v.svg new file mode 100644 index 0000000000..095be8455d --- /dev/null +++ b/assets/cursors/cursor-resize-v.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-type-vertical.svg b/assets/cursors/cursor-type-vertical.svg new file mode 100644 index 0000000000..62b0d50f65 --- /dev/null +++ b/assets/cursors/cursor-type-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 39b39fc294..78927ef970 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -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> { + 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), diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 7c13b8f755..eb882f5e77 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -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) { - 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) { + clear(a, false); +} + +fn clear(a: &mut Arc, 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) { } } // 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); } } diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5b213f3b08..c4d3cd6bb4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -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 { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 586deb604c..138d75ed61 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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()); diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index 8f4def2dcd..90fc007910 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "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 { } // 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; diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index ef010d7f32..10df5322e1 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -5,8 +5,10 @@ //! (). 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 { numbers::make_numbers ), ] + .into_iter() + .chain(font_sheet::specs()) + .collect() } /// Release Type on a Path's command (the id in [`specs`]). diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet.rs b/crates/engine/src/cmd/addons/typetools/font_sheet.rs new file mode 100644 index 0000000000..5f86fe9ea4 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/font_sheet.rs @@ -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 { + 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) -> Result { + 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 { + 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> { + 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 = 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 = 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 { + 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 { + 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)> = 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 = vec![]; + // The entries whose font lacks a glyph needed by the sample. + let mut fallback: Vec = 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::(); + (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 = (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> = 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 = 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 { + const NAMED: usize = 5; + let (first, more) = (fallback.iter().take(NAMED).cloned().collect::>(), 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, 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 { + const NAMED: usize = 5; + let (first, more) = (skipped.iter().take(NAMED).cloned().collect::>(), 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; diff --git a/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs new file mode 100644 index 0000000000..143f1dc2b3 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/font_sheet/tests.rs @@ -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::>(), 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 = 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 = e.iter().map(|(_, t)| origin(t).0).collect(); + assert!(!xs.is_empty(), "the sheet has entries"); + assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}"); + // One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart. + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap(); + let e = entries(&group(&s, &r)); + let step = (500.0 - 24.0) / 3.0 + 12.0; + for (i, (_, t)) in e.iter().enumerate() { + let (x, y) = origin(t); + assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}"); + } + assert_eq!(r["artboards"], json!([])); +} + +/// The journal records the active artboard, so a replay in a new session lays the sheet out on the +/// same one; an action leaves it out, and a named artboard goes ahead of it. +#[test] +fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let start = s.journal.len(); + let params = json!({"families": ["Inter"], "margin": 10}); + let r = s.execute(COMMAND, ¶ms).unwrap(); + let e = entries(&group(&s, &r)); + assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard"); + let (id, recorded) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1))); + assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays"); + + // A replay in a session whose view has no active artboard uses the recorded one. + let mut fresh = session(); + fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap(); + let r = fresh.replay(COMMAND, &recorded).unwrap(); + let e = entries(&group(&fresh, &r)); + assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard"); + // A named artboard goes ahead of the recorded one. + let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap(); + let e = entries(&group(&fresh, &r)); + let first = fresh.doc().unwrap().doc.artboards[0].rect; + assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9); + assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard"); +} + +/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column. +#[test] +fn a_right_to_left_sample_stays_inside_its_column() { + let mut s = session(); + let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}"; + let board = s.doc().unwrap().doc.artboards[0].rect; + // Alone, and under a left-to-right label: each line starts at the column's left edge. + for labels in [false, true] { + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap(); + assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}"); + for (name, t) in &entries(&group(&s, &r)) { + let x = origin(t).0; + assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}"); + let layout = vectorcraft_text::layout(FontDb::global(), t); + for line in &layout.lines { + let left = x + line.x0; + assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge"); + } + } + } +} + +#[test] +fn a_variation_selector_does_not_require_a_separate_glyph() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + assert!(face.covers('A')); + assert!(!face.covers('\u{fe0f}')); + let text = "A\u{fe0f}"; + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["fallback"], json!([])); + assert!(r.get("warning").is_none(), "{r}"); + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 1); + assert_eq!(e[0].1.plain_text(), text); +} + +#[test] +fn coverage_uses_the_samples_numeral_system() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + assert!(face.covers('1')); + assert!(!face.covers('\u{661}')); + for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] { + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}})) + .unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(r["skipped"], json!([])); + assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}"); + if missing { + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}"); + } else { + assert!(r.get("warning").is_none(), "{r}"); + } + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 1); + assert_eq!(e[0].1.plain_text(), text); + assert_eq!(e[0].1.runs[0].style.digits.id(), digits); + } +} + +/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase +/// letter but not its capital is named in `fallback`, plain and composite fonts alike. +#[test] +fn coverage_checks_the_capitals_all_caps_draws() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + let lower = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let mut up = c.to_uppercase(); + face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital")); + let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let text = lower.to_string(); + let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}"); + let e = entries(&group(&s, &r)); + assert!(e[0].1.runs[0].style.all_caps); + assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case"); + // Layout picks the font for the character as typed, so one the font lacks still falls back + // when the font has its capitals. + let uncased = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let up: String = c.to_uppercase().collect(); + !face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has every character whose capitals it has")); + let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap(); + assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}"); +} + +/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with +/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike. +#[test] +fn coverage_checks_the_capitals_small_caps_draws() { + let mut s = session(); + let face = FontDb::global().face("Inter", "Regular").unwrap(); + let lower = (0x80..0x3000u32) + .filter_map(char::from_u32) + .find(|&c| { + let mut up = c.to_uppercase(); + c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u)) + }) + .unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital")); + let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let text = lower.to_string(); + let families = json!(["Inter", "CF Sheet Small Caps"]); + let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}"); + let e = entries(&group(&s, &r)); + assert_eq!(e.len(), 2); + assert!(e[0].1.runs[0].style.small_caps.is_some()); + assert_eq!(r["fallback"], families, "{lower:?}: {r}"); +} + +#[test] +fn bad_params_are_refused_without_a_change() { + let mut s = session(); + let before = steps(&s); + let long = "x".repeat(MAX_CHARS + 1); + for bad in [ + json!({"text": ""}), + json!({"text": " "}), + json!({"text": "two\nlines"}), + json!({"text": "two\u{2028}lines"}), + json!({"text": "two\u{2029}paragraphs"}), + json!({"text": long}), + json!({"text": 5}), + json!({"size": 0.5}), + json!({"size": "12"}), + json!({"columns": 0}), + json!({"columns": 1.5}), + json!({"gap": -1}), + json!({"margin": 2000}), + json!({"margin": 300}), + json!({"columns": 50, "gap": 1000}), + json!({"filter": "no family is called this"}), + json!({"filter": 3}), + json!({"families": []}), + json!({"families": "Inter"}), + json!({"families": ["Inter", "inter"]}), + json!({"families": ["No Such Family Anywhere"]}), + json!({"families": [""]}), + json!({"families": ["Inter"], "filter": "Inter"}), + json!({"families": ["Inter"], "filter": ""}), + json!({"families": ["Inter"], "filter": " "}), + json!({"labels": "yes"}), + json!({"allStyles": 1}), + json!({"newArtboards": "no"}), + ] { + assert!(s.execute(COMMAND, &bad).is_err(), "{bad}"); + } + assert_eq!(steps(&s), before); + let layers = &s.doc().unwrap().doc.layers; + assert!(!layers.is_empty(), "the document keeps its layers"); + assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn"); +} + +/// Fonts left out are named in the warning, the first five of them, with a count of the rest. +#[test] +fn fonts_left_out_are_named_in_a_warning() { + let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::>(); + 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::>(), ["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::>(), ["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::>(), ["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::>(), ["Inter"]); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before.0); + assert_eq!(steps(&s), before.1); +} + +/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is +/// named in `fallback`, as a plain font is. +#[test] +fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() { + let mut s = session(); + let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}"; + let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap(); + assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact); + assert!(!coverage.lacking.is_empty()); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap(); + assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}"); + assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}"); + // A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system. + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap(); + assert_eq!(r["fallback"], json!([]), "{r}"); + s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}})) + .unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap(); + assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}"); +} + +#[test] +fn labels_without_overlap_need_no_additional_layouts() { + use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread}; + + let mut counts = vec![]; + for labels in [false, true] { + let mut s = session(); + let before = layouts_on_this_thread(); + let ink_before = ink_work_on_this_thread(); + let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap(); + let ink_after = ink_work_on_this_thread(); + counts.push(layouts_on_this_thread() - before); + assert_eq!(r["count"], BUNDLED.len()); + let mut outlines = 0; + for (_, t) in entries(&group(&s, &r)) { + assert!(t.cached_ink.unwrap().1.is_some()); + assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 }); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64; + assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t)); + } + assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once"); + assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry"); + } + assert!(counts[0] > 0); + assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts"); +} + +#[test] +fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() { + use vectorcraft_doc::{CharStyle, TextRun}; + + for text in ["Hamburg", " "] { + for labels in [false, true] { + let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() }; + let sample = TextRun::new(text, style.clone()); + let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) }; + let t = super::laid_out(first, more, false); + let layout = vectorcraft_text::layout(FontDb::global(), &t); + let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t); + assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars"); + let ink = t.cached_ink.unwrap().1; + assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t)); + let ink = ink.unwrap(); + for (_, bar) in bars { + let bounds = vectorcraft_geom::Shape::bounding_box(&bar); + assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1); + } + } + } +} + +#[test] +fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() { + let mut s = Session::new(); + s.execute("file.new", &json!({"artboards": 3})).unwrap(); + let state = s.doc().unwrap(); + let document = (state.uid, state.reverts); + let artboard = state.doc.artboards[1].id; + s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() }); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + for params in [json!({"index": 0}), json!({"indices": [1, 0]})] { + let error = s.execute("artboard.delete", ¶ms).unwrap_err(); + assert_eq!(error.to_string(), "The artboard is in use."); + assert_eq!(s.doc().unwrap().doc, before.0); + assert_eq!(steps(&s), before.1); + } + s.execute("file.new", &json!({"artboards": 2})).unwrap(); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected"); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.doc_mut().unwrap().reverts += 1; + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected"); +} + +/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too. +#[test] +fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() { + let mut s = Session::new(); + s.execute("file.new", &json!({"artboards": 3})).unwrap(); + let state = s.doc().unwrap(); + let document = (state.uid, state.reverts); + let artboard = state.doc.artboards[1].id; + s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() }); + let before = (s.doc().unwrap().doc.clone(), steps(&s)); + for (command, params) in [ + ("artboard.cut", json!({"index": 1})), + ("artboard.deleteEmpty", json!({})), + ("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})), + ] { + let error = s.execute(command, ¶ms).unwrap_err(); + assert_eq!(error.to_string(), "The artboard is in use.", "{command}"); + assert_eq!(s.doc().unwrap().doc, before.0, "{command}"); + assert_eq!(steps(&s), before.1, "{command}"); + } + s.execute("artboard.cut", &json!({"index": 2})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut"); +} + +#[test] +fn it_needs_a_document() { + let mut s = Session::new(); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} + +#[test] +fn a_locked_layer_takes_no_sheet() { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + let before = steps(&s); + assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err()); + assert_eq!(steps(&s), before); +} + +#[test] +fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() { + let mut s = session(); + let editable = s.doc().unwrap().doc.layers[0].id; + let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap(); + let gid = NodeId(r["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid)); + assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked"); + assert!(!holds(locked)); +} diff --git a/crates/engine/src/cmd/conceptvector.rs b/crates/engine/src/cmd/conceptvector.rs new file mode 100644 index 0000000000..469c0c1080 --- /dev/null +++ b/crates/engine/src/cmd/conceptvector.rs @@ -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>), + 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>, + provider: String, + outcome: Outcome, +} + +/// The session's providers and jobs. +pub(crate) struct ConceptState { + pub(crate) registry: cv::Registry, + jobs: VecDeque, + 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 { + 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 { + self.concept.jobs.clone() + } + + /// Puts back the jobs that [`Self::concept_jobs_snapshot`] took. + pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque) { + 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) { + 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, 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 = 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>)> { + 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, + /// 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 { + 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 = 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::>().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, 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 { + 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) -> Option { + 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>>, + /// The styles the provider's parts had made when last asked, inside the panic guard. + done: usize, + made: Vec, +} + +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 { + 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 { + 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 = 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 { + 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 { + 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 { + let list: Vec = 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 { + 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 { + 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 { + 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 { + 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::>().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 = 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 = 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, Vec) = 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 = 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 { + 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 = 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, Option)> = 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 = 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::>() })) +} + +#[cfg(test)] +thread_local! { + /// How many times [`place_row`] has looked at an object on this thread. + pub(crate) static LOOKS: std::cell::Cell = 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, start: f64, obstacles: &[Rect]) -> Option { + // 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> = row(start) + .iter() + .map(|b| { + let mut lane: Vec = 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::() { + 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 { + 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 + ), + ] +} diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 934151589b..be8155274e 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -174,7 +174,7 @@ pub fn specs() -> Vec { "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> { } /// 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 { +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewArt, bbox_angle: f64) -> Result { 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 { + (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, 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 { 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 { // 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); diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1054ca3ddc..13291b5307 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -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; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 8068418edd..a1271a39a9 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -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 { 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 { 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 { } 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() } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 08404a3092..eda5d19d23 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index f69ac40822..999953eb52 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -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(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result) -> Result { + 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)), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 81c23e9684..b57811b4ae 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -151,9 +151,9 @@ mod formats; pub(crate) use access::FILES_READ; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; +pub(crate) use access::{READ_TOO_LARGE, check_images_in, check_scripts_of, with_read_limit, with_readable_settings_folder}; #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE}; -pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 0a4cf89b18..4696dc9c35 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -289,6 +289,31 @@ thread_local! { pub(crate) static FILES_READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn regular_write_target(path: &str) -> Result<()> { + if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) { + return Err(EngineError::Other(format!("{path}: not a file"))); + } + Ok(()) +} + +thread_local! { + static READ_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +pub(crate) const READ_TOO_LARGE: &str = "File exceeds scoped read limit"; + +pub(crate) fn with_read_limit(max: usize, f: impl FnOnce() -> T) -> T { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + READ_LIMIT.with(|limit| limit.set(self.0)); + } + } + let _restore = Restore(READ_LIMIT.with(|limit| limit.replace(Some(limit.get().map_or(max, |outer| outer.min(max)))))); + f() +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { use std::io::Read; @@ -299,27 +324,35 @@ pub(crate) fn read_file(path: &str) -> Result> { if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); } - if crate::file_access::in_script_command() { - let max = SCRIPT_OPEN_MAX_BYTES; - let read = || -> std::io::Result> { - let file = std::fs::File::open(path)?; - let meta = file.metadata()?; - if !meta.is_file() { - return Err(std::io::Error::other("not a file")); - } - if meta.len() > max as u64 { - return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); - } - let mut bytes = Vec::new(); - file.take(max as u64 + 1).read_to_end(&mut bytes)?; - if bytes.len() > max { - return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); - } - Ok(bytes) - }; - read().map_err(|e| EngineError::Other(format!("{path}: {e}"))) - } else { - std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + // A script command reads at most `SCRIPT_OPEN_MAX_BYTES`, and a scoped limit + // (`with_read_limit`) at most its own count, whichever is smaller. + let script = crate::file_access::in_script_command().then_some(SCRIPT_OPEN_MAX_BYTES); + let scoped = READ_LIMIT.with(std::cell::Cell::get); + let Some(cap) = [script, scoped].into_iter().flatten().min() else { + return std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))); + }; + let too_large = |bytes: u64| { + if script.is_some_and(|max| bytes > max as u64) { + Some(EngineError::Other(format!("{path}: {SCRIPT_OPEN_TOO_LARGE}"))) + } else if scoped.is_some_and(|max| bytes > max as u64) { + Some(EngineError::Other(READ_TOO_LARGE.into())) + } else { + None + } + }; + let file = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let meta = file.metadata().map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + if !meta.is_file() { + return Err(EngineError::Other(format!("{path}: not a file"))); + } + if let Some(e) = too_large(meta.len()) { + return Err(e); + } + let mut bytes = Vec::new(); + file.take(cap as u64 + 1).read_to_end(&mut bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + match too_large(bytes.len() as u64) { + Some(e) => Err(e), + None => Ok(bytes), } } @@ -748,6 +781,28 @@ mod tests { use super::*; use crate::file_access::{AutomationRoots, confine}; + #[test] + fn scoped_read_limit_bounds_reads_and_restores_the_previous_limit() { + let path = std::env::temp_dir().join(format!("vc-access-read-limit-{}", std::process::id())); + std::fs::write(&path, b"12345").unwrap(); + let path_text = path.to_str().unwrap(); + assert_eq!(read_file(path_text).unwrap(), b"12345"); + with_read_limit(5, || { + assert_eq!(read_file(path_text).unwrap(), b"12345"); + with_read_limit(4, || { + assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE); + with_read_limit(6, || assert!(read_file(path_text).is_err())); + }); + assert_eq!(read_file(path_text).unwrap(), b"12345"); + std::fs::write(&path, b"123456").unwrap(); + assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE); + }); + assert_eq!(read_file(path_text).unwrap(), b"123456"); + let _ = std::panic::catch_unwind(|| with_read_limit(0, || panic!("test unwind"))); + assert_eq!(read_file(path_text).unwrap(), b"123456"); + std::fs::remove_file(path).unwrap(); + } + /// An error about a path the client did not give, under roots that don't let it be read: the /// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no /// name or its name is not valid text, and every root and the reason stay whole. A path inside the diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 821c74acb0..a7e19bc0cb 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -14,7 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // 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 { } 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 { 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 { (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); } }; diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 0497031f48..7aea6d4e99 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -45,9 +45,10 @@ pub(crate) fn unique_file_names_keeping_dots<'a>(names: impl IntoIterator) -> Vec { - distinct_names_by(names, str::to_lowercase) + distinct_names_by(names, super::screens::fold) } /// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same @@ -93,6 +94,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); } } + distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?; } for (p, bytes) in &files { write_file(p, bytes)?; @@ -112,6 +114,62 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do Ok(merge(out, extra)) } +/// An error when two of `paths` are the same file. A link that leads nowhere is compared by the file +/// its write creates; another path whose real path cannot be found (a folder that may not be read) +/// is compared as written, and its write then reports its own error. Two names in one folder that +/// differ only in letter case are treated as the same file on every volume. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator) -> Result<()> { + let mut targets = std::collections::HashSet::new(); + for path in paths { + let real = crate::file_access::resolve(path) + .ok() + .or_else(|| dangling_target(path)) + .or_else(|| std::path::absolute(path).ok()) + .unwrap_or_else(|| std::path::PathBuf::from(path)); + let key = match (real.parent(), real.file_name().and_then(|n| n.to_str())) { + (Some(dir), Some(name)) => dir.join(super::screens::fold(name)), + _ => real, + }; + if !targets.insert(key) { + return Err(EngineError::Other("output destinations resolve to the same file".into())); + } + } + Ok(()) +} + +/// The file a write to `path` creates when `path` is a link (or a chain of at most 40 links) that +/// leads to a file that does not exist yet. +#[cfg(not(target_arch = "wasm32"))] +fn dangling_target(path: &str) -> Option { + let mut at = std::path::PathBuf::from(path); + let mut followed = false; + for _ in 0..40 { + if !std::fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink()) { + break; + } + let next = std::fs::read_link(&at).ok()?; + at = match at.parent() { + Some(parent) if next.is_relative() => parent.join(next), + _ => next, + }; + followed = true; + } + if !followed { + return None; + } + // Resolved as the primary destination is; a name that is not UTF-8 keeps its bytes, with its + // folder's links followed. + match at.to_str() { + Some(text) => crate::file_access::resolve(text).ok(), + None => { + let folder = std::fs::canonicalize(at.parent()?).ok()?; + Some(folder.join(at.file_name()?)) + } + } + .or_else(|| std::path::absolute(&at).ok()) +} + /// `a` with the fields of `b`. pub(crate) fn merge(mut a: Value, b: Value) -> Value { if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) { @@ -143,3 +201,37 @@ pub(crate) fn write_or_return(path: Option<&str>, bytes: &[u8], extra: Value) -> }; Ok(merge(out, extra)) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + fn folder(tag: &str) -> std::io::Result { + 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); + } +} diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index bd21723558..d434dcf6ec 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -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 // 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 } 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()) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 005cc4a557..2dd408acdc 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -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 diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 8878456b5c..d040e319f2 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -85,6 +85,7 @@ pub struct SavePlan { /// Where to write. `None` when no path is known (never saved, converted from an older version, /// restored by Data Recovery, or a format other than the document's own): the caller asks for one or takes the bytes. pub path: Option, + pub path_given: bool, pub format: &'static Format, /// The format's options (only those its encoder reads). pub options: Map, @@ -348,7 +349,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { } } let lossy_source = super::lossy_source(st, p); - Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept }) + let path_given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + Ok(SavePlan { mode, path, path_given, format, options, name, folder, modified, notes, lossy_source, kept }) } /// The native save options, which a save also takes beside the path. @@ -602,8 +604,9 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, - /// The client did not give the path: a file the file access refuses before anything is - /// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]). + /// The client did not give the path ([`SavePlan::path_given`]): a file the file access refuses + /// before anything is written is named as [`super::access::naming_in_error`] names it + /// ([`SaveJob::naming_refusals`]). redact_paths: bool, } @@ -966,7 +969,8 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option>()) { return Ok(stopped); } - // Every path is checked against the file access in force before the first file is - // written. A refused file, or a folder at a file's path, is not handed to `write`, so a - // writer that does not check the file access writes none of the files; the error is the - // file access's own refusal, as the writers that check it give. + // Every path is checked against the file access in force, and as a write target, before + // the first file is written. A refused file is not handed to `write`, so a writer that does + // not check the file access writes none of the files; the error is the file access's own + // refusal, as the writers that check it give. #[cfg(not(target_arch = "wasm32"))] - if files.len() > 1 - && let Some(refused) = files.iter().find_map(|(p, _)| { - super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }) - }) - { - return Err(refused); + if files.len() > 1 { + let named = |e, p: &str| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }; + for (p, _) in &files { + super::may_write(p).map_err(|e| named(e, p))?; + } + for (p, _) in &files { + super::access::regular_write_target(p).map_err(|e| named(e, p))?; + } + 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() { @@ -1271,8 +1272,8 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); let job = save_job(s, plan)?; + let given = job.plan.path_given; let job = if given { job } else { job.naming_refusals() }; let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. @@ -1416,7 +1417,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; an access-rule, file-type (a directory), read-only (an existing read-only file) or destination-collision failure found before writing leaves every file unchanged; a later write failure can leave earlier files written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 1c67a44203..109dd1c59e 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -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| { diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 6e63170f88..3c6343ebea 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -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); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a2dd7f83a6..4975d3ec48 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "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 { "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 { fn artboard_delete(s: &mut Session, p: &Value) -> Result { 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 { 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 })) } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index d719434f28..54eb05b312 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -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, + /// 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 { + 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, 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 { } fn describe(s: &mut Session, _: &Value) -> Result { - 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); } } diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 0f604d81f1..4adf91a9c8 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "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 Vec { "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 { "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 { "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 { 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 { 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 { 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> { 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 { 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 { @@ -2614,12 +2629,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { 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 diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index fb9d2df26b..0bc243be41 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -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"), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 988c64a83e..fa90cccf8e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -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", diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 77e6d03395..6ead038f2d 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{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: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), @@ -138,6 +138,12 @@ fn preview(s: &mut Session, p: &Value) -> Result { 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 { 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 { // 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()); } diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index 1051342262..c5927f3bfd 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -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> { + 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, +) -> Result> { 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>) { } } +/// 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) -> Option { + 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> { + 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 { +/// 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)> { 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 = 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)) } diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 4936a06d74..df8b4995de 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1197,6 +1197,7 @@ pub fn jobs(s: &mut Session, store: &Arc) -> Result<(Vec 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; diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index e3bbe41d23..72bc9aec80 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -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"), diff --git a/crates/engine/src/concept_vector.rs b/crates/engine/src/concept_vector.rs new file mode 100644 index 0000000000..da5ae76304 --- /dev/null +++ b/crates/engine/src/concept_vector.rs @@ -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