mirror of
https://github.com/storytold/designcraft.git
synced 2026-11-27 10:33:34 +00:00
Merge branch 'main' into web-relink
This commit is contained in:
@@ -110,3 +110,7 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
|
||||
|
||||
## Shared libraries
|
||||
|
||||
Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers.
|
||||
|
||||
Generated
+206
-102
@@ -1091,12 +1091,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1105,7 +1105,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
@@ -1159,16 +1164,16 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"craft-math",
|
||||
"craft-offcrypto",
|
||||
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"craft-wordmodel",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"log",
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1190,9 +1195,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -1278,10 +1283,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-idml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1ad5f35bf#1ad5f35bf0b33f5846fd8aec782f0ba5a9e3b596"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2#899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ad5f35bf)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ad5f35bf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -1298,9 +1303,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)",
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
@@ -1320,10 +1326,32 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6#ea1c84290dadec636900b4d1bce107e59ca3f0d6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6)",
|
||||
"craft-metadata",
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
@@ -1373,7 +1401,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1381,7 +1409,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6#ea1c84290dadec636900b4d1bce107e59ca3f0d6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1409,33 +1445,55 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6#ea1c84290dadec636900b4d1bce107e59ca3f0d6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
"craft-tiff",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"craft-cfb",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"sha1 0.11.0",
|
||||
@@ -1458,10 +1516,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551#8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1469,10 +1527,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551#8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1491,10 +1549,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f)",
|
||||
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"hayro",
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1522,7 +1580,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-prepress"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"craft-pdf",
|
||||
@@ -1548,7 +1606,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6#ea1c84290dadec636900b4d1bce107e59ca3f0d6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d15bf1f35b17b759870f9e5111b9a5d243f64888#d15bf1f35b17b759870f9e5111b9a5d243f64888"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1559,9 +1617,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
@@ -1573,14 +1631,17 @@ source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423a
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"flate2",
|
||||
"kurbo",
|
||||
"roxmltree 0.21.2",
|
||||
"thiserror 2.0.21",
|
||||
"usvg 0.48.1",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1614,7 +1675,16 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6#ea1c84290dadec636900b4d1bce107e59ca3f0d6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1644,7 +1714,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1690,7 +1760,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf#6d0b33c0cd63ae4250c180a04eb4a4d66ab81448"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -1713,15 +1783,6 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1ad5f35bf#1ad5f35bf0b33f5846fd8aec782f0ba5a9e3b596"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1734,7 +1795,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2#899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1749,6 +1820,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1776,16 +1857,6 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f23b0f33f0d00b157476533a43cbbcfd901aa1f1#f23b0f33f0d00b157476533a43cbbcfd901aa1f1"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
@@ -1798,7 +1869,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1ad5f35bf#1ad5f35bf0b33f5846fd8aec782f0ba5a9e3b596"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1808,7 +1879,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2b9a325f57624804ed423aded16695eddb815119#2b9a325f57624804ed423aded16695eddb815119"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7ad4765ee55496d0ccdb7659ad7a6375c7bbb484#7ad4765ee55496d0ccdb7659ad7a6375c7bbb484"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2#899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2009,7 +2090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"craft-update",
|
||||
@@ -2034,10 +2115,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-cli"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-file-formats",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
"designcraft-doc",
|
||||
@@ -2053,7 +2134,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-color"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"kurbo",
|
||||
@@ -2065,7 +2146,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-compose"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-doc",
|
||||
@@ -2085,7 +2166,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-doc"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"designcraft-color",
|
||||
@@ -2098,7 +2179,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-engine"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"caseless",
|
||||
"craft-atomic",
|
||||
@@ -2106,11 +2187,12 @@ dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-file-formats",
|
||||
"craft-indd",
|
||||
"craft-mime",
|
||||
"craft-prepress",
|
||||
"craft-print",
|
||||
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ad5f35bf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f23b0f33f0d00b157476533a43cbbcfd901aa1f1)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
"designcraft-doc",
|
||||
@@ -2143,9 +2225,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-epub"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-epub",
|
||||
"craft-mime",
|
||||
"designcraft-color",
|
||||
"designcraft-doc",
|
||||
"zip 3.0.0",
|
||||
@@ -2153,7 +2236,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-fonts"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"core-text",
|
||||
"harfrust 0.13.3",
|
||||
@@ -2166,7 +2249,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-format"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-designcraft-format",
|
||||
"designcraft-doc",
|
||||
@@ -2176,7 +2259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-geom"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"flo_curves",
|
||||
"kurbo",
|
||||
@@ -2189,12 +2272,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-idml"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-file-formats",
|
||||
"craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ad5f35bf)",
|
||||
"craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)",
|
||||
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ad5f35bf)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)",
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
"designcraft-doc",
|
||||
@@ -2207,12 +2290,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-images"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
|
||||
"craft-file-formats",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"craft-psd",
|
||||
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)",
|
||||
"designcraft-color",
|
||||
@@ -2228,7 +2311,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-mcp"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-file-formats",
|
||||
"designcraft-engine",
|
||||
@@ -2242,11 +2325,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-pdf"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cms",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"craft-pdf",
|
||||
"craft-prepress",
|
||||
"designcraft-color",
|
||||
@@ -2268,10 +2351,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-pptx"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)",
|
||||
"craft-pptx",
|
||||
"designcraft-color",
|
||||
@@ -2289,10 +2372,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-render"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea1c84290dadec636900b4d1bce107e59ca3f0d6)",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
|
||||
"craft-pdf",
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
@@ -2310,11 +2393,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-textimport"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-docx",
|
||||
"craft-file-formats",
|
||||
"craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ad5f35bf)",
|
||||
"craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2)",
|
||||
"craft-rtf",
|
||||
"craft-wordmodel",
|
||||
"craft-xlsx",
|
||||
@@ -2324,7 +2407,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-tools"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"designcraft-color",
|
||||
"designcraft-compose",
|
||||
@@ -2336,7 +2419,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-ui-egui"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-dialogs",
|
||||
"craft-file-formats",
|
||||
@@ -2371,7 +2454,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "designcraft-web"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"designcraft-engine",
|
||||
"designcraft-format",
|
||||
@@ -3457,7 +3540,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hayro-interpret",
|
||||
@@ -3477,7 +3560,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -3486,7 +3569,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3504,7 +3587,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3522,12 +3605,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4168,7 +4251,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=40525913633942f84b06d4837a8d90534a55d63f#40525913633942f84b06d4837a8d90534a55d63f"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -7511,6 +7594,27 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-geom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.0.8"
|
||||
@@ -8612,7 +8716,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+22
-20
@@ -4,39 +4,41 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/designcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared RFC 4648 encoding; document decoding policies remain local.
|
||||
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
|
||||
# Shared reader and writer; publish the immutable revision before this consumer.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.1.0", default-features = false }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0", default-features = false }
|
||||
craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b1b4602a71d19e09ad33f7752a10d6598cf39b2b", version = "=0.1.0" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
|
||||
craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
|
||||
craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "1ad5f35bf", version = "=0.1.0" }
|
||||
craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2", version = "=0.1.0" }
|
||||
craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "47bf5650b0d503b97bfb5e841746c4957897d11f", version = "=0.1.0" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "cc23ffd4d26f3074808e2187d332564817624f8f", version = "=0.1.0", features = ["tree-render", "tree-text"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "1ad5f35bf", version = "=0.1.0" }
|
||||
craft-xml-dtd = { package = "craft-xml", git = "https://github.com/storytold/craft-libs", rev = "f23b0f33f0d00b157476533a43cbbcfd901aa1f1", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2", version = "=0.1.0" }
|
||||
craft-xml-dtd = { package = "craft-xml", git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "bfea7d9800a9f14e496209f9df30e9ef45655701", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "2b9a325f57624804ed423aded16695eddb815119", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7ad4765ee55496d0ccdb7659ad7a6375c7bbb484", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7ad4765ee55496d0ccdb7659ad7a6375c7bbb484", version = "=0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "387c64892b30fdad491b263cc3d9eac660d88dcc", version = "=0.1.0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ea1c84290dadec636900b4d1bce107e59ca3f0d6", version = "=0.1.0" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "ea1c84290dadec636900b4d1bce107e59ca3f0d6", version = "=0.1.0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bfea7d9800a9f14e496209f9df30e9ef45655701", version = "=0.1.0" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d15bf1f35b17b759870f9e5111b9a5d243f64888", version = "=0.1.0" }
|
||||
craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "eed3c28cf016723d004d6f2c79c61424c15d4558", version = "=0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551", version = "=0.1.0" }
|
||||
craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "f6cab1980", version = "=0.1.0" }
|
||||
# Shared keyboard bindings: chords, overrides, conflicts, egui dispatch, the Keyboard Shortcuts dialog.
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", features = ["egui", "ui"] }
|
||||
# Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch.
|
||||
craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.1.0", features = ["flatten"] }
|
||||
craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0", features = ["flatten"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
designcraft-geom = { path = "crates/geom" }
|
||||
designcraft-color = { path = "crates/color" }
|
||||
@@ -101,7 +103,7 @@ craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-li
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
|
||||
# ICC colour management: working spaces, transforms, black point compensation (craft-libs).
|
||||
craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f" }
|
||||
craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813" }
|
||||
|
||||
# ui
|
||||
# Shared frontend components; keep this dependency above the engine boundary.
|
||||
@@ -151,16 +153,16 @@ debug = 0
|
||||
|
||||
# Opt-in cancelable macOS termination on the pinned winit 0.30 line.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.8.2" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.8.2" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
# The hayro crates from craft-libs' vendor/ directory (pdfcraft's, plus the plate mode and decode
|
||||
# limits craft-pdf and craft-prepress need); same revision as craft-pdf.
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.7.1" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.7.0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.3.0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.1.0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "40525913633942f84b06d4837a8d90534a55d63f", version = "=0.1.0" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.7.1" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.7.0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.7.2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.3.0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
+13
-6
@@ -4,7 +4,7 @@
|
||||
- 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md).
|
||||
- FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage.
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** minor (Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** minor (obsolete CI gap removed; tracked-change selection mapping; Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026
|
||||
- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.
|
||||
|
||||
- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.
|
||||
@@ -376,11 +376,10 @@ Ranked; detail and estimates in [docs/roadmap.md](docs/roadmap.md), the full lis
|
||||
|
||||
1. **Alpha gate:** Primary Text Frame page fixes: autoflow adds pages users can't delete (#165) (5–7 h)
|
||||
2. Basic editing on every platform: copy/paste, context menus, caret formatting (30–50 h)
|
||||
3. CI running `cargo xtask ci` on pull requests (4–8 h)
|
||||
4. INDD real-file corpus: measure what `.indd` files keep through indd-utils (10–30 h)
|
||||
5. IDML real-file corpus and fixes (60–100 h)
|
||||
6. Composition oracle against InDesign; optical kerning tuning; overset rule (70–125 h)
|
||||
7. Start on any GPU; find every installed font (25–50 h)
|
||||
3. INDD real-file corpus: measure what `.indd` files keep through indd-utils (10–30 h)
|
||||
4. IDML real-file corpus and fixes (60–100 h)
|
||||
5. Composition oracle against InDesign; optical kerning tuning; overset rule (70–125 h)
|
||||
6. Start on any GPU; find every installed font (25–50 h)
|
||||
|
||||
## Documents
|
||||
|
||||
@@ -395,6 +394,9 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-11-15** · Removed the obsolete gap saying pull requests have no test workflow: [CI](.github/workflows/ci.yml) runs the shared quality gate on every pull request and push to main (#1352). No readiness percentage change.
|
||||
- **2026-11-15** · Accepting tracked deletions or rejecting insertions follows body-text selections through the removed text, including resolving all changes, and preserves independent cell and footnote insertion points. No readiness percentage change.
|
||||
- **2026-11-15** · Format follow-ups to the craft-libs cutover (craft-libs#778; ported from #2734 by Dylan M. Taylor): IDML export keeps CDATA image contents and table spans such as `inf` reach the table edge; DOCX plain-text import leaves out deleted tracked changes and expands inline objects; an XLSX number cell that isn't a number shows as written; unmarked CMYK JPEGs keep the shared decoder's ink polarity; PPTX export writes exact opacity; PDF export repins craft-pdf and craft-prepress to craft-libs main. No readiness percentage change.
|
||||
- **2026-11-14** · `object.stroke` refuses a tint or gap tint outside 0 to 1, a weight outside 0 to 1000 pt, a miter limit outside 1 to 500, a gap overprint that isn't true or false, and an alignment, cap, join or arrowhead name it doesn't have, instead of clamping the numbers and skipping the names. The Stroke panel's Weight and Miter Limit fields keep their values in those ranges. No readiness percentage change.
|
||||
- **2026-11-14** · Photo books no longer freeze the canvas (#1411; based on #2051 by texjer). The image cache keeps only the mip level each image is drawn at, for every format and display quality: a TIFF, PNG, PSD or CMYK JPEG used to keep its full decode too (48 MB for a 12 MP photo), so after about a dozen photos each edit evicted and decoded them again on the render thread. The canvas no longer waits for decodes: an image not cached at its size shows a light box or another cached level and decodes on one of three background threads (within the same in-flight memory limit as the decodes ahead of a render), and finished decodes are drawn in batches, at most one canvas render every 250 ms. Zooming into an image decodes it at most twice. Thumbnails and exports still wait for every image. No readiness percentage change.
|
||||
- **2026-11-14** · IDML export keeps each endnote reference as its number in superscript text, as the endnote frame lists it, instead of dropping it; the endnotes are still written as plain text, without IDML's endnote elements (#2753). No readiness percentage change.
|
||||
@@ -452,6 +454,7 @@ Newest first.
|
||||
- **2026-10-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. No readiness percentage change.
|
||||
- **2026-10-25** · Duplicate Layer (`layer.duplicate`; the layer's context menu in the Layers panel, or a layer dropped on Create New Layer) adds a copy named after the layer with " copy" added ("Art copy" for Art) above the layer, with its settings, a copy of every object on it and copies of its ruler guides, on document and parent pages, in one undo step. Copied frames stay threaded to the copies of frames on the same layer and are not threaded to frames on other layers. A copied override of a parent item overrides that item's copy, and pages hide the copy where they hide the parent item. Hyperlinks on copied objects and text get copies that go to the same destinations. No readiness percentage change.
|
||||
- **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change.
|
||||
- **2026-10-24** · Table › Cell Options › Diagonal Lines… (`table.setCell` `diagonal`, `table.getCellDiagonal`): as in InDesign, a cell can carry a diagonal line from the top left corner to the bottom right, from the top right to the bottom left, or both, with the weight, type, color, tint, gap color and gap tint that cell edges take, drawn in front of the cell's contents or behind them. The lines draw on screen and in PDF and are saved in the native format. No readiness percentage change.
|
||||
- **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change.
|
||||
- **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change.
|
||||
- **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load unchanged. No readiness percentage change.
|
||||
@@ -534,6 +537,7 @@ Newest first.
|
||||
- **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change.
|
||||
- **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change.
|
||||
- **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. No readiness percentage change.
|
||||
- **2026-10-21** · Layer Options has InDesign's Lock Guides: the layer's ruler guides can't be moved or deleted while its objects stay editable (`layer.set {lockGuides}`), and IDML reads and writes the layer's `LockGuides` (it was always written as false). The options are arranged as InDesign's: Show Layer and Show Guides, Lock Layer and Lock Guides, Print Layer. Found in the Learn Skills Daily course, chapter 32. No readiness percentage change.
|
||||
- **2026-10-20** · Smart guides: an edge being drawn or resized snaps to the page's centre line, as in InDesign, so a frame drawn from the top margin to the middle of the page stops there instead of at the nearest baseline grid line. No readiness percentage change.
|
||||
- **2026-10-21** · An empty graphic frame's X joins its corners, so a frame slanted with Direct Selection keeps its X corner to corner, as InDesign draws it; it used to stay across the old rectangle. Found in Zero2Graphic's *How to Page Layout design in Adobe InDesign 2022 CC*. No readiness percentage change.
|
||||
- **2026-10-21** · Paragraph Border and Paragraph Shading link their four sides as InDesign's: the stroke weights, offsets and corners have the "Make all settings the same" link, on when the four are the same, so a side typed in sets all four; with the link off a side is set alone (a border with only a thick left side). Found in the Learn Skills Daily course, chapter 40. No readiness percentage change.
|
||||
@@ -878,6 +882,7 @@ Newest first.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Track Changes resolution maps body selections through removed text and preserves nested text positions |
|
||||
| 2026-10-12 | minor | Manual text threading landed; alpha distance 15–25 h → 5–7 h (Primary Text Frame page fixes, #165) |
|
||||
| 2026-10-11 | minor | Localized Japanese print, import and table controls; readiness estimates unchanged |
|
||||
| 2026-10-10 | minor | Full number 42% → 47% (plain weighted sum, no new evidence); readiness table with hours per audience |
|
||||
@@ -895,3 +900,5 @@ The shared craft-installer UI preserves this revision's install options and prov
|
||||
- **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change.
|
||||
|
||||
- PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged.
|
||||
|
||||
- Format reuse: HTML data URIs and file serialization use craft-mime Base64 encoding; existing decoder policies and document budgets remain unchanged.
|
||||
|
||||
@@ -42,7 +42,7 @@ use designcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The usage block. Shared by `--help` (stdout, success) and an unknown command (stderr, failure).
|
||||
const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # built-in PDF/X checks (including visible unembedded fonts; the standard defaults to the file's own)\n designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the saved first-page preview, at most SIZE px\n designcraft-cli links\n designcraft-cli --version";
|
||||
const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--frames N] [--chars N] [--images N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # built-in PDF/X checks (including visible unembedded fonts; the standard defaults to the file's own)\n designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the saved first-page preview, at most SIZE px\n designcraft-cli links\n designcraft-cli --version";
|
||||
|
||||
/// `script --help`: the script syntax, otherwise only in `describe script.run` and docs/agents.md.
|
||||
const SCRIPT_HELP: &str = r#"usage: designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]
|
||||
@@ -692,11 +692,15 @@ fn script(args: &[String]) -> Result<(), String> {
|
||||
let report = if keep_going {
|
||||
// Run every step; failures become {"error": …} results.
|
||||
let mut results: Vec<Value> = Vec::new();
|
||||
for st in &steps {
|
||||
let mut failed = None;
|
||||
for (i, st) in steps.iter().enumerate() {
|
||||
let r = designcraft_engine::script::resolve(&st.params, &results).and_then(|p| exec(b, &st.command, p));
|
||||
results.push(r.unwrap_or_else(|e| json!({"error": e, "command": st.command})));
|
||||
results.push(r.unwrap_or_else(|e| {
|
||||
failed.get_or_insert_with(|| (i, st.command.clone(), e.clone()));
|
||||
json!({"error": e, "command": st.command})
|
||||
}));
|
||||
}
|
||||
designcraft_engine::script::Report { results, failed: None }
|
||||
designcraft_engine::script::Report { results, failed }
|
||||
} else {
|
||||
designcraft_engine::script::run(&steps, |id, p| exec(b, id, p))
|
||||
};
|
||||
|
||||
@@ -97,6 +97,9 @@ fn row(rows: &mut Vec<Row>, name: impl Into<String>, ms: f64, budget: Option<f64
|
||||
|
||||
/// Measure `doc`. `runs` = repetitions per row (median).
|
||||
fn measure(doc: &Document, runs: usize) -> Result<Vec<Row>, String> {
|
||||
if doc.spreads.is_empty() {
|
||||
return Err("cannot benchmark a document with no spreads".into());
|
||||
}
|
||||
let mut rows = vec![];
|
||||
let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
|
||||
let chars: usize = doc.stories.values().map(|s| s.text.len()).sum();
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
//! What the command line does with its arguments, pinned.
|
||||
//!
|
||||
//! Every assertion here was measured, not intended: these tests say what the parser does today,
|
||||
//! including where that is odd (an unknown option taken as a filter, a `--opt=value` form that
|
||||
//! only the automation roots have). They exist so that moving to a derived parser — the work
|
||||
//! photocraft#7071 lists, which this parser needs too — changes the surface where that is the
|
||||
//! point and nowhere else.
|
||||
//!
|
||||
//! They assert the exit code, which stream the output went to, and that an error names the
|
||||
//! argument it is about. They do not assert wording, so a message can be improved without
|
||||
//! editing a test, except in the few places where the wording *is* the behaviour and the test
|
||||
//! says so.
|
||||
//!
|
||||
//! `tests/cli.rs` holds what the subcommands then do: exports, scripts, the MCP server.
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// `designcraft-cli` with stdin closed, so a subcommand that reads a script does not wait.
|
||||
fn cli() -> Command {
|
||||
let mut c = Command::new(env!("CARGO_BIN_EXE_designcraft-cli"));
|
||||
c.stdin(Stdio::null());
|
||||
c
|
||||
}
|
||||
|
||||
/// What one invocation did.
|
||||
struct Ran {
|
||||
code: Option<i32>,
|
||||
out: String,
|
||||
err: String,
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> Ran {
|
||||
let out = cli().args(args).output().unwrap_or_else(|e| panic!("{args:?}: {e}"));
|
||||
Ran { code: out.status.code(), out: String::from_utf8_lossy(&out.stdout).into_owned(), err: String::from_utf8_lossy(&out.stderr).into_owned() }
|
||||
}
|
||||
|
||||
impl Ran {
|
||||
/// Succeeded, said nothing on stderr; gives back what it printed.
|
||||
fn succeeded(self, what: &str) -> String {
|
||||
assert_eq!(self.code, Some(0), "{what}: {:?}", self.err);
|
||||
assert_eq!(self.err, "", "{what} wrote to stderr");
|
||||
self.out
|
||||
}
|
||||
|
||||
/// Failed with the usage exit code, said nothing on stdout; gives back the complaint.
|
||||
fn failed(self, what: &str) -> String {
|
||||
assert_eq!(self.code, Some(1), "{what}: expected a usage failure, got {:?} / {:?}", self.out, self.err);
|
||||
assert_eq!(self.out, "", "{what} wrote to stdout");
|
||||
self.err
|
||||
}
|
||||
}
|
||||
|
||||
/// A port with nothing listening on it, so `--connect` and `--port` fail the same way every time.
|
||||
fn closed_port() -> String {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
port.to_string()
|
||||
}
|
||||
|
||||
/// A directory of this test's own, removed when the test ends.
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("dc-args-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Every subcommand, in the order the usage block lists them.
|
||||
const SUBCOMMANDS: [&str; 10] = ["run", "commands", "describe", "script", "app", "mcp", "perf", "bench", "validate-pdf", "links"];
|
||||
|
||||
#[test]
|
||||
fn with_no_arguments_it_prints_the_usage_block_and_fails() {
|
||||
let err = run(&[]).failed("no arguments");
|
||||
assert!(err.starts_with("usage: designcraft-cli run"), "{err:?}");
|
||||
// The usage block names every subcommand, which is how `<sub> --help` finds its lines.
|
||||
for sub in SUBCOMMANDS {
|
||||
assert!(err.contains(&format!("designcraft-cli {sub}")), "usage names {sub}: {err:?}");
|
||||
}
|
||||
// An empty argument is a command nobody has, not a request for help.
|
||||
run(&[""]).failed("an empty argument");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_goes_to_stdout_and_succeeds_in_all_three_spellings() {
|
||||
let long = run(&["--help"]).succeeded("--help");
|
||||
assert!(long.starts_with("usage: designcraft-cli run"), "{long:?}");
|
||||
// The community links are under the usage block, for someone who has nowhere else to ask.
|
||||
assert!(long.contains("Community:") && long.contains("discord"), "{long:?}");
|
||||
for spelling in ["-h", "help"] {
|
||||
assert_eq!(run(&[spelling]).succeeded(spelling), long, "{spelling} prints the same help");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_command_fails_with_the_same_text_on_stderr() {
|
||||
let usage = run(&["--help"]).succeeded("--help");
|
||||
for unknown in ["bogus", "-x", "--nope", "Run"] {
|
||||
let err = run(&[unknown]).failed(unknown);
|
||||
assert_eq!(err, usage, "{unknown}: the same usage, on stderr");
|
||||
// Asking for help about a command nobody has is still that command: `<sub> --help`
|
||||
// answered with the whole usage block on stdout and succeeded, which skipped the
|
||||
// unknown-command failure entirely (noted in review).
|
||||
for spelling in ["--help", "-h"] {
|
||||
let err = run(&[unknown, spelling]).failed(&format!("{unknown} {spelling}"));
|
||||
assert_eq!(err, usage, "{unknown} {spelling}: the same usage, on stderr");
|
||||
}
|
||||
}
|
||||
// A real subcommand still answers about itself, and only about itself.
|
||||
for sub in SUBCOMMANDS.iter().filter(|s| **s != "script") {
|
||||
let text = run(&[sub, "--help"]).succeeded(sub);
|
||||
assert!(text.contains(&format!("designcraft-cli {sub}")), "{sub} --help describes {sub}: {text:?}");
|
||||
assert_ne!(text, usage, "{sub} --help is about {sub}, not the whole usage block");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_version_is_the_crate_version() {
|
||||
let expected = format!("designcraft-cli {}\n", env!("CARGO_PKG_VERSION"));
|
||||
for spelling in ["--version", "-V", "version"] {
|
||||
assert_eq!(run(&[spelling]).succeeded(spelling), expected, "{spelling}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `<sub> --help` asks about that subcommand. It answers from the usage block, on stdout, and
|
||||
/// nothing else happens: no export is written, no port is dialled, no measurement is taken, and a
|
||||
/// file named earlier in the same line is not opened or complained about (photocraft#423).
|
||||
#[test]
|
||||
fn every_subcommand_answers_help_without_running_anything() {
|
||||
let dir = temp_dir("help");
|
||||
let png = dir.join("ran.png");
|
||||
let dead = closed_port();
|
||||
let cases: [(&str, Vec<&str>); 10] = [
|
||||
("run", vec!["run", "--sample", "--export", png.to_str().unwrap()]),
|
||||
("commands", vec!["commands"]),
|
||||
("describe", vec!["describe", "file.open"]),
|
||||
("script", vec!["script", "no-such-script.dcs"]),
|
||||
("app", vec!["app", "--port", &dead, "document.list"]),
|
||||
("mcp", vec!["mcp", "--connect", &dead]),
|
||||
("perf", vec!["perf", "--pages", "1", "--runs", "1"]),
|
||||
("bench", vec!["bench", "no-such-document.designcraft"]),
|
||||
("validate-pdf", vec!["validate-pdf", "no-such-file.pdf"]),
|
||||
("links", vec!["links"]),
|
||||
];
|
||||
for (sub, args) in cases {
|
||||
for flag in ["--help", "-h"] {
|
||||
let mut args = args.clone();
|
||||
args.push(flag);
|
||||
let what = format!("{sub} {flag}");
|
||||
let out = run(&args).succeeded(&what);
|
||||
assert!(out.contains(&format!("designcraft-cli {sub}")), "{what} names it: {out:?}");
|
||||
assert!(!out.contains("unknown option"), "{what}: {out:?}");
|
||||
// None of the work the rest of the line asks for was done.
|
||||
assert!(!png.exists(), "{what} exported a file");
|
||||
assert!(!out.contains("cannot connect") && !out.contains("render threads"), "{what}: {out:?}");
|
||||
// Either operating system's wording, so this catches a file the help path opened on
|
||||
// Windows as well as on unix.
|
||||
assert!(!out.contains("No such file") && !out.contains("cannot find the file"), "{what}: {out:?}");
|
||||
}
|
||||
}
|
||||
// `script`'s own help is longer than one usage line: it documents the script syntax, which is
|
||||
// otherwise only in `describe script.run` and the docs.
|
||||
let out = run(&["script", "--help"]).succeeded("script --help");
|
||||
assert!(out.contains("Script text, one step per line"), "{out:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The subcommands that have options refuse an option they do not know, and name it.
|
||||
#[test]
|
||||
fn an_unknown_option_is_refused_by_name() {
|
||||
let cases: [Vec<&str>; 5] = [
|
||||
vec!["run", "--nope"],
|
||||
vec!["script", "-", "--nope"],
|
||||
vec!["mcp", "--nope"],
|
||||
vec!["perf", "--nope"],
|
||||
vec!["bench", "f.designcraft", "--nope"],
|
||||
];
|
||||
for args in cases {
|
||||
let err = run(&args).failed(&format!("{args:?}"));
|
||||
assert!(err.contains("--nope"), "{args:?}: {err:?}");
|
||||
assert!(err.contains("unknown"), "{args:?}: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The subcommands whose argument is a word, not an option, take an unknown option as that word:
|
||||
/// `commands --nope` filters the command list by `--nope` and finds nothing. Each of these would
|
||||
/// be an error under the rule photocraft#7071 settles on; today they are not, and a change of
|
||||
/// mind shows up here.
|
||||
#[test]
|
||||
fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() {
|
||||
// A filter that matches no command: an empty list, successfully.
|
||||
assert_eq!(run(&["commands", "--nope"]).succeeded("commands --nope").trim(), "[]");
|
||||
// A command id nobody has.
|
||||
let err = run(&["describe", "--nope"]).failed("describe --nope");
|
||||
assert!(err.contains("no command `--nope`"), "{err:?}");
|
||||
// A path nobody has. `--nope` has to fail the way an ordinary missing path fails, because
|
||||
// that is what shows it reached the file system as a path instead of being read as an
|
||||
// option. Asserting only that the complaint names `--nope` does not show that: a parser that
|
||||
// rejected unknown options would name it too (noted in review).
|
||||
//
|
||||
// So the two are compared with the name taken out. That holds the shape of the failure
|
||||
// without asserting the operating system's wording for a missing file -- Windows says "The
|
||||
// system cannot find the file specified" -- which an earlier round of review rightly took
|
||||
// out of this test. `failed` already checks the exit code and that stdout stayed empty.
|
||||
let as_option = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope");
|
||||
let as_path = run(&["validate-pdf", "nope.pdf"]).failed("validate-pdf nope.pdf");
|
||||
assert!(as_option.contains("--nope"), "{as_option:?}");
|
||||
assert_eq!(
|
||||
as_option.replace("--nope", "<name>"),
|
||||
as_path.replace("nope.pdf", "<name>"),
|
||||
"`--nope` must fail as a missing path does, not as an option"
|
||||
);
|
||||
// A method name for the running app, so the error is about reaching the app.
|
||||
let dead = closed_port();
|
||||
let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope");
|
||||
assert!(err.contains("cannot connect"), "{err:?}");
|
||||
// And `links`, which takes nothing, ignores what it is given.
|
||||
let out = run(&["links", "--nope"]).succeeded("links --nope");
|
||||
assert_eq!(out, run(&["links"]).succeeded("links"));
|
||||
}
|
||||
|
||||
/// There is no `--opt=value` form. The two automation roots are the exception: they have one,
|
||||
/// because a folder whose name starts with `-` has no other way in there.
|
||||
#[test]
|
||||
fn only_the_automation_roots_have_an_opt_equals_value_form() {
|
||||
let cases: [(&str, Vec<&str>); 3] = [
|
||||
("--scale=2", vec!["run", "--scale=2", "--sample"]),
|
||||
("--pages=2", vec!["perf", "--pages=2"]),
|
||||
("--save=out.designcraft", vec!["script", "-", "--save=out.designcraft"]),
|
||||
];
|
||||
for (token, args) in cases {
|
||||
let err = run(&args).failed(&format!("{args:?}"));
|
||||
assert!(err.contains("unknown"), "{args:?}: {err:?}");
|
||||
// The whole token is named, `=value` and all, so it is clear what was not understood.
|
||||
assert!(err.contains(token), "{args:?}: {err:?}");
|
||||
}
|
||||
// The roots read the value after `=`: an empty one is refused as a folder, which is the
|
||||
// parser having taken it rather than ignoring the form.
|
||||
let err = run(&["mcp", "--automation-read-root="]).failed("empty root");
|
||||
assert!(err.contains("--automation-read-root") && err.contains("folder"), "{err:?}");
|
||||
// A root given more than once adds another folder, in either spelling, rather than the last
|
||||
// one winning or the repeat being refused: the roots are repeatable (`...` in the usage), and
|
||||
// `mcp_automation_roots_take_several_folders` covers what the extra folder grants. This PR
|
||||
// first pinned the older behaviour, where a second root was an error; upstream has made them
|
||||
// repeatable since, so what is pinned here is today's.
|
||||
//
|
||||
// Checked by what fails rather than by letting the server start: the stray token after the
|
||||
// roots is the error, which shows both roots were taken.
|
||||
for second in [vec!["--automation-read-root=b"], vec!["--automation-read-root", "b"]] {
|
||||
let mut args = vec!["mcp", "--automation-read-root=a"];
|
||||
args.extend(second.iter().copied());
|
||||
args.push("stray");
|
||||
let err = run(&args).failed(&format!("{second:?}"));
|
||||
assert!(err.contains("stray"), "the stray token is what fails: {err:?}");
|
||||
assert!(!err.contains("twice"), "a repeated root is not refused any more: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An option that needs a value and has none says which option, and nothing runs.
|
||||
#[test]
|
||||
fn a_missing_value_names_its_option() {
|
||||
let dir = temp_dir("missing");
|
||||
let png = dir.join("out.png");
|
||||
let cases: [(&str, Vec<&str>); 9] = [
|
||||
("--export", vec!["run", "--sample", "--export"]),
|
||||
("--in", vec!["run", "--in"]),
|
||||
("--all-pages", vec!["run", "--sample", "--all-pages"]),
|
||||
// Before an export, too: the order of the options is nothing to judge until this one has
|
||||
// a value, so it is not reported as an export it is not in front of.
|
||||
("--scale", vec!["run", "--sample", "--scale", "--export", png.to_str().unwrap()]),
|
||||
("--page", vec!["run", "--sample", "--page"]),
|
||||
("--save", vec!["script", "-", "--save"]),
|
||||
("--connect", vec!["script", "-", "--connect"]),
|
||||
("--port", vec!["app", "--port"]),
|
||||
("--pages", vec!["perf", "--pages"]),
|
||||
];
|
||||
for (option, args) in cases {
|
||||
let err = run(&args).failed(&format!("{args:?}"));
|
||||
assert!(err.contains(option), "{args:?} names {option}: {err:?}");
|
||||
assert!(err.contains("needs"), "{args:?}: {err:?}");
|
||||
}
|
||||
assert!(!png.exists(), "nothing is exported");
|
||||
|
||||
// A missing value after an export is found before that export runs: the line writes nothing,
|
||||
// as a malformed line always did.
|
||||
let first = dir.join("first.png");
|
||||
let line = ["run", "--sample", "--export", first.to_str().unwrap(), "--scale", "--export", png.to_str().unwrap()];
|
||||
let err = run(&line).failed("a missing value after an export");
|
||||
assert!(err.contains("--scale needs a value"), "{err:?}");
|
||||
assert!(!first.exists(), "the export before it was not written");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `--help` wins wherever it appears after the subcommand, even where an option would take it as
|
||||
/// its value: `run --in -h` prints `run`'s usage and opens nothing.
|
||||
#[test]
|
||||
fn help_wins_even_where_an_option_would_take_it_as_a_value() {
|
||||
for flag in ["-h", "--help"] {
|
||||
let out = run(&["run", "--in", flag]).succeeded(&format!("run --in {flag}"));
|
||||
assert!(out.contains("designcraft-cli run"), "{out:?}");
|
||||
}
|
||||
// And each subcommand's usage lists every option it takes.
|
||||
let perf = run(&["perf", "--help"]).succeeded("perf --help");
|
||||
for option in ["--pages", "--frames", "--chars", "--images", "--runs", "--strict"] {
|
||||
assert!(perf.contains(option), "perf --help lists {option}: {perf:?}");
|
||||
}
|
||||
let validate = run(&["validate-pdf", "--help"]).succeeded("validate-pdf --help");
|
||||
assert!(validate.contains("--standard"), "{validate:?}");
|
||||
}
|
||||
|
||||
/// An option that takes no value does not swallow the token after it: that token is read as the
|
||||
/// next argument, and refused if it is not one.
|
||||
#[test]
|
||||
fn a_flag_that_takes_no_value_leaves_the_next_token_alone() {
|
||||
let err = run(&["run", "--sample", "extra", "--export", "out.png"]).failed("run --sample extra");
|
||||
assert!(err.contains("extra"), "{err:?}");
|
||||
let err = run(&["perf", "--strict", "3"]).failed("perf --strict 3");
|
||||
assert!(err.contains('3'), "{err:?}");
|
||||
}
|
||||
|
||||
/// A value flag given twice keeps the last value. (The automation roots are the exception, above.)
|
||||
#[test]
|
||||
fn a_repeated_value_flag_keeps_the_last_value() {
|
||||
let dir = temp_dir("repeat");
|
||||
let at = |args: &[&str], name: &str| -> Vec<u8> {
|
||||
let path = dir.join(name);
|
||||
let mut full: Vec<&str> = vec!["run", "--sample"];
|
||||
full.extend_from_slice(args);
|
||||
let out = path.to_str().unwrap();
|
||||
full.extend(["--export", out]);
|
||||
let ran = run(&full);
|
||||
assert_eq!(ran.code, Some(0), "{full:?}: {:?}", ran.err);
|
||||
std::fs::read(&path).unwrap()
|
||||
};
|
||||
// `--scale`: the size of the image says which value was used.
|
||||
let one = at(&[], "1.png");
|
||||
let three = at(&["--scale", "3"], "3.png");
|
||||
assert_eq!(at(&["--scale", "2", "--scale", "3"], "23.png"), three, "the last --scale won");
|
||||
assert_ne!(three, one, "and --scale 3 is not --scale 1");
|
||||
// `--page`: which page was exported says it.
|
||||
let second = at(&["--page", "1"], "p1.png");
|
||||
assert_ne!(second, one, "page 1 of the sample is not page 0");
|
||||
assert_eq!(at(&["--page", "1", "--page", "0"], "p10.png"), one, "the last --page won");
|
||||
// `--connect` and `--port`: the address the error names says it.
|
||||
let (a, b) = (closed_port(), closed_port());
|
||||
for args in [vec!["mcp", "--connect", &a, "--connect", &b], vec!["app", "--port", &a, "--port", &b, "document.list"]] {
|
||||
let err = run(&args).failed(&format!("{args:?}"));
|
||||
assert!(err.contains(&format!("127.0.0.1:{b}")), "{args:?} dialled the last port: {err:?}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The flags that are meant to repeat each take effect, in order.
|
||||
#[test]
|
||||
fn the_repeatable_flags_all_take_effect() {
|
||||
let dir = temp_dir("each");
|
||||
let (a, b) = (dir.join("a.png"), dir.join("b.png"));
|
||||
let ran = run(&[
|
||||
"run",
|
||||
"--sample",
|
||||
"--cmd",
|
||||
"document.list",
|
||||
"--cmd",
|
||||
"document.list",
|
||||
"--export",
|
||||
a.to_str().unwrap(),
|
||||
"--export",
|
||||
b.to_str().unwrap(),
|
||||
]);
|
||||
assert_eq!(ran.code, Some(0), "{:?}", ran.err);
|
||||
// One result line per `--cmd`, in the order given.
|
||||
let results: Vec<&str> = ran.out.lines().collect();
|
||||
assert_eq!(results.len(), 2, "{results:?}");
|
||||
assert_eq!(results[0], results[1]);
|
||||
// And one file per `--export`.
|
||||
assert_eq!(std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap());
|
||||
assert_eq!(ran.err.lines().filter(|l| l.starts_with("wrote ")).count(), 2, "{:?}", ran.err);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A subcommand given nothing to do does nothing, quietly or with its own usage line. `run` with
|
||||
/// no arguments is the one that says nothing at all: there is no document to act on and nothing
|
||||
/// was asked of it.
|
||||
#[test]
|
||||
fn a_subcommand_with_nothing_to_do_says_so_or_says_nothing() {
|
||||
assert_eq!(run(&["run"]).succeeded("run"), "");
|
||||
// `script` with no file reads stdin, which is closed here: an empty script, run.
|
||||
let out = run(&["script"]).succeeded("script");
|
||||
assert!(out.contains("\"completed\": 0"), "{out:?}");
|
||||
// The two that need an argument print the usage line for themselves.
|
||||
for sub in ["describe", "bench", "validate-pdf"] {
|
||||
let err = run(&[sub]).failed(sub);
|
||||
assert!(err.contains(&format!("designcraft-cli {sub}")), "{sub}: {err:?}");
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,31 @@ fn cli() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_designcraft-cli"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_without_spreads_reports_an_error_instead_of_panicking() {
|
||||
struct Fixture(std::path::PathBuf);
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
let path = std::env::temp_dir().join(format!("dc-cli-empty-bench-{}.designcraft", std::process::id()));
|
||||
assert!(std::fs::symlink_metadata(&path).is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound));
|
||||
let fixture = Fixture(path);
|
||||
let mut document = designcraft_doc::Document::new(&Default::default());
|
||||
document.spreads.clear();
|
||||
document.check().unwrap();
|
||||
let bytes = designcraft_format::save(&document).unwrap();
|
||||
assert!(designcraft_format::load(&bytes).unwrap().spreads.is_empty());
|
||||
std::fs::write(&fixture.0, bytes).unwrap();
|
||||
|
||||
let out = cli().args(["bench", fixture.0.to_str().unwrap(), "--runs", "1"]).output().unwrap();
|
||||
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(1), "{err}");
|
||||
assert!(err.contains("cannot benchmark a document with no spreads"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_from_stdin_with_references_saves_and_exports() {
|
||||
let dir = std::env::temp_dir().join(format!("dc-cli-{}", std::process::id()));
|
||||
@@ -151,11 +176,49 @@ fn script_export_of_the_document_in_the_running_app_saves_a_copy() {
|
||||
#[test]
|
||||
fn failing_script_exits_nonzero_with_the_step() {
|
||||
let mut child = cli().args(["script", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
child.stdin.take().unwrap().write_all(b"document.inspect\nno.such.command\n").unwrap();
|
||||
child.stdin.take().unwrap().write_all(b"document.inspect\nno.such.command\ndocument.inspect\n").unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(v["failedIndex"], 1);
|
||||
assert_eq!(v["completed"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_going_reports_the_first_failure_and_does_not_write_outputs() {
|
||||
struct Outputs([std::path::PathBuf; 2]);
|
||||
impl Drop for Outputs {
|
||||
fn drop(&mut self) {
|
||||
for path in &self.0 {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
let root = std::env::temp_dir();
|
||||
let name = format!("dc-cli-keep-going-{}", std::process::id());
|
||||
let paths = [root.join(format!("{name}.designcraft")), root.join(format!("{name}.png"))];
|
||||
assert!(paths.iter().all(|path| !path.exists()));
|
||||
let outputs = Outputs(paths);
|
||||
|
||||
let mut child = cli()
|
||||
.args(["script", "-", "--keep-going", "--save", outputs.0[0].to_str().unwrap(), "--export", outputs.0[1].to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
child.stdin.take().unwrap().write_all(b"no.such.command\ndocument.inspect\nno.other.command\n").unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
|
||||
assert!(!out.status.success());
|
||||
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(v["completed"], 3);
|
||||
assert_eq!(v["failedIndex"], 0);
|
||||
assert_eq!(v["failedCommand"], "no.such.command");
|
||||
assert!(v["results"][0]["error"].is_string());
|
||||
assert!(v["results"][1].is_object() && v["results"][1]["error"].is_null());
|
||||
assert!(v["results"][2]["error"].is_string());
|
||||
assert!(outputs.0.iter().all(|path| !path.exists()), "--save and --export require a successful script");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
mod args;
|
||||
mod cli;
|
||||
|
||||
@@ -41,9 +41,10 @@ struct RecentMenu {
|
||||
separator: Option<PredefinedMenuItem>,
|
||||
}
|
||||
|
||||
/// Accelerator for "Cmd+Shift+]" (modifier-less shortcuts stay in the app so typing works).
|
||||
/// Accelerator for "Cmd+Shift+]". Shortcuts the bar would never see, such as modifier-less ones
|
||||
/// or Option on a character key, stay in the app (`menus::native_key_equivalent`).
|
||||
fn accel(sc: &str) -> Option<Accelerator> {
|
||||
if !(sc.contains("Cmd") || sc.contains("Ctrl") || sc.contains("Alt")) {
|
||||
if !menus::native_key_equivalent(sc) {
|
||||
return None;
|
||||
}
|
||||
Accelerator::from_str(&sc.replace("Cmd", "CMD").replace("Alt", "ALT").replace("Shift", "SHIFT").replace("Ctrl", "CTRL")).ok()
|
||||
|
||||
@@ -91,3 +91,6 @@ display_name = "Jonathan Cardoso"
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
@@ -53,8 +53,12 @@ pub struct Spacing {
|
||||
pub optical_size: Option<f64>,
|
||||
/// Korean text breaks between syllables instead of at spaces.
|
||||
pub korean_char_breaks: bool,
|
||||
/// 0: minimum adjustment; 1: push in; 2: push out first; 3: push out only.
|
||||
/// JIS X 4051 禁則処理 type: 0: minimum adjustment (調整量優先); 1: push in first (追い込み
|
||||
/// 優先, the default); 2: push out first (追い出し優先); 3: push out only (追い出しのみ).
|
||||
pub kinsoku_priority: u8,
|
||||
/// The paragraph has CJK text, so the 禁則 priority biases its breaks. A Latin paragraph's
|
||||
/// breaks are left alone by the (default) push-in-first policy.
|
||||
pub kinsoku_cjk: bool,
|
||||
}
|
||||
|
||||
impl Default for Spacing {
|
||||
@@ -77,19 +81,25 @@ impl Default for Spacing {
|
||||
optical: false,
|
||||
optical_size: None,
|
||||
korean_char_breaks: false,
|
||||
kinsoku_priority: 0,
|
||||
kinsoku_priority: 1,
|
||||
kinsoku_cjk: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Spacing {
|
||||
/// Push out only: the 追い込み (compression that would pull the next character in) is
|
||||
/// unavailable, so every line end is pushed out (and no line is compressed at its end).
|
||||
pub(crate) fn push_out_only(&self) -> bool {
|
||||
self.kinsoku_cjk && self.kinsoku_priority == 3
|
||||
}
|
||||
/// Per-tier (word, letter, glyph) stretch and shrink of glyph `g` as a box.
|
||||
fn box_elastic(&self, g: &Glyph) -> ([f64; 3], [f64; 3]) {
|
||||
if g.locked_advance {
|
||||
return ([0.0; 3], [0.0; 3]);
|
||||
}
|
||||
let moji_stretch = if self.justify { g.moji.stretch } else { 0.0 };
|
||||
let moji_shrink = if self.kinsoku_priority == 3 { 0.0 } else { g.moji.shrink };
|
||||
let moji_shrink = if self.push_out_only() { 0.0 } else { g.moji.shrink };
|
||||
if !self.justify {
|
||||
return ([0.0; 3], [moji_shrink, 0.0, 0.0]);
|
||||
}
|
||||
@@ -276,13 +286,18 @@ fn kinsoku_allows(a: char, b: char) -> bool {
|
||||
!NO_START.contains(b) && !NO_END.contains(a)
|
||||
}
|
||||
|
||||
/// Hangul: Jamo, compatibility Jamo, the syllables, and Jamo Extended-A/B. Shared with the
|
||||
/// paragraph's CJK gate so the two classifications cannot drift apart.
|
||||
pub(crate) fn is_hangul(c: char) -> bool {
|
||||
matches!(c as u32, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF)
|
||||
}
|
||||
|
||||
/// Hangul, and Han ideographs (hanja) in Korean text: Korean is set word by word (KLREQ), so
|
||||
/// these letters break like Western ones, at spaces.
|
||||
fn korean_letter(g: &Glyph) -> bool {
|
||||
let c = g.ch as u32;
|
||||
let hangul = matches!(c, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF);
|
||||
let han = matches!(c, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x3FFFF);
|
||||
hangul || (han && g.lang.is_some_and(|t| designcraft_doc::language_subtag(t) == "ko"))
|
||||
let c = g.ch;
|
||||
let han = matches!(c as u32, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x3FFFF);
|
||||
is_hangul(c) || (han && g.lang.is_some_and(|t| designcraft_doc::language_subtag(t) == "ko"))
|
||||
}
|
||||
|
||||
/// Is the place between glyphs `a` and `b` one where CJK text may break (next to an ideograph, kana
|
||||
@@ -413,7 +428,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
let mut p = Item::penalty(0.0, -INF, false);
|
||||
p.hang = prev_hang;
|
||||
if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) {
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only());
|
||||
}
|
||||
it.push(p);
|
||||
ig.push(i + 1);
|
||||
@@ -427,7 +442,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
let mut gl = Item::glue(w, st, sh);
|
||||
gl.hang = prev_hang;
|
||||
if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) {
|
||||
gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3);
|
||||
gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only());
|
||||
}
|
||||
gl.over = sp.space_overflow(g);
|
||||
last_space = it.len();
|
||||
@@ -440,7 +455,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
let mut p = Item::penalty(0.0, 0.0, false);
|
||||
p.hang = prev_hang;
|
||||
if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) {
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only());
|
||||
}
|
||||
last_space = it.len();
|
||||
it.push(p);
|
||||
@@ -462,7 +477,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
let (st, sh) = sp.box_elastic(g);
|
||||
let mut bx = Item::boxed(g.adv, st, sh);
|
||||
bx.hang = hang_left(g, sp) - g.moji.start;
|
||||
bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, sp.kinsoku_priority != 3);
|
||||
bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, !sp.push_out_only());
|
||||
it.push(bx);
|
||||
ig.push(i);
|
||||
let next_is_space = glyphs.get(i + 1).is_none_or(|n| n.is_space());
|
||||
@@ -470,12 +485,12 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
if matches!(g.ch, '-' | '\u{2010}') {
|
||||
let mut p = Item::penalty(0.0, 50.0, true);
|
||||
p.hang = right_hang(g, sp);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only());
|
||||
push_inword(&mut it, &mut ig, p, i + 1, sp);
|
||||
} else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) {
|
||||
let mut p = Item::penalty(0.0, 0.0, false);
|
||||
p.hang = right_hang(g, sp);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only());
|
||||
push_inword(&mut it, &mut ig, p, i + 1, sp);
|
||||
} else if hyph_after[i] {
|
||||
let hw = hyphen_width(g, &mut hy_cache);
|
||||
@@ -497,7 +512,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S
|
||||
let mut p = Item::penalty(0.0, -INF, false);
|
||||
p.hang = if n > 0 { right_hang(&glyphs[n - 1], sp) } else { 0.0 };
|
||||
if let Some(g) = glyphs.last() {
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3);
|
||||
p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only());
|
||||
}
|
||||
it.push(p);
|
||||
ig.push(n);
|
||||
@@ -638,11 +653,19 @@ fn hyphen_allowed(it: Item, n: Node, sp: &Spacing, widths: &[f64], items: &[Item
|
||||
}
|
||||
|
||||
/// Fitness class and cumulative penalty for a candidate line break.
|
||||
fn break_demerits(n: Node, r: f64, pp: f64, flagged: bool, priority: u8) -> (usize, f64) {
|
||||
let preference = match priority {
|
||||
1 if r > 0.0 => 4.0,
|
||||
2 if r < 0.0 => 4.0,
|
||||
_ => 1.0,
|
||||
fn break_demerits(n: Node, r: f64, pp: f64, flagged: bool, priority: u8, cjk: bool) -> (usize, f64) {
|
||||
// 禁則 priority (JIS X 4051): push-in-first rates breaks whose line would have to be
|
||||
// stretched (r > 0: the next character is pushed out) worse than ones it can reach by
|
||||
// compressing (追い込み); push-out-first the other way. Adjustment-amount mode and a
|
||||
// paragraph without CJK text rate every candidate by its adjustment alone.
|
||||
let preference = if !cjk {
|
||||
1.0
|
||||
} else {
|
||||
match priority {
|
||||
1 if r > 0.0 => 4.0,
|
||||
2 if r < 0.0 => 4.0,
|
||||
_ => 1.0,
|
||||
}
|
||||
};
|
||||
let bad = preference * 100.0 * r.abs().powi(3);
|
||||
let lp = 10.0 + bad;
|
||||
@@ -770,7 +793,7 @@ fn kp_pass(input: PassInput<'_>) -> Option<Vec<Break>> {
|
||||
if flagged && !hyphen_allowed(it, n, sp, &sw, items, target) {
|
||||
continue;
|
||||
}
|
||||
let (fit, total) = break_demerits(n, r, pp, flagged, sp.kinsoku_priority);
|
||||
let (fit, total) = break_demerits(n, r, pp, flagged, sp.kinsoku_priority, sp.kinsoku_cjk);
|
||||
let hs = if flagged { (n.hyphens as usize + 1).min(states - 1) } else { 0 };
|
||||
let slot = &mut best[fit * states + hs];
|
||||
if slot.is_none_or(|(bd, _)| total < bd) {
|
||||
@@ -925,7 +948,7 @@ pub fn greedy(
|
||||
while start < n {
|
||||
let w = width(line).max(1.0);
|
||||
let mut x = -hang_left(&glyphs[start], sp) + glyphs[start].moji.start;
|
||||
let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, sp.kinsoku_priority != 3)[1];
|
||||
let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, !sp.push_out_only())[1];
|
||||
let mut last_natural: Option<(usize, bool)> = None;
|
||||
let mut last_ok: Option<(usize, bool)> = None; // (break position = end glyph, hyphen)
|
||||
let mut last_space: Option<(usize, f64)> = None; // (break position, line width there)
|
||||
@@ -952,9 +975,10 @@ pub fn greedy(
|
||||
}
|
||||
let hang_r = right_hang(g, sp);
|
||||
let adv = if g.ch == '\t' { tab(line, x, i) } else { g.adv };
|
||||
let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3)[1];
|
||||
let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only())[1];
|
||||
let available = shrink + sp.box_elastic(g).1.iter().sum::<f64>() + end_shrink;
|
||||
if sp.kinsoku_priority == 2
|
||||
if sp.kinsoku_cjk
|
||||
&& sp.kinsoku_priority == 2
|
||||
&& x + adv - hang_r > w + FIT_EPS
|
||||
&& let Some((end, hyphen)) = last_natural
|
||||
{
|
||||
|
||||
@@ -1000,6 +1000,13 @@ pub struct FrameSpec {
|
||||
}
|
||||
|
||||
impl FrameSpec {
|
||||
/// The baseline grid when the text area can be counted in its steps: a step so small, or a
|
||||
/// first line so far off, that the count is more than an f64 holds is no grid (as for the lines).
|
||||
fn countable_grid(&self) -> Option<(f64, f64)> {
|
||||
self.grid
|
||||
.filter(|&(g_start, inc)| inc > 0.0 && inc.is_finite() && [self.area.y0, self.area.y1].iter().all(|y| ((y - g_start) / inc).is_finite()))
|
||||
}
|
||||
|
||||
pub fn columns(&self) -> Vec<Rect> {
|
||||
let a = self.area;
|
||||
// Primary frames inherit the document limit (216), beyond the interactive frame editor's 40.
|
||||
@@ -1633,6 +1640,8 @@ struct NestedLineStyleInput<'a, 'b, 'font> {
|
||||
range: Range<usize>,
|
||||
props: &'a designcraft_doc::ParaProps,
|
||||
para_chars: &'a designcraft_doc::CharProps,
|
||||
/// The paragraph has CJK text, so its 禁則 priority applies.
|
||||
cjk: bool,
|
||||
drop_end: usize,
|
||||
base_leading: f64,
|
||||
base_cap: f64,
|
||||
@@ -1658,6 +1667,7 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) {
|
||||
range: prange,
|
||||
props: pp,
|
||||
para_chars: base_chars,
|
||||
cjk,
|
||||
drop_end,
|
||||
base_leading,
|
||||
base_cap,
|
||||
@@ -1680,7 +1690,7 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) {
|
||||
let cols_here = &cols[cur.fi];
|
||||
let col = span_rect(cols_here, cols_here[cur.col.min(cols_here.len() - 1)], pp.span_columns);
|
||||
let col = SplitCfg::of(pp).map_or(col, |c| c.sub_rect(col, 0));
|
||||
let spacing = spacing_for(pp, base_chars.size, story);
|
||||
let spacing = spacing_for(pp, base_chars.size, story, cjk);
|
||||
let mut lines: Vec<(std::ops::Range<usize>, String)> = Vec::new();
|
||||
for _ in 0..3 {
|
||||
// The same drop cap, spacing, hyphenation and breaker as the layout below.
|
||||
@@ -2788,6 +2798,10 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
|
||||
},
|
||||
&mut table,
|
||||
);
|
||||
// The paragraph's script decides whether its 禁則 priority applies. Classify the shaped
|
||||
// glyphs before split_drop_cap removes the drop cap and prepend_label adds the list
|
||||
// label: a CJK drop cap is part of the paragraph, a generated label is not.
|
||||
let cjk = paragraph_is_cjk(&sp.glyphs);
|
||||
// An empty paragraph has no glyphs of its own, so its only addressable character is its
|
||||
// hidden paragraph mark (the `\n` just past `prange.end`). A leading/size override applied
|
||||
// there (e.g. selecting the pilcrow to adjust line height) still needs to set the line's
|
||||
@@ -2808,7 +2822,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
|
||||
let face = db.face(&base_chars.font_family, &base_chars.font_style);
|
||||
face.cap_height * base_chars.size / face.upem * base_chars.v_scale
|
||||
};
|
||||
let drop_grid = cur_frame.and_then(|f| f.grid).filter(|_| pp.grid_align == GridAlign::AllLines).map(|g| g.1);
|
||||
let drop_grid = cur_frame.and_then(FrameSpec::countable_grid).filter(|_| pp.grid_align == GridAlign::AllLines).map(|g| g.1);
|
||||
// Align Left Edge (left-to-right paragraphs).
|
||||
let drop_align = pp.drop_cap_align_left && pp.direction == designcraft_doc::TextDirection::LeftToRight;
|
||||
// Tab stops for the drop cap, with the start-side indent (the right one, right to left).
|
||||
@@ -2820,6 +2834,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
|
||||
range: prange.clone(),
|
||||
props: pp,
|
||||
para_chars: base_chars,
|
||||
cjk,
|
||||
drop_end,
|
||||
base_leading,
|
||||
base_cap,
|
||||
@@ -2934,7 +2949,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
|
||||
let mut hyph_after = hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars));
|
||||
suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens);
|
||||
let base_size = base_chars.size;
|
||||
let spacing = spacing_for(pp, base_size, story);
|
||||
let spacing = spacing_for(pp, base_size, story, cjk);
|
||||
// An empty paragraph takes its height from its paragraph mark's character format.
|
||||
let mark_chars = if glyphs.is_empty() { doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) } else { base_chars.clone() };
|
||||
let mark_leading = match mark_chars.leading {
|
||||
@@ -3935,8 +3950,9 @@ fn optical_for(pp: &ParaProps, story: &Story) -> (bool, Option<f64>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breaker parameters from the paragraph's settings.
|
||||
fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story) -> Spacing {
|
||||
/// Breaker parameters from the paragraph's settings; `cjk` says the paragraph has CJK text (so
|
||||
/// its 禁則 priority applies).
|
||||
fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story, cjk: bool) -> Spacing {
|
||||
let (optical, optical_size) = optical_for(pp, story);
|
||||
Spacing {
|
||||
justify: pp.align.is_justified(),
|
||||
@@ -3958,15 +3974,51 @@ fn spacing_for(pp: &ParaProps, base_size: f64, story: &Story) -> Spacing {
|
||||
optical,
|
||||
optical_size,
|
||||
korean_char_breaks: pp.korean_char_breaks,
|
||||
kinsoku_cjk: cjk,
|
||||
// JIS X 4051 禁則処理: the empty value is InDesign's default and the UI's "Push In First",
|
||||
// and 調整量優先 (adjustment amount) is the breaker's minimum-adjustment mode 0.
|
||||
kinsoku_priority: match pp.kinsoku_type.as_str() {
|
||||
"KinsokuPushInFirst" => 1,
|
||||
"" | "KinsokuPushInFirst" => 1,
|
||||
"KinsokuPushOutFirst" => 2,
|
||||
"KinsokuPushOutOnly" => 3,
|
||||
"KinsokuPrioritizeAdjustmentAmount" => 0,
|
||||
_ => 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the paragraph's own shaped glyphs contain CJK text, the gate for its 禁則 priority.
|
||||
/// Called before `split_drop_cap` and `prepend_label`, so a drop cap counts and generated list
|
||||
/// and story labels do not. A text variable or page number keeps its marker in [`Glyph::ch`], so
|
||||
/// its replacement text is what the paragraph shows; inspect that too.
|
||||
fn paragraph_is_cjk(glyphs: &[Glyph]) -> bool {
|
||||
glyphs.iter().any(|g| is_cjk_char(g.ch) || g.generated_text.as_deref().is_some_and(|text| text.chars().any(is_cjk_char)))
|
||||
}
|
||||
|
||||
/// Is `c` CJK text (the scripts the 禁則 line-start/line-end rules are about): ideographs, kana,
|
||||
/// CJK punctuation and full/half-width forms, bopomofo, Hangul.
|
||||
fn is_cjk_char(c: char) -> bool {
|
||||
// Hangul comes from the breaker's classification (Jamo including Extended-A/B, syllables),
|
||||
// so the two sets agree. Bopomofo is 0x3100..=0x312F; 0x3130..=0x318F is Hangul.
|
||||
breaker::is_hangul(c)
|
||||
|| matches!(
|
||||
c as u32,
|
||||
0x2E80..=0x2FFF
|
||||
| 0x3000..=0x30FF
|
||||
| 0x3100..=0x312F
|
||||
| 0x3190..=0x33FF
|
||||
| 0x3400..=0x4DBF
|
||||
| 0x4E00..=0x9FFF
|
||||
| 0xA000..=0xA4CF
|
||||
| 0xF900..=0xFAFF
|
||||
| 0xFE30..=0xFE4F
|
||||
| 0xFF00..=0xFFEF
|
||||
// Extension B and later (U+20000..): the same range as the breaker's Han check,
|
||||
// so the kinsoku settings apply to a paragraph of supplementary-plane text alone.
|
||||
| 0x20000..=0x3FFFF
|
||||
)
|
||||
}
|
||||
|
||||
/// Desired word spacing, letter spacing and glyph scaling apply to every line (any alignment).
|
||||
fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) {
|
||||
for i in 0..glyphs.len() {
|
||||
@@ -5219,7 +5271,7 @@ fn layout_line(
|
||||
let mut offset = 0.0;
|
||||
// Kashidas: in justified Arabic, the joins of words take the extra length first.
|
||||
let kashidas = if justify_this { allocate_kashidas(&line, &mut add, pp, seg, &mut extra) } else { Vec::new() };
|
||||
if (justify_this || squeeze_last) && (extra >= 0.0 || sp.kinsoku_priority != 3) {
|
||||
if (justify_this || squeeze_last) && (extra >= 0.0 || !sp.push_out_only()) {
|
||||
extra = mojikumi::distribute(line.get_mut(seg..).unwrap_or_default(), extra, add.get_mut(seg..).unwrap_or_default());
|
||||
}
|
||||
if (justify_this || squeeze_last) && !spaces.is_empty() {
|
||||
@@ -6253,7 +6305,7 @@ fn vertical_justify(
|
||||
}
|
||||
};
|
||||
let center = f.opts.vertical_justification == VerticalJustification::Center;
|
||||
let step = f.grid.map(|(_, inc)| inc).filter(|inc| *inc > 0.0 && inc.is_finite()).filter(|_| match f.opts.vertical_justification {
|
||||
let step = f.countable_grid().map(|(_, inc)| inc).filter(|_| match f.opts.vertical_justification {
|
||||
VerticalJustification::Justify => idx.iter().zip(&rows).any(|(&i, &k)| k == n && on_grid(i)),
|
||||
_ => idx.iter().any(|&i| on_grid(i)),
|
||||
});
|
||||
|
||||
@@ -34,6 +34,10 @@ pub struct PlacedCell {
|
||||
pub repeated: bool,
|
||||
/// Graphic cell content (drawn at `clip`'s top left, clipped to it).
|
||||
pub graphic: Option<designcraft_doc::Graphic>,
|
||||
/// The cell's diagonal lines (Cell Options › Diagonal Lines), corner to corner of `rect`.
|
||||
pub diagonals: Vec<StrokeSeg>,
|
||||
/// Whether the diagonals are drawn over the cell's contents (otherwise under them).
|
||||
pub diagonals_in_front: bool,
|
||||
}
|
||||
|
||||
/// One cell edge (or the table border) to stroke.
|
||||
@@ -91,6 +95,10 @@ impl TableFrag {
|
||||
c.rect = c.rect + v;
|
||||
c.clip = c.clip + v;
|
||||
c.origin += v;
|
||||
for s in &mut c.diagonals {
|
||||
s.a += v;
|
||||
s.b += v;
|
||||
}
|
||||
}
|
||||
for r in &mut self.rows {
|
||||
r.1 += dy;
|
||||
@@ -474,6 +482,14 @@ fn emit(
|
||||
overset,
|
||||
repeated,
|
||||
graphic: cell.graphic.clone(),
|
||||
diagonals: cell
|
||||
.diagonal
|
||||
.segments(rect)
|
||||
.into_iter()
|
||||
.filter(|_| cell.diagonal.stroke.is_visible())
|
||||
.map(|(a, b)| StrokeSeg { a, b, stroke: cell.diagonal.stroke.clone() })
|
||||
.collect(),
|
||||
diagonals_in_front: cell.diagonal.in_front,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,42 @@ fn explicit_cell_edges_override_table_border_without_changing_native_defaults()
|
||||
assert_eq!(right.stroke.weight, 2.0, "unoverridden right edge keeps the table border");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_cross_the_placed_cell_corner_to_corner() {
|
||||
let mut table = Table::new(77, 2, 2, 0, 0, 100.0);
|
||||
let stroke = CellStroke { weight: 3.0, ..Default::default() };
|
||||
let cell = table.cell_mut(0, 0).unwrap();
|
||||
cell.col_span = 2;
|
||||
cell.diagonal = designcraft_doc::CellDiagonal { lines: designcraft_doc::DiagonalLines::Crossed, stroke: stroke.clone(), in_front: false };
|
||||
table.cell_mut(1, 0).unwrap().diagonal.lines = designcraft_doc::DiagonalLines::TopLeft;
|
||||
table.cell_mut(1, 0).unwrap().diagonal.stroke.color = designcraft_color::swatch::NONE.into();
|
||||
let composed = compose_table(table);
|
||||
let fragment = &composed.frames[0].tables[0];
|
||||
let merged = fragment.cells.iter().find(|c| (c.row, c.col) == (0, 0)).unwrap();
|
||||
let r = merged.rect;
|
||||
let ends: Vec<_> = merged.diagonals.iter().map(|s| (s.a, s.b)).collect();
|
||||
assert_eq!(ends, [(Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)), (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1))], "across the merged cell");
|
||||
assert!(merged.diagonals.iter().all(|s| s.stroke == stroke) && !merged.diagonals_in_front);
|
||||
assert!(fragment.cells.iter().filter(|c| c.row == 1).all(|c| c.diagonals.is_empty()), "none, or an invisible stroke, draws nothing");
|
||||
assert!(fragment.strokes.iter().all(|s| s.a.x == s.b.x || s.a.y == s.b.y), "the edges stay edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_move_with_their_cell_in_a_bottom_justified_frame() {
|
||||
let mut table = Table::new(77, 1, 1, 0, 0, 100.0);
|
||||
table.cell_mut(0, 0).unwrap().diagonal.lines = designcraft_doc::DiagonalLines::TopLeft;
|
||||
let mut doc = Document::new(&NewDocument::default());
|
||||
let layer = doc.default_layer();
|
||||
let (fid, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 300.0), layer, "", ParaFormat::default()).unwrap();
|
||||
doc.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Bottom;
|
||||
doc.story_mut(sid).unwrap().insert_table(0, table);
|
||||
let composed = crate::compose_story(&doc, sid, &ComposeOptions::default());
|
||||
let cell = &composed.frames[0].tables[0].cells[0];
|
||||
assert!(cell.rect.y0 > 100.0, "the table sits at the bottom: {:?}", cell.rect);
|
||||
let s = &cell.diagonals[0];
|
||||
assert_eq!((s.a, s.b), (Point::new(cell.rect.x0, cell.rect.y0), Point::new(cell.rect.x1, cell.rect.y1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_cell_keeps_explicit_border_suppression() {
|
||||
let mut table = Table::new(77, 2, 2, 0, 0, 100.0);
|
||||
|
||||
@@ -3000,6 +3000,19 @@ fn vertical_justification_with_an_extreme_grid_increment_stays_finite() {
|
||||
assert!((b - natural).abs() < 1e-6, "Top, grid away from the line: baseline {b}, natural {natural}");
|
||||
}
|
||||
}
|
||||
|
||||
// A grid whose first line is too far off to count the text area in its 0.7 pt steps: Bottom
|
||||
// takes the room as it does without a grid.
|
||||
let mut area = Rect::ZERO;
|
||||
let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| {
|
||||
let spec = frame_specs(d, sid).remove(0);
|
||||
area = spec.area;
|
||||
let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options;
|
||||
opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(-1.7e308, 0.7));
|
||||
opts.vertical_justification = Bottom;
|
||||
});
|
||||
let b = lines[0].baseline;
|
||||
assert!((b - area.y1).abs() < 1e-6, "Bottom with a far-off grid: baseline {b}, text area {area:?}");
|
||||
}
|
||||
|
||||
/// In a shaped frame that narrows and widens again, Align to Baseline Grid takes the grid step
|
||||
@@ -5195,6 +5208,22 @@ fn drop_cap_on_a_baseline_grid_reaches_down_by_grid_steps() {
|
||||
assert!((lines[2].baseline - cap_of(dc) - (lines[0].baseline - cap_of(body))).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// A grid the lines can't count in steps (its first line too far off for a 0.7 pt step) is no grid
|
||||
/// for the drop cap either: it reaches down to line 3 at the 12 pt leading the lines are set at.
|
||||
#[test]
|
||||
fn drop_cap_skips_a_grid_the_lines_skip() {
|
||||
let (d, sid, _) = drop_doc(LOREM, ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), ..drop_cap(3, 1) });
|
||||
let mut specs = frame_specs(&d, sid);
|
||||
specs[0].grid = Some((-1.7e308, 0.7));
|
||||
let cs = compose(&d, d.story(sid).unwrap(), &specs, &ComposeOptions::default());
|
||||
let lines = all_lines(&cs);
|
||||
assert!((lines[2].baseline - lines[0].baseline - 24.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[2].baseline);
|
||||
let dc = &lines[0].glyphs[0];
|
||||
assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "drop cap baseline {} below line 1", dc.y);
|
||||
let b = lines[0].drop_cap.unwrap();
|
||||
assert!((b.baseline - lines[2].baseline).abs() < 1e-6, "{}", b.baseline);
|
||||
}
|
||||
|
||||
/// A line with a larger auto leading doesn't move the drop cap: it reaches down `lines − 1`
|
||||
/// leadings of the text after it, not to where line N is set.
|
||||
#[test]
|
||||
@@ -6976,6 +7005,224 @@ fn mojikumi_kinsoku_push_in_and_push_out_select_different_legal_breaks() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph that can compress: the Mojikumi table gives its ideographs shrinkable space, so
|
||||
/// a line ending before a 禁則 boundary can be pulled in (追い込み) or pushed out (追い出し).
|
||||
fn kinsoku_push_pull_doc(kind: Option<&str>) -> (Document, StoryId) {
|
||||
kinsoku_push_pull_doc_text("甲乙丙丁戊己庚辛", kind)
|
||||
}
|
||||
|
||||
/// Same paragraph with a different body: used for the supplementary-plane ideographs, whose
|
||||
/// CJK classification must match the breaker's Han set.
|
||||
fn kinsoku_push_pull_doc_text(text: &str, kind: Option<&str>) -> (Document, StoryId) {
|
||||
use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
|
||||
let (mut d, sid, _) = doc_with(
|
||||
text,
|
||||
Rect::new(0.0, 0.0, 45.0, 300.0),
|
||||
ParaAttrs {
|
||||
composer: Some(Composer::SingleLine),
|
||||
mojikumi: Some("MojikumiTable/Compress".into()),
|
||||
kinsoku_type: kind.map(str::to_string),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
|
||||
name: "Compress".into(),
|
||||
based_on: "SimpChineseDefault".into(),
|
||||
overrides: vec![MojikumiAki {
|
||||
target_class: 12,
|
||||
side_class: 12,
|
||||
after: true,
|
||||
minimum: 0.0,
|
||||
desired: 1.0,
|
||||
maximum: 2.0,
|
||||
priority: 1,
|
||||
..Default::default()
|
||||
}],
|
||||
});
|
||||
(d, sid)
|
||||
}
|
||||
|
||||
fn first_line_end(cs: &ComposedStory) -> (usize, f64) {
|
||||
let line = all_lines(cs)[0];
|
||||
(line.range.end, line.end_x)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_kinsoku_type_composes_as_push_in_first() {
|
||||
// The empty value is InDesign's default (and what the UI's "Push In First" stores): it must
|
||||
// behave as push-in-first, not as the minimum-adjustment mode.
|
||||
let (d, sid) = kinsoku_push_pull_doc(None);
|
||||
let default = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushInFirst"));
|
||||
let push_in = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushOutFirst"));
|
||||
let push_out = compose_story(&d, sid, &ComposeOptions::default());
|
||||
assert_eq!(first_line_end(&default).0, first_line_end(&push_in).0);
|
||||
assert!(first_line_end(&default).0 > first_line_end(&push_out).0, "{:?} vs {:?}", first_line_end(&default), first_line_end(&push_out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_out_only_leaves_the_line_end_uncompressed() {
|
||||
// Push-out-only turns the 追い込み compression off: the line cannot be squeezed to reach a
|
||||
// break, so it ends earlier (and never past the measure).
|
||||
let (d, sid) = kinsoku_push_pull_doc(None);
|
||||
let push_in = compose_story(&d, sid, &ComposeOptions::default());
|
||||
let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushOutOnly"));
|
||||
let push_out_only = compose_story(&d, sid, &ComposeOptions::default());
|
||||
assert!(first_line_end(&push_out_only).0 <= first_line_end(&push_in).0);
|
||||
for cs in [&push_in, &push_out_only] {
|
||||
for line in all_lines(cs) {
|
||||
assert!(line.end_x <= line.x1 + 0.01, "line end {} past the measure {}", line.end_x, line.x1);
|
||||
}
|
||||
}
|
||||
// Push-out-only's first line is not compressed to the measure: it ends short of it.
|
||||
let (_, short) = first_line_end(&push_out_only);
|
||||
let line = all_lines(&push_out_only)[0];
|
||||
assert!(line.x1 - short > 0.5, "no compression: end {short} vs measure {}", line.x1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supplementary_ideograph_paragraph_keeps_the_kinsoku_gate() {
|
||||
// Extension B 以降の漢字 (U+20000..) は breaker では Han として扱われる。段落全体の CJK 判定
|
||||
// (is_cjk_char) がそこを落とすと、補助面だけの段落で禁則の指定が効かなくなる。
|
||||
// 補助面だけの本文でも、追い込みと追い出しで行末が変わる (指定が効いている) こと。
|
||||
let first_end = |text: &str, kind: Option<&str>| {
|
||||
let (d, sid) = kinsoku_push_pull_doc_text(text, kind);
|
||||
first_line_end(&compose_story(&d, sid, &ComposeOptions::default())).0
|
||||
};
|
||||
let bmp = "甲乙丙丁戊己庚辛";
|
||||
let sup = "\u{20000}\u{20001}\u{20002}\u{20003}\u{20004}\u{20005}\u{20006}\u{20007}";
|
||||
// 対照: BMP の漢字だけの段落では、追い込みと追い出しで行末が変わる
|
||||
assert_ne!(first_end(bmp, None), first_end(bmp, Some("KinsokuPushOutOnly")), "BMP の対照で禁則の指定が効いていない");
|
||||
// 補助面だけの段落でも同じように効く (判定から漏れると、どちらも同じ行末になる)
|
||||
assert_ne!(first_end(sup, None), first_end(sup, Some("KinsokuPushOutOnly")), "補助面だけの段落で禁則の指定が効いていない");
|
||||
// 判定そのもの (Extension B の最初と最後、Ext G の終わり)
|
||||
assert!(is_cjk_char('\u{20000}'));
|
||||
assert!(is_cjk_char('\u{2A6DF}'));
|
||||
assert!(is_cjk_char('\u{3FFFF}'));
|
||||
assert!(!is_cjk_char('A'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hangul_jamo_extended_blocks_count_as_cjk() {
|
||||
// `is_cjk_char` takes Hangul from the breaker's classification, so the syllables and the
|
||||
// Jamo Extended-A/B blocks count as well: a Hangul-only paragraph keeps its 禁則 priority.
|
||||
for c in ['\u{A960}', '\u{A97F}', '\u{D7B0}', '\u{D7FF}'] {
|
||||
assert!(is_cjk_char(c), "U+{:04X} is Hangul", c as u32);
|
||||
}
|
||||
assert!(is_cjk_char('\u{3105}'), "bopomofo is still CJK");
|
||||
}
|
||||
|
||||
/// Shape `text` as a one-paragraph story with the default font and styles: the glyph list the
|
||||
/// composition classifies before `split_drop_cap` and `prepend_label`.
|
||||
fn shape_for_script_test(text: &str) -> Vec<Glyph> {
|
||||
shape_for_script_test_with(text, &SubstCtx::default())
|
||||
}
|
||||
|
||||
/// Same, with text variables resolved through `sub`.
|
||||
fn shape_for_script_test_with(text: &str, sub: &SubstCtx) -> Vec<Glyph> {
|
||||
let db = designcraft_fonts::FontDb::global().scoped(0);
|
||||
let mut styles = Vec::new();
|
||||
let mut missing = std::collections::HashMap::new();
|
||||
let mut table = shape::StyleTable { styles: &mut styles, missing: &mut missing };
|
||||
let mut story = Story::new(StoryId(0));
|
||||
story.insert(0, text);
|
||||
let doc_styles = designcraft_doc::Styles::default();
|
||||
shape::shape_para(
|
||||
shape::ShapeInput {
|
||||
db: &db,
|
||||
styles: &doc_styles,
|
||||
story: &story,
|
||||
range: 0..text.len(),
|
||||
para_chars: &designcraft_doc::CharProps::default(),
|
||||
auto_leading: shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true },
|
||||
sub,
|
||||
nested: &[],
|
||||
grep: &[],
|
||||
lines: &[],
|
||||
drop_cap: (0, ""),
|
||||
},
|
||||
&mut table,
|
||||
)
|
||||
.glyphs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_script_counts_a_drop_cap_but_not_a_generated_label() {
|
||||
// The 禁則 gate reads the paragraph's own shaped glyphs. The drop cap has not been split off
|
||||
// yet, so a CJK one still makes the paragraph CJK.
|
||||
assert!(paragraph_is_cjk(&shape_for_script_test("漢abc")));
|
||||
// A generated list label is prepended after the gate, so it is not part of the paragraph.
|
||||
let mut glyphs = shape_for_script_test("abc");
|
||||
assert!(!paragraph_is_cjk(&glyphs));
|
||||
let db = designcraft_fonts::FontDb::global().scoped(0);
|
||||
let mut styles = Vec::new();
|
||||
let mut missing = std::collections::HashMap::new();
|
||||
let mut table = shape::StyleTable { styles: &mut styles, missing: &mut missing };
|
||||
let n = prepend_label(
|
||||
&db,
|
||||
&mut glyphs,
|
||||
"第1章",
|
||||
0,
|
||||
&designcraft_doc::CharProps::default(),
|
||||
shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true },
|
||||
&mut table,
|
||||
);
|
||||
assert!(n > 0);
|
||||
// The label's glyphs are CJK, so a gate computed after prepend_label would flip the answer.
|
||||
assert!(glyphs.iter().take(n).any(|g| is_cjk_char(g.ch)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_script_reads_a_text_variable_replacement() {
|
||||
// A text variable's glyphs keep the source marker in `ch`; the paragraph shows the replacement,
|
||||
// so a CJK replacement makes it CJK text even though no source character is.
|
||||
let marker = designcraft_doc::vars::var_char(0).expect("variable 0");
|
||||
let text = format!("{marker}abc");
|
||||
let sub = SubstCtx { vars: Arc::new(vec!["漢字".into()]), ..Default::default() };
|
||||
let glyphs = shape_for_script_test_with(&text, &sub);
|
||||
assert!(!glyphs.iter().any(|g| is_cjk_char(g.ch)), "the source is only the marker and Latin text");
|
||||
assert!(glyphs.iter().any(|g| g.generated_text.as_deref().is_some_and(|t| t.chars().any(is_cjk_char))));
|
||||
assert!(paragraph_is_cjk(&glyphs), "the CJK replacement is the paragraph's text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinsoku_priority_modes_map_to_breaker_policies() {
|
||||
let mut pp = ParaProps::default();
|
||||
let story = designcraft_doc::Story::new(designcraft_doc::StoryId::default());
|
||||
for (kind, priority) in [
|
||||
("", 1u8),
|
||||
("KinsokuPushInFirst", 1),
|
||||
("KinsokuPushOutFirst", 2),
|
||||
("KinsokuPushOutOnly", 3),
|
||||
("KinsokuPrioritizeAdjustmentAmount", 0),
|
||||
("KinsokuSomethingElse", 0),
|
||||
] {
|
||||
pp.kinsoku_type = kind.to_string();
|
||||
let sp = spacing_for(&pp, 12.0, &story, true);
|
||||
assert_eq!(sp.kinsoku_priority, priority, "{kind}");
|
||||
assert!(sp.kinsoku_cjk, "{kind}");
|
||||
assert!(!spacing_for(&pp, 12.0, &story, false).kinsoku_cjk, "{kind}: Latin text is not biased");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latin_paragraphs_are_not_biased_by_the_kinsoku_priority() {
|
||||
// A justified Latin paragraph composes the same with push-in-first, push-out-first and
|
||||
// minimum adjustment: the policy is about CJK 禁則, and a Latin paragraph has none.
|
||||
let compose_with = |kind: &str| {
|
||||
let (mut d, sid, _) =
|
||||
doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 500.0), ParaAttrs { align: Some(Align::FullyJustified), ..Default::default() });
|
||||
d.story_mut(sid).unwrap().paras[0].para.kinsoku_type = Some(kind.to_string());
|
||||
compose_story(&d, sid, &ComposeOptions::default())
|
||||
};
|
||||
let ends = |cs: &ComposedStory| all_lines(cs).iter().map(|l| l.range.end).collect::<Vec<_>>();
|
||||
let push_in = ends(&compose_with(""));
|
||||
assert_eq!(ends(&compose_with("KinsokuPushInFirst")), push_in);
|
||||
assert_eq!(ends(&compose_with("KinsokuPushOutFirst")), push_in);
|
||||
assert_eq!(ends(&compose_with("KinsokuPrioritizeAdjustmentAmount")), push_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mojikumi_priority_and_elastic_line_start_are_used_in_placement() {
|
||||
use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
|
||||
|
||||
@@ -113,7 +113,10 @@ attr_set! {
|
||||
kinsoku: Option<crate::cjk::Kinsoku> = None => "deserialize_explicit_value",
|
||||
/// Preserved spacing-table reference; compatibility audit reports unsupported composition.
|
||||
mojikumi: String = String::new(),
|
||||
/// Preserved priority policy; the current breaker does not implement these priorities.
|
||||
/// JIS X 4051 禁則処理 type, applied by both composers to CJK text: empty (the default)
|
||||
/// and `KinsokuPushInFirst` compose as push-in-first, `KinsokuPushOutFirst`,
|
||||
/// `KinsokuPushOutOnly` and `KinsokuPrioritizeAdjustmentAmount` (minimum adjustment) as
|
||||
/// their names say.
|
||||
kinsoku_type: String = String::new(),
|
||||
kinsoku_hang: crate::cjk::KinsokuHang = crate::cjk::KinsokuHang::None,
|
||||
bunri_kinshi: bool = false,
|
||||
|
||||
@@ -176,6 +176,7 @@ impl Document {
|
||||
locked: false,
|
||||
printable: true,
|
||||
show_guides: true,
|
||||
lock_guides: false,
|
||||
suppress_wrap_when_hidden: false,
|
||||
});
|
||||
// A-Parent.
|
||||
|
||||
@@ -577,6 +577,9 @@ pub struct Layer {
|
||||
pub printable: bool,
|
||||
#[serde(default = "yes")]
|
||||
pub show_guides: bool,
|
||||
/// Lock Guides: the layer's ruler guides can't be moved or deleted.
|
||||
#[serde(default)]
|
||||
pub lock_guides: bool,
|
||||
#[serde(default)]
|
||||
pub suppress_wrap_when_hidden: bool,
|
||||
}
|
||||
@@ -955,6 +958,15 @@ pub enum HyperlinkDest {
|
||||
Anchor(u64),
|
||||
}
|
||||
|
||||
/// Whether a URL may be used as an external link. Only web and mail schemes are allowed: a
|
||||
/// `file:`, `javascript:` or UNC link can make a recipient's PDF viewer contact an attacker.
|
||||
pub fn is_safe_link_url(url: &str) -> bool {
|
||||
let Some((scheme, rest)) = url.split_once(':') else { return false };
|
||||
!rest.is_empty()
|
||||
&& !url.chars().any(|c| c.is_control() || c.is_whitespace())
|
||||
&& matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https" | "mailto")
|
||||
}
|
||||
|
||||
impl HyperlinkDest {
|
||||
/// The name a hyperlink is given when none is supplied.
|
||||
pub fn label(&self) -> String {
|
||||
|
||||
@@ -153,9 +153,9 @@ impl Guide {
|
||||
pub fn visible_in(&self, d: &crate::Document) -> bool {
|
||||
self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| l.visible && l.show_guides))
|
||||
}
|
||||
/// Can be dragged: neither it nor its layer is locked.
|
||||
/// Can be dragged: neither it nor its layer is locked, nor are the layer's guides.
|
||||
pub fn editable_in(&self, d: &crate::Document) -> bool {
|
||||
!self.locked && self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| !l.locked && l.visible && l.show_guides))
|
||||
!self.locked && self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| !l.locked && !l.lock_guides && l.visible && l.show_guides))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -174,6 +174,7 @@ impl Names<'_> {
|
||||
for s in &mut c.strokes {
|
||||
self.cell_stroke(s);
|
||||
}
|
||||
self.cell_stroke(&mut c.diagonal.stroke);
|
||||
}
|
||||
}
|
||||
/// One story's own text, objects and tables (cell and note text are visited separately).
|
||||
@@ -239,8 +240,8 @@ impl Document {
|
||||
/// Point every reference to swatch `from` at `to`: tints based on it, colour groups, inks,
|
||||
/// styles, page items (fills, strokes, gaps, effects, column rules, the swatch an image is
|
||||
/// coloured with), text, kenten and ruby colours, rules, shading, borders and border gaps,
|
||||
/// tables (with stroke gaps and cell images), footnotes, gradient stops, endnotes and the
|
||||
/// footnote rule. The swatch itself is renamed by the caller.
|
||||
/// tables (with stroke gaps, diagonal lines and cell images), footnotes, gradient stops,
|
||||
/// endnotes and the footnote rule. The swatch itself is renamed by the caller.
|
||||
pub fn rename_swatch_refs(&mut self, from: &str, to: &str) {
|
||||
if from == to {
|
||||
return;
|
||||
|
||||
+24
-1
@@ -22,7 +22,7 @@ mod grid;
|
||||
mod merge;
|
||||
mod story;
|
||||
|
||||
pub use cell::{AltFills, AltStrokes, Cell, CellStroke, Column, Row, RowHeightMode, RowKind, TableOptions};
|
||||
pub use cell::{AltFills, AltStrokes, Cell, CellDiagonal, CellStroke, Column, DiagonalLines, Row, RowHeightMode, RowKind, TableOptions};
|
||||
pub use grid::CellRange;
|
||||
|
||||
/// Most rows a table holds, as InDesign allows.
|
||||
@@ -366,4 +366,27 @@ mod tests {
|
||||
assert_eq!(back, explicit);
|
||||
assert_eq!(back.blank_like().border_overrides, explicit.border_overrides);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_diagonal_lines_roundtrip_and_run_corner_to_corner() {
|
||||
let plain = serde_json::to_value(Cell::default()).unwrap();
|
||||
assert!(plain.get("diagonal").is_none(), "a cell without diagonal lines saves none");
|
||||
let diagonal = CellDiagonal { lines: DiagonalLines::Crossed, stroke: CellStroke { weight: 2.0, ..Default::default() }, in_front: false };
|
||||
let cell = Cell { diagonal: diagonal.clone(), ..Cell::default() };
|
||||
let back: Cell = serde_json::from_str(&serde_json::to_string(&cell).unwrap()).unwrap();
|
||||
assert_eq!(back.diagonal, diagonal);
|
||||
assert_eq!(back.blank_like().diagonal, diagonal, "new cells take the cell's formatting");
|
||||
let r = designcraft_geom::Rect::new(10.0, 20.0, 110.0, 70.0);
|
||||
let p = designcraft_geom::Point::new;
|
||||
let down = (p(10.0, 20.0), p(110.0, 70.0));
|
||||
let up = (p(110.0, 20.0), p(10.0, 70.0));
|
||||
for (lines, want) in [
|
||||
(DiagonalLines::None, vec![]),
|
||||
(DiagonalLines::TopLeft, vec![down]),
|
||||
(DiagonalLines::TopRight, vec![up]),
|
||||
(DiagonalLines::Crossed, vec![down, up]),
|
||||
] {
|
||||
assert_eq!(CellDiagonal { lines, ..Default::default() }.segments(r), want, "{lines:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +74,55 @@ impl Default for CellStroke {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cell Options › Diagonal Lines: the diagonals drawn across a cell.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DiagonalLines {
|
||||
#[default]
|
||||
None,
|
||||
/// From the top left corner to the bottom right corner.
|
||||
TopLeft,
|
||||
/// From the top right corner to the bottom left corner.
|
||||
TopRight,
|
||||
/// Both diagonals.
|
||||
Crossed,
|
||||
}
|
||||
|
||||
/// A cell's diagonal lines, their stroke, and whether they are drawn in front of the cell's
|
||||
/// contents (Draw › Diagonal In Front) or behind them (Content In Front).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct CellDiagonal {
|
||||
pub lines: DiagonalLines,
|
||||
pub stroke: CellStroke,
|
||||
pub in_front: bool,
|
||||
}
|
||||
|
||||
impl Default for CellDiagonal {
|
||||
fn default() -> Self {
|
||||
CellDiagonal { lines: DiagonalLines::None, stroke: CellStroke::default(), in_front: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl CellDiagonal {
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == CellDiagonal::default()
|
||||
}
|
||||
|
||||
/// The diagonals' ends in the cell rectangle `r`, as (start, end) pairs.
|
||||
pub fn segments(&self, r: designcraft_geom::Rect) -> Vec<(designcraft_geom::Point, designcraft_geom::Point)> {
|
||||
use designcraft_geom::Point;
|
||||
let down = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y1));
|
||||
let up = (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1));
|
||||
match self.lines {
|
||||
DiagonalLines::None => vec![],
|
||||
DiagonalLines::TopLeft => vec![down],
|
||||
DiagonalLines::TopRight => vec![up],
|
||||
DiagonalLines::Crossed => vec![down, up],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CellStroke {
|
||||
pub fn none() -> Self {
|
||||
CellStroke { weight: 0.0, ..Default::default() }
|
||||
@@ -207,6 +256,9 @@ pub struct Cell {
|
||||
/// content box, origin at the box's top left).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub graphic: Option<crate::Graphic>,
|
||||
/// Cell Options › Diagonal Lines.
|
||||
#[serde(default, skip_serializing_if = "CellDiagonal::is_default")]
|
||||
pub diagonal: CellDiagonal,
|
||||
}
|
||||
|
||||
impl Default for Cell {
|
||||
@@ -228,6 +280,7 @@ impl Default for Cell {
|
||||
stroke_defined: [false; 4],
|
||||
style: String::new(),
|
||||
graphic: None,
|
||||
diagonal: CellDiagonal::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ workspace = true
|
||||
testing = []
|
||||
|
||||
[dependencies]
|
||||
craft-mime = { workspace = true }
|
||||
craft-print = { workspace = true }
|
||||
craft-docpath = { workspace = true }
|
||||
designcraft-images = { workspace = true }
|
||||
|
||||
@@ -311,7 +311,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
load(&path)?;
|
||||
let mut b = s.book.as_ref().ok_or_else(no_book)?.clone();
|
||||
let at = p.get("at").and_then(Value::as_u64).map_or(b.documents.len(), |i| (i as usize).min(b.documents.len()));
|
||||
// Keep a valid existing source attached to its chapter when inserting before it.
|
||||
let shift_source = b.style_source < b.documents.len() && at <= b.style_source;
|
||||
b.documents.insert(at, path);
|
||||
if shift_source {
|
||||
b.style_source += 1;
|
||||
}
|
||||
save(&b)?;
|
||||
s.book = Some(b);
|
||||
ok()
|
||||
@@ -323,6 +328,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
return Err(bad("book.remove", format!("no document {i}")));
|
||||
}
|
||||
b.documents.remove(i);
|
||||
if i < b.style_source {
|
||||
b.style_source -= 1;
|
||||
}
|
||||
if b.style_source >= b.documents.len() {
|
||||
b.style_source = 0;
|
||||
}
|
||||
@@ -466,4 +474,75 @@ mod tests {
|
||||
// As the one-style-at-a-time loop left them: each name once, at its last position.
|
||||
assert_eq!(kept, [("b", 2), ("a", 3), ("c", 4)]);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_book_fixture(path: &std::path::Path, documents: &[&str], style_source: usize) -> Session {
|
||||
let book = super::Book {
|
||||
path: path.to_str().unwrap().to_string(),
|
||||
documents: documents.iter().map(|path| path.to_string()).collect(),
|
||||
style_source,
|
||||
};
|
||||
super::save(&book).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("book.open", &json!({"path": book.path})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn assert_book_style_source(s: &Session, path: &std::path::Path, index: usize, source: Option<&str>) {
|
||||
let mut reopened = Session::new();
|
||||
reopened.execute("book.open", &json!({"path": path.to_str().unwrap()})).unwrap();
|
||||
for book in [s.book.as_ref().unwrap(), reopened.book.as_ref().unwrap()] {
|
||||
assert_eq!(book.style_source, index, "{book:?}");
|
||||
assert_eq!(book.documents.get(index).map(String::as_str), source, "{book:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn adding_a_chapter_keeps_the_existing_style_source() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = dir.path().join("book.dcbook");
|
||||
let inserted = dir.path().join("inserted.designcraft");
|
||||
let inserted = inserted.to_str().unwrap();
|
||||
let doc = designcraft_doc::Document::new(&Default::default());
|
||||
std::fs::write(inserted, designcraft_format::save(&doc).unwrap()).unwrap();
|
||||
let chapters = ["a.designcraft", "b.designcraft", "c.designcraft"];
|
||||
for (documents, source, at, expected_index, expected_source) in [
|
||||
(&chapters[..], 1, 0, 2, Some("b.designcraft")),
|
||||
(&chapters[..], 1, 1, 2, Some("b.designcraft")),
|
||||
(&chapters[..], 1, 2, 1, Some("b.designcraft")),
|
||||
(&chapters[..], 1, 3, 1, Some("b.designcraft")),
|
||||
(&[][..], 0, 0, 0, Some(inserted)),
|
||||
(&chapters[..], 3, 0, 3, Some("c.designcraft")),
|
||||
(&chapters[..], usize::MAX, 0, usize::MAX, None),
|
||||
] {
|
||||
let mut s = open_book_fixture(&path, documents, source);
|
||||
s.execute("book.add", &json!({"path": inserted, "at": at})).unwrap();
|
||||
assert_book_style_source(&s, &path, expected_index, expected_source);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn removing_a_chapter_keeps_a_surviving_style_source() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = dir.path().join("book.dcbook");
|
||||
let chapters = ["a.designcraft", "b.designcraft", "c.designcraft"];
|
||||
for (documents, source, removed, expected_index, expected_source) in [
|
||||
(&chapters[..], 1, 0, 0, Some("b.designcraft")),
|
||||
(&chapters[..], 2, 0, 1, Some("c.designcraft")),
|
||||
(&chapters[..], 1, 2, 1, Some("b.designcraft")),
|
||||
(&chapters[..], 0, 2, 0, Some("a.designcraft")),
|
||||
(&chapters[..], 1, 1, 1, Some("c.designcraft")),
|
||||
(&chapters[..], 2, 2, 0, Some("a.designcraft")),
|
||||
(&chapters[..1], 0, 0, 0, None),
|
||||
(&chapters[..], 3, 0, 0, Some("b.designcraft")),
|
||||
(&chapters[..], usize::MAX, 0, 0, Some("b.designcraft")),
|
||||
] {
|
||||
let mut s = open_book_fixture(&path, documents, source);
|
||||
s.execute("book.remove", &json!({"index": removed})).unwrap();
|
||||
assert_book_style_source(&s, &path, expected_index, expected_source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,13 @@ fn parse(p: &Value) -> Result<Option<ButtonAction>> {
|
||||
"lastPage" => ButtonAction::GoToLastPage,
|
||||
"nextPage" => ButtonAction::GoToNextPage,
|
||||
"previousPage" => ButtonAction::GoToPreviousPage,
|
||||
"url" => ButtonAction::GoToUrl { url: p.get("url").and_then(Value::as_str).ok_or_else(|| bad("button.set", "`url` required"))?.to_string() },
|
||||
"url" => {
|
||||
let url = p.get("url").and_then(Value::as_str).ok_or_else(|| bad("button.set", "`url` required"))?;
|
||||
if !designcraft_doc::is_safe_link_url(url) {
|
||||
return Err(bad("button.set", "`url` must start with http://, https:// or mailto:"));
|
||||
}
|
||||
ButtonAction::GoToUrl { url: url.to_string() }
|
||||
}
|
||||
o => return Err(bad("button.set", format!("unknown action `{o}`"))),
|
||||
}))
|
||||
}
|
||||
@@ -179,4 +185,16 @@ mod tests {
|
||||
assert_eq!(designcraft_render::pdf_page_count(&bytes), Some(3), "the update still reads");
|
||||
assert!(s.execute("button.list", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buttons_refuse_non_web_schemes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 1})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [72, 72, 200, 120]})).unwrap()["id"].clone();
|
||||
for bad in ["javascript:alert(1)", "file:///etc/passwd", "\\\\attacker\\share"] {
|
||||
let e = s.execute("button.set", &json!({"ids": [id.clone()], "action": "url", "url": bad})).expect_err("refused").to_string();
|
||||
assert!(e.contains("http://"), "{bad}: {e}");
|
||||
}
|
||||
s.execute("button.set", &json!({"ids": [id], "action": "url", "url": "https://example.com"})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,19 @@ fn caption(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether any item on the document spreads, inside groups included, is a live caption: the
|
||||
/// items [`refresh_live`] visits.
|
||||
pub(crate) fn has_live(d: &Document) -> bool {
|
||||
let mut found = false;
|
||||
for it in d.spreads.iter().flat_map(|sp| &sp.items) {
|
||||
it.walk(&mut |i| found |= i.live_caption.is_some());
|
||||
if found {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Bring live captions up to date with their source objects (the text frame's story is
|
||||
/// replaced when its text changed; a caption whose source is gone keeps its last text).
|
||||
pub(crate) fn refresh_live(d: &mut Document) -> bool {
|
||||
@@ -136,6 +149,17 @@ pub(crate) fn refresh_live(d: &mut Document) -> bool {
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep a text selection inside its story after `refresh_live` replaced the story's text.
|
||||
pub(crate) fn clamp_text_selection(d: &Document, sel: &mut Selection) {
|
||||
if let Some(ts) = sel.text.as_mut()
|
||||
&& ts.cell.is_none()
|
||||
&& let Some(st) = d.story(ts.story)
|
||||
{
|
||||
ts.anchor = designcraft_doc::floor_char_boundary(&st.text, ts.anchor);
|
||||
ts.focus = designcraft_doc::floor_char_boundary(&st.text, ts.focus);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
@@ -178,4 +202,107 @@ mod tests {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s), "Photo: First", "one undo step for both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_caption_follows_a_committed_gesture() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap();
|
||||
let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap();
|
||||
let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap());
|
||||
let text = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.stories[&d.item(cid).unwrap().text_frame().unwrap().story].text.clone()
|
||||
};
|
||||
s.begin_interaction("Alt Text").unwrap();
|
||||
s.preview("object.altText", json!({"text": "Second", "ids": [a]})).unwrap();
|
||||
let revision = s.doc().unwrap().revision;
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!(text(&s), "Photo: Second", "updated when the gesture commits");
|
||||
assert_ne!(s.doc().unwrap().revision, revision, "caches keyed by the revision draw the new caption");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s), "Photo: First", "one undo step for both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_sized_live_caption_fits_a_committed_gesture() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap();
|
||||
let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap();
|
||||
let cid = r["ids"][0].as_u64().unwrap();
|
||||
s.execute("object.textFrameOptions", &json!({"ids": [cid], "autoSize": "heightOnly"})).unwrap();
|
||||
let height = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(cid)).unwrap().bounds().height();
|
||||
let short = height(&s);
|
||||
let long = "A harbour at dawn, with the fishing boats coming in one after another past the lighthouse and the long stone pier";
|
||||
s.begin_interaction("Alt Text").unwrap();
|
||||
s.preview("object.altText", json!({"text": long, "ids": [a]})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert!(height(&s) > short + 5.0, "the caption frame grows with its text: {short} -> {}", height(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_live_caption_follows_its_source() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("frame.create", &json!({"rect": [300, 72, 400, 172]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap();
|
||||
let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap();
|
||||
let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap());
|
||||
// The only live caption sits inside a group, not at the top of the spread.
|
||||
s.execute("object.group", &json!({"ids": [cid.0, b]})).unwrap();
|
||||
let text = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.stories[&d.item(cid).unwrap().text_frame().unwrap().story].text.clone()
|
||||
};
|
||||
s.execute("object.altText", &json!({"text": "Second", "ids": [a]})).unwrap();
|
||||
assert_eq!(text(&s), "Photo: Second", "updated by a command");
|
||||
s.begin_interaction("Alt Text").unwrap();
|
||||
s.preview("object.altText", json!({"text": "Third", "ids": [a]})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!(text(&s), "Photo: Third", "updated when the gesture commits");
|
||||
}
|
||||
|
||||
/// A session with a live caption reading "Photo: First" and the caret at its end.
|
||||
fn caret_at_end_of_live_caption() -> (Session, designcraft_doc::StoryId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap();
|
||||
let r = s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap();
|
||||
let cid = designcraft_doc::ItemId(r["ids"][0].as_u64().unwrap());
|
||||
let sid = s.doc().unwrap().doc.item(cid).unwrap().text_frame().unwrap().story;
|
||||
let len = "Photo: First".len();
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": len, "focus": len})).unwrap();
|
||||
(s, sid)
|
||||
}
|
||||
|
||||
fn assert_caret_inside(s: &Session, sid: designcraft_doc::StoryId) {
|
||||
let st = s.doc().unwrap();
|
||||
let len = st.doc.stories[&sid].text.len();
|
||||
let ts = st.selection.text.unwrap();
|
||||
assert!(ts.anchor <= len && ts.focus <= len, "caret {}..{} past the end of {len} bytes", ts.anchor, ts.focus);
|
||||
assert!(s.ime_text_context().is_some(), "the caret still describes its text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caret_stays_inside_a_live_caption_that_discards_typing() {
|
||||
let (mut s, sid) = caret_at_end_of_live_caption();
|
||||
s.execute("text.insert", &json!({"text": " and more"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.stories[&sid].text, "Photo: First");
|
||||
assert_caret_inside(&s, sid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caret_stays_inside_a_live_caption_after_a_committed_gesture() {
|
||||
let (mut s, sid) = caret_at_end_of_live_caption();
|
||||
s.begin_interaction("Typing").unwrap();
|
||||
s.preview("text.insert", json!({"text": " and more"})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.stories[&sid].text, "Photo: First");
|
||||
assert_caret_inside(&s, sid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Type › Track Changes: record edits as inserted / deleted text; accept or reject them.
|
||||
|
||||
use designcraft_doc::{ChangeMark, Document, Story, StoryId};
|
||||
use designcraft_doc::{ChangeMark, Document, Selection, Story, StoryId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, cmd, has_doc};
|
||||
@@ -46,7 +46,7 @@ fn ranges(st: &Story, mark: ChangeMark) -> Vec<std::ops::Range<usize>> {
|
||||
}
|
||||
|
||||
/// Accept (or reject) every change in `sid`.
|
||||
fn resolve(d: &mut Document, sid: StoryId, accept: bool) -> usize {
|
||||
fn resolve(d: &mut Document, sel: &mut Selection, sid: StoryId, accept: bool) -> usize {
|
||||
let (remove, keep) = if accept { (ChangeMark::Deleted, ChangeMark::Inserted) } else { (ChangeMark::Inserted, ChangeMark::Deleted) };
|
||||
let (removed, keep_count) = {
|
||||
let st = match d.story(sid) {
|
||||
@@ -68,6 +68,7 @@ fn resolve(d: &mut Document, sid: StoryId, accept: bool) -> usize {
|
||||
});
|
||||
}
|
||||
for r in removed {
|
||||
super::notes::follow_delete(sel, sid, r.clone());
|
||||
d.adjust_text_ranges(sid, r, 0);
|
||||
}
|
||||
n
|
||||
@@ -96,10 +97,12 @@ fn one(s: &mut Session, p: &Value, accept: bool) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if delete {
|
||||
super::notes::follow_delete(sel, sid, r.clone());
|
||||
d.adjust_text_ranges(sid, r.clone(), 0);
|
||||
}
|
||||
if let Some(t) = &mut sel.text
|
||||
&& t.story == sid
|
||||
&& t.cell.is_none()
|
||||
{
|
||||
let len = d.story(sid).map_or(0, |x| x.len());
|
||||
t.anchor = t.anchor.min(len);
|
||||
@@ -163,10 +166,11 @@ fn all(s: &mut Session, p: &Value, accept: bool) -> Result<Value> {
|
||||
let ids: Vec<StoryId> = d.stories.keys().copied().filter(|id| only.is_none_or(|o| o == *id)).collect();
|
||||
let mut n = 0;
|
||||
for id in ids {
|
||||
n += resolve(d, id, accept);
|
||||
n += resolve(d, sel, id, accept);
|
||||
}
|
||||
// The caret may now be past the end.
|
||||
// A body-text edit must not clamp a cell or note caret against the body length.
|
||||
if let Some(t) = &mut sel.text
|
||||
&& t.cell.is_none()
|
||||
&& let Some(st) = d.story(t.story)
|
||||
{
|
||||
t.anchor = t.anchor.min(st.len());
|
||||
@@ -220,4 +224,91 @@ mod tests {
|
||||
assert_eq!(text(&s), "The dog sat");
|
||||
assert!(s.execute("changes.list", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Removing a tracked run follows the selected text by UTF-8 byte offsets, including undo.
|
||||
#[test]
|
||||
fn resolving_a_removed_change_follows_the_text_selection() {
|
||||
use designcraft_doc::ChangeMark;
|
||||
|
||||
for (command, mark) in [
|
||||
("changes.accept", ChangeMark::Deleted),
|
||||
("changes.reject", ChangeMark::Inserted),
|
||||
("changes.acceptAll", ChangeMark::Deleted),
|
||||
("changes.rejectAll", ChangeMark::Inserted),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let sid = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "ab猫cdéfg"})).unwrap()["story"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.edit(|d, _| {
|
||||
d.story_mut(designcraft_doc::StoryId(sid)).unwrap().format_chars(2..5, |f| f.over.change = Some(mark));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": 9, "focus": 5})).unwrap();
|
||||
let params = if command.ends_with("All") { json!({"story": sid}) } else { json!({"story": sid, "start": 2}) };
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text, "abcdéfg", "{command}");
|
||||
let selected = s.doc().unwrap().selection.text.unwrap();
|
||||
assert_eq!((selected.anchor, selected.focus), (6, 2), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let selected = s.doc().unwrap().selection.text.unwrap();
|
||||
assert_eq!((selected.anchor, selected.focus), (9, 5), "undo {command}");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
let selected = s.doc().unwrap().selection.text.unwrap();
|
||||
assert_eq!((selected.anchor, selected.focus), (6, 2), "redo {command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// All-change resolution removes disjoint runs from the end and maps each one once.
|
||||
#[test]
|
||||
fn resolving_all_changes_follows_multiple_removed_runs() {
|
||||
use designcraft_doc::ChangeMark;
|
||||
|
||||
for (command, mark) in [("changes.acceptAll", ChangeMark::Deleted), ("changes.rejectAll", ChangeMark::Inserted)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let sid = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "a猫bécδd"})).unwrap()["story"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.edit(|d, _| {
|
||||
let story = d.story_mut(designcraft_doc::StoryId(sid)).unwrap();
|
||||
story.format_chars(1..4, |f| f.over.change = Some(mark));
|
||||
story.format_chars(5..7, |f| f.over.change = Some(mark));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": 10, "focus": 4})).unwrap();
|
||||
s.execute(command, &json!({"story": sid})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text, "abcδd", "{command}");
|
||||
let selected = s.doc().unwrap().selection.text.unwrap();
|
||||
assert_eq!((selected.anchor, selected.focus), (5, 1), "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A body-story change leaves the independent footnote insertion point alone.
|
||||
#[test]
|
||||
fn resolving_body_changes_keeps_a_footnote_caret() {
|
||||
for command in ["changes.accept", "changes.acceptAll"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let sid = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "abcd"})).unwrap()["story"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("text.select", &json!({"story": sid, "anchor": 4, "focus": 4})).unwrap();
|
||||
s.execute("footnote.insert", &json!({"text": "Footnote text beyond body"})).unwrap();
|
||||
let before = s.doc().unwrap().selection.text.unwrap();
|
||||
s.edit(|d, _| {
|
||||
d.story_mut(designcraft_doc::StoryId(sid))
|
||||
.unwrap()
|
||||
.format_chars(0..1, |f| f.over.change = Some(designcraft_doc::ChangeMark::Deleted));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let params = if command.ends_with("All") { json!({"story": sid}) } else { json!({"story": sid, "start": 0}) };
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.text.unwrap(), before, "{command}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -438,6 +438,36 @@ mod pptx_tests {
|
||||
assert!(s.execute("file.exportPptx", &json!({"pages": [9]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_diagonal_lines_export_as_cell_diagonal_borders() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();
|
||||
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
for (row, col, lines) in [(0, 0, "topLeft"), (0, 1, "topRight"), (1, 0, "crossed")] {
|
||||
s.execute("table.setCell", &json!({"row": row, "col": col, "diagonal": {"lines": lines, "weight": 3}})).unwrap();
|
||||
}
|
||||
let r = s.execute("file.exportPptx", &json!({})).unwrap();
|
||||
let x = read(&mut unzip(r["base64"].as_str().unwrap()), "ppt/slides/slide1.xml");
|
||||
let cells: Vec<&str> = x.split("</a:tc>").filter(|c| c.contains("<a:tcPr")).collect();
|
||||
assert_eq!(cells.len(), 4, "{x}");
|
||||
let has = |c: &str| (c.contains("<a:lnTlToBr w=\"38100\""), c.contains("<a:lnBlToTr w=\"38100\""));
|
||||
let got: Vec<(bool, bool)> = cells.iter().map(|c| has(c)).collect();
|
||||
assert_eq!(got, [(true, false), (false, true), (true, true), (false, false)], "{x}");
|
||||
// The diagonals follow the four edges and come before the cell's fill, in the schema's order.
|
||||
let c = cells[2];
|
||||
let at = |tag: &str| c.find(tag).unwrap_or(usize::MAX);
|
||||
assert!(at("<a:lnB ") < at("<a:lnTlToBr") && at("<a:lnTlToBr") < at("<a:lnBlToTr"), "{c}");
|
||||
assert!(c.rfind("Fill").is_some_and(|f| f > at("<a:lnBlToTr")), "{c}");
|
||||
// The slide has no drawing order for them, so diagonals behind the contents are reported.
|
||||
let behind = |r: &serde_json::Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("diagonal lines"));
|
||||
assert!(!behind(&r), "{}", r["warnings"]);
|
||||
s.execute("table.setCell", &json!({"row": 1, "col": 0, "diagonal": {"inFront": false}})).unwrap();
|
||||
let r = s.execute("file.exportPptx", &json!({})).unwrap();
|
||||
assert!(behind(&r), "{}", r["warnings"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_option_places_a_picture() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -83,19 +83,7 @@ pub(super) fn load_bytes(b: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
Ok((d, warnings))
|
||||
}
|
||||
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
|
||||
out.push(B64[(n >> 18) as usize & 63] as char);
|
||||
out.push(B64[(n >> 12) as usize & 63] as char);
|
||||
out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' });
|
||||
out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' });
|
||||
}
|
||||
out
|
||||
}
|
||||
pub use craft_mime::transfer::base64 as base64_encode;
|
||||
|
||||
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(s.len() * 3 / 4);
|
||||
@@ -181,3 +169,20 @@ mod extension_tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_base64_tests {
|
||||
use super::{base64_decode, base64_encode};
|
||||
|
||||
#[test]
|
||||
fn serialization_encoding_preserves_all_bytes_and_padding() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
for n in 0..=bytes.len() {
|
||||
let encoded = base64_encode(&bytes[..n]);
|
||||
assert_eq!(encoded.len(), n.div_ceil(3) * 4);
|
||||
assert!(!encoded.contains(['\r', '\n']));
|
||||
assert_eq!(base64_decode(&encoded), bytes[..n]);
|
||||
}
|
||||
assert_eq!(base64_encode(&[0xfb, 0xff, 0xff]), "+///");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,19 +54,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
delete
|
||||
),
|
||||
cmd!("guide.deleteAll", "Delete All Guides on Spread", ["View", "Grids & Guides"], None, "{spread?}", has_doc, |s, p| {
|
||||
let r = super::spread_param(p, "guide.deleteAll")?;
|
||||
s.edit(|d, sel| {
|
||||
let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?;
|
||||
let mut n = 0;
|
||||
for pg in &mut sp.pages {
|
||||
n += pg.guides.len();
|
||||
pg.guides.clear();
|
||||
}
|
||||
sel.guides.retain(|g| g.spread != r);
|
||||
Ok(json!({"deleted": n}))
|
||||
})
|
||||
}),
|
||||
cmd!(
|
||||
"guide.deleteAll",
|
||||
"Delete All Guides on Spread",
|
||||
["View", "Grids & Guides"],
|
||||
None,
|
||||
"{spread?} — a locked guide, and the guides of a layer that is locked, hidden or locks its guides, stay → {deleted}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let r = super::spread_param(p, "guide.deleteAll")?;
|
||||
s.edit(|d, sel| {
|
||||
let keep = kept_guides(d, r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?;
|
||||
let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?;
|
||||
let n: usize = sp.pages.iter_mut().zip(&keep).map(|(pg, keep)| drop_editable(&mut pg.guides, keep)).sum();
|
||||
// The guides kept can't be selected: the spread's selected guides are gone.
|
||||
sel.guides.retain(|g| g.spread != r);
|
||||
Ok(json!({"deleted": n}))
|
||||
})
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"view.lockColumnGuides",
|
||||
"Lock Column Guides",
|
||||
@@ -112,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select All Guides",
|
||||
["Edit"],
|
||||
Some("Cmd+Alt+G"),
|
||||
"{spread?} — every guide on the spread that is not locked or on a locked or hidden layer → {selected: n}",
|
||||
"{spread?} — every guide on the spread that is not locked or on a layer that is locked, hidden or locks its guides → {selected: n}",
|
||||
has_doc,
|
||||
select_all
|
||||
),
|
||||
@@ -566,6 +572,7 @@ fn create_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad("layout.createGuides", format!("a single command may create at most {MAX_GUIDES_CREATED} guides")))?;
|
||||
let layer = s.doc()?.active_layer;
|
||||
s.edit(|d, sel| {
|
||||
let keep = kept_guides(d, r).ok_or_else(|| bad("layout.createGuides", "no such spread"))?;
|
||||
if remove {
|
||||
// The cleared pages' guide addresses name the new guides now.
|
||||
sel.guides.retain(|g| g.spread != r || only.is_some_and(|o| o != g.page));
|
||||
@@ -577,7 +584,7 @@ fn create_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
if remove {
|
||||
pg.guides.clear();
|
||||
drop_editable(&mut pg.guides, keep.get(pi).map_or(&[][..], Vec::as_slice));
|
||||
}
|
||||
let area: Rect = if to_page { pg.bounds() } else { pg.margin_rect() };
|
||||
for y in grid_positions(area.y0, area.y1, rows, rg)? {
|
||||
@@ -607,6 +614,20 @@ fn create_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Per page of spread `r`, the guides that can't be edited (locked, or on a layer that is locked,
|
||||
/// hidden or locks its guides): what removing guides leaves. `None` without the spread.
|
||||
fn kept_guides(d: &designcraft_doc::Document, r: designcraft_doc::SpreadRef) -> Option<Vec<Vec<bool>>> {
|
||||
Some(d.spread(r)?.pages.iter().map(|pg| pg.guides.iter().map(|g| !g.editable_in(d)).collect()).collect())
|
||||
}
|
||||
|
||||
/// Remove the guides `keep` doesn't mark (the editable ones); returns how many went.
|
||||
fn drop_editable(guides: &mut Vec<Guide>, keep: &[bool]) -> usize {
|
||||
let before = guides.len();
|
||||
let mut keep = keep.iter();
|
||||
guides.retain(|_| keep.next().copied().unwrap_or(false));
|
||||
before - guides.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -953,6 +974,53 @@ mod layer_tests {
|
||||
assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0);
|
||||
}
|
||||
|
||||
/// Layer Options › Lock Guides: the layer's guides stay where they are (moving and deleting
|
||||
/// them is refused) while its objects stay editable.
|
||||
#[test]
|
||||
fn lock_guides_locks_only_the_layers_guides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let layer = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.activate", &json!({"id": layer})).unwrap();
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 100})).unwrap();
|
||||
let frame = s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.set", &json!({"id": layer, "lockGuides": true})).unwrap();
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let g = d.spreads[0].pages[0].guides[0].clone();
|
||||
assert!(g.visible_in(&d) && !g.editable_in(&d));
|
||||
for command in ["guide.move", "guide.delete"] {
|
||||
assert!(s.execute(command, &json!({"page": 0, "index": 0, "position": 200})).is_err(), "{command} moved a locked guide");
|
||||
}
|
||||
assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 100.0);
|
||||
// The layer's objects aren't locked.
|
||||
s.execute("transform.move", &json!({"ids": [frame], "dx": 10, "dy": 0})).unwrap();
|
||||
s.execute("layer.set", &json!({"id": layer, "lockGuides": false})).unwrap();
|
||||
s.execute("guide.move", &json!({"page": 0, "index": 0, "position": 200})).unwrap();
|
||||
assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_all_and_remove_existing_keep_locked_guides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let grid = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.activate", &json!({"id": grid})).unwrap();
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 100})).unwrap();
|
||||
let free = s.execute("layer.new", &json!({"name": "Free"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.activate", &json!({"id": free})).unwrap();
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 200})).unwrap();
|
||||
s.execute("layer.set", &json!({"id": grid, "lockGuides": true})).unwrap();
|
||||
let positions = |s: &mut Session| {
|
||||
s.execute("guide.list", &json!({})).unwrap().as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(s.execute("guide.deleteAll", &json!({})).unwrap()["deleted"], 1);
|
||||
assert_eq!(positions(&mut s), [100.0], "the locked layer's guide stays");
|
||||
s.execute("guide.add", &json!({"orientation": "vertical", "position": 200})).unwrap();
|
||||
s.execute("layout.createGuides", &json!({"columns": 2, "removeExisting": true, "page": 0})).unwrap();
|
||||
let after = positions(&mut s);
|
||||
assert!(after.contains(&100.0) && !after.contains(&200.0), "{after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_follow_their_layer() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -101,6 +101,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// and kept the old destination (noted in review).
|
||||
fn dest_param(id: &str, d: &designcraft_doc::Document, p: &Value) -> Result<Option<HyperlinkDest>> {
|
||||
if let Some(u) = str_param(p, "url") {
|
||||
if !designcraft_doc::is_safe_link_url(u) {
|
||||
return Err(bad(id, "`url` must start with http://, https:// or mailto:"));
|
||||
}
|
||||
return Ok(Some(HyperlinkDest::Url(u.to_string())));
|
||||
}
|
||||
if let Some(e) = str_param(p, "email") {
|
||||
@@ -195,6 +198,19 @@ mod panel_tests {
|
||||
s.execute("bookmark.rename", &json!({"index": 0, "name": "Back"})).unwrap();
|
||||
assert_eq!(s.execute("bookmark.list", &json!({})).unwrap()[0]["name"], "Back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperlinks_refuse_non_web_schemes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 1})).unwrap();
|
||||
let id = s.execute("frame.create", &json!({"rect": [72, 72, 200, 120]})).unwrap()["id"].clone();
|
||||
for bad in ["javascript:alert(1)", "file:///etc/passwd", "data:text/html,hi", "\\\\attacker\\share"] {
|
||||
let e = s.execute("hyperlink.create", &json!({"ids": [id.clone()], "url": bad})).expect_err("refused").to_string();
|
||||
assert!(e.contains("http://"), "{bad}: {e}");
|
||||
}
|
||||
s.execute("hyperlink.create", &json!({"ids": [id.clone()], "url": "mailto:info@example.com"})).unwrap();
|
||||
s.execute("hyperlink.create", &json!({"ids": [id], "url": "https://example.com"})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -29,7 +29,7 @@ pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(ID, format!("`{k}` is true or false"))),
|
||||
};
|
||||
let (visible, locked, printable) = (flag("visible")?, flag("locked")?, flag("printable")?);
|
||||
let (guides, wrap) = (flag("showGuides")?, flag("suppressWrapWhenHidden")?);
|
||||
let (guides, lock_guides, wrap) = (flag("showGuides")?, flag("lockGuides")?, flag("suppressWrapWhenHidden")?);
|
||||
s.edit(|d, _| {
|
||||
if let Some(n) = &name
|
||||
&& d.layers.iter().any(|l| l.id != id && l.name == *n)
|
||||
@@ -48,6 +48,7 @@ pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(&mut l.locked, locked),
|
||||
(&mut l.printable, printable),
|
||||
(&mut l.show_guides, guides),
|
||||
(&mut l.lock_guides, lock_guides),
|
||||
(&mut l.suppress_wrap_when_hidden, wrap),
|
||||
] {
|
||||
if let Some(v) = v {
|
||||
|
||||
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Insert Pages…",
|
||||
["Layout", "Pages"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{count?: 1 (1 to 9999), after?: 0-based page index (default: the last page; past it: at the end), before?: 0-based page index (instead of `after`; 0: at the start), parent?: id|\"A-Parent\"|\"A\"|null}",
|
||||
"{count?: 1 (1 to 9999), after?: 0-based page index (default: the last page; past it: at the end), before?: 0-based page index (instead of `after`; 0: at the start), parent?: id|\"A-Parent\"|\"A\"|null (default: the parent of the page they follow, or of the first page)}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
const ID: &str = "layout.pages.insert";
|
||||
@@ -50,7 +50,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
(_, Some(b)) => b.checked_sub(1),
|
||||
(a, None) => Some(a.unwrap_or(n.saturating_sub(1))),
|
||||
};
|
||||
let parent = parent_ref(ID, &st.doc, p.get("parent"))?.unwrap_or_else(|| st.doc.parents.first().map(|x| x.id));
|
||||
// No parent given: the new pages continue the page they follow (the first page when
|
||||
// they go at the start), [None] included (#2788); in a document without pages, the
|
||||
// first parent.
|
||||
let parent = parent_ref(ID, &st.doc, p.get("parent"))?.unwrap_or_else(|| match st.doc.page(after.unwrap_or(0)) {
|
||||
Some(pg) => pg.parent,
|
||||
None => st.doc.parents.first().map(|x| x.id),
|
||||
});
|
||||
s.edit(|d, _| {
|
||||
let ids = d.insert_pages(after, count, parent)?;
|
||||
Ok(json!({"pages": ids.len(), "total": d.page_count()}))
|
||||
@@ -705,6 +711,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
locked: false,
|
||||
printable: true,
|
||||
show_guides: true,
|
||||
lock_guides: false,
|
||||
suppress_wrap_when_hidden: false,
|
||||
},
|
||||
);
|
||||
@@ -727,7 +734,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
[],
|
||||
None,
|
||||
"{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, suppressWrapWhenHidden?} — names are unique and not empty",
|
||||
"{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, lockGuides?, suppressWrapWhenHidden?} — names are unique and not empty",
|
||||
has_doc,
|
||||
set_layer
|
||||
),
|
||||
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste Image",
|
||||
[],
|
||||
None,
|
||||
"{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at one point per pixel, as File › Place sizes an image, and at most 60% of the page width",
|
||||
"{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at the size File › Place gives it (the resolution stored in the file, or one point per pixel when the file stores none) and at most 60% of the page width",
|
||||
has_doc,
|
||||
paste_image
|
||||
)]
|
||||
@@ -140,8 +140,8 @@ fn paste_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(at) => at,
|
||||
None => sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center()),
|
||||
};
|
||||
// The size File › Place gives it: one point per pixel (`designcraft_images::natural_size`), at
|
||||
// most 60% of the page width.
|
||||
// The size File › Place gives it (`designcraft_images::natural_size`): the resolution stored in
|
||||
// the file, or one point per pixel when it stores none, at most 60% of the page width.
|
||||
let (nw, nh) = designcraft_render::natural_size(&bytes, 0).unwrap_or((f64::from(pw), f64::from(ph)));
|
||||
let w = nw.min(d.settings.page_width * 0.6);
|
||||
let h = nh * w / nw;
|
||||
@@ -224,6 +224,39 @@ mod tests {
|
||||
assert!((b.center().x - page.center().x).abs() < 1e-9 && (b.center().y - page.center().y).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
/// `png` with a pHYs chunk after IHDR giving `ppm` pixels per meter on both axes.
|
||||
fn png_with_phys(png: &[u8], ppm: u32) -> Vec<u8> {
|
||||
let mut data = ppm.to_be_bytes().repeat(2);
|
||||
data.push(1);
|
||||
let mut kind_and_data = b"pHYs".to_vec();
|
||||
kind_and_data.extend_from_slice(&data);
|
||||
let mut crc = 0xFFFF_FFFFu32;
|
||||
for &b in &kind_and_data {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
|
||||
}
|
||||
}
|
||||
// Signature (8) + IHDR chunk (length 4 + type 4 + data 13 + CRC 4).
|
||||
let mut out = png[..33].to_vec();
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(&kind_and_data);
|
||||
out.extend_from_slice(&(!crc).to_be_bytes());
|
||||
out.extend_from_slice(&png[33..]);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_image_file_comes_in_at_its_stored_resolution() {
|
||||
let mut s = doc();
|
||||
// 5669 pixels per meter is 144 ppi: 40 × 30 pixels place 20 × 15 points.
|
||||
let png = png_with_phys(&png(40, 30), 5669);
|
||||
let r = s.execute(ID, &json!({"base64": base64_encode(&png), "at": [300, 400]})).unwrap();
|
||||
let b = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().bounds();
|
||||
assert!((b.width() - 20.0).abs() < 0.01 && (b.height() - 15.0).abs() < 0.01, "{b:?}");
|
||||
assert!((b.center().x - 300.0).abs() < 1e-9 && (b.center().y - 400.0).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_empty_frame_takes_the_image() {
|
||||
let mut s = doc();
|
||||
|
||||
@@ -279,7 +279,14 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let skew = if st.skew != 0.0 { Affine::new([1.0, 0.0, -st.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
|
||||
let shatai = st.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY);
|
||||
let a = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
let mut a = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
// Upright in vertical text, as the canvas and the PDF export draw it (#2895):
|
||||
// without the turn, CJK glyphs lay on their sides along the column.
|
||||
if ft.vertical
|
||||
&& let Some(turn) = g.vertical_xf(l.baseline)
|
||||
{
|
||||
a = turn * a;
|
||||
}
|
||||
let key = (li, st.fill.clone(), st.fill_tint, st.stroke.clone(), st.stroke_tint, st.stroke_weight, st.stroke_behind_fill);
|
||||
let k = match runs.iter().position(|r| r.0 == key) {
|
||||
Some(k) => k,
|
||||
@@ -298,6 +305,8 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (sr, _) = spread_xf(d, *id).ok_or(designcraft_doc::DocError::NoItem(*id))?;
|
||||
let at = d.spread(sr).and_then(|sp| sp.items.iter().position(|i| i.id == *id));
|
||||
let text_xf = d.text_xf(&it);
|
||||
// Text space → the item's inner space: a vertical frame's quarter turn (#2895).
|
||||
let text_local = d.text_local(&it);
|
||||
let make = |d: &mut Document, ((_, fill, ft, stroke, stt, sw, behind), bp): ((usize, String, f32, String, f32, f64, bool), BezPath)| {
|
||||
let mut o = Item::new(ItemId(d.alloc()), it.layer, Shape::Path, PathData::from_bezpath(&bp));
|
||||
o.xf = text_xf;
|
||||
@@ -319,8 +328,10 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
one
|
||||
} else {
|
||||
let mut g = Item::new(ItemId(d.alloc()), it.layer, Shape::Group, PathData::default());
|
||||
// Each line is in text space: in the group (which has the frame's transform) it
|
||||
// takes the frame's text turn, so the columns of vertical text stay columns.
|
||||
for p in &mut parts {
|
||||
p.xf = Affine::IDENTITY;
|
||||
p.xf = text_local;
|
||||
}
|
||||
g.xf = it.xf;
|
||||
g.content = Content::Group { items: parts.into_iter().map(Arc::new).collect() };
|
||||
@@ -689,4 +700,49 @@ mod tests {
|
||||
assert!(!it.path.is_closed());
|
||||
assert_eq!(it.path.anchor_count(), 6);
|
||||
}
|
||||
|
||||
/// #2895: Create Outlines on vertical text draws the glyphs where the canvas does. Upright
|
||||
/// glyphs take their own quarter turn, and a frame of several columns (a group of lines) keeps
|
||||
/// the frame's turn: the columns stay columns, read top to bottom.
|
||||
#[test]
|
||||
fn outlines_of_vertical_text_stay_where_the_text_was_drawn() {
|
||||
let family = "DC Test Outline Vertical";
|
||||
designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::font_with(family, &['一', '日']).unwrap());
|
||||
for (text, columns) in [("日一", 1), ("日一\n一日", 2)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id =
|
||||
s.execute("frame.create", &json!({"rect": [100, 100, 300, 500], "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("selection.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.char", &json!({"fontFamily": family, "fontStyle": "Regular"})).unwrap();
|
||||
s.execute("type.storyDirection", &json!({"vertical": true})).unwrap();
|
||||
// Where the canvas draws each glyph (render/src/text.rs): the frame's text transform,
|
||||
// then each upright glyph's turn, then its place on the line.
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let it = d.item(ItemId(id)).unwrap().clone();
|
||||
let story = it.text_frame().unwrap().story;
|
||||
let cs = designcraft_compose::compose_story(&d, story, &Default::default());
|
||||
let ft = cs.frame(ItemId(id)).unwrap();
|
||||
assert!(ft.vertical);
|
||||
assert_eq!(ft.lines.len(), columns, "{text}");
|
||||
let db = designcraft_fonts::FontDb::global();
|
||||
let text_xf = d.text_xf(&it);
|
||||
let mut drawn: Option<kurbo::Rect> = None;
|
||||
for l in &ft.lines {
|
||||
for g in l.glyphs.iter().filter(|g| g.visible) {
|
||||
assert!(g.upright, "{text}: CJK is set upright");
|
||||
let turn = g.vertical_xf(l.baseline).unwrap();
|
||||
let a = text_xf * turn * Affine::translate((g.x, l.baseline + g.y)) * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
let b = (a * db.outline(&g.face, g.gid).as_ref().clone()).bounding_box();
|
||||
drawn = Some(drawn.map_or(b, |r| r.union(b)));
|
||||
}
|
||||
}
|
||||
let drawn = drawn.unwrap();
|
||||
let out = ItemId(s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap());
|
||||
let b = s.doc().unwrap().doc.item(out).unwrap().bounds();
|
||||
for (got, want) in [(b.x0, drawn.x0), (b.y0, drawn.y0), (b.x1, drawn.x1), (b.y1, drawn.y1)] {
|
||||
assert!((got - want).abs() < 0.01, "{text}: outlines {b:?}, drawn {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -495,6 +495,7 @@ mod swatch_options_tests {
|
||||
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
s.execute("table.select", &json!({"what": "table"})).unwrap();
|
||||
s.execute("table.setCell", &json!({"stroke": {"weight": 2, "type": "dashed", "gapColor": "Brand", "edges": ["all"]}})).unwrap();
|
||||
s.execute("table.setCell", &json!({"diagonal": {"lines": "crossed", "type": "dashed", "color": "Brand", "gapColor": "Brand"}})).unwrap();
|
||||
s.execute("swatch.newColorGroup", &json!({"name": "Brand Colors", "swatches": ["Brand"]})).unwrap();
|
||||
s.execute("style.character.create", &json!({"name": "Accent"})).unwrap();
|
||||
let image = s.execute("frame.create", &json!({"rect": [72, 300, 200, 400], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -557,6 +558,7 @@ mod swatch_options_tests {
|
||||
basic.chars.ruby_stroke.as_deref() == Some(name),
|
||||
d.styles.char_style("Accent").unwrap().chars.kenten_fill.as_deref() == Some(name),
|
||||
story.tables.values().any(|t| t.cells.iter().all(|c| c.strokes.iter().all(|e| e.gap_color == name))),
|
||||
story.tables.values().any(|t| t.cells.iter().all(|c| c.diagonal.stroke.color == name && c.diagonal.stroke.gap_color == name)),
|
||||
d.spreads.iter().flat_map(|sp| &sp.items).any(|it| it.graphic().is_some_and(|g| g.fill.swatch == name)),
|
||||
story.tables.values().any(|t| t.cells.iter().any(|c| c.graphic.as_ref().is_some_and(|g| g.fill.swatch == name))),
|
||||
]
|
||||
@@ -571,10 +573,10 @@ mod swatch_options_tests {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.swatch("Brand").is_none());
|
||||
assert!(matches!(d.swatch("Signal Orange").unwrap().value, SwatchValue::Color { color_type: designcraft_color::ColorType::Spot, .. }));
|
||||
assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 14]);
|
||||
assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 15]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Brand").is_some());
|
||||
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 14]);
|
||||
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 15]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -595,7 +597,7 @@ mod swatch_options_tests {
|
||||
assert!(s.execute("swatch.options", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.swatches, before.swatches);
|
||||
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 14]);
|
||||
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 15]);
|
||||
// [Paper]'s colour can change; its name can't.
|
||||
s.execute("swatch.options", &json!({"name": "[Paper]", "to": "[Paper]", "color": "#fff8e0"})).unwrap();
|
||||
}
|
||||
@@ -605,7 +607,7 @@ mod swatch_options_tests {
|
||||
let (mut s, id, sid) = brand_doc();
|
||||
let r = s.execute("swatch.options", &json!({"name": "Brand", "nameWithValue": true, "color": {"c": 10, "m": 20, "y": 30, "k": 40}})).unwrap();
|
||||
assert_eq!(r["name"], "C=10 M=20 Y=30 K=40");
|
||||
assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 14]);
|
||||
assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 15]);
|
||||
// Later colour edits keep the name in step until the swatch is named by hand.
|
||||
let r = s.execute("swatch.options", &json!({"name": "C=10 M=20 Y=30 K=40", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap();
|
||||
assert_eq!(r["name"], "C=0 M=0 Y=0 K=50");
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
use designcraft_compose as compose;
|
||||
use designcraft_doc::story::floor_char_boundary;
|
||||
use designcraft_doc::{
|
||||
AltFills, CellAddr, CellRange, CellStroke, Document, RowHeightMode, RowKind, Selection, StoryId, StrokeType, Table, TableSel, TextSel,
|
||||
VerticalJustification,
|
||||
AltFills, CellAddr, CellRange, CellStroke, DiagonalLines, Document, RowHeightMode, RowKind, Selection, StoryId, StrokeType, Table, TableSel,
|
||||
TextSel, VerticalJustification,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use super::target::{edit_table, target};
|
||||
use super::{CellRange, CellStroke, Document, Result, Session, StrokeType, Table, Value, VerticalJustification, bad, compose, json, ok, str_param};
|
||||
use super::target::{clamp_selection, target};
|
||||
use super::{
|
||||
CellRange, CellStroke, DiagonalLines, Document, Result, Session, StrokeType, Table, Value, VerticalJustification, bad, compose, json, ok,
|
||||
str_param,
|
||||
};
|
||||
|
||||
/// Cell edges chosen for a stroke edit: the target range's four outer sides (physical left and
|
||||
/// right) and the lines between its rows and columns.
|
||||
@@ -146,6 +149,48 @@ impl StrokeEdit {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `diagonal` edit of `table.setCell`: the lines, their stroke attributes and Draw.
|
||||
struct DiagonalEdit {
|
||||
lines: Option<DiagonalLines>,
|
||||
stroke: StrokeEdit,
|
||||
in_front: Option<bool>,
|
||||
}
|
||||
|
||||
impl DiagonalEdit {
|
||||
fn parse(doc: &Document, v: &Value, cmd: &str) -> Result<DiagonalEdit> {
|
||||
if !v.is_object() {
|
||||
return Err(bad(cmd, "diagonal must be an object"));
|
||||
}
|
||||
let lines = match v.get("lines").filter(|l| !l.is_null()) {
|
||||
Some(Value::String(name)) => match name.as_str() {
|
||||
"none" => Some(DiagonalLines::None),
|
||||
"topLeft" => Some(DiagonalLines::TopLeft),
|
||||
"topRight" => Some(DiagonalLines::TopRight),
|
||||
"crossed" => Some(DiagonalLines::Crossed),
|
||||
other => return Err(bad(cmd, format!("unknown diagonal lines `{other}`: none, topLeft, topRight or crossed"))),
|
||||
},
|
||||
Some(other) => return Err(bad(cmd, format!("diagonal lines must be a string, not {other}"))),
|
||||
None => None,
|
||||
};
|
||||
let in_front = match v.get("inFront").filter(|f| !f.is_null()) {
|
||||
Some(Value::Bool(b)) => Some(*b),
|
||||
Some(other) => return Err(bad(cmd, format!("inFront must be true or false, not {other}"))),
|
||||
None => None,
|
||||
};
|
||||
Ok(DiagonalEdit { lines, stroke: StrokeEdit::parse(doc, v, cmd)?, in_front })
|
||||
}
|
||||
|
||||
fn apply(&self, d: &mut designcraft_doc::CellDiagonal) {
|
||||
if let Some(l) = self.lines {
|
||||
d.lines = l;
|
||||
}
|
||||
d.stroke = self.stroke.apply(d.stroke.clone());
|
||||
if let Some(f) = self.in_front {
|
||||
d.in_front = f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stroke drawn on side `side` of the owner cell at `(r, c)` (where that side meets its
|
||||
/// first neighbour), as rendering resolves it; the cell's own copy if the side has no stretch.
|
||||
fn drawn_side(t: &Table, owners: &[(usize, usize)], (r, c): (usize, usize), side: usize) -> Option<CellStroke> {
|
||||
@@ -247,13 +292,15 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(sv) => Some((StrokeEdit::parse(doc, sv, ID)?, EdgeSel::parse(sv.get("edges"), ID)?)),
|
||||
None => None,
|
||||
};
|
||||
edit_table(s, &g, ID, |t| {
|
||||
let diagonal = match p.get("diagonal").filter(|v| !v.is_null()) {
|
||||
Some(dv) => Some(DiagonalEdit::parse(doc, dv, ID)?),
|
||||
None => None,
|
||||
};
|
||||
let apply = |t: &mut Table| {
|
||||
let owners = t.owners();
|
||||
let nc = t.ncols();
|
||||
let nr = t.nrows();
|
||||
let rtl = t.options.direction == designcraft_doc::TextDirection::RightToLeft;
|
||||
// Local edits outrank previously imported edges, including explicit zero/None.
|
||||
let priority = if stroke.is_some() { next_cell_stroke_priority(t) } else { 0 };
|
||||
let rg = g.range;
|
||||
// Edges are inner or outer within the selection grown to whole merged cells, so a
|
||||
// merged cell selected through one of its grid positions keeps its own outline.
|
||||
@@ -271,6 +318,28 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An edge that already shows the edit as its own local stroke, drawn along the whole
|
||||
// side, is left as it is; the edit renumbers no edge when every chosen edge is. Edits
|
||||
// to other edges of the table do not count. A neighbor that wins a tie on a shared edge,
|
||||
// or on one part of a merged cell's side, draws its own stroke, so that edge still takes
|
||||
// the edit.
|
||||
let mut priority = 0;
|
||||
if let Some((edit, _)) = &stroke {
|
||||
let shown = |&(r, c, i): &(usize, usize, usize), base: &CellStroke| {
|
||||
t.cell(r, c).is_some_and(|cell| {
|
||||
cell.stroke_defined[i]
|
||||
&& cell.border_overrides[i]
|
||||
&& cell.strokes[i] == edit.apply(base.clone())
|
||||
&& compose::table::cell_side_strokes(t, &owners, (r, c), i).iter().all(|side| *side.stroke == cell.strokes[i])
|
||||
})
|
||||
};
|
||||
if bases.iter().all(|(edge, base)| shown(edge, base)) {
|
||||
bases.clear();
|
||||
} else {
|
||||
// Local edits outrank previously imported edges, including explicit zero/None.
|
||||
priority = next_cell_stroke_priority(t);
|
||||
}
|
||||
}
|
||||
let mut edited = std::collections::HashSet::new();
|
||||
for (r, c) in t.selected_owners(rg) {
|
||||
let Some(cell) = t.cell_mut(r, c) else { continue };
|
||||
@@ -295,10 +364,17 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = rotation {
|
||||
cell.rotation = v;
|
||||
}
|
||||
if let Some(tx) = &text {
|
||||
// A cell that already holds the text keeps its story as it is: replacing it would
|
||||
// give every character the first character's format and bump the story's revision.
|
||||
if let Some(tx) = &text
|
||||
&& cell.text.text != *tx
|
||||
{
|
||||
let len = cell.text.len();
|
||||
cell.text.replace(0..len, tx);
|
||||
}
|
||||
if let Some(edit) = &diagonal {
|
||||
edit.apply(&mut cell.diagonal);
|
||||
}
|
||||
if let Some((edit, _)) = &stroke {
|
||||
for i in 0..4 {
|
||||
if let Some(base) = bases.remove(&(r, c, i)) {
|
||||
@@ -313,6 +389,22 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Keep both copies of unmerged shared boundaries consistent, including in RTL tables.
|
||||
mirror_edited_cell_edges(t, rg, (nr, nc, rtl), stroke.as_ref(), &edited, &owners);
|
||||
};
|
||||
// When every value already matches the target cells, the document is left as it is and no
|
||||
// undo step is recorded.
|
||||
let current = s.doc()?.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;
|
||||
let mut edited_table = Table::clone(current);
|
||||
apply(&mut edited_table);
|
||||
if edited_table == **current {
|
||||
return ok();
|
||||
}
|
||||
// The edited copy takes the table's place, so the table is not copied a second time.
|
||||
s.edit(|d, sel| {
|
||||
let st = d.story_mut(g.story).ok_or_else(|| bad(ID, "no story"))?;
|
||||
let t = st.tables.get_mut(&g.table).ok_or_else(|| bad(ID, "no table"))?;
|
||||
*t = std::sync::Arc::new(edited_table);
|
||||
st.rev = st.rev.wrapping_add(1);
|
||||
clamp_selection(d, sel);
|
||||
ok()
|
||||
})
|
||||
}
|
||||
@@ -372,6 +464,40 @@ pub(super) fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(out))
|
||||
}
|
||||
|
||||
/// The diagonal lines of the target cells and their stroke; values that differ are null. The
|
||||
/// result also names the target cells (`story`, `table`, `rows`, `cols`).
|
||||
pub(super) fn get_cell_diagonal(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const ID: &str = "table.getCellDiagonal";
|
||||
let g = target(s, p, ID)?;
|
||||
let st = s.doc()?;
|
||||
let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;
|
||||
let keys = ["lines", "weight", "color", "tint", "type", "gapColor", "gapTint", "inFront"];
|
||||
let mut slots: [Option<Value>; 8] = Default::default();
|
||||
for (r, c) in t.selected_owners(g.range) {
|
||||
let Some(cell) = t.cell(r, c) else { continue };
|
||||
let d = &cell.diagonal;
|
||||
let e = &d.stroke;
|
||||
let values =
|
||||
[json!(d.lines), json!(e.weight), json!(e.color), json!(e.tint), json!(e.kind), json!(e.gap_color), json!(e.gap_tint), json!(d.in_front)];
|
||||
for (slot, v) in slots.iter_mut().zip(values) {
|
||||
match slot {
|
||||
None => *slot = Some(v),
|
||||
Some(cur) if *cur != v => *cur = Value::Null,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = serde_json::Map::new();
|
||||
for (k, v) in keys.iter().zip(slots) {
|
||||
out.insert((*k).into(), v.unwrap_or(Value::Null));
|
||||
}
|
||||
out.insert("story".into(), json!(g.story.0));
|
||||
out.insert("table".into(), json!(g.table));
|
||||
out.insert("rows".into(), json!([g.range.r0, g.range.r1]));
|
||||
out.insert("cols".into(), json!([g.range.c0, g.range.c1]));
|
||||
Ok(Value::Object(out))
|
||||
}
|
||||
|
||||
/// Only saturation needs rebasing. Preserve every distinct priority's order and keep
|
||||
/// zero/negative priorities untouched; the work is bounded by the table's edges.
|
||||
fn next_cell_stroke_priority(t: &mut Table) -> i32 {
|
||||
@@ -485,3 +611,130 @@ mod arabic_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod set_cell_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn set_cell_with_the_values_the_cells_already_have_records_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [0, 0, 400, 300], "content": "text", "text": ""})).unwrap();
|
||||
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let edit = json!({"rows": [0, 1], "cols": [0, 0], "fill": "[Black]", "tint": 0.5, "insets": [1, 2, 3, 4], "vj": "center", "rotation": 90, "text": "Same"});
|
||||
s.execute("table.setCell", &edit).unwrap();
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.history.undo.len(), st.revision)
|
||||
};
|
||||
let before = state(&s);
|
||||
s.execute("table.setCell", &edit).unwrap();
|
||||
assert_eq!(state(&s), before, "no undo step and no new revision when nothing changes");
|
||||
s.execute("table.setCell", &json!({"rows": [0, 1], "cols": [0, 0], "tint": 0.25})).unwrap();
|
||||
assert_eq!(state(&s).0, before.0 + 1, "a changed value is still one undo step");
|
||||
|
||||
let stroke = json!({"rows": [0, 0], "cols": [1, 1], "stroke": {"weight": 2, "edges": ["all"]}});
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
let before = state(&s);
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
assert_eq!(state(&s), before, "the same stroke again is not a new undo step");
|
||||
s.execute("table.setCell", &json!({"rows": [1, 1], "cols": [0, 0], "stroke": {"weight": 3, "edges": ["all"]}})).unwrap();
|
||||
let before = state(&s);
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
assert_eq!(state(&s), before, "an edit to other edges does not make the same stroke a new undo step");
|
||||
s.execute("table.setCell", &json!({"rows": [1, 1], "cols": [1, 1], "stroke": {"weight": 4, "edges": ["all"]}})).unwrap();
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
assert_eq!(state(&s).0, before.0 + 2, "an edge a later edit changed takes the stroke again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cell_with_the_same_text_keeps_mixed_character_formatting() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [0, 0, 400, 300], "content": "text", "text": ""})).unwrap();
|
||||
let story = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
|
||||
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let edit = json!({"rows": [0, 0], "cols": [0, 0], "text": "Mixed"});
|
||||
s.execute("table.setCell", &edit).unwrap();
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(story).ok_or_else(|| bad("test", "no story"))?;
|
||||
for t in st.tables.values_mut() {
|
||||
let cell = std::sync::Arc::make_mut(t).cell_mut(0, 0).ok_or_else(|| bad("test", "no cell"))?;
|
||||
cell.text.format_chars(0..2, |f| f.over.font_family = Some("Source Serif 4".into()));
|
||||
}
|
||||
ok()
|
||||
})
|
||||
.unwrap();
|
||||
let cell_text = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.doc.story(story).and_then(|x| x.tables.values().next().cloned()).unwrap();
|
||||
t.cell(0, 0).unwrap().text.clone()
|
||||
};
|
||||
let formatted = cell_text(&s);
|
||||
assert!(formatted.chars.len() > 1, "the cell text has two character formats");
|
||||
let before = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision);
|
||||
s.execute("table.setCell", &edit).unwrap();
|
||||
assert_eq!(cell_text(&s), formatted, "the same text keeps its character formats");
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision), before, "the same text is not an undo step");
|
||||
s.execute("table.setCell", &json!({"rows": [0, 0], "cols": [0, 0], "text": "Other"})).unwrap();
|
||||
assert_eq!(cell_text(&s).text, "Other", "different text still replaces the cell's text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cell_stroke_applies_when_the_neighbor_draws_a_different_edge() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [0, 0, 400, 300], "content": "text", "text": ""})).unwrap();
|
||||
let story = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
|
||||
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 2, "cols": 1})).unwrap();
|
||||
let stroke = json!({"rows": [0, 0], "cols": [0, 0], "stroke": {"weight": 2, "edges": ["bottom"]}});
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
// The cell below keeps the same priority on the shared edge but a heavier stroke, so it
|
||||
// wins the tie and draws the edge.
|
||||
s.edit(|d, _| {
|
||||
let st = d.story_mut(story).ok_or_else(|| bad("test", "no story"))?;
|
||||
for t in st.tables.values_mut() {
|
||||
let cell = std::sync::Arc::make_mut(t).cell_mut(1, 0).ok_or_else(|| bad("test", "no cell"))?;
|
||||
cell.strokes[0].weight = 5.0;
|
||||
}
|
||||
ok()
|
||||
})
|
||||
.unwrap();
|
||||
let drawn = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.doc.story(story).and_then(|x| x.tables.values().next().cloned()).unwrap();
|
||||
drawn_side(&t, &t.owners(), (0, 0), 2).map(|x| x.weight)
|
||||
};
|
||||
assert_eq!(drawn(&s), Some(5.0), "the cell below draws the shared edge");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
assert_eq!(drawn(&s), Some(2.0), "the edit takes the drawn edge");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "the edit is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cell_stroke_applies_when_part_of_a_merged_side_draws_a_different_edge() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [0, 0, 400, 300], "content": "text", "text": ""})).unwrap();
|
||||
let story = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
|
||||
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
s.execute("table.merge", &json!({"rows": [0, 1], "cols": [0, 0]})).unwrap();
|
||||
let stroke = json!({"rows": [0, 1], "cols": [0, 0], "stroke": {"weight": 2, "edges": ["right"]}});
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
s.execute("table.setCell", &json!({"rows": [1, 1], "cols": [1, 1], "stroke": {"weight": 4, "edges": ["left"]}})).unwrap();
|
||||
let drawn = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
let t = st.doc.story(story).and_then(|x| x.tables.values().next().cloned()).unwrap();
|
||||
compose::table::cell_side_strokes(&t, &t.owners(), (0, 0), 3).iter().map(|x| x.stroke.weight).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(drawn(&s), [2.0, 4.0], "the lower neighbor draws its part of the merged side");
|
||||
s.execute("table.setCell", &stroke).unwrap();
|
||||
assert_eq!(drawn(&s), [2.0, 2.0], "the edit takes every part of the merged side");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ pub(super) fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter_map(|(r, c)| {
|
||||
let cell = t.cell(r, c)?;
|
||||
Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill,
|
||||
"insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style}))
|
||||
"insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style, "diagonal": cell.diagonal}))
|
||||
})
|
||||
.collect();
|
||||
out["cells"] = json!(cells);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::cell::{get_cell_stroke, set_cell};
|
||||
use super::cell::{get_cell_diagonal, get_cell_stroke, set_cell};
|
||||
use super::content::{drop_cells, place_graphic, sort_rows};
|
||||
use super::options::{get, options};
|
||||
use super::selection::{go_to_row, move_rc, select, step_cell, toggle_selection};
|
||||
@@ -292,7 +292,7 @@ fn table_specs() -> Vec<CommandSpec> {
|
||||
"Cell Options",
|
||||
[],
|
||||
None,
|
||||
"{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj? | verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, rotation?: 0|90|180|270 (Cell Options › Text › Rotation; kept and written back to IDML, composed horizontally for now), text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",
|
||||
"{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj? | verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, rotation?: 0|90|180|270 (Cell Options › Text › Rotation; kept and written back to IDML, composed horizontally for now), text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}, diagonal?: {lines?: none|topLeft|topRight|crossed (Cell Options › Diagonal Lines: top left to bottom right, top right to bottom left, or both), weight?, color?, tint?, type?, gapColor?, gapTint? (as stroke), inFront?: bool (true: Diagonal In Front, false: Content In Front)}, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",
|
||||
in_table,
|
||||
set_cell
|
||||
),
|
||||
@@ -305,6 +305,15 @@ fn table_specs() -> Vec<CommandSpec> {
|
||||
in_table_or_ids,
|
||||
get_cell_stroke
|
||||
),
|
||||
cmd!(
|
||||
query "table.getCellDiagonal",
|
||||
"Get Cell Diagonal Lines",
|
||||
[],
|
||||
None,
|
||||
"{story?, table?, rows?, cols?} → {lines, weight, color, tint, type, gapColor, gapTint, inFront} of the target cells' diagonal lines (a value that differs between them is null), with story, table, rows: [a, b] and cols: [a, b] naming the target cells",
|
||||
in_table_or_ids,
|
||||
get_cell_diagonal
|
||||
),
|
||||
cmd!(
|
||||
"table.setRowHeight",
|
||||
"Row Height",
|
||||
|
||||
@@ -300,6 +300,54 @@ mod style_tests {
|
||||
assert_eq!(t.cell(1, 0).unwrap().first_baseline, designcraft_doc::FirstBaseline::Ascent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_are_a_cell_option_of_the_target_cells() {
|
||||
use designcraft_doc::DiagonalLines;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();
|
||||
let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
|
||||
s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
|
||||
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let fresh = s.execute("table.getCellDiagonal", &json!({})).unwrap();
|
||||
assert_eq!((&fresh["lines"], &fresh["weight"], &fresh["inFront"]), (&json!("none"), &json!(1.0), &json!(true)));
|
||||
let p = json!({"rows": [0, 0], "cols": [0, 1], "diagonal": {"lines": "crossed", "weight": 2, "color": "[Paper]", "type": "dotted", "inFront": false}});
|
||||
s.execute("table.setCell", &p).unwrap();
|
||||
let cell = |s: &Session, r: usize, c: usize| {
|
||||
s.doc().unwrap().doc.story(sid).unwrap().tables.values().next().unwrap().cell(r, c).unwrap().diagonal.clone()
|
||||
};
|
||||
let d = cell(&s, 0, 1);
|
||||
assert_eq!(
|
||||
(d.lines, d.stroke.weight, d.stroke.color.as_str(), &d.stroke.kind, d.in_front),
|
||||
(DiagonalLines::Crossed, 2.0, "[Paper]", &designcraft_doc::StrokeType::Dotted, false)
|
||||
);
|
||||
assert!(cell(&s, 1, 0).is_default(), "other cells keep none");
|
||||
// Only the attributes given change.
|
||||
s.execute("table.setCell", &json!({"row": 0, "col": 0, "diagonal": {"lines": "topRight"}})).unwrap();
|
||||
let d = cell(&s, 0, 0);
|
||||
assert_eq!((d.lines, d.stroke.weight, d.in_front), (DiagonalLines::TopRight, 2.0, false));
|
||||
let got = s.execute("table.getCellDiagonal", &json!({"rows": [0, 0], "cols": [0, 1]})).unwrap();
|
||||
assert_eq!(
|
||||
(&got["lines"], &got["weight"], &got["color"], &got["inFront"]),
|
||||
(&serde_json::Value::Null, &json!(2.0), &json!("[Paper]"), &json!(false)),
|
||||
"{got}"
|
||||
);
|
||||
let tid = s.doc().unwrap().doc.story(sid).unwrap().tables.keys().next().copied().unwrap();
|
||||
assert_eq!(
|
||||
(&got["story"], &got["table"], &got["rows"], &got["cols"]),
|
||||
(&json!(sid.0), &json!(tid), &json!([0, 0]), &json!([0, 1])),
|
||||
"the result names the target cells"
|
||||
);
|
||||
let shown = s.execute("table.get", &json!({})).unwrap()["cells"][1]["diagonal"].clone();
|
||||
assert_eq!((&shown["lines"], &shown["inFront"]), (&json!("crossed"), &json!(false)));
|
||||
for bad in [json!({"lines": "x"}), json!({"lines": 1}), json!({"inFront": "yes"}), json!({"weight": -1}), json!("crossed")] {
|
||||
assert!(s.execute("table.setCell", &json!({"row": 0, "col": 0, "diagonal": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(cell(&s, 0, 0).lines, DiagonalLines::TopRight, "a refused edit changes nothing");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(cell(&s, 0, 0).lines, DiagonalLines::Crossed, "one undo step per edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_and_table_styles_apply_and_follow_edits() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
//! (`/work2` isn't inside `/work`), in the case the file system stores (so a case-variant name
|
||||
//! reaches the same folder on an ordinary Windows volume, and a distinct sibling in a
|
||||
//! case-sensitive one stays outside). Two roots don't make their common parent one.
|
||||
//! - On Windows a network path (`\\server\share`, `\\?\UNC\...`, WebDAV's `\\host@SSL\share`), a
|
||||
//! device path (`\\.\...`) or a verbatim path that isn't a disk (a volume by its `\\?\Volume{…}` name is local) is refused by its name before
|
||||
//! the file system is asked about it, unless a root is on that same server and share (or that
|
||||
//! same verbatim prefix). Looking such a path up would contact a host the agent chose. A link
|
||||
//! whose text leads to one is refused before it is followed.
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
//! Roots are in force on a thread inside [`confine`], and in the whole process after
|
||||
@@ -24,7 +29,7 @@
|
||||
//! guard against other programs on the computer.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -110,7 +115,8 @@ impl AutomationRoots {
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {}", path.display())),
|
||||
};
|
||||
}
|
||||
let resolved = resolve(path)?;
|
||||
let folders: Vec<&Path> = roots.iter().map(|r| r.resolved.as_path()).collect();
|
||||
let resolved = resolve(path, &folders)?;
|
||||
if roots.iter().any(|r| inside(&resolved, &r.resolved)) {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -210,7 +216,10 @@ pub fn check_write(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(path: &Path) -> Result<PathBuf, String> {
|
||||
///
|
||||
/// A Windows network, device or non-disk verbatim prefix is refused before any of that, unless one
|
||||
/// of `roots` (resolved folders) already stands on the same server and share or the same verbatim prefix.
|
||||
fn resolve(path: &Path, roots: &[&Path]) -> Result<PathBuf, String> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
@@ -218,7 +227,26 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
|
||||
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
|
||||
return Err(format!("automation path rejected: reserved device names are not allowed: {}", path.display()));
|
||||
}
|
||||
// Win32 trims a trailing period or space from a name where it looks one up, but not always from a name in the middle: refused as given.
|
||||
if cfg!(windows) && has_trimmed_name(path) {
|
||||
return Err(format!("automation path rejected: a name Windows trims: {}", path.display()));
|
||||
}
|
||||
// Before `absolute` too: on Windows that call asks the system about the path.
|
||||
if let Some(why) = refused_prefix(path, roots) {
|
||||
return Err(format!("automation path rejected: {why}: {}", path.display()));
|
||||
}
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {}: {e}", path.display()))?;
|
||||
if let Some(why) = refused_prefix(&absolute, roots) {
|
||||
return Err(format!("automation path rejected: {why}: {}", path.display()));
|
||||
}
|
||||
// A link is judged by its own text: canonicalizing one that leads to a network path would
|
||||
// contact that host. Only Windows has such prefixes. One walk of the whole path covers every
|
||||
// shorter one the loop below tries.
|
||||
if cfg!(windows)
|
||||
&& let Some(why) = link_leads_to_refused_prefix(&absolute, roots)
|
||||
{
|
||||
return Err(format!("automation path rejected: {why}: {}", path.display()));
|
||||
}
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute.as_path();
|
||||
@@ -273,6 +301,213 @@ pub(crate) fn is_device_name(component: &str) -> bool {
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
/// A Windows path prefix that isn't a local disk: opening or even resolving a path that starts
|
||||
/// with one can reach another computer.
|
||||
#[derive(Debug)]
|
||||
enum OffDisk {
|
||||
/// `\\server\share` or `\\?\UNC\server\share`; WebDAV's `\\host@SSL\share` is a server name too.
|
||||
Unc(OsString, OsString),
|
||||
/// `\\.\device`, which no root stands on: a configured one is canonicalized to a disk path.
|
||||
Device,
|
||||
/// `\\?\` followed by anything but a drive or `UNC`.
|
||||
Verbatim(OsString),
|
||||
}
|
||||
|
||||
impl OffDisk {
|
||||
/// The prefix of `path` when it isn't a local disk. A drive letter, a path without a prefix
|
||||
/// and every path off Windows give `None`.
|
||||
fn of(path: &Path) -> Option<Self> {
|
||||
use std::path::Prefix;
|
||||
let Some(Component::Prefix(prefix)) = path.components().next() else { return Self::unparsed(path) };
|
||||
match prefix.kind() {
|
||||
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => None,
|
||||
Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => Some(Self::Unc(server.to_os_string(), share.to_os_string())),
|
||||
Prefix::DeviceNS(_) => Some(Self::Device),
|
||||
// A volume named by its GUID (a folder a volume is mounted in) is on this computer.
|
||||
Prefix::Verbatim(rest) if is_volume_name(rest) => None,
|
||||
Prefix::Verbatim(rest) => Some(Self::Verbatim(rest.to_os_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows path `std` finds no prefix in, though Windows reads one: two separators that aren't a whole
|
||||
/// `\\server\share` (`\\server`, `\\\x`) name a computer, so that is a UNC path with no share; `\??\` is
|
||||
/// the NT form of `\\?\` (`\??\UNC\server\share`), so that is a device path.
|
||||
fn unparsed(path: &Path) -> Option<Self> {
|
||||
let bytes = path.as_os_str().as_encoded_bytes();
|
||||
let separator = |b: Option<&u8>| matches!(b, Some(b'\\' | b'/'));
|
||||
if !cfg!(windows) {
|
||||
None
|
||||
} else if separator(bytes.first()) && separator(bytes.get(1)) {
|
||||
Some(Self::Unc(OsString::new(), OsString::new()))
|
||||
} else if bytes.get(..4).is_some_and(|b| b.eq_ignore_ascii_case(br"\??\")) {
|
||||
Some(Self::Device)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal for a path with this prefix, which names the prefix.
|
||||
fn refusal(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unc(..) => "UNC paths are refused unless a root is on the same server and share",
|
||||
Self::Device => "device paths are refused",
|
||||
Self::Verbatim(_) => "verbatim paths are refused unless a root uses the same prefix",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `other` is the same server and share, or the same verbatim prefix, the ASCII case aside. This
|
||||
/// decides only whether that host may be contacted; [`inside`] still decides the folder.
|
||||
fn same_as(&self, other: &Self) -> bool {
|
||||
let same = |a: &OsString, b: &OsString| a.eq_ignore_ascii_case(b);
|
||||
match (self, other) {
|
||||
(Self::Unc(server, share), Self::Unc(other_server, other_share)) => same(server, other_server) && same(share, other_share),
|
||||
(Self::Verbatim(rest), Self::Verbatim(other)) => same(rest, other),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `path` must not be looked up: it starts with a Windows network, device or non-disk
|
||||
/// verbatim prefix and none of `roots` stands on that same server and share or verbatim prefix. A local path gives `None`.
|
||||
fn refused_prefix(path: &Path, roots: &[&Path]) -> Option<&'static str> {
|
||||
let prefix = OffDisk::of(path)?;
|
||||
if roots.iter().filter_map(|root| OffDisk::of(root)).any(|root| root.same_as(&prefix)) { None } else { Some(prefix.refusal()) }
|
||||
}
|
||||
|
||||
/// How many links in a row [`link_leads_to_refused_prefix`] follows before it gives up and refuses.
|
||||
const MAX_LINK_HOPS: usize = 40;
|
||||
|
||||
/// How many spellings of a path one walk scans in all, so a hostile set of links can't make it
|
||||
/// scan without end.
|
||||
const MAX_SPELLINGS: usize = 1024;
|
||||
|
||||
/// The refusal for a link in `path`, taken from the link's own text.
|
||||
///
|
||||
/// Folders are inspected from the top down with [`std::fs::symlink_metadata`], which doesn't follow
|
||||
/// a link, and a link's target is read with [`std::fs::read_link`]. A link to a network path is
|
||||
/// therefore refused before [`std::fs::canonicalize`] could open that host, also when the link is
|
||||
/// only an ancestor of the name. A link whose target can't be read, the one after
|
||||
/// [`MAX_LINK_HOPS`] in a row, or a walk past [`MAX_SPELLINGS`] spellings, is refused rather than
|
||||
/// opened.
|
||||
fn link_leads_to_refused_prefix(path: &Path, roots: &[&Path]) -> Option<&'static str> {
|
||||
follow_links(path, roots, &mut std::collections::HashSet::new(), MAX_LINK_HOPS)
|
||||
}
|
||||
|
||||
/// [`link_leads_to_refused_prefix`] for one spelling of the path. `judged` holds every spelling the
|
||||
/// walk has scanned (so none is scanned twice, nor in a cycle forever) and `hops_left` the links
|
||||
/// still allowed in this chain, which the other spelling of a target does not use up.
|
||||
fn follow_links(path: &Path, roots: &[&Path], judged: &mut std::collections::HashSet<PathBuf>, hops_left: usize) -> Option<&'static str> {
|
||||
// A \\?\ path is opened as written, so a link before its `..` is followed; rebuilding the path below would pop that link unseen.
|
||||
if matches!(path.components().next(), Some(Component::Prefix(p)) if p.kind().is_verbatim())
|
||||
&& path.components().any(|c| c == Component::ParentDir)
|
||||
{
|
||||
return Some("parent traversal in a verbatim path");
|
||||
}
|
||||
// Without a trailing separator: Windows reads `remote\` as a folder to go into, so a link named `remote` would be followed by the
|
||||
// probe itself, to wherever it leads, instead of being seen as a link.
|
||||
let normalized: PathBuf = path.components().collect();
|
||||
let path = normalized.as_path();
|
||||
if !judged.insert(path.to_path_buf()) {
|
||||
return None;
|
||||
}
|
||||
if judged.len() > MAX_SPELLINGS {
|
||||
return Some("too many links");
|
||||
}
|
||||
let mut ancestors: Vec<&Path> = path.ancestors().collect();
|
||||
ancestors.reverse();
|
||||
for prefix in ancestors {
|
||||
if prefix.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(why) = refused_prefix(prefix, roots) {
|
||||
return Some(why);
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(prefix) {
|
||||
Ok(meta) => meta,
|
||||
// Nothing is there, so no link is below it.
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => return None,
|
||||
// Anything else (no permission to look): a link below it can't be seen, so don't go on.
|
||||
Err(_) => return Some("a folder that can't be looked at"),
|
||||
};
|
||||
if !meta.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if hops_left == 0 {
|
||||
return Some("too many links");
|
||||
}
|
||||
let Ok(target) = std::fs::read_link(prefix) else { return Some("a link that leads nowhere") };
|
||||
if cfg!(windows) && is_native_name(&target) {
|
||||
return Some("device paths are refused");
|
||||
}
|
||||
// Win32 lookups trim a trailing period or space, the kernel follows a link target as written: the two could name different things.
|
||||
if cfg!(windows) && has_trimmed_name(&target) {
|
||||
return Some("a link to a name Windows trims");
|
||||
}
|
||||
// Judged as written: joined onto the link's folder, a bare `\\server` would keep that folder's drive.
|
||||
if let Some(why) = refused_prefix(&target, roots) {
|
||||
return Some(why);
|
||||
}
|
||||
let joined = match prefix.parent() {
|
||||
Some(parent) if !target.is_absolute() && !parent.as_os_str().is_empty() => parent.join(target),
|
||||
_ => target,
|
||||
};
|
||||
let next = match path.strip_prefix(prefix) {
|
||||
Ok(rest) if !rest.as_os_str().is_empty() => joined.join(rest),
|
||||
_ => joined,
|
||||
};
|
||||
if let Some(why) = refused_prefix(&next, roots) {
|
||||
return Some(why);
|
||||
}
|
||||
// Windows takes the `..` of a relative target by name, so `missing\..\remote` is `remote`
|
||||
// though `missing` isn't there: judge that spelling as well as the one written.
|
||||
let by_name = lexical(&next);
|
||||
if by_name != next
|
||||
&& let Some(why) = follow_links(&by_name, roots, judged, hops_left - 1)
|
||||
{
|
||||
return Some(why);
|
||||
}
|
||||
return follow_links(&next, roots, judged, hops_left - 1);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `rest` (the part after `\\?\`) names a volume by its GUID, `Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`: a local volume, such as the one
|
||||
/// a folder is a mount point of.
|
||||
fn is_volume_name(rest: &OsStr) -> bool {
|
||||
let bytes = rest.as_encoded_bytes();
|
||||
bytes.len() == 44
|
||||
&& bytes.get(..7).is_some_and(|b| b.eq_ignore_ascii_case(b"Volume{"))
|
||||
&& bytes.ends_with(b"}")
|
||||
&& bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() })
|
||||
}
|
||||
|
||||
/// Whether `path` is a name that starts with one separator and no drive (`\Device\Mup\server\share`, `\RPC Control\x`,
|
||||
/// `\??\UNC\x`, `\work`), as a link may hold one: `std` sees no prefix in it, yet the system reads it in its own object
|
||||
/// namespace or on the link's drive, and may follow it to wherever it names. Joined onto the link's folder it would look local.
|
||||
fn is_native_name(path: &Path) -> bool {
|
||||
matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\'))
|
||||
}
|
||||
|
||||
/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up.
|
||||
fn has_trimmed_name(path: &Path) -> bool {
|
||||
path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' '))))
|
||||
}
|
||||
|
||||
/// `path` with its `.` and `..` taken by name, never above its root.
|
||||
fn lexical(path: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
Component::CurDir => {}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -545,6 +780,240 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A path with no Windows prefix, a drive letter, and every path off Windows have no off-disk prefix to refuse.
|
||||
#[test]
|
||||
fn a_local_path_has_no_off_disk_prefix() {
|
||||
for p in ["/home/me/a.designcraft", "a.designcraft", r"C:\Projects\a.designcraft", r"\\?\C:\Projects\a.designcraft"] {
|
||||
assert!(OffDisk::of(Path::new(p)).is_none(), "{p}");
|
||||
assert_eq!(refused_prefix(Path::new(p), &[]), None, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A network, device or non-disk verbatim path is refused by its name before the file system is
|
||||
/// asked, so no host the agent names is contacted. The error names the prefix; it is not the
|
||||
/// error that opening the path would give. Nothing here touches the network.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_network_path_is_refused_before_it_is_opened() {
|
||||
let (base, roots) = folders("unc");
|
||||
let paths = [
|
||||
(r"\\203.0.113.5\s\x.designcraft", "UNC"),
|
||||
(r"\\?\UNC\203.0.113.5\s\x.designcraft", "UNC"),
|
||||
("//203.0.113.5/s/x.designcraft", "UNC"),
|
||||
(r"\\host@SSL\share\x.designcraft", "UNC"),
|
||||
(r"\\host@SSL@443\share\x.designcraft", "UNC"),
|
||||
(r"\\203.0.113.5", "UNC"),
|
||||
(r"\\\203.0.113.5\s\x.designcraft", "UNC"),
|
||||
("//203.0.113.5", "UNC"),
|
||||
(r"\\.\PhysicalDrive0", "device path"),
|
||||
(r"\\?\GLOBALROOT\Device\Mup\203.0.113.5\s\x.designcraft", "verbatim path"),
|
||||
(r"\??\UNC\203.0.113.5\s\x.designcraft", "device path"),
|
||||
];
|
||||
for (p, kind) in paths {
|
||||
for access in [Access::Read, Access::Write] {
|
||||
let e = roots.check(p, access).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected:"), "{p}: {e}");
|
||||
assert!(e.contains(kind), "{p}: {e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
let e = roots.check(s(base.join("outside/secret.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "a local path is still judged by its folder: {e}");
|
||||
let verbatim = format!(r"\\?\{}", s(base.join("in").join("a.designcraft")));
|
||||
assert_eq!(roots.check(&verbatim, Access::Read), Ok(()), "a verbatim disk path is a local path: {verbatim}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A root on a share lets that server and share through (either spelling, any ASCII case) and nothing else.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_root_on_a_share_lets_only_that_share_through() {
|
||||
assert!(OffDisk::of(Path::new(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x")).is_none(), "a volume by GUID is local");
|
||||
assert!(OffDisk::of(Path::new(r"\\?\Volume{remote}\x")).is_some(), "a name that is not a GUID is not a volume");
|
||||
let share = [Path::new(r"\\?\UNC\FileServer\Projects\work")];
|
||||
assert_eq!(refused_prefix(Path::new(r"\\fileserver\projects\a.designcraft"), &share), None);
|
||||
assert_eq!(refused_prefix(Path::new(r"\\?\UNC\FILESERVER\PROJECTS\a.designcraft"), &share), None);
|
||||
assert!(refused_prefix(Path::new(r"\\fileserver\secret\a.designcraft"), &share).is_some(), "another share");
|
||||
assert!(refused_prefix(Path::new(r"\\203.0.113.5\Projects\a.designcraft"), &share).is_some(), "another server");
|
||||
let work = [Path::new(r"\\?\UNC\work\Projects\w")];
|
||||
assert!(refused_prefix(Path::new("\\\\wor\u{212a}\\Projects\\a.designcraft"), &work).is_some(), "U+212A is not k");
|
||||
assert!(refused_prefix(Path::new(r"\\.\PhysicalDrive0"), &share).is_some(), "a share is not a device");
|
||||
let device = [Path::new(r"\\.\PhysicalDrive0")];
|
||||
assert!(refused_prefix(Path::new(r"\\.\PhysicalDrive0"), &device).is_some(), "a device is refused even when a root names it");
|
||||
}
|
||||
|
||||
/// A link whose text is a bare `\\server` (no share) is refused as written: joined onto the link's folder
|
||||
/// it would read as a local path and pass.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_link_to_a_bare_server_name_is_refused() {
|
||||
let (base, roots) = folders("unc-link-bare");
|
||||
let link = base.join("in").join("bare");
|
||||
if std::os::windows::fs::symlink_dir(r"\\203.0.113.5", &link).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let e = roots.check(s(link.join("x.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("UNC"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Nine links that each go through `sub\..\` to the next are nine links, not a reason to give up: both
|
||||
/// spellings of each target are judged once.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_chain_of_links_with_parent_names_is_followed_in_few_steps() {
|
||||
let (base, roots) = folders("link-chain");
|
||||
let folder = base.join("in");
|
||||
std::fs::create_dir_all(folder.join("sub")).unwrap();
|
||||
for n in 1..=9 {
|
||||
let target = if n == 9 { "sub".to_string() } else { format!(r"sub\..\l{}", n + 1) };
|
||||
if std::os::windows::fs::symlink_dir(&target, folder.join(format!("l{n}"))).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
}
|
||||
assert_eq!(roots.check(s(folder.join("l1").join("x.designcraft")), Access::Read), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that starts with one separator and no drive is a native or rooted name, whichever object directory it
|
||||
/// names (`\Device`, `\RPC Control`, `\BaseNamedObjects`, `\??`): a link to it is refused, and it is the same
|
||||
/// with the rest of the path after it.
|
||||
#[test]
|
||||
fn rooted_names_without_a_drive_are_native_names() {
|
||||
for p in
|
||||
[r"\Device", r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\GLOBAL??", r"\work", r"\"]
|
||||
{
|
||||
assert!(is_native_name(Path::new(p)), "{p}");
|
||||
}
|
||||
for p in [r"Device", r"work\x", r"C:\x", r"C:\Device", r"\\server\share", r"\\?\C:\x", ""] {
|
||||
assert!(!is_native_name(Path::new(p)), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A link whose text is a native NT name (`\Device\Mup\server\share`) isn't a local path just because
|
||||
/// `std` sees no prefix in it: it is refused as written, before it is joined onto the link's folder.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_link_to_a_native_device_name_is_refused() {
|
||||
let (base, roots) = folders("native-link");
|
||||
let link = base.join("in").join("native");
|
||||
if std::os::windows::fs::symlink_dir(r"\Device\Mup\203.0.113.5\s", &link).is_err()
|
||||
|| std::fs::read_link(&link).ok().as_deref() != Some(std::path::Path::new(r"\Device\Mup\203.0.113.5\s"))
|
||||
{
|
||||
eprintln!("skipped: this system can't make that link, or stores its text differently");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let e = roots.check(s(link.join("x.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("device path"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link whose target ends in a period or a space (`remote.`) is refused as written: Win32 lookups trim
|
||||
/// that ending but the kernel follows the text as it is, so the two could name different things.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_link_to_a_name_windows_trims_is_refused() {
|
||||
let (base, roots) = folders("trimmed-link");
|
||||
let link = base.join("in").join("trimmed");
|
||||
if std::os::windows::fs::symlink_dir(r"remote.", &link).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let e = roots.check(s(link.join("x.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("name Windows trims"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A path that names a link with a trailing separator (`remote\`) is judged as the link: Windows reads that as a
|
||||
/// folder to go into, and would follow the link to a network path to find out what it is.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_link_with_a_trailing_separator_is_judged_as_the_link() {
|
||||
let (base, roots) = folders("slashed-link");
|
||||
let link = base.join("in").join("slashed");
|
||||
if std::os::windows::fs::symlink_dir(r"\\203.0.113.5\s", &link).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let e = roots.check(format!(r"{}\", link.display()), Access::Read).unwrap_err();
|
||||
assert!(e.contains("UNC"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A path with a name that ends in a space (`remote \x`) is refused as given: Windows keeps that space in the
|
||||
/// middle of a path but trims it when it looks the folder up by itself, so the two could name different things.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_path_with_a_name_windows_trims_is_refused() {
|
||||
let (base, roots) = folders("trimmed-path");
|
||||
let e = roots.check(s(base.join("in").join("remote ").join("x.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("name Windows trims"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_verbatim_path_with_a_parent_name_is_refused() {
|
||||
let (base, roots) = folders("verbatim-dotdot");
|
||||
let p = format!(r"\\?\{}\..\a.designcraft", s(base.join("in").join("sub")));
|
||||
let e = roots.check(&p, Access::Read).unwrap_err();
|
||||
assert!(e.contains("parent traversal in a verbatim path"), "{p}: {e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link whose relative target goes through a missing folder and back (`missing\..\remote`) is
|
||||
/// judged with the `..` taken by name too, as Windows takes it: `remote` is a link to a network path.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_relative_link_through_a_missing_folder_still_reaches_the_network_check() {
|
||||
let (base, roots) = folders("unc-link-dotdot");
|
||||
let (remote, alias) = (base.join("in").join("remote"), base.join("in").join("alias"));
|
||||
if std::os::windows::fs::symlink_dir(r"\\203.0.113.5\s", &remote).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
assert!(std::os::windows::fs::symlink_dir(r"missing\..\remote", &alias).is_ok());
|
||||
let e = roots.check(s(alias.join("x.designcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("UNC"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link whose text names a network path, or that has one as a folder on the way, is refused
|
||||
/// from that text before the link is followed: following it would contact the host.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_link_to_a_network_path_is_refused_before_it_is_followed() {
|
||||
let (base, roots) = folders("unc-link");
|
||||
let file_link = base.join("in/leak.designcraft");
|
||||
if std::os::windows::fs::symlink_file(r"\\203.0.113.5\s\x.designcraft", &file_link).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let folder_link = base.join("in/folder-leak");
|
||||
assert!(std::os::windows::fs::symlink_dir(r"\\203.0.113.5\s", &folder_link).is_ok());
|
||||
for path in [file_link, folder_link.join("x.designcraft")] {
|
||||
let e = roots.check(s(path.clone()), Access::Read).unwrap_err();
|
||||
assert!(e.contains("UNC"), "{}: {e}", path.display());
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{}: {e}", path.display());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
|
||||
@@ -684,11 +684,13 @@ impl Session {
|
||||
if spec.undoable
|
||||
&& let Some(st) = self.active_mut()
|
||||
&& st.interaction.is_none()
|
||||
&& st.doc.spreads.iter().any(|sp| sp.items.iter().any(|i| i.live_caption.is_some()))
|
||||
&& cmd::captions::has_live(&st.doc)
|
||||
{
|
||||
let mut d = (*st.doc).clone();
|
||||
if cmd::captions::refresh_live(&mut d) {
|
||||
cmd::captions::clamp_text_selection(&d, &mut st.selection);
|
||||
st.doc = Arc::new(d);
|
||||
st.bump_revision();
|
||||
}
|
||||
}
|
||||
self.autosize_changed(spec, before.as_ref());
|
||||
|
||||
@@ -705,6 +705,40 @@ fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() {
|
||||
discard(dir.path(), uid);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn another_sessions_write_queued_behind_a_cancelled_one_is_not_replaced() {
|
||||
let _turn = background();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut a = dirty_session();
|
||||
a.recovery_dir = Some(dir.path().to_path_buf());
|
||||
let uid = a.docs[0].uid;
|
||||
let mut b = dirty_session();
|
||||
b.recovery_dir = Some(dir.path().to_path_buf());
|
||||
b.docs[0].uid = uid;
|
||||
b.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap();
|
||||
let held = testing::hold_next_write(dir.path());
|
||||
a.execute("file.recovery.save", &json!({"background": true})).unwrap();
|
||||
held.wait_until_held();
|
||||
// Saving cancels the held write, so the other session's write is queued to follow it.
|
||||
let saved = tempfile::tempdir().unwrap();
|
||||
a.execute("file.saveAs", &json!({"path": saved.path().join("saved.designcraft").to_string_lossy()})).unwrap();
|
||||
let queued = b.execute("file.recovery.save", &json!({"background": true})).unwrap();
|
||||
assert_eq!(queued["queued"], 1, "{queued}");
|
||||
// A later edit in the first session does not take the place of that waiting write.
|
||||
a.execute("frame.create", &json!({"rect": [30, 30, 50, 50]})).unwrap();
|
||||
a.execute("frame.create", &json!({"rect": [40, 40, 50, 50]})).unwrap();
|
||||
let err = a.execute("file.recovery.save", &json!({"background": true})).unwrap_err();
|
||||
assert!(err.to_string().contains("another session"), "{err}");
|
||||
held.release();
|
||||
assert_eq!(finished_writes(&mut b), 1, "the other session's write ran");
|
||||
let mut reopened = Session::new();
|
||||
assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1);
|
||||
assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "the other session's snapshot was kept");
|
||||
discard(dir.path(), reopened.doc().unwrap().uid);
|
||||
discard(dir.path(), uid);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_background_recovery_write_reports_another_sessions_held_write() {
|
||||
|
||||
@@ -209,7 +209,7 @@ fn resolve_in(params: &Value, results: &[Value], max_ref: usize, budget: &mut us
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Report {
|
||||
pub results: Vec<Value>,
|
||||
/// The failing step (index, command, message); later steps didn't run.
|
||||
/// The first failing step (index, command, message), if any.
|
||||
pub failed: Option<(usize, String, String)>,
|
||||
}
|
||||
|
||||
|
||||
@@ -321,6 +321,18 @@ impl Session {
|
||||
let st = self.doc_mut()?;
|
||||
let Some(it) = st.interaction.take() else { return Ok(()) };
|
||||
if !Arc::ptr_eq(&it.doc, &st.doc) {
|
||||
// Previews skip the live caption refresh, so the committed change brings captions up
|
||||
// to date here, in the same undo step, and auto-sizes the caption frames it changed.
|
||||
if crate::cmd::captions::has_live(&st.doc) {
|
||||
let mut d = (*st.doc).clone();
|
||||
if crate::cmd::captions::refresh_live(&mut d) {
|
||||
let todo = crate::autosize::candidates(&d, Some(&st.doc));
|
||||
crate::autosize::fit(&mut d, todo);
|
||||
crate::cmd::captions::clamp_text_selection(&d, &mut st.selection);
|
||||
st.doc = Arc::new(d);
|
||||
st.bump_revision();
|
||||
}
|
||||
}
|
||||
record_undo(st, HistoryEntry { label: it.label, doc: it.doc, selection: it.selection });
|
||||
}
|
||||
if let Some((c, p)) = it.preview {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! `layout.pages.insert` without a `parent` gives the new pages the parent of the page they
|
||||
//! follow, [None] included, instead of always the first parent (#2788).
|
||||
use designcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn parents(s: &Session) -> Vec<Option<u64>> {
|
||||
s.doc().unwrap().doc.pages().map(|(_, _, p)| p.parent.map(|id| id.0)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_added_after_a_page_without_a_parent_has_none() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 2})).unwrap();
|
||||
let a = s.doc().unwrap().doc.parents.first().map(|p| p.id.0).unwrap();
|
||||
s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": null})).unwrap();
|
||||
assert_eq!(parents(&s), [Some(a), None]);
|
||||
// As the Pages panel's Create new page button does: after the current page, no parent.
|
||||
s.execute("layout.pages.insert", &json!({"after": 1, "count": 1})).unwrap();
|
||||
assert_eq!(parents(&s), [Some(a), None, None], "the new page continues the page it follows");
|
||||
s.execute("layout.pages.insert", &json!({"after": 0, "count": 1})).unwrap();
|
||||
assert_eq!(parents(&s), [Some(a), Some(a), None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_inserted_at_the_start_take_the_first_page_s_parent() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 2})).unwrap();
|
||||
let a = s.doc().unwrap().doc.parents.first().map(|p| p.id.0).unwrap();
|
||||
s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": null})).unwrap();
|
||||
s.execute("layout.pages.insert", &json!({"before": 0, "count": 1})).unwrap();
|
||||
assert_eq!(parents(&s), [None, None, Some(a)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parent_given_still_wins() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"pages": 1})).unwrap();
|
||||
s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": null})).unwrap();
|
||||
let a = s.doc().unwrap().doc.parents.first().map(|p| p.id.0).unwrap();
|
||||
s.execute("layout.pages.insert", &json!({"after": 0, "count": 1, "parent": a})).unwrap();
|
||||
assert_eq!(parents(&s), [None, Some(a)]);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod combined_close_glyph;
|
||||
mod distribute_locks;
|
||||
mod export_page_input;
|
||||
mod insert_pages_bounds;
|
||||
mod insert_pages_parent;
|
||||
mod param_keys;
|
||||
mod pdf_backend;
|
||||
mod preflight_resolution;
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "DesignCraft EPUB 3 (reflowable) export: stories in reading order,
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-mime = { workspace = true }
|
||||
craft-epub = { workspace = true }
|
||||
designcraft-doc = { workspace = true }
|
||||
designcraft-color = { workspace = true }
|
||||
|
||||
+1
-11
@@ -266,14 +266,4 @@ pub fn export_html(doc: &Document, opts: &HtmlOptions) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn base64(data: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
|
||||
for (i, shift) in [18, 12, 6, 0].into_iter().enumerate() {
|
||||
out.push(if i <= c.len() { T[(n >> shift & 63) as usize] as char } else { '=' });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub(crate) use craft_mime::transfer::base64;
|
||||
|
||||
@@ -1046,6 +1046,7 @@ fn text_hidden_by_inherited_conditions_or_deletion_is_not_exported() {
|
||||
locked: false,
|
||||
printable: true,
|
||||
show_guides: true,
|
||||
lock_guides: false,
|
||||
suppress_wrap_when_hidden: false,
|
||||
});
|
||||
d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 300.0), hidden_layer, "On a hidden layer", ParaFormat::default()).unwrap();
|
||||
@@ -1074,3 +1075,12 @@ fn a_threaded_story_is_skipped_only_when_every_frame_is_hidden() {
|
||||
d.item_mut(b).unwrap().hidden = true;
|
||||
assert_eq!(story(&d), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_keeps_binary_padding_and_long_data_uris_on_one_line() {
|
||||
assert_eq!(base64(b""), "");
|
||||
assert_eq!(base64(&[0xfb, 0xff, 0xff]), "+///");
|
||||
assert_eq!(base64(&[0xff]), "/w==");
|
||||
assert_eq!(base64(&[0xff, 0xff]), "//8=");
|
||||
assert_eq!(base64(&[0; 60]), "A".repeat(80));
|
||||
}
|
||||
|
||||
@@ -278,6 +278,19 @@ impl FontFace {
|
||||
.get_or_init(|| if self.is_variable() { None } else { self.skrifa().and_then(|f| name(&f, &[StringId::POSTSCRIPT_NAME])) })
|
||||
.as_deref()
|
||||
}
|
||||
/// The PostScript name of this face as an instance of its variable font (Adobe TN #5902): a
|
||||
/// named instance's name, or one built from the axis values for a point between them. `None`
|
||||
/// for a static face; the default point gets the file's `name` ID 6.
|
||||
///
|
||||
/// [`Self::postscript_name`] is the file's own `name` ID 6, which names the font's default
|
||||
/// instance: embedding by it put every weight of a variable font into a PDF under one name
|
||||
/// (#1690).
|
||||
pub fn instance_postscript_name(&self) -> Option<String> {
|
||||
if !self.is_variable() {
|
||||
return None;
|
||||
}
|
||||
crate::psname::instance_postscript_name(&self.skrifa()?, &self.coords)
|
||||
}
|
||||
|
||||
/// Glyph id for `c` (0 = .notdef).
|
||||
pub fn glyph_for(&self, c: char) -> u32 {
|
||||
|
||||
@@ -13,6 +13,7 @@ mod group;
|
||||
mod kind;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac_fonts;
|
||||
pub mod psname;
|
||||
#[cfg(any(test, feature = "testing"))]
|
||||
pub mod testing;
|
||||
mod vertical;
|
||||
|
||||
@@ -0,0 +1,499 @@
|
||||
//! The PostScript name of a variable font's named instance (Adobe TN #5902).
|
||||
//!
|
||||
//! `name` ID 6 names the font's **default** instance, so every instance of a variable font embeds
|
||||
//! under the same name: all the weights of Noto Sans KR went into a PDF as `NotoSansKR-Thin`, and
|
||||
//! Acrobat's font list, preflight and a print shop's checks then report Thin for every weight
|
||||
//! (#1690). The outlines were right; only the name was wrong.
|
||||
|
||||
use skrifa::raw::TableProvider;
|
||||
use skrifa::{FontRef, MetadataProvider, raw::types::NameId};
|
||||
|
||||
/// Longest PostScript name `name` ID 6 may carry (OpenType), which is where this name goes.
|
||||
///
|
||||
/// TN #5902 works to 127 characters and prescribes a "last resort" name past that; the shorter
|
||||
/// limit here is the one that matters for a name written into the font's own `name` table.
|
||||
const MAX_LEN: usize = 63;
|
||||
|
||||
/// Axis values count as the same instance within this much (user units).
|
||||
const AXIS_EPSILON: f32 = 1e-4;
|
||||
|
||||
/// The PostScript name for the instance of `font` at `coords`, or `None` for a static font; the
|
||||
/// default point gets the file's `name` ID 6.
|
||||
///
|
||||
/// TN #5902: a named instance's own `postScriptNameID` wins; otherwise the name is the family
|
||||
/// prefix (`name` ID 25, else the typographic family, else the family -- OpenType reads a missing
|
||||
/// ID 16 as ID 1) joined to the instance's subfamily with a hyphen, keeping only ASCII letters and
|
||||
/// digits. A point no named instance covers is named by its axis values
|
||||
/// ([`arbitrary_instance_name`]). No more than 63 characters either way, the limit of the `name`
|
||||
/// ID 6 this goes into, where the note allows 127.
|
||||
pub fn instance_postscript_name(font: &FontRef<'_>, coords: &[([u8; 4], f32)]) -> Option<String> {
|
||||
let axes = font.axes();
|
||||
// `fvar` coordinates are 16.16, so two instances can sit 1/65536 apart -- closer than
|
||||
// AXIS_EPSILON. Asking for an exact instance would then match whichever of them came first
|
||||
// and give the one asked for the other's name, so an exact match is looked for first and the
|
||||
// tolerance is only a fallback for a point that is not exactly on any instance (noted in
|
||||
// review).
|
||||
let at = |tolerance: f32| {
|
||||
let axes = &axes;
|
||||
move |ni: &skrifa::NamedInstance<'_>| {
|
||||
axes.iter().zip(ni.user_coords()).all(|(axis, value)| (effective(&axis, coords) - value).abs() <= tolerance)
|
||||
}
|
||||
};
|
||||
let exact = at(0.0);
|
||||
let near = at(AXIS_EPSILON);
|
||||
let Some(instance) = font.named_instances().iter().find(|ni| exact(ni)).or_else(|| font.named_instances().iter().find(|ni| near(ni))) else {
|
||||
return arbitrary_instance_name(font, coords);
|
||||
};
|
||||
if let Some(id) = instance.postscript_name_id()
|
||||
&& let Some(name) = string(font, id)
|
||||
{
|
||||
// The font names this instance itself, so the name is used as it stands -- a hyphen is
|
||||
// legal in a PostScript name, and `Pretendard-Heavy` is the name, not a family and a
|
||||
// subfamily to join (noted in review). Only characters a PostScript name cannot hold are
|
||||
// dropped.
|
||||
let kept = legal(&name);
|
||||
if !kept.is_empty() {
|
||||
return Some(truncate(kept));
|
||||
}
|
||||
}
|
||||
let prefix = family_prefix(font)?;
|
||||
let subfamily = string(font, instance.subfamily_name_id()).map(|s| keep(&s)).filter(|s| !s.is_empty())?;
|
||||
Some(join(&prefix, &subfamily))
|
||||
}
|
||||
|
||||
/// TN #5902's family prefix: `name` ID 25, else the typographic family (ID 16), else the family
|
||||
/// (ID 1, which OpenType says stands in for a missing ID 16), keeping ASCII letters and digits.
|
||||
fn family_prefix(font: &FontRef<'_>) -> Option<String> {
|
||||
[NameId::VARIATIONS_POSTSCRIPT_NAME_PREFIX, NameId::TYPOGRAPHIC_FAMILY_NAME, NameId::FAMILY_NAME]
|
||||
.into_iter()
|
||||
.find_map(|id| string(font, id).map(|s| keep(&s)).filter(|s| !s.is_empty()))
|
||||
}
|
||||
|
||||
/// The value of `axis` at `coords` (its default when absent), inside the axis. Compared, not
|
||||
/// `clamp`ed -- `fvar` is font data, and `f32::clamp` panics on a range whose minimum is past
|
||||
/// its maximum.
|
||||
fn effective(axis: &skrifa::Axis, coords: &[([u8; 4], f32)]) -> f32 {
|
||||
let tag = axis.tag().to_be_bytes();
|
||||
let asked = coords.iter().find(|(t, _)| *t == tag).map_or(axis.default_value(), |(_, v)| *v);
|
||||
if asked < axis.min_value() {
|
||||
axis.min_value()
|
||||
} else if asked > axis.max_value() {
|
||||
axis.max_value()
|
||||
} else {
|
||||
asked
|
||||
}
|
||||
}
|
||||
|
||||
/// TN #5902's name for a point no named instance covers: the family prefix, then `_<value><tag>`
|
||||
/// for each axis away from its default, in `fvar` order -- `AndreVar_900wght_5.5wdth`. Axes at
|
||||
/// their default are left out, as the note allows, so the default point itself has no
|
||||
/// descriptors and gets the file's `name` ID 6.
|
||||
///
|
||||
/// Returning `None` for every such point, which this did first, left all of them embedding under
|
||||
/// the default instance's name -- the bug this module is for, at any weight that is not a named
|
||||
/// one (noted in review).
|
||||
fn arbitrary_instance_name(font: &FontRef<'_>, coords: &[([u8; 4], f32)]) -> Option<String> {
|
||||
let axes = font.axes();
|
||||
if axes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let prefix = family_prefix(font)?;
|
||||
let mut name = prefix.clone();
|
||||
for axis in axes.iter() {
|
||||
let tag = axis.tag().to_be_bytes();
|
||||
let value = effective(&axis, coords);
|
||||
let fixed = to_fixed(value);
|
||||
if fixed == to_fixed(axis.default_value()) {
|
||||
continue;
|
||||
}
|
||||
name.push('_');
|
||||
name.push_str(&fixed_decimal(fixed));
|
||||
// Trailing spaces are dropped from a tag (`ital`, `wd `); anything else not a letter or
|
||||
// digit cannot be in the name either.
|
||||
name.push_str(&keep(&String::from_utf8_lossy(&tag)));
|
||||
}
|
||||
if name == prefix {
|
||||
return string(font, NameId::POSTSCRIPT_NAME).map(|s| truncate(legal(&s))).filter(|s| !s.is_empty());
|
||||
}
|
||||
if name.chars().count() <= MAX_LEN {
|
||||
return Some(name);
|
||||
}
|
||||
// TN #5902's last resort: the prefix, `-`, an identifier for this instance, and `...`.
|
||||
let id = format!("{:08X}", digest(&name));
|
||||
let room = MAX_LEN - 1 - id.len() - 3;
|
||||
Some(format!("{}-{id}...", prefix.chars().take(room).collect::<String>()))
|
||||
}
|
||||
|
||||
/// A user coordinate as `fvar`'s 16.16 fixed point. A value past `i32` saturates and NaN is 0, as
|
||||
/// `as` does; neither reaches here from a font that parsed.
|
||||
fn to_fixed(v: f32) -> i32 {
|
||||
(f64::from(v) * 65536.0).round() as i32
|
||||
}
|
||||
|
||||
/// The shortest decimal that reads back as the 16.16 value `v` (TN #5902 and its appendix): no
|
||||
/// trailing zeroes, no decimal point for a whole number, `0` for zero and no `+`. A value under
|
||||
/// one keeps the `0` before its point (`0.5`), the zero the integer part needs, not padding.
|
||||
fn fixed_decimal(v: i32) -> String {
|
||||
let x = f64::from(v) / 65536.0;
|
||||
// Sixteen fractional bits need at most six decimal places to come back exactly.
|
||||
for places in 0..=6 {
|
||||
let s = format!("{x:.places$}");
|
||||
let back = s.parse::<f64>().map(|b| (b * 65536.0).round() as i64);
|
||||
if back == Ok(i64::from(v)) {
|
||||
let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s };
|
||||
return if s == "-0" { "0".into() } else { s };
|
||||
}
|
||||
}
|
||||
format!("{x}")
|
||||
}
|
||||
|
||||
/// `prefix-subfamily`, or, when that is past [`MAX_LEN`], both halves shortened with a digest of
|
||||
/// the whole after them.
|
||||
///
|
||||
/// Both halves matter. The subfamily is what tells two instances of one family apart, so cutting
|
||||
/// its end lets `Thin` and `Thin Italic` meet; the prefix is what tells two families apart, so
|
||||
/// cutting *its* end lets `FamilyOne` and `FamilyTwo` meet. Neither can be shortened on its own
|
||||
/// and stay unique, so a name that does not fit keeps a readable piece of each and ends in a
|
||||
/// digest of `prefix-subfamily` entire -- the shape TN #5902 prescribes as a "last resort" name
|
||||
/// for an instance that cannot be named inside the limit. A PDF embedding two instances under one
|
||||
/// name is the thing this function exists to stop.
|
||||
///
|
||||
/// Shortening only one half -- what this did before -- collided two ways, both noted in review: a
|
||||
/// 62-character subfamily took a digest of the subfamily alone, so every family reached the same
|
||||
/// head and the same digest, and a 60-character one left room for two prefix characters, so
|
||||
/// `FamilyOne` and `FamilyTwo` both shortened to `Fa`.
|
||||
fn join(prefix: &str, subfamily: &str) -> String {
|
||||
let whole = format!("{prefix}-{subfamily}");
|
||||
if whole.chars().count() <= MAX_LEN {
|
||||
return whole;
|
||||
}
|
||||
// The subfamily is usually the short half, so it is served first, down to the floor the
|
||||
// prefix keeps for itself; the prefix takes what is left. The digest, not either piece, is
|
||||
// what actually keeps this name off another one.
|
||||
let sub_room = (VISIBLE - PREFIX_MIN - 1).min(subfamily.chars().count());
|
||||
let short_prefix: String = prefix.chars().take(VISIBLE - 1 - sub_room).collect();
|
||||
let short_subfamily: String = subfamily.chars().take(sub_room).collect();
|
||||
format!("{short_prefix}-{short_subfamily}-{:08x}", digest(&whole))
|
||||
}
|
||||
|
||||
/// Characters a shortened name's readable `prefix-subfamily` gets, the rest going to the digest
|
||||
/// and the hyphen before it.
|
||||
const VISIBLE: usize = MAX_LEN - DIGEST_LEN - 1;
|
||||
|
||||
/// A shortened name keeps at least this much of the prefix, so it still says which family it is.
|
||||
const PREFIX_MIN: usize = 8;
|
||||
|
||||
/// Hex characters the last-resort digest takes.
|
||||
const DIGEST_LEN: usize = 8;
|
||||
|
||||
/// FNV-1a over the whole `prefix-subfamily`, so two names that agree as far as the limit still
|
||||
/// differ. Not a security property -- only that two different strings rarely collide.
|
||||
fn digest(s: &str) -> u32 {
|
||||
s.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193))
|
||||
}
|
||||
|
||||
/// The characters a PostScript name may hold: printable ASCII except the delimiters `[](){}<>/%`
|
||||
/// and space (OpenType `name` ID 6). Used for a name the font supplies itself.
|
||||
fn legal(s: &str) -> String {
|
||||
s.chars().filter(|c| c.is_ascii_graphic() && !matches!(c, '[' | ']' | '(' | ')' | '{' | '}' | '<' | '>' | '/' | '%')).collect()
|
||||
}
|
||||
|
||||
/// A `name` table string, preferring the US English Windows record a PDF reader looks at.
|
||||
///
|
||||
/// Picking the first record of the right platform took whichever language came first, so a font
|
||||
/// whose subfamily is listed in another language before English generated its name from that
|
||||
/// one -- or from a string whose characters all drop out, leaving no name at all (noted in
|
||||
/// review). US English (0x0409 on Windows, 0 on Macintosh) is tried first.
|
||||
fn string(font: &FontRef<'_>, id: NameId) -> Option<String> {
|
||||
let name = font.name().ok()?;
|
||||
let records = name.name_record();
|
||||
let pick = |platform: u16, language: Option<u16>| {
|
||||
records.iter().find(|r| r.name_id() == id && r.platform_id() == platform && language.is_none_or(|want| r.language_id() == want))
|
||||
};
|
||||
let record = pick(3, Some(0x0409))
|
||||
.or_else(|| pick(1, Some(0)))
|
||||
.or_else(|| pick(3, None))
|
||||
.or_else(|| pick(1, None))
|
||||
.or_else(|| records.iter().find(|r| r.name_id() == id))?;
|
||||
let text = record.string(name.string_data()).ok()?.chars().collect::<String>();
|
||||
(!text.trim().is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
/// ASCII letters and digits of `s`, which is what a PostScript name may hold.
|
||||
fn keep(s: &str) -> String {
|
||||
s.chars().filter(char::is_ascii_alphanumeric).collect()
|
||||
}
|
||||
|
||||
/// `s` at most [`MAX_LEN`] characters, cut on a character boundary (the name is ASCII here, so
|
||||
/// this is a byte cut, but the font's own string need not have been).
|
||||
fn truncate(s: String) -> String {
|
||||
match s.char_indices().nth(MAX_LEN) {
|
||||
Some((at, _)) => s[..at].to_string(),
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A variable font named like Noto Sans KR: a `wght` axis and four named instances, with the
|
||||
/// family prefix in name ID 25.
|
||||
fn variable(entries: &[(u16, &str)], instances: &[(u16, Option<u16>, Vec<f32>)]) -> Vec<u8> {
|
||||
let base = crate::testing::font_with_names(entries, &['A']).expect("a font with these names");
|
||||
crate::testing::with_fvar(&base, &[(*b"wght", 100.0, 100.0, 900.0, 256)], instances).expect("an fvar")
|
||||
}
|
||||
|
||||
fn at(font: &[u8], weight: f32) -> Option<String> {
|
||||
let f = skrifa::FontRef::new(font).expect("the fixture parses");
|
||||
instance_postscript_name(&f, &[(*b"wght", weight)])
|
||||
}
|
||||
|
||||
/// `name` ID 6 names the default instance, so every weight embedded under it: the four
|
||||
/// weights of Noto Sans KR all went into the PDF as `NotoSansKR-Thin` (#1690).
|
||||
#[test]
|
||||
fn each_named_instance_has_its_own_postscript_name() {
|
||||
// 1 family, 6 the default instance's PostScript name, 25 the variations prefix,
|
||||
// 257.. the instances' subfamily names.
|
||||
let font = variable(
|
||||
&[(1, "Noto Sans KR"), (6, "NotoSansKR-Thin"), (25, "NotoSansKR"), (257, "Thin"), (258, "Regular"), (259, "Bold"), (260, "Black")],
|
||||
&[(257, None, vec![100.0]), (258, None, vec![400.0]), (259, None, vec![700.0]), (260, None, vec![900.0])],
|
||||
);
|
||||
assert_eq!(at(&font, 100.0).as_deref(), Some("NotoSansKR-Thin"));
|
||||
assert_eq!(at(&font, 400.0).as_deref(), Some("NotoSansKR-Regular"));
|
||||
assert_eq!(at(&font, 700.0).as_deref(), Some("NotoSansKR-Bold"));
|
||||
assert_eq!(at(&font, 900.0).as_deref(), Some("NotoSansKR-Black"));
|
||||
// A point between the named instances is not one of them, and is named by its value
|
||||
// (TN #5902, arbitrary instances).
|
||||
assert_eq!(at(&font, 550.0).as_deref(), Some("NotoSansKR_550wght"));
|
||||
}
|
||||
|
||||
/// An instance that names its own PostScript name uses it **as it stands**: the font is
|
||||
/// naming the instance, not handing over a family and a subfamily to join, and a hyphen is
|
||||
/// legal in a PostScript name (noted in review).
|
||||
#[test]
|
||||
fn an_instances_own_postscript_name_is_used_as_it_stands() {
|
||||
let font = variable(
|
||||
&[(1, "Pretendard Variable"), (6, "PretendardVariable-Regular"), (25, "PretendardVariable"), (257, "Bold"), (300, "Pretendard-Heavy")],
|
||||
&[(257, Some(300), vec![700.0])],
|
||||
);
|
||||
assert_eq!(at(&font, 700.0).as_deref(), Some("Pretendard-Heavy"), "the hyphen the font wrote is kept");
|
||||
|
||||
// Only the characters a PostScript name cannot hold are dropped: the delimiters and
|
||||
// spaces, not punctuation a name may carry.
|
||||
let odd = variable(&[(1, "Fixture"), (25, "Fixture"), (257, "Bold"), (300, "Fix (ture)/Bold+2_x")], &[(257, Some(300), vec![700.0])]);
|
||||
assert_eq!(at(&odd, 700.0).as_deref(), Some("FixtureBold+2_x"));
|
||||
}
|
||||
|
||||
/// Two instances must not arrive at the same name. Cutting the end of a long name would do
|
||||
/// exactly that, so the family prefix gives way and the subfamily -- the part that tells the
|
||||
/// instances apart -- is kept whole where there is room (noted in review; TN #5902 keeps the
|
||||
/// identifier for the same reason). The digest after it is what keeps the name off another
|
||||
/// family's, which shortening the prefix alone did not.
|
||||
#[test]
|
||||
fn a_long_name_keeps_the_subfamily_that_tells_instances_apart() {
|
||||
let long_prefix = "P".repeat(70);
|
||||
let font = variable(
|
||||
&[(1, "Fixture"), (25, &long_prefix), (257, "CondensedExtraBoldItalic"), (258, "CondensedExtraBoldOblique")],
|
||||
&[(257, None, vec![700.0]), (258, None, vec![800.0])],
|
||||
);
|
||||
let (a, b) = (at(&font, 700.0).expect("a name"), at(&font, 800.0).expect("a name"));
|
||||
assert!(a.len() <= MAX_LEN && b.len() <= MAX_LEN, "within the limit: {} and {}", a.len(), b.len());
|
||||
assert!(a.contains("-CondensedExtraBoldItalic-"), "the subfamily survives: {a}");
|
||||
assert!(b.contains("-CondensedExtraBoldOblique-"), "the subfamily survives: {b}");
|
||||
assert!(a.starts_with(&long_prefix[..8]) && b.starts_with(&long_prefix[..8]), "and so does enough of the family: {a}");
|
||||
assert_ne!(a, b, "two instances never share a name");
|
||||
}
|
||||
|
||||
/// A name listed in another language before English must not be the one the name is built
|
||||
/// from (noted in review).
|
||||
#[test]
|
||||
fn the_english_record_is_preferred() {
|
||||
// `with_names` writes the whole table, so every record this needs is in the one call:
|
||||
// the subfamily is listed in Japanese *before* US English for the same id.
|
||||
let base = crate::testing::font_with("Fixture", &['A']).unwrap();
|
||||
let named = crate::testing::with_names(
|
||||
&base,
|
||||
&[
|
||||
(3, 1, 0x0411, 1, "Fixture"),
|
||||
(3, 1, 0x0409, 1, "Fixture"),
|
||||
(3, 1, 0x0409, 25, "Fixture"),
|
||||
(3, 1, 0x0411, 257, "\u{592A}\u{5B57}"),
|
||||
(3, 1, 0x0409, 257, "Bold"),
|
||||
],
|
||||
)
|
||||
.expect("a name table with both languages");
|
||||
let font = crate::testing::with_fvar(&named, &[(*b"wght", 100.0, 100.0, 900.0, 256)], &[(257, None, vec![700.0])]).unwrap();
|
||||
let f = skrifa::FontRef::new(&font).unwrap();
|
||||
assert_eq!(instance_postscript_name(&f, &[(*b"wght", 700.0)]).as_deref(), Some("Fixture-Bold"));
|
||||
}
|
||||
|
||||
/// An instance with no PostScript name of its own, beside one that has one: `fvar` writes
|
||||
/// 0xFFFF for "none", and 0 would be the copyright notice's id (noted in review).
|
||||
#[test]
|
||||
fn an_instance_without_its_own_name_falls_back_to_the_generated_one() {
|
||||
let font = variable(
|
||||
&[(0, "Copyright 2026 Nobody"), (1, "Fixture"), (25, "Fixture"), (257, "Bold"), (258, "Black"), (300, "Fixture-TheBold")],
|
||||
&[(257, Some(300), vec![700.0]), (258, None, vec![900.0])],
|
||||
);
|
||||
assert_eq!(at(&font, 700.0).as_deref(), Some("Fixture-TheBold"), "the instance that names itself");
|
||||
assert_eq!(at(&font, 900.0).as_deref(), Some("Fixture-Black"), "and the one that does not is generated");
|
||||
}
|
||||
|
||||
/// Without ID 25 the typographic family is the prefix, then the family; and a name a
|
||||
/// PostScript name cannot hold keeps only its letters and digits.
|
||||
#[test]
|
||||
fn the_prefix_falls_back_and_the_name_is_sanitised() {
|
||||
let typographic = variable(&[(1, "Fixture"), (16, "Fixture Display"), (257, "Semi Bold")], &[(257, None, vec![600.0])]);
|
||||
assert_eq!(at(&typographic, 600.0).as_deref(), Some("FixtureDisplay-SemiBold"));
|
||||
|
||||
let family_only = variable(&[(1, "Fixture (Beta)"), (257, "Extra Light")], &[(257, None, vec![200.0])]);
|
||||
assert_eq!(at(&family_only, 200.0).as_deref(), Some("FixtureBeta-ExtraLight"));
|
||||
}
|
||||
|
||||
/// `name` ID 6 carries at most 63 characters.
|
||||
#[test]
|
||||
fn a_name_stays_within_the_limit() {
|
||||
let long = "L".repeat(80);
|
||||
let font = variable(&[(1, "Fixture"), (25, &long), (257, "Regular")], &[(257, None, vec![400.0])]);
|
||||
let name = at(&font, 400.0).expect("a name");
|
||||
assert!(name.len() <= MAX_LEN, "within the limit: {name}");
|
||||
// Both halves are kept, the subfamily whole here because it is short, and the digest
|
||||
// after them is what tells this name from another family's (noted in review).
|
||||
assert!(name.contains("-Regular-"), "and the subfamily is kept: {name}");
|
||||
assert!(name.starts_with(&long[..8]), "with enough of the family to name it: {name}");
|
||||
}
|
||||
|
||||
/// A static font has no named instances, so it keeps its own `name` ID 6.
|
||||
#[test]
|
||||
fn a_static_font_has_no_instance_name() {
|
||||
let base = crate::testing::font_with_names(&[(1, "Fixture"), (6, "Fixture-Regular")], &['A']).unwrap();
|
||||
let f = skrifa::FontRef::new(&base).unwrap();
|
||||
assert_eq!(instance_postscript_name(&f, &[]), None);
|
||||
}
|
||||
|
||||
/// `fvar` coordinates are 16.16, so two instances can sit 1/65536 apart -- inside
|
||||
/// AXIS_EPSILON. Asking for one of them matched whichever came first and returned the
|
||||
/// other's name (noted in review).
|
||||
#[test]
|
||||
fn two_instances_closer_than_the_tolerance_keep_their_own_names() {
|
||||
// 1.0 and 1.0 + 1/65536, one 16.16 step apart: distinct in the file and 1.5e-5 apart,
|
||||
// which is inside AXIS_EPSILON (1e-4). The axis has to be a small-numbered one for the
|
||||
// two to be different f32s at all -- at a weight of 400 a step of 1/65536 is below half
|
||||
// an ulp, so the file cannot hold two such instances there in the first place.
|
||||
let step = 1.0 / 65536.0;
|
||||
let base = crate::testing::font_with_names(&[(1, "Test"), (6, "Test-Regular"), (25, "Test"), (257, "Regular"), (258, "RegularPlus")], &['A'])
|
||||
.expect("a font with these names");
|
||||
let font = crate::testing::with_fvar(&base, &[(*b"slnt", 0.0, 1.0, 2.0, 256)], &[(257, None, vec![1.0]), (258, None, vec![1.0 + step])])
|
||||
.expect("an fvar");
|
||||
let slnt = |font: &[u8], v: f32| {
|
||||
let f = skrifa::FontRef::new(font).expect("the fixture parses");
|
||||
instance_postscript_name(&f, &[(*b"slnt", v)])
|
||||
};
|
||||
assert_ne!(1.0f32, 1.0 + step, "the two coordinates really are different numbers");
|
||||
assert_eq!(slnt(&font, 1.0).as_deref(), Some("Test-Regular"), "the exact instance wins");
|
||||
assert_eq!(slnt(&font, 1.0 + step).as_deref(), Some("Test-RegularPlus"), "and so does the one next to it");
|
||||
// A point on neither still falls back to the tolerance, which is what it is for.
|
||||
assert_eq!(slnt(&font, 1.0 + step / 2.0).as_deref(), Some("Test-Regular"), "a point in between takes the nearest match");
|
||||
}
|
||||
|
||||
/// Two instances must never arrive at one name: a PDF would then embed two different ones
|
||||
/// under it. Both halves of the name can be what tells them apart, and shortening either in
|
||||
/// isolation collided -- the subfamily's tail for two instances of a family, the prefix's for
|
||||
/// two families (both noted in review).
|
||||
#[test]
|
||||
fn two_names_that_agree_as_far_as_the_limit_still_differ() {
|
||||
// Same family, subfamilies differing only past the limit.
|
||||
let head = "A".repeat(61);
|
||||
let (a, b) = (join("Family", &format!("{head}B")), join("Family", &format!("{head}C")));
|
||||
assert_ne!(a, b, "{a} and {b} name different instances of one family");
|
||||
|
||||
// Different families, one subfamily. 62 characters took the digest path, which digested
|
||||
// the subfamily alone, so every family reached the same head and the same digest; 60 left
|
||||
// room for two prefix characters, so `FamilyOne` and `FamilyTwo` both became `Fa`.
|
||||
for len in [60, 62] {
|
||||
let sub = "A".repeat(len);
|
||||
let (one, two) = (join("FamilyOne", &sub), join("FamilyTwo", &sub));
|
||||
assert_ne!(one, two, "subfamily of {len}: {one} and {two} name different families");
|
||||
}
|
||||
|
||||
// A one-character difference anywhere in the prefix is enough, however far past the cut.
|
||||
let long = "P".repeat(80);
|
||||
let (p, q) = (join(&format!("{long}A"), "Thin"), join(&format!("{long}B"), "Thin"));
|
||||
assert_ne!(p, q, "{p} and {q} name different families");
|
||||
|
||||
// Every shortened name is inside the limit, and is a name a PDF can hold.
|
||||
for name in [a, b, p, q, join("FamilyOne", &"A".repeat(62))] {
|
||||
assert!(name.chars().count() <= MAX_LEN, "{} characters: {name}", name.chars().count());
|
||||
assert_eq!(legal(&name), name, "{name} has a character a PostScript name may not hold");
|
||||
}
|
||||
|
||||
// An ordinary name is untouched, and so is one that fits exactly.
|
||||
assert_eq!(join("NotoSansKR", "Thin"), "NotoSansKR-Thin");
|
||||
let exact = join("Family", &"A".repeat(MAX_LEN - "Family-".len()));
|
||||
assert_eq!(exact.chars().count(), MAX_LEN);
|
||||
assert!(exact.starts_with("Family-") && exact.ends_with('A'), "kept whole: {exact}");
|
||||
}
|
||||
|
||||
/// TN #5902's own examples for arbitrary instances, and the rules beside them: axes at their
|
||||
/// default are left out, the default point itself keeps `name` ID 6, and values are the
|
||||
/// shortest decimal that reads back as the same 16.16 number (noted in review).
|
||||
#[test]
|
||||
fn a_point_no_instance_names_is_named_by_its_axis_values() {
|
||||
// 16 "Andre Var" and no prefix of its own; `wght` and `wdth`, no named instances.
|
||||
let base = crate::testing::font_with_names(&[(1, "Andre Var"), (16, "Andre Var")], &['A']).expect("a font with these names");
|
||||
let font =
|
||||
crate::testing::with_fvar(&base, &[(*b"wght", -10.0, 400.0, 1000.0, 256), (*b"wdth", -10.0, 100.0, 200.0, 257)], &[]).expect("an fvar");
|
||||
let f = skrifa::FontRef::new(&font).expect("the fixture parses");
|
||||
let name = |wght: f32, wdth: f32| instance_postscript_name(&f, &[(*b"wght", wght), (*b"wdth", wdth)]);
|
||||
assert_eq!(name(900.0, 5.5).as_deref(), Some("AndreVar_900wght_5.5wdth"), "the note's example");
|
||||
assert_eq!(name(-2.9, -1.4).as_deref(), Some("AndreVar_-2.9wght_-1.4wdth"), "and its negative one");
|
||||
assert_eq!(name(900.0, 100.0).as_deref(), Some("AndreVar_900wght"), "an axis at its default is left out");
|
||||
assert_eq!(name(400.0, 100.0), None, "the default point is the one name ID 6 names");
|
||||
assert_eq!(name(5000.0, 100.0).as_deref(), Some("AndreVar_1000wght"), "a value past the axis is where the font draws it");
|
||||
// An axis the caller does not mention is at its default.
|
||||
assert_eq!(instance_postscript_name(&f, &[(*b"wdth", 150.0)]).as_deref(), Some("AndreVar_150wdth"));
|
||||
|
||||
// The shortest decimal that comes back as the same fixed value.
|
||||
assert_eq!(fixed_decimal(0), "0");
|
||||
assert_eq!(fixed_decimal(to_fixed(0.5)), "0.5");
|
||||
assert_eq!(fixed_decimal(to_fixed(-2.9)), "-2.9");
|
||||
assert_eq!(fixed_decimal(1), "0.00002", "one 65536th");
|
||||
assert_eq!(fixed_decimal(to_fixed(100.0)), "100");
|
||||
for v in [1, -1, 3, 32768, 65535, 65537, -190054, 0x7fff_ffff, -0x7fff_ffff] {
|
||||
let s = fixed_decimal(v);
|
||||
assert_eq!((s.parse::<f64>().unwrap() * 65536.0).round() as i64, i64::from(v), "{v} came back from {s}");
|
||||
assert!(!s.ends_with('0') || !s.contains('.'), "no trailing zero: {s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Too many axes for the limit: TN #5902's last resort, the prefix, an identifier and `...`,
|
||||
/// still one name per point.
|
||||
#[test]
|
||||
fn a_point_too_long_to_describe_gets_the_last_resort_name() {
|
||||
let tags: Vec<[u8; 4]> = (0..12u8).map(|i| [b'a', b'x', b'0' + i / 10, b'0' + i % 10]).collect();
|
||||
let axes: Vec<_> = tags.iter().map(|t| (*t, 0.0, 0.0, 1000.0, 256)).collect();
|
||||
let base = crate::testing::font_with_names(&[(16, "Andre Var"), (25, "AndreVar")], &['A']).expect("names");
|
||||
let font = crate::testing::with_fvar(&base, &axes, &[]).expect("an fvar");
|
||||
let f = skrifa::FontRef::new(&font).expect("the fixture parses");
|
||||
let point = |v: f32| instance_postscript_name(&f, &tags.iter().map(|t| (*t, v)).collect::<Vec<_>>()).expect("a name");
|
||||
let (a, b) = (point(123.25), point(456.5));
|
||||
for n in [&a, &b] {
|
||||
assert!(n.starts_with("AndreVar-") && n.ends_with("..."), "the last resort's shape: {n}");
|
||||
assert!(n.chars().count() <= MAX_LEN, "within the limit: {n}");
|
||||
assert_eq!(legal(n), *n, "only characters a PostScript name may hold: {n}");
|
||||
}
|
||||
assert_ne!(a, b, "two points, two names");
|
||||
}
|
||||
|
||||
/// `fvar` is font data: an axis whose minimum is past its maximum names a point without a
|
||||
/// panic (`f32::clamp` would have panicked).
|
||||
#[test]
|
||||
fn a_malformed_axis_range_does_not_panic() {
|
||||
let base = crate::testing::font_with_names(&[(16, "Odd")], &['A']).expect("names");
|
||||
let font = crate::testing::with_fvar(&base, &[(*b"wght", 900.0, 400.0, 100.0, 256)], &[]).expect("an fvar");
|
||||
let Ok(f) = skrifa::FontRef::new(&font) else { return };
|
||||
let _ = instance_postscript_name(&f, &[(*b"wght", 550.0)]);
|
||||
let _ = instance_postscript_name(&f, &[(*b"wght", f32::NAN)]);
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,42 @@ pub fn font_with_names(entries: &[(u16, &str)], chars: &[char]) -> Option<Vec<u8
|
||||
with_tables(&base, vec![(*b"name", name)])
|
||||
}
|
||||
|
||||
/// `font` with an `fvar` table: `axes` are (tag, min, default, max, axis name id) and `instances`
|
||||
/// are (subfamily name id, PostScript name id, one user coordinate per axis). Version 1.0, with
|
||||
/// the optional `postScriptNameID` present only when some instance names one.
|
||||
pub fn with_fvar(font: &[u8], axes: &[([u8; 4], f32, f32, f32, u16)], instances: &[(u16, Option<u16>, Vec<f32>)]) -> Option<Vec<u8>> {
|
||||
let fixed = |v: f32| ((v * 65536.0).round() as i32).to_be_bytes();
|
||||
let any_ps = instances.iter().any(|(_, ps, _)| ps.is_some());
|
||||
let axis_count = u16::try_from(axes.len()).ok()?;
|
||||
let instance_size = axis_count.checked_mul(4)?.checked_add(if any_ps { 6 } else { 4 })?;
|
||||
let mut t = Vec::new();
|
||||
for v in [1u16, 0, 16, 2, axis_count, 20, u16::try_from(instances.len()).ok()?, instance_size] {
|
||||
t.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
for (tag, min, def, max, name_id) in axes {
|
||||
t.extend_from_slice(tag);
|
||||
t.extend_from_slice(&fixed(*min));
|
||||
t.extend_from_slice(&fixed(*def));
|
||||
t.extend_from_slice(&fixed(*max));
|
||||
t.extend_from_slice(&0u16.to_be_bytes());
|
||||
t.extend_from_slice(&name_id.to_be_bytes());
|
||||
}
|
||||
for (subfamily, ps, coords) in instances {
|
||||
if coords.len() != axes.len() {
|
||||
return None;
|
||||
}
|
||||
t.extend_from_slice(&subfamily.to_be_bytes());
|
||||
t.extend_from_slice(&0u16.to_be_bytes());
|
||||
coords.iter().for_each(|v| t.extend_from_slice(&fixed(*v)));
|
||||
if any_ps {
|
||||
// 0xFFFF is "no PostScript name" in `fvar`; 0 is the copyright notice's name id, so
|
||||
// writing 0 made an instance look as though it named itself (noted in review).
|
||||
t.extend_from_slice(&ps.unwrap_or(0xFFFF).to_be_bytes());
|
||||
}
|
||||
}
|
||||
with_tables(font, vec![(*b"fvar", t)])
|
||||
}
|
||||
|
||||
/// Every table of the font file `font`: (tag, bytes).
|
||||
fn tables_of(font: &[u8]) -> Option<Vec<([u8; 4], Vec<u8>)>> {
|
||||
let be16 = |b: &[u8], at: usize| b.get(at..at + 2).and_then(|s| s.try_into().ok()).map(u16::from_be_bytes);
|
||||
@@ -326,3 +362,28 @@ pub fn with_meta(font: &[u8], dlng: Option<&str>, slng: Option<&str>) -> Option<
|
||||
pub fn installed_face(bytes: Vec<u8>, path: std::path::PathBuf) -> Option<crate::FontFace> {
|
||||
crate::FontDb::with_font_dirs(vec![]).new_faces(bytes, crate::FontSource::Installed(path)).into_iter().next()
|
||||
}
|
||||
|
||||
/// A synthetic weight-variable font with Regular and SemiBold named instances, using bundled outlines.
|
||||
/// Only discovery is variable; the outlines do not change with weight.
|
||||
pub fn variable_font(family: &str) -> Option<Vec<u8>> {
|
||||
let base =
|
||||
font_with_names(&[(1, family), (2, "Regular"), (6, "SyntheticVF-Regular"), (256, "Weight"), (257, "Regular"), (258, "SemiBold")], &['X'])?;
|
||||
// fvar 1.0: one weight axis and two named instances, without PostScript name IDs.
|
||||
let mut fvar = Vec::new();
|
||||
for v in [1u16, 0, 16, 2, 1, 20, 2, 8] {
|
||||
fvar.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
fvar.extend_from_slice(b"wght");
|
||||
for v in [100i32 << 16, 400 << 16, 900 << 16] {
|
||||
fvar.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
for v in [0u16, 256] {
|
||||
fvar.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
for (id, weight) in [(257u16, 400i32), (258, 600)] {
|
||||
fvar.extend_from_slice(&id.to_be_bytes());
|
||||
fvar.extend_from_slice(&0u16.to_be_bytes());
|
||||
fvar.extend_from_slice(&(weight << 16).to_be_bytes());
|
||||
}
|
||||
with_tables(&base, vec![(*b"fvar", fvar)])
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ pub(super) fn p(name: &str, ty: &str, val: impl Into<String>) -> El {
|
||||
|
||||
/// Insert a `<Properties>` element as the first child when there are any.
|
||||
pub(super) fn with_props(el: El, props: Vec<El>) -> El {
|
||||
crate::xml::from_craft(craft_idml::with_props(crate::xml::to_craft(&el), props.into_iter().map(|p| crate::xml::to_craft(&p)).collect()))
|
||||
crate::xml::from_craft_for_write(craft_idml::with_props(crate::xml::to_craft(&el), props.into_iter().map(|p| crate::xml::to_craft(&p)).collect()))
|
||||
}
|
||||
|
||||
pub(super) fn pkg_root(kind: &str) -> El {
|
||||
|
||||
@@ -318,7 +318,7 @@ fn layer_el(l: &designcraft_doc::Layer) -> El {
|
||||
.attr("Locked", bool_s(l.locked))
|
||||
.attr("IgnoreWrap", bool_s(l.suppress_wrap_when_hidden))
|
||||
.attr("ShowGuides", bool_s(l.show_guides))
|
||||
.attr("LockGuides", "false")
|
||||
.attr("LockGuides", bool_s(l.lock_guides))
|
||||
.attr("UI", "true")
|
||||
.attr("Expendable", "true")
|
||||
.attr("Printable", bool_s(l.printable));
|
||||
|
||||
@@ -489,6 +489,7 @@ impl<'r> Importer<'r> {
|
||||
locked: e.get("Locked") == Some("true"),
|
||||
printable: e.get("Printable") != Some("false"),
|
||||
show_guides: e.get("ShowGuides") != Some("false"),
|
||||
lock_guides: e.get("LockGuides") == Some("true"),
|
||||
suppress_wrap_when_hidden: e.get("IgnoreWrap") == Some("true"),
|
||||
});
|
||||
if let Some(s) = e.get("Self") {
|
||||
@@ -507,6 +508,7 @@ impl<'r> Importer<'r> {
|
||||
locked: false,
|
||||
printable: true,
|
||||
show_guides: true,
|
||||
lock_guides: false,
|
||||
suppress_wrap_when_hidden: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -160,15 +160,11 @@ impl<'r> Importer<'r> {
|
||||
if r >= nr || c >= nc {
|
||||
continue;
|
||||
}
|
||||
let (mut cs, mut rs) = model_cell.span();
|
||||
if model_cell.values.get("RowSpan").is_some_and(|v| v.eq_ignore_ascii_case("inf") || v.eq_ignore_ascii_case("infinity")) {
|
||||
rs = (nr - r) as u32;
|
||||
}
|
||||
if model_cell.values.get("ColumnSpan").is_some_and(|v| v.eq_ignore_ascii_case("inf") || v.eq_ignore_ascii_case("infinity")) {
|
||||
cs = (nc - c) as u32;
|
||||
}
|
||||
let rs = (rs as usize).min(nr - r);
|
||||
let cs = (cs as usize).min(nc - c);
|
||||
// Preserve the prior importer behavior for malformed positive spans such as `inf`:
|
||||
// saturate the float-to-integer conversion, then clamp before grid arithmetic.
|
||||
let span = |key| model_cell.values.prop(key).and_then(|v| v.trim().parse::<f64>().ok()).unwrap_or(1.0).max(1.0) as usize;
|
||||
let rs = span("RowSpan").min(nr - r);
|
||||
let cs = span("ColumnSpan").min(nc - c);
|
||||
let mut cell = t.cell(r, c).cloned().unwrap_or_default();
|
||||
let cell_el = crate::xml::from_craft(model_cell.to_el());
|
||||
let cell_style =
|
||||
|
||||
@@ -2688,6 +2688,25 @@ fn layers_import_and_export_in_stacking_order() {
|
||||
assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);
|
||||
}
|
||||
|
||||
/// Layer Options › Lock Guides is IDML's `LockGuides`: read, and written back (it was always
|
||||
/// written as false).
|
||||
#[test]
|
||||
fn layer_lock_guides_round_trips() {
|
||||
let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
|
||||
<Layer Self="L1" Name="Grid" LockGuides="true" ShowGuides="true"/>
|
||||
<Layer Self="L2" Name="Art"/>
|
||||
<idPkg:Spread src="Spreads/Spread_s.xml"/>
|
||||
</Document>"#;
|
||||
let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
|
||||
<Spread Self="s"><Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/></Spread>
|
||||
</idPkg:Spread>"#;
|
||||
let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap();
|
||||
let lock = |d: &Document, name: &str| d.layers.iter().find(|l| l.name == name).unwrap().lock_guides;
|
||||
assert!(lock(&d, "Grid") && !lock(&d, "Art"));
|
||||
let back = import_idml(&export_idml(&d)).unwrap();
|
||||
assert!(lock(&back, "Grid") && !lock(&back, "Art"));
|
||||
}
|
||||
|
||||
/// Synthetic forward references: both a body anchor and a footnote anchor own
|
||||
/// a group containing a text frame whose story is serialized later.
|
||||
#[test]
|
||||
@@ -3126,6 +3145,22 @@ fn hostile_table_spans_are_clamped_before_arithmetic() {
|
||||
assert_eq!(table.cell(1, 1).unwrap().col_span, 2);
|
||||
}
|
||||
|
||||
/// Spans are read as numbers: a fraction rounds down, a span past the table (even one too large for
|
||||
/// 32 bits) reaches its edge, and anything under 1 or not a number spans one cell.
|
||||
#[test]
|
||||
fn numeric_table_spans_round_down_and_stop_at_the_table_edge() {
|
||||
for (raw, rows, cols) in
|
||||
[("1.5", 1, 1), ("2.5", 2, 2), ("4000000000", 2, 3), ("1e300", 2, 3), ("0", 1, 1), ("-3", 1, 1), ("NaN", 1, 1), ("x", 1, 1)]
|
||||
{
|
||||
let story = CASCADE_STORY.replace("Name=\"0:0\"", &format!("Name=\"0:0\" RowSpan=\"{raw}\" ColumnSpan=\"{raw}\""));
|
||||
let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();
|
||||
document.check().unwrap();
|
||||
let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
|
||||
let cell = table.cell(0, 0).unwrap();
|
||||
assert_eq!((cell.row_span, cell.col_span), (rows, cols), "{raw}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_idml_edge_priorities_roundtrip_without_clamping() {
|
||||
let story = CASCADE_STORY.replace(
|
||||
|
||||
+23
-4
@@ -227,6 +227,16 @@ pub fn parse(bytes: &[u8]) -> Result<El, String> {
|
||||
}
|
||||
|
||||
pub(crate) fn from_craft(el: craft_xml::El) -> El {
|
||||
from_craft_with_cdata(el, false)
|
||||
}
|
||||
|
||||
/// Convert shared XML trees back into the writer's tree without losing CDATA boundaries.
|
||||
/// Parsing deliberately folds CDATA into text, but write-side model composition must retain it.
|
||||
pub(crate) fn from_craft_for_write(el: craft_xml::El) -> El {
|
||||
from_craft_with_cdata(el, true)
|
||||
}
|
||||
|
||||
fn from_craft_with_cdata(el: craft_xml::El, preserve_cdata: bool) -> El {
|
||||
El {
|
||||
name: el.name,
|
||||
attrs: el.attrs,
|
||||
@@ -234,11 +244,10 @@ pub(crate) fn from_craft(el: craft_xml::El) -> El {
|
||||
.children
|
||||
.into_iter()
|
||||
.filter_map(|n| match n {
|
||||
craft_xml::Node::El(e) => Some(Node::El(from_craft(e))),
|
||||
craft_xml::Node::El(e) => Some(Node::El(from_craft_with_cdata(e, preserve_cdata))),
|
||||
craft_xml::Node::Text(t) => Some(Node::Text(t)),
|
||||
// The parser joins CDATA to the text around it, so only trees built for export
|
||||
// (`<Contents>` image data passed through `with_props`) carry sections here.
|
||||
craft_xml::Node::CData(t) => Some(Node::CData(t)),
|
||||
craft_xml::Node::CData(t) if preserve_cdata => Some(Node::CData(t)),
|
||||
craft_xml::Node::CData(t) => Some(Node::Text(t)),
|
||||
craft_xml::Node::Pi { target, data } => Some(Node::Pi(target, data.trim().to_string())),
|
||||
craft_xml::Node::Comment(_) => None,
|
||||
})
|
||||
@@ -250,6 +259,16 @@ pub(crate) fn from_craft(el: craft_xml::El) -> El {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parsed_cdata_is_text_but_write_conversion_preserves_its_boundary() {
|
||||
let tree = craft_xml::El { name: "Contents".into(), attrs: Vec::new(), children: vec![craft_xml::Node::CData("JVBERi0=".into())] };
|
||||
assert_eq!(from_craft(tree.clone()).children, vec![Node::Text("JVBERi0=".into())]);
|
||||
|
||||
let written = from_craft_for_write(tree);
|
||||
assert_eq!(written.children, vec![Node::CData("JVBERi0=".into())]);
|
||||
assert!(String::from_utf8(document(&written)).unwrap().contains("<![CDATA[JVBERi0=]]>"));
|
||||
}
|
||||
|
||||
/// Issue #712: nesting past the budget is an error from the parser, not a stack overflow later.
|
||||
#[test]
|
||||
fn nesting_past_the_budget_is_refused() {
|
||||
|
||||
@@ -402,7 +402,7 @@ pub fn decode_rgba(bytes: &[u8]) -> Option<image::RgbaImage> {
|
||||
}
|
||||
let decoded = craft_image_codecs::decode_with(bytes, &decode_options()).ok()?;
|
||||
if decoded.layout().is_cmyk() {
|
||||
let raster = cmyk_raster(&decoded, bytes)?;
|
||||
let raster = cmyk_raster(&decoded)?;
|
||||
return to_display_rgba(Pixels::Cmyk(raster), decoded.icc.as_deref(), &DisplayColour::active());
|
||||
}
|
||||
let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8())?;
|
||||
@@ -479,39 +479,20 @@ fn decode_options() -> craft_image_codecs::DecodeOptions {
|
||||
craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits { max_alloc: MAX_RGBA_BYTES, ..Default::default() }, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Whether an APP14 "Adobe" segment comes before the image data.
|
||||
fn adobe_marker(bytes: &[u8]) -> bool {
|
||||
let mut i = 2;
|
||||
while let Some(&[0xFF, marker, hi, lo]) = bytes.get(i..i + 4).and_then(|s| <&[u8; 4]>::try_from(s).ok()) {
|
||||
// Start of scan or end of image: no more header segments.
|
||||
if marker == 0xDA || marker == 0xD9 {
|
||||
return false;
|
||||
}
|
||||
let len = usize::from(u16::from_be_bytes([hi, lo]));
|
||||
if marker == 0xEE && bytes.get(i + 4..i + 9) == Some(b"Adobe".as_slice()) {
|
||||
return true;
|
||||
}
|
||||
i += 2 + len;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn cmyk_raster(image: &craft_image_codecs::Image, bytes: &[u8]) -> Option<CmykRaster> {
|
||||
/// Convert the shared decoder's CMYK values to the app's ink raster without changing their
|
||||
/// polarity. `craft-image-codecs` already interprets Adobe-marked and unmarked JPEG CMYK and
|
||||
/// YCCK samples; inverting unmarked JPEGs here reverses their documented device-ink values.
|
||||
fn cmyk_raster(image: &craft_image_codecs::Image) -> Option<CmykRaster> {
|
||||
let converted = image.convert(craft_image_codecs::ChannelLayout::CmykA, craft_image_codecs::SampleType::U8);
|
||||
let pixels = usize::try_from(converted.width()).ok()?.checked_mul(usize::try_from(converted.height()).ok()?)?;
|
||||
let data = converted.as_u8()?;
|
||||
if data.len() != pixels.checked_mul(5)? {
|
||||
return None;
|
||||
}
|
||||
let invert = bytes.starts_with(&[0xFF, 0xD8]) && !adobe_marker(bytes);
|
||||
let mut cmyk = Vec::with_capacity(pixels.checked_mul(4)?);
|
||||
let mut alpha = Vec::with_capacity(pixels);
|
||||
for &[c, m, y, k, a] in data.as_chunks::<5>().0 {
|
||||
if invert {
|
||||
cmyk.extend([255 - c, 255 - m, 255 - y, 255 - k]);
|
||||
} else {
|
||||
cmyk.extend([c, m, y, k]);
|
||||
}
|
||||
cmyk.extend([c, m, y, k]);
|
||||
alpha.push(a);
|
||||
}
|
||||
let alpha = alpha.iter().any(|&a| a < 255).then_some(alpha);
|
||||
@@ -609,7 +590,7 @@ pub fn decode_cmyk_tiff(bytes: &[u8]) -> Option<CmykRaster> {
|
||||
return None;
|
||||
}
|
||||
let image = craft_image_codecs::decode_with(bytes, &decode_options()).ok()?;
|
||||
image.layout().is_cmyk().then(|| cmyk_raster(&image, bytes)).flatten()
|
||||
image.layout().is_cmyk().then(|| cmyk_raster(&image)).flatten()
|
||||
}
|
||||
|
||||
/// An SVG rasterised so its longer side is `max_side` pixels: premultiplied RGBA8.
|
||||
|
||||
@@ -1053,3 +1053,54 @@ fn reduced_decoding_refuses_progressive_jpegs_whose_full_size_coefficients_are_o
|
||||
let gray = decode_rgba_reduced(&progressive_jpeg(10_240, 8_800, 1), 3).unwrap();
|
||||
assert_eq!(gray.dimensions(), (1_280, 1_100));
|
||||
}
|
||||
|
||||
/// Planar CMYK TIFFs and CMYK TIFFs with associated (premultiplied) alpha keep their inks through
|
||||
/// the shared decoder, so the PDF export's RGB fallback is only for other inks and oversized files.
|
||||
#[test]
|
||||
fn planar_and_premultiplied_cmyk_tiffs_keep_their_inks() {
|
||||
use tiff::encoder::colortype::CMYKA8;
|
||||
// 2×1, PlanarConfiguration 2: one strip per ink, 100% K then C0 M100 Y100 K0.
|
||||
let (bps, offsets, counts, data) = (134u32, 142u32, 158u32, 174u32);
|
||||
let entries: [(u16, u16, u32, u32); 10] = [
|
||||
(256, 4, 1, 2), // width
|
||||
(257, 4, 1, 1), // height
|
||||
(258, 3, 4, bps), // bits per sample
|
||||
(259, 3, 1, 1), // no compression
|
||||
(262, 3, 1, 5), // separated (CMYK)
|
||||
(273, 4, 4, offsets), // strip offsets
|
||||
(277, 3, 1, 4), // samples per pixel
|
||||
(278, 4, 1, 1), // rows per strip
|
||||
(279, 4, 4, counts), // strip byte counts
|
||||
(284, 3, 1, 2), // planar
|
||||
];
|
||||
let mut t = b"II*\0".to_vec();
|
||||
t.extend(8u32.to_le_bytes());
|
||||
t.extend(10u16.to_le_bytes());
|
||||
for (tag, kind, count, value) in entries {
|
||||
t.extend(tag.to_le_bytes());
|
||||
t.extend(kind.to_le_bytes());
|
||||
t.extend(count.to_le_bytes());
|
||||
t.extend(value.to_le_bytes());
|
||||
}
|
||||
t.extend(0u32.to_le_bytes());
|
||||
assert_eq!(t.len(), bps as usize);
|
||||
t.extend([8u16; 4].iter().flat_map(|b| b.to_le_bytes()));
|
||||
t.extend((0..4u32).flat_map(|i| (data + 2 * i).to_le_bytes()));
|
||||
t.extend([2u32; 4].iter().flat_map(|c| c.to_le_bytes()));
|
||||
assert_eq!(t.len(), data as usize);
|
||||
t.extend([0, 0, 0, 255, 0, 255, 255, 0]);
|
||||
assert!(is_cmyk_tiff(&t));
|
||||
assert_eq!(decode_cmyk_tiff(&t), Some(CmykRaster { width: 2, height: 1, cmyk: vec![0, 0, 0, 255, 0, 255, 255, 0], alpha: None }));
|
||||
|
||||
// ExtraSamples 1 (associated alpha): the second pixel is C0 M100 Y100 K0 at half coverage.
|
||||
let mut b = Vec::new();
|
||||
let mut enc = tiff::encoder::TiffEncoder::new(std::io::Cursor::new(&mut b)).unwrap();
|
||||
let mut img = enc.new_image::<CMYKA8>(2, 1).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap();
|
||||
img.write_data(&[0, 0, 0, 255, 255, 0, 128, 128, 0, 128]).unwrap();
|
||||
let r = decode_cmyk_tiff(&b).expect("a CMYK TIFF with associated alpha keeps its inks");
|
||||
assert_eq!(r.alpha, Some(vec![255, 128]));
|
||||
assert_eq!(&r.cmyk[..4], &[0, 0, 0, 255]);
|
||||
let straight = &r.cmyk[4..];
|
||||
assert!(straight[0] <= 1 && straight[1] >= 254 && straight[2] >= 254 && straight[3] <= 1, "made straight: {straight:?}");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources methods.
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
use std::io::{BufRead, Read, Write};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -18,6 +18,30 @@ const INVALID_PARAMS: i64 = -32602;
|
||||
const INTERNAL_ERROR: i64 = -32603;
|
||||
const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
|
||||
/// Most bytes one request line may hold. A client that never sends a newline must not grow the
|
||||
/// reader's buffer without bound (audit: DesignCraft #3).
|
||||
const MAX_LINE_BYTES: u64 = 4 << 20;
|
||||
|
||||
/// Drop the rest of an over-long request line without buffering it.
|
||||
fn discard_line(input: &mut impl BufRead) -> std::io::Result<()> {
|
||||
loop {
|
||||
let (consume, done) = {
|
||||
let available = input.fill_buf()?;
|
||||
if available.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
match available.iter().position(|&b| b == b'\n') {
|
||||
Some(i) => (i + 1, true),
|
||||
None => (available.len(), false),
|
||||
}
|
||||
};
|
||||
input.consume(consume);
|
||||
if done {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTRUCTIONS: &str = "DesignCraft is a page-layout app (an InDesign clone). Coordinates are points in spread \
|
||||
space (y down; on a single-page spread the page's top-left is (0,0); a default Letter page is 612×792). Every action \
|
||||
is a command: find ids and parameters with list_commands and run them with execute (or several with batch). Typical \
|
||||
@@ -63,9 +87,23 @@ impl Server {
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
buf.clear();
|
||||
if input.read_until(b'\n', &mut buf)? == 0 {
|
||||
// A client that never sends a newline must not grow this buffer without bound
|
||||
// (audit: DesignCraft #3). Read one byte past the limit, then drop the rest.
|
||||
if (&mut input).take(MAX_LINE_BYTES + 1).read_until(b'\n', &mut buf)? == 0 {
|
||||
break;
|
||||
}
|
||||
if buf.len() as u64 > MAX_LINE_BYTES {
|
||||
// The terminator may already be in `buf` (a line exactly at the limit); only a
|
||||
// line cut before its newline leaves a rest to drop.
|
||||
if buf.last() != Some(&b'\n') {
|
||||
discard_line(&mut input)?;
|
||||
}
|
||||
let reply = serde_json::to_vec(&error(Value::Null, INVALID_REQUEST, "request line is too long")).map_err(std::io::Error::other)?;
|
||||
output.write_all(&reply)?;
|
||||
output.write_all(b"\n")?;
|
||||
output.flush()?;
|
||||
continue;
|
||||
}
|
||||
// Invalid UTF-8 becomes U+FFFD, so the line gets a parse error instead of ending the stream.
|
||||
let line = String::from_utf8_lossy(&buf);
|
||||
let line = line.trim_end_matches(['\r', '\n']);
|
||||
|
||||
@@ -98,6 +98,47 @@ fn serve_survives_invalid_utf8_line() {
|
||||
assert_eq!(lines[3]["id"], 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_rejects_an_over_long_line_and_keeps_serving() {
|
||||
let mut s = server();
|
||||
let mut input = vec![b'x'; 4 << 20];
|
||||
input.push(b'\n');
|
||||
input.extend_from_slice(json!({"jsonrpc":"2.0","id":7,"method":"ping"}).to_string().as_bytes());
|
||||
input.push(b'\n');
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_slice(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
assert_eq!(lines[0]["error"]["code"], -32600);
|
||||
assert_eq!(lines[1]["id"], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_discards_the_rest_of_an_over_long_line_without_a_newline() {
|
||||
let mut s = server();
|
||||
let mut input = vec![b'x'; (4 << 20) + 10];
|
||||
input.push(b'\n');
|
||||
input.extend_from_slice(json!({"jsonrpc":"2.0","id":8,"method":"ping"}).to_string().as_bytes());
|
||||
input.push(b'\n');
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_slice(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
assert_eq!(lines[0]["error"]["code"], -32600);
|
||||
assert_eq!(lines[1]["id"], 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_stops_at_eof_in_an_over_long_line() {
|
||||
let mut s = server();
|
||||
let input = vec![b'x'; (4 << 20) + 10];
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_slice(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
assert_eq!(lines[0]["error"]["code"], -32600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_round_trip_over_serve() {
|
||||
let mut s = server();
|
||||
|
||||
+37
-2
@@ -11,6 +11,13 @@ use krilla::outline::{Outline, OutlineNode};
|
||||
|
||||
use crate::export::Sheet;
|
||||
|
||||
/// A URL a PDF link annotation may carry. Only ordinary web and mail schemes are written; a
|
||||
/// `javascript:`, `data:`, `file:` or custom scheme is left out rather than embedded in the PDF
|
||||
/// (audit: DesignCraft #4).
|
||||
fn allowed_link(url: &str) -> Option<&str> {
|
||||
designcraft_doc::is_safe_link_url(url).then_some(url)
|
||||
}
|
||||
|
||||
/// Index of the output sheet showing absolute page `abs`.
|
||||
pub(crate) fn sheet_of_page(doc: &Document, sheets: &[Sheet], abs: usize) -> Option<usize> {
|
||||
let (si, pi) = doc.page_loc(abs)?;
|
||||
@@ -67,7 +74,10 @@ pub(crate) fn annotations(doc: &Document, cache: &designcraft_compose::Cache, sh
|
||||
);
|
||||
let Some(rect) = rect else { continue };
|
||||
let target = match &h.dest {
|
||||
HyperlinkDest::Url(u) => Target::Action(Action::Link(LinkAction::new(u.clone()))),
|
||||
HyperlinkDest::Url(u) => match allowed_link(u) {
|
||||
Some(u) => Target::Action(Action::Link(LinkAction::new(u.to_string()))),
|
||||
None => continue,
|
||||
},
|
||||
HyperlinkDest::Email(e) => Target::Action(Action::Link(LinkAction::new(format!("mailto:{e}")))),
|
||||
HyperlinkDest::Page(p) => match sheet_of_page(doc, sheets, *p) {
|
||||
Some(i) => Target::Destination(XyzDestination::new(i, krilla::geom::Point::from_xy(0.0, 0.0)).into()),
|
||||
@@ -101,8 +111,9 @@ pub(crate) fn annotations(doc: &Document, cache: &designcraft_compose::Cache, sh
|
||||
let total = doc.page_count();
|
||||
let page = match action {
|
||||
B::GoToUrl { url } => {
|
||||
let Some(url) = allowed_link(url) else { continue };
|
||||
out.push(Annotation::new_link(
|
||||
LinkAnnotation::new(rect, Target::Action(Action::Link(LinkAction::new(url.clone())))),
|
||||
LinkAnnotation::new(rect, Target::Action(Action::Link(LinkAction::new(url.to_string())))),
|
||||
Some(it.name.clone()),
|
||||
));
|
||||
continue;
|
||||
@@ -165,3 +176,27 @@ pub(crate) fn outline(doc: &Document, sheets: &[Sheet]) -> Option<Outline> {
|
||||
}
|
||||
Some(o)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::allowed_link;
|
||||
|
||||
#[test]
|
||||
fn only_web_and_mail_schemes_become_link_annotations() {
|
||||
for ok in ["https://example.com", "HTTP://example.com", "mailto:a@b.example"] {
|
||||
assert_eq!(allowed_link(ok), Some(ok));
|
||||
}
|
||||
for bad in [
|
||||
"javascript:alert(1)",
|
||||
"JavaScript:alert(1)",
|
||||
"data:text/html,x",
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.com",
|
||||
"vbscript:x",
|
||||
"example.com",
|
||||
"",
|
||||
] {
|
||||
assert_eq!(allowed_link(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,6 +267,29 @@ fn tables_export_cell_text() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_diagonal_lines_export_in_front_of_or_behind_the_cell_text() {
|
||||
let export = |lines, in_front| {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let mut t = designcraft_doc::Table::new(9, 1, 1, 0, 0, 200.0);
|
||||
let cell = t.cell_mut(0, 0).unwrap();
|
||||
cell.text.insert(0, "Ink");
|
||||
let stroke = designcraft_doc::CellStroke { weight: 3.0, ..Default::default() };
|
||||
cell.diagonal = designcraft_doc::CellDiagonal { lines, stroke, in_front };
|
||||
d.story_mut(sid).unwrap().insert_table(0, t);
|
||||
let bytes = export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap();
|
||||
// The table's edges are 1 pt; the diagonals are the 3 pt strokes.
|
||||
paint_order(&bytes).into_iter().filter(|(op, w)| op.ends_with("text") || *w == 3.0).map(|(op, _)| op).collect::<Vec<_>>()
|
||||
};
|
||||
use designcraft_doc::DiagonalLines;
|
||||
let (text, line) = ("fill text".to_string(), "stroke path".to_string());
|
||||
assert_eq!(export(DiagonalLines::None, true), [text.clone(), text.clone(), text.clone()]);
|
||||
assert_eq!(export(DiagonalLines::Crossed, true), [text.clone(), text.clone(), text.clone(), line.clone(), line.clone()], "Diagonal In Front");
|
||||
assert_eq!(export(DiagonalLines::TopLeft, false), [line.clone(), text.clone(), text.clone(), text.clone()], "Content In Front");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_cap_text_extracts_in_order() {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
@@ -758,6 +781,40 @@ fn small_caps_and_small_cap_figures_extract_as_typed() {
|
||||
assert!(uncompressed(&d, PdfOptions::default()).contains("/ActualText"));
|
||||
}
|
||||
|
||||
/// Links and buttons from an imported document still go through the export allowlist.
|
||||
#[test]
|
||||
fn link_annotation_export_refuses_non_web_schemes() {
|
||||
use designcraft_doc::{ButtonAction, Hyperlink, HyperlinkDest, HyperlinkSource, Shape};
|
||||
use designcraft_geom::shapes::rectangle;
|
||||
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
let safe = ItemId(d.alloc());
|
||||
let mut safe_item = Item::new(safe, lid, Shape::Rectangle, rectangle(Rect::new(72.0, 72.0, 200.0, 120.0)));
|
||||
safe_item.button = Some(ButtonAction::GoToUrl { url: "https://example.com/button".into() });
|
||||
d.insert_item(SpreadRef::Doc(0), safe_item, None).unwrap();
|
||||
let unsafe_id = ItemId(d.alloc());
|
||||
let mut unsafe_item = Item::new(unsafe_id, lid, Shape::Rectangle, rectangle(Rect::new(72.0, 200.0, 200.0, 248.0)));
|
||||
unsafe_item.button = Some(ButtonAction::GoToUrl { url: "file:///etc/passwd".into() });
|
||||
d.insert_item(SpreadRef::Doc(0), unsafe_item, None).unwrap();
|
||||
d.hyperlinks.push(Hyperlink {
|
||||
id: 1,
|
||||
name: "bad".into(),
|
||||
source: HyperlinkSource::Item { id: safe },
|
||||
dest: HyperlinkDest::Url("javascript:alert(1)".into()),
|
||||
});
|
||||
d.hyperlinks.push(Hyperlink {
|
||||
id: 2,
|
||||
name: "good".into(),
|
||||
source: HyperlinkSource::Item { id: safe },
|
||||
dest: HyperlinkDest::Url("https://example.com/link".into()),
|
||||
});
|
||||
let s = uncompressed(&d, PdfOptions::default());
|
||||
assert!(s.contains("https://example.com/button") && s.contains("https://example.com/link"), "safe links export: {s}");
|
||||
assert!(!s.contains("file:///etc/passwd"), "a file URL is not exported: {s}");
|
||||
assert!(!s.contains("javascript:"), "a javascript URL is not exported: {s}");
|
||||
}
|
||||
|
||||
/// A clipping path on a placed image becomes a clip in the page content, inside the frame's.
|
||||
#[test]
|
||||
fn clipping_path_clips_the_image() {
|
||||
|
||||
+75
-59
@@ -370,72 +370,88 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
for c in &t.cells {
|
||||
if !c.diagonals_in_front {
|
||||
self.cell_diagonals(s, c);
|
||||
}
|
||||
self.table_cell(s, c);
|
||||
if c.diagonals_in_front {
|
||||
self.cell_diagonals(s, c);
|
||||
}
|
||||
}
|
||||
for seg in &t.strokes {
|
||||
let st = &seg.stroke;
|
||||
let Some(col) = self.swatch_color(&st.color, st.tint) else { continue };
|
||||
let kind = self.doc.stroke_kind(&st.kind);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(seg.a);
|
||||
bp.line_to(seg.b);
|
||||
let Some(p) = to_path(&bp) else { continue };
|
||||
// Butt-ended fills close the table's corners the way square caps do.
|
||||
let (ca, cb) = t.corner_capped(seg);
|
||||
let mut capped = BezPath::new();
|
||||
capped.move_to(ca);
|
||||
capped.line_to(cb);
|
||||
let Some(cp) = to_path(&capped) else { continue };
|
||||
// Gap colour under dashes, dots and stripes: the whole edge, solid.
|
||||
if !matches!(kind, designcraft_doc::StrokeType::Solid)
|
||||
&& st.gap_color != designcraft_color::swatch::NONE
|
||||
&& let Some(gap) = self.swatch_color(&st.gap_color, st.gap_tint)
|
||||
{
|
||||
s.set_fill(None);
|
||||
s.set_stroke(Some(Stroke {
|
||||
paint: gap.into(),
|
||||
width: st.weight as f32,
|
||||
line_cap: krilla::paint::LineCap::Butt,
|
||||
..Default::default()
|
||||
}));
|
||||
s.draw_path(&cp);
|
||||
s.set_stroke(None);
|
||||
}
|
||||
// Stripes, wavy and hash types are fills along the edge.
|
||||
if let Some(o) = kind.outline(&capped, st.weight, 0.05)
|
||||
&& let Some(op) = to_path(&o)
|
||||
{
|
||||
s.set_stroke(None);
|
||||
s.set_fill(Some(solid_fill(col, 1.0)));
|
||||
s.draw_path(&op);
|
||||
s.set_fill(None);
|
||||
continue;
|
||||
}
|
||||
let (cap, dash) = match &kind {
|
||||
designcraft_doc::StrokeType::Dashed { pattern }
|
||||
if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) =>
|
||||
{
|
||||
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
|
||||
if pat.len() % 2 == 1 {
|
||||
pat.extend(pat.clone());
|
||||
}
|
||||
(krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 }))
|
||||
}
|
||||
designcraft_doc::StrokeType::Dotted
|
||||
if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) =>
|
||||
{
|
||||
(krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }))
|
||||
}
|
||||
_ => (krilla::paint::LineCap::Square, None),
|
||||
};
|
||||
s.set_fill(None);
|
||||
s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() }));
|
||||
s.draw_path(&p);
|
||||
s.set_stroke(None);
|
||||
self.cell_stroke(s, seg, t.corner_capped(seg));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cell's diagonal lines, clipped to the cell so their caps stay inside it.
|
||||
fn cell_diagonals(&mut self, s: &mut Surface, c: &designcraft_compose::PlacedCell) {
|
||||
if c.diagonals.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(clip) = to_path(&c.rect.to_path(0.1)) else { return };
|
||||
s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero);
|
||||
for seg in &c.diagonals {
|
||||
self.cell_stroke(s, seg, (seg.a, seg.b));
|
||||
}
|
||||
s.pop();
|
||||
}
|
||||
|
||||
/// One cell edge or diagonal: the gap color, then the stroke type. `capped` holds the ends the
|
||||
/// butt-ended fills (stripes, wavy, hash, the gap color) run between.
|
||||
fn cell_stroke(&mut self, s: &mut Surface, seg: &designcraft_compose::StrokeSeg, capped: (designcraft_geom::Point, designcraft_geom::Point)) {
|
||||
let st = &seg.stroke;
|
||||
let Some(col) = self.swatch_color(&st.color, st.tint) else { return };
|
||||
let kind = self.doc.stroke_kind(&st.kind);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(seg.a);
|
||||
bp.line_to(seg.b);
|
||||
let Some(p) = to_path(&bp) else { return };
|
||||
// Butt-ended fills close the table's corners the way square caps do.
|
||||
let (ca, cb) = capped;
|
||||
let mut capped = BezPath::new();
|
||||
capped.move_to(ca);
|
||||
capped.line_to(cb);
|
||||
let Some(cp) = to_path(&capped) else { return };
|
||||
// Gap colour under dashes, dots and stripes: the whole edge, solid.
|
||||
if !matches!(kind, designcraft_doc::StrokeType::Solid)
|
||||
&& st.gap_color != designcraft_color::swatch::NONE
|
||||
&& let Some(gap) = self.swatch_color(&st.gap_color, st.gap_tint)
|
||||
{
|
||||
s.set_fill(None);
|
||||
s.set_stroke(Some(Stroke { paint: gap.into(), width: st.weight as f32, line_cap: krilla::paint::LineCap::Butt, ..Default::default() }));
|
||||
s.draw_path(&cp);
|
||||
s.set_stroke(None);
|
||||
}
|
||||
// Stripes, wavy and hash types are fills along the edge.
|
||||
if let Some(o) = kind.outline(&capped, st.weight, 0.05)
|
||||
&& let Some(op) = to_path(&o)
|
||||
{
|
||||
s.set_stroke(None);
|
||||
s.set_fill(Some(solid_fill(col, 1.0)));
|
||||
s.draw_path(&op);
|
||||
s.set_fill(None);
|
||||
return;
|
||||
}
|
||||
let (cap, dash) = match &kind {
|
||||
designcraft_doc::StrokeType::Dashed { pattern } if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) => {
|
||||
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
|
||||
if pat.len() % 2 == 1 {
|
||||
pat.extend(pat.clone());
|
||||
}
|
||||
(krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 }))
|
||||
}
|
||||
designcraft_doc::StrokeType::Dotted if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) => {
|
||||
(krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }))
|
||||
}
|
||||
_ => (krilla::paint::LineCap::Square, None),
|
||||
};
|
||||
s.set_fill(None);
|
||||
s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() }));
|
||||
s.draw_path(&p);
|
||||
s.set_stroke(None);
|
||||
}
|
||||
|
||||
fn fill_rect(&self, s: &mut Surface, r: Rect, c: krilla::color::Color) {
|
||||
self.fill_path(s, &r.to_path(0.1), c);
|
||||
}
|
||||
|
||||
+13
-16
@@ -13,6 +13,14 @@ use crate::fonts::Fonts;
|
||||
use crate::model::{Media, Slide};
|
||||
use crate::{PptxError, PptxOptions, Result};
|
||||
|
||||
/// Preserve fractional DesignCraft opacity in DrawingML instead of rounding it through 8-bit alpha.
|
||||
pub(crate) fn color_with_opacity(color: designcraft_color::Color, opacity: f32) -> craft_pptx::ColorRef {
|
||||
let [r, g, b, _] = color.to_rgba8(1.0);
|
||||
let color = craft_pptx::ColorRef::rgb(craft_pptx::Rgba::rgb(r, g, b));
|
||||
let alpha = (f64::from(opacity.clamp(0.0, 1.0)) * 100_000.0).round() as i32;
|
||||
if alpha == 100_000 { color } else { color.with(craft_pptx::ColorTransform::Alpha(alpha)) }
|
||||
}
|
||||
|
||||
/// Objects PowerPoint can't show as editable objects, which a caller should rasterise before
|
||||
/// exporting: placed PDF and EPS graphics, type on a path, and effects without a DrawingML
|
||||
/// counterpart.
|
||||
@@ -362,20 +370,9 @@ impl<'a> Exporter<'a> {
|
||||
pub(crate) fn model_color(&self, swatch: &str, tint: f32, alpha: f32) -> Option<craft_pptx::ColorRef> {
|
||||
if let Some(gradient) = resolve_gradient(&self.doc.swatches, swatch) {
|
||||
let (_, color, gradient_alpha) = gradient.expanded_stops().into_iter().next()?;
|
||||
let total_alpha = gradient_alpha * alpha;
|
||||
let [r, g, b, _] = color.to_rgba8(1.0);
|
||||
let mut c = craft_pptx::ColorRef::rgb(craft_pptx::Rgba::rgb(r, g, b));
|
||||
if total_alpha < 1.0 {
|
||||
c = c.with(craft_pptx::ColorTransform::Alpha((total_alpha * 100_000.0).round() as i32));
|
||||
}
|
||||
return Some(c);
|
||||
return Some(color_with_opacity(color, gradient_alpha * alpha));
|
||||
}
|
||||
let [r, g, b, _] = self.doc.resolve_color(swatch, tint)?.to_rgba8(1.0);
|
||||
let mut c = craft_pptx::ColorRef::rgb(craft_pptx::Rgba::rgb(r, g, b));
|
||||
if alpha < 1.0 {
|
||||
c = c.with(craft_pptx::ColorTransform::Alpha((alpha * 100_000.0).round() as i32));
|
||||
}
|
||||
Some(c)
|
||||
Some(color_with_opacity(self.doc.resolve_color(swatch, tint)?, alpha))
|
||||
}
|
||||
|
||||
fn model_fill(&mut self, fill: &designcraft_doc::Fill, closed: bool, opacity: f32) -> craft_pptx::Fill {
|
||||
@@ -389,9 +386,9 @@ impl<'a> Exporter<'a> {
|
||||
let stops = gradient
|
||||
.expanded_stops()
|
||||
.into_iter()
|
||||
.map(|(offset, color, alpha)| {
|
||||
let [r, g, b, a] = color.to_rgba8(alpha * opacity);
|
||||
craft_pptx::style::GradientStop { pos: f64::from(offset), color: craft_pptx::ColorRef::rgb(craft_pptx::Rgba::rgba(r, g, b, a)) }
|
||||
.map(|(offset, color, alpha)| craft_pptx::style::GradientStop {
|
||||
pos: f64::from(offset),
|
||||
color: color_with_opacity(color, alpha * opacity),
|
||||
})
|
||||
.collect();
|
||||
let shape = match gradient.kind {
|
||||
|
||||
@@ -167,6 +167,9 @@ fn table(ex: &mut Exporter, t: &TableFrag, m: Affine, k: f64, opacity: f32) {
|
||||
if t.cells.iter().any(|c| c.graphic.is_some()) {
|
||||
ex.warn("graphic cells are exported empty");
|
||||
}
|
||||
if t.cells.iter().any(|c| !c.diagonals.is_empty() && !c.diagonals_in_front) {
|
||||
ex.warn("diagonal lines drawn behind cell contents are exported without that drawing order");
|
||||
}
|
||||
let edges_of = EdgeIndex::new(&t.strokes);
|
||||
let id = ex.id();
|
||||
let mut model = craft_pptx::table::Table {
|
||||
@@ -223,6 +226,10 @@ fn table(ex: &mut Exporter, t: &TableFrag, m: Affine, k: f64, opacity: f32) {
|
||||
edges_of.stroke(a, b)
|
||||
};
|
||||
cell.borders = ['L', 'R', 'T', 'B'].map(|side| Some(model_border(ex, edge(side), k, opacity)));
|
||||
// Cell Options › Diagonal Lines.
|
||||
let diagonal = |down: bool| placed.diagonals.iter().find(|s| ((s.a.x < s.b.x) == (s.a.y < s.b.y)) == down);
|
||||
cell.diag_down = diagonal(true).map(|seg| model_border(ex, Some(seg), k, opacity));
|
||||
cell.diag_up = diagonal(false).map(|seg| model_border(ex, Some(seg), k, opacity));
|
||||
}
|
||||
}
|
||||
ex.native_shapes.push(craft_pptx::Shape {
|
||||
|
||||
@@ -397,13 +397,11 @@ pub(crate) fn model_body(ex: &mut Exporter, seg: &Segment, k: f64, opacity: f32,
|
||||
fn color(ex: &Exporter, swatch: &str, tint: f32, opacity: f32) -> Option<craft_pptx::ColorRef> {
|
||||
let color = if let Some(gradient) = resolve_gradient(&ex.doc.swatches, swatch) {
|
||||
let (_, color, alpha) = gradient.expanded_stops().into_iter().next()?;
|
||||
let [r, g, b, a] = color.to_rgba8(alpha * opacity);
|
||||
craft_pptx::Rgba::rgba(r, g, b, a)
|
||||
return Some(crate::slide::color_with_opacity(color, alpha * opacity));
|
||||
} else {
|
||||
let [r, g, b, a] = ex.doc.resolve_color(swatch, tint)?.to_rgba8(opacity);
|
||||
craft_pptx::Rgba::rgba(r, g, b, a)
|
||||
ex.doc.resolve_color(swatch, tint)?
|
||||
};
|
||||
Some(craft_pptx::ColorRef::rgb(color))
|
||||
Some(crate::slide::color_with_opacity(color, opacity))
|
||||
}
|
||||
|
||||
fn run_props(ex: &mut Exporter, run: Option<&Run>, size: f64, k: f64, opacity: f32) -> craft_pptx::text::RunProps {
|
||||
|
||||
@@ -547,6 +547,55 @@ fn table_edges_paint_gap_colour_between_dashes_and_stripes() {
|
||||
assert!(column.iter().any(|p| ink(*p)) && column.iter().any(|p| cyan(*p)), "stripes and gap: {column:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_diagonal_lines_draw_in_front_of_or_behind_the_cell_text() {
|
||||
let render = |lines, in_front| {
|
||||
let mut d = Document::new(&NewDocument::default());
|
||||
let lid = d.default_layer();
|
||||
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap();
|
||||
let mut t = designcraft_doc::Table::new(1, 1, 1, 0, 0, 200.0);
|
||||
t.rows[0].height = 60.0;
|
||||
t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly;
|
||||
let cell = t.cell_mut(0, 0).unwrap();
|
||||
cell.text.insert(0, "WWWWWWWWWWWWWWWWWWWW");
|
||||
cell.text.format_chars(0..20, |f| f.over.size = Some(30.0));
|
||||
let stroke = designcraft_doc::CellStroke { weight: 6.0, color: "C=100 M=0 Y=0 K=0".into(), ..Default::default() };
|
||||
cell.diagonal = designcraft_doc::CellDiagonal { lines, stroke, in_front };
|
||||
d.story_mut(sid).unwrap().insert_table(0, t);
|
||||
let cache = Cache::new();
|
||||
let rect = cache.get(&d, sid, None).frames[0].tables[0].cell(0, 0).unwrap().rect;
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 0;
|
||||
let img = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();
|
||||
let cyan = |p: [u8; 4]| p[0] < 80 && p[2] > 150;
|
||||
let inside = |x: f64, y: f64| x > rect.x0 + 4.0 && x < rect.x1 - 4.0 && y > rect.y0 + 4.0 && y < rect.y1 - 4.0;
|
||||
let count = |a: (f64, f64), b: (f64, f64)| {
|
||||
(0..=200)
|
||||
.map(|i| (a.0 + (b.0 - a.0) * i as f64 / 200.0, a.1 + (b.1 - a.1) * i as f64 / 200.0))
|
||||
.filter(|&(x, y)| inside(x, y) && cyan(img.pixel(x as u32, y as u32)))
|
||||
.count()
|
||||
};
|
||||
let down = count((rect.x0, rect.y0), (rect.x1, rect.y1));
|
||||
let up = count((rect.x1, rect.y0), (rect.x0, rect.y1));
|
||||
// Just past the corner, outside the cell.
|
||||
let outside = img.pixel((rect.x1 + 2.0) as u32, (rect.y1 + 2.0) as u32);
|
||||
(down, up, cyan(outside))
|
||||
};
|
||||
use designcraft_doc::DiagonalLines;
|
||||
assert_eq!(render(DiagonalLines::None, true), (0, 0, false));
|
||||
let (down, up, outside) = render(DiagonalLines::Crossed, true);
|
||||
assert!(down > 150 && up > 150 && !outside, "crossed: {down} {up} {outside}");
|
||||
let (down, up, _) = render(DiagonalLines::TopLeft, true);
|
||||
// The other diagonal meets this one only where they cross, near the middle.
|
||||
assert!(down > 150 && up < 40, "top left to bottom right: {down} {up}");
|
||||
let (down, up, _) = render(DiagonalLines::TopRight, true);
|
||||
assert!(down < 40 && up > 150, "top right to bottom left: {down} {up}");
|
||||
// The text covers part of the line drawn behind it.
|
||||
let (behind, _, _) = render(DiagonalLines::TopLeft, false);
|
||||
let (front, _, _) = render(DiagonalLines::TopLeft, true);
|
||||
assert!(behind + 10 < front, "content in front: {behind} vs {front}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_dash_patterns_draw_solid_and_fill_types_close_table_corners() {
|
||||
let fine = designcraft_doc::StrokeType::Dashed { pattern: vec![1e-6, 1e-6] };
|
||||
|
||||
+47
-22
@@ -498,6 +498,9 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
for c in &t.cells {
|
||||
if !c.diagonals_in_front {
|
||||
draw_cell_diagonals(ctx, f, xf, c);
|
||||
}
|
||||
if let Some(g) = &c.graphic {
|
||||
ctx.set_transform(f.view * xf);
|
||||
ctx.push_clip_layer(&c.clip.to_path(0.1));
|
||||
@@ -507,36 +510,58 @@ impl Renderer {
|
||||
} else if let Some(cft) = c.text.frames.first() {
|
||||
self.draw_text(ctx, f, &c.text, cft, xf * Affine::translate(c.origin.to_vec2()));
|
||||
}
|
||||
if c.diagonals_in_front {
|
||||
draw_cell_diagonals(ctx, f, xf, c);
|
||||
}
|
||||
}
|
||||
ctx.set_transform(f.view * xf);
|
||||
for s in &t.strokes {
|
||||
let Some(col) = doc.resolve_color(&s.stroke.color, s.stroke.tint) else { continue };
|
||||
let kind = doc.stroke_kind(&s.stroke.kind);
|
||||
let line = kurbo::Line::new(s.a, s.b).to_path(0.1);
|
||||
// Butt-ended fills close the table's corners the way square caps do.
|
||||
let (ca, cb) = t.corner_capped(s);
|
||||
let capped = kurbo::Line::new(ca, cb).to_path(0.1);
|
||||
// Gap colour under dashes, dots and stripes: the whole edge, solid.
|
||||
if !matches!(kind, designcraft_doc::StrokeType::Solid)
|
||||
&& let Some(gap) = doc.resolve_color(&s.stroke.gap_color, s.stroke.gap_tint)
|
||||
{
|
||||
ctx.set_paint(color_of(&gap, 1.0));
|
||||
ctx.set_stroke(kurbo::Stroke::new(s.stroke.weight).with_caps(kurbo::Cap::Butt));
|
||||
ctx.stroke_path(&capped);
|
||||
}
|
||||
ctx.set_paint(color_of(&col, 1.0));
|
||||
// Stripes, wavy and hash types are fills along the edge.
|
||||
if let Some(o) = kind.outline(&capped, s.stroke.weight, 0.05 * f.px) {
|
||||
ctx.fill_path(&o);
|
||||
continue;
|
||||
}
|
||||
ctx.set_stroke(cell_stroke(&kind, s.stroke.weight, s.a.distance(s.b)));
|
||||
ctx.stroke_path(&line);
|
||||
draw_cell_stroke(ctx, f, s, t.corner_capped(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cell's diagonal lines, clipped to the cell so their caps stay inside it.
|
||||
fn draw_cell_diagonals(ctx: &mut RenderContext, f: &Frame, xf: Affine, c: &designcraft_compose::PlacedCell) {
|
||||
if c.diagonals.is_empty() {
|
||||
return;
|
||||
}
|
||||
ctx.set_transform(f.view * xf);
|
||||
ctx.push_clip_layer(&c.rect.to_path(0.1));
|
||||
for s in &c.diagonals {
|
||||
draw_cell_stroke(ctx, f, s, (s.a, s.b));
|
||||
}
|
||||
ctx.pop_layer();
|
||||
}
|
||||
|
||||
/// One cell edge or diagonal: the gap color, then the stroke type. `capped` holds the ends the
|
||||
/// butt-ended fills (stripes, wavy, hash, the gap color) run between.
|
||||
fn draw_cell_stroke(ctx: &mut RenderContext, f: &Frame, s: &designcraft_compose::StrokeSeg, capped: (kurbo::Point, kurbo::Point)) {
|
||||
let doc = f.doc;
|
||||
let Some(col) = doc.resolve_color(&s.stroke.color, s.stroke.tint) else { return };
|
||||
let kind = doc.stroke_kind(&s.stroke.kind);
|
||||
let line = kurbo::Line::new(s.a, s.b).to_path(0.1);
|
||||
// Butt-ended fills close the table's corners the way square caps do.
|
||||
let capped = kurbo::Line::new(capped.0, capped.1).to_path(0.1);
|
||||
// Gap colour under dashes, dots and stripes: the whole edge, solid.
|
||||
if !matches!(kind, designcraft_doc::StrokeType::Solid)
|
||||
&& let Some(gap) = doc.resolve_color(&s.stroke.gap_color, s.stroke.gap_tint)
|
||||
{
|
||||
ctx.set_paint(color_of(&gap, 1.0));
|
||||
ctx.set_stroke(kurbo::Stroke::new(s.stroke.weight).with_caps(kurbo::Cap::Butt));
|
||||
ctx.stroke_path(&capped);
|
||||
}
|
||||
ctx.set_paint(color_of(&col, 1.0));
|
||||
// Stripes, wavy and hash types are fills along the edge.
|
||||
if let Some(o) = kind.outline(&capped, s.stroke.weight, 0.05 * f.px) {
|
||||
ctx.fill_path(&o);
|
||||
return;
|
||||
}
|
||||
ctx.set_stroke(cell_stroke(&kind, s.stroke.weight, s.a.distance(s.b)));
|
||||
ctx.stroke_path(&line);
|
||||
}
|
||||
|
||||
/// A run's stroke colour, if it has one.
|
||||
fn stroke_of(doc: &designcraft_doc::Document, st: &designcraft_compose::RunStyle) -> Option<TextPaint> {
|
||||
if st.stroke == designcraft_color::swatch::NONE {
|
||||
|
||||
@@ -319,6 +319,7 @@ fn plain_blocks(blocks: &[std::sync::Arc<Block>]) -> String {
|
||||
out.push('\n');
|
||||
}
|
||||
first = false;
|
||||
// The importer accepts tracked changes: deletions are left out, inline objects expanded.
|
||||
let text = p.final_text();
|
||||
let is_break = |c: char| matches!(c, designcraft_doc::PAGE_BREAK | designcraft_doc::COLUMN_BREAK);
|
||||
out.push_str(&text.chars().map(|c| if is_break(c) { '\n' } else { c }).collect::<String>());
|
||||
|
||||
@@ -256,6 +256,31 @@ fn imports_styles_runs_footnotes_and_tables() {
|
||||
assert_eq!(i.char_styles[0].chars.font_style.as_deref(), Some("Italic"));
|
||||
}
|
||||
|
||||
/// Word stores its built-in heading names in lower case (`heading 1`); they come in under the
|
||||
/// name Word shows, `Heading 1`, as in v0.21.0.
|
||||
#[test]
|
||||
fn built_in_headings_take_the_name_word_shows() {
|
||||
let styles = format!(
|
||||
r#"<w:styles {W}>
|
||||
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="Heading9"><w:name w:val="heading 9"/></w:style>
|
||||
</w:styles>"#
|
||||
);
|
||||
let document = format!(
|
||||
r#"<w:document {W}><w:body>
|
||||
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>One</w:t></w:r></w:p>
|
||||
<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Two</w:t></w:r></w:p>
|
||||
<w:p><w:pPr><w:pStyle w:val="Heading9"/></w:pPr><w:r><w:t>Nine</w:t></w:r></w:p>
|
||||
</w:body></w:document>"#
|
||||
);
|
||||
let i = import(&docx(&document, &styles, "")).unwrap();
|
||||
let used: Vec<&str> = i.story.paras.iter().map(|p| p.style.as_str()).collect();
|
||||
assert_eq!(used, ["Heading 1", "Heading 2", "Heading 9"]);
|
||||
let names: Vec<&str> = i.para_styles.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Heading 1", "Heading 2", "Heading 9"]);
|
||||
}
|
||||
|
||||
/// A content control inside a paragraph (`w:sdt`) keeps its text, also around a hyperlink.
|
||||
#[test]
|
||||
fn inline_content_control_text_is_kept() {
|
||||
|
||||
@@ -38,9 +38,11 @@ fn sheet_cells(
|
||||
let mut cut = false;
|
||||
let result = package.sheet(entry, |row| {
|
||||
for cell in row.cells {
|
||||
let value = match &cell.value {
|
||||
craft_xlsx::CellValue::Invalid(s) => s.clone(),
|
||||
other => display(other.resolve(&strings, date_1904)),
|
||||
let value = match cell.value {
|
||||
// A value that doesn't read as its type says (`inf`, `n/a` in a number cell) is
|
||||
// shown as written, as the importer did before the shared reader.
|
||||
craft_xlsx::CellValue::Invalid(raw) => raw,
|
||||
value => display(value.resolve(&strings, date_1904)),
|
||||
};
|
||||
text_bytes = text_bytes.saturating_add(value.len());
|
||||
if cells.len() >= max_cells || text_bytes > max_text_bytes {
|
||||
@@ -418,6 +420,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_cells_that_are_not_numbers_show_as_written() {
|
||||
for text in ["inf", "Infinity", "NaN", "n/a", "12 apples"] {
|
||||
let book = one_value(&format!(r#"<c r="A2"><v>{text}</v></c>"#));
|
||||
let rows = crate::xlsx_records(&book, None).unwrap();
|
||||
assert_eq!(rows[1][0], text, "cell {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_string_values_are_not_reformatted_as_numbers() {
|
||||
for text in ["00123", "1e3", "12.0", " 42 "] {
|
||||
|
||||
@@ -247,7 +247,12 @@ fn draw_inverse_highlight(
|
||||
let skew =
|
||||
if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
|
||||
let shatai = style.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY);
|
||||
let ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
let mut ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
if ft.vertical
|
||||
&& let Some(turn) = g.vertical_xf(l.baseline)
|
||||
{
|
||||
ga = turn * ga;
|
||||
}
|
||||
rc.set_transform(view * *m * ga);
|
||||
rc.fill_path(&outline);
|
||||
}
|
||||
|
||||
@@ -408,7 +408,18 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest
|
||||
let fields = p.get("fields").cloned().unwrap_or(Value::Null);
|
||||
let d = match id {
|
||||
"frameSize" => crate::dialogs::frame_size_dialog(app, fields),
|
||||
// Bound to the target cells and document, as Table › Cell Options › Diagonal Lines… opens it.
|
||||
"diagonalLines" => match crate::dialogs::diagonal_lines_dialog(app, fields) {
|
||||
Ok(d) => d,
|
||||
Err(e) => return err(e),
|
||||
},
|
||||
"contactSheet" => crate::dialogs::contact_sheet_dialog(app, fields),
|
||||
"fittingOptions" => {
|
||||
let mut d = crate::dialogs::Dialog::new(id, fields);
|
||||
d.unit = app.session.active().map_or(designcraft_geom::Unit::Picas, |s| s.doc.settings.horizontal_units);
|
||||
d.vertical_unit = Some(d.unit);
|
||||
d
|
||||
}
|
||||
_ => crate::dialogs::Dialog::new(id, fields),
|
||||
};
|
||||
let v = serde_json::to_value(&d).unwrap_or_default();
|
||||
@@ -537,6 +548,25 @@ mod automation_contract_tests {
|
||||
app.run("style.paragraph.edit", json!({"name":designcraft_doc::BASIC_PARAGRAPH,"chars":{"size":18}})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);
|
||||
}
|
||||
#[test]
|
||||
fn diagonal_lines_opened_through_the_control_channel_applies_to_its_target_cells() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
|
||||
let response = call(&mut app, &ctx, "ui.dialog.open", json!({"id": "diagonalLines", "fields": {"lines": "crossed"}}));
|
||||
assert_eq!(response["ok"], true, "{response}");
|
||||
app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap();
|
||||
let response = call(&mut app, &ctx, "ui.dialog.confirm", json!({}));
|
||||
assert_eq!(response["ok"], true, "{response}");
|
||||
let st = app.session.active().unwrap();
|
||||
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
|
||||
let lines: Vec<_> = t.cells.iter().map(|c| c.diagonal.lines).collect();
|
||||
use designcraft_doc::DiagonalLines::{Crossed, None as No};
|
||||
assert_eq!(lines, [Crossed, No, No, No]);
|
||||
}
|
||||
|
||||
/// `ui.dialog.open` opens Place Contact Sheet as the menu does: bare numbers are in the
|
||||
/// document's ruler unit, so `1` on an inch document is an inch, not a pica.
|
||||
#[test]
|
||||
|
||||
+510
-42
@@ -26,6 +26,10 @@ pub struct Dialog {
|
||||
/// from when it opened, so a bare `50` means what it did then. `None` falls back to `unit`.
|
||||
#[serde(skip)]
|
||||
pub vertical_unit: Option<Unit>,
|
||||
/// The document contents the dialog opened with (Diagonal Lines), held while it is open: an
|
||||
/// edit replaces them, so a dialog whose document holds other contents knows it was edited.
|
||||
#[serde(skip)]
|
||||
pub contents: Option<std::sync::Arc<designcraft_doc::Document>>,
|
||||
}
|
||||
|
||||
impl Dialog {
|
||||
@@ -86,7 +90,7 @@ impl Dialog {
|
||||
if id == "ruby" {
|
||||
fields.entry("section".to_string()).or_insert(json!("cjk.rubyPlacement"));
|
||||
}
|
||||
Dialog { id: id.into(), fields, unit: Unit::Picas, vertical_unit: None }
|
||||
Dialog { id: id.into(), fields, unit: Unit::Picas, vertical_unit: None, contents: None }
|
||||
}
|
||||
/// Set a field and report a genuine Find domain/mode transition to the caller.
|
||||
pub(crate) fn set_field(&mut self, key: &str, value: Value) -> bool {
|
||||
@@ -3272,7 +3276,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
|
||||
// The menu items' translations (every language has them), without the ellipsis.
|
||||
"convertTextToTable" => crate::i18n::tr(&app.ui.language, "Convert Text to Table…").trim_end_matches('…').trim_end(),
|
||||
"convertTableToText" => crate::i18n::tr(&app.ui.language, "Convert Table to Text…").trim_end_matches('…').trim_end(),
|
||||
"cellOptions" => crate::i18n::tr(&app.ui.language, "Cell Options"),
|
||||
"cellOptions" | "diagonalLines" => crate::i18n::tr(&app.ui.language, "Cell Options"),
|
||||
"createGuides" => crate::i18n::tr(&app.ui.language, "Create Guides"),
|
||||
"marginsAndColumns" => crate::i18n::tr(&app.ui.language, "Margins and Columns"),
|
||||
"textFrameOptions" => crate::i18n::tr(&app.ui.language, "Text Frame Options"),
|
||||
@@ -4082,12 +4086,12 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
|
||||
egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {
|
||||
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
|
||||
text_field(ui, &mut d, k, 70.0);
|
||||
measure_field(ui, &mut d, k, 70.0);
|
||||
}
|
||||
ui.end_row();
|
||||
for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {
|
||||
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
|
||||
text_field(ui, &mut d, k, 70.0);
|
||||
measure_field(ui, &mut d, k, 70.0);
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
@@ -4161,6 +4165,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
|
||||
"insertTable" => insert_table_dialog(app, ui, &mut d),
|
||||
"convertTextToTable" | "convertTableToText" => convert_table_dialog(app, ui, &mut d),
|
||||
"cellOptions" => cell_options(app, ui, &mut d),
|
||||
"diagonalLines" => diagonal_lines(app, ui, &mut d),
|
||||
"createGuides" => create_guides_dialog(app, ui, &mut d),
|
||||
"marginsAndColumns" => margins_and_columns_dialog(app, ui, &mut d),
|
||||
"textFrameOptions" => {
|
||||
@@ -4362,7 +4367,7 @@ fn cell_options_edges_changed(app: &mut DesignApp, d: &mut Dialog, edges: &crate
|
||||
let v = cur.get(k).cloned().unwrap_or(Value::Null);
|
||||
// Null shows mixed values; the user can't type it.
|
||||
let field = d.fields.get(k).filter(|f| !f.is_null());
|
||||
if field.is_none() || field == seed.get(k) {
|
||||
if field.is_none_or(|f| same_cell_value(seed.get(k), k, f)) {
|
||||
d.fields.insert(k.into(), v.clone());
|
||||
}
|
||||
seed.insert(k.into(), v);
|
||||
@@ -4370,13 +4375,19 @@ fn cell_options_edges_changed(app: &mut DesignApp, d: &mut Dialog, edges: &crate
|
||||
d.fields.insert("seed".into(), Value::Object(seed));
|
||||
}
|
||||
|
||||
/// Whether the dialog field `k` holds the cells' value `seed`. The Type list picks a stroke type
|
||||
/// by name (`"solid"`), and the cells' value is the type itself (`{"kind": "solid"}`).
|
||||
fn same_cell_value(seed: Option<&Value>, k: &str, v: &Value) -> bool {
|
||||
seed == Some(v) || (k == "type" && v.as_str().is_some_and(|name| seed == Some(&json!({"kind": name}))))
|
||||
}
|
||||
|
||||
/// Apply the Cell Options fields that differ from the cells' values, as one `table.setCell`.
|
||||
fn confirm_cell_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {
|
||||
let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
|
||||
let mut stroke = Map::new();
|
||||
let mut params = Map::new();
|
||||
for (k, is_stroke) in CELL_OPTION_KEYS {
|
||||
let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && seed.get(k) != Some(*v)) else { continue };
|
||||
let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && !same_cell_value(seed.get(k), k, v)) else { continue };
|
||||
match (is_stroke, k) {
|
||||
(true, _) => {
|
||||
stroke.insert(k.into(), v.clone());
|
||||
@@ -4399,6 +4410,170 @@ fn confirm_cell_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String
|
||||
app.run("table.setCell", Value::Object(params))
|
||||
}
|
||||
|
||||
/// The line buttons of Cell Options › Diagonal Lines: the `diagonal.lines` name and its label.
|
||||
const DIAGONAL_LINES: [(&str, &str); 4] = [
|
||||
("none", "No Diagonal Lines"),
|
||||
("topLeft", "Diagonal Line from Top Left to Bottom Right"),
|
||||
("topRight", "Diagonal Line from Top Right to Bottom Left"),
|
||||
("crossed", "Crossed Diagonal Lines"),
|
||||
];
|
||||
|
||||
/// Cell Options › Diagonal Lines keys (`table.getCellDiagonal` names).
|
||||
const DIAGONAL_KEYS: [&str; 8] = ["lines", "weight", "type", "color", "tint", "gapColor", "gapTint", "inFront"];
|
||||
|
||||
/// Table › Cell Options › Diagonal Lines… for the target cells. The fields start from the
|
||||
/// cells' values (`seed`); OK applies the fields that differ from it. The dialog keeps the
|
||||
/// document it opened in (`document`: uid and identity epoch, and `Dialog::contents`) and its
|
||||
/// target cells (`cells`).
|
||||
pub fn open_diagonal_lines(app: &mut DesignApp) -> Result<Value, String> {
|
||||
app.ui.dialog = Some(diagonal_lines_dialog(app, Value::Null)?);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The Diagonal Lines dialog for the target cells, with the `DIAGONAL_KEYS` values in `params`
|
||||
/// (from `ui.dialog.open`) entered in place of the cells' values.
|
||||
pub fn diagonal_lines_dialog(app: &mut DesignApp, params: Value) -> Result<Dialog, String> {
|
||||
let cur = app.session.execute("table.getCellDiagonal", &json!({})).map_err(|e| e.to_string())?;
|
||||
let st = app.session.active().ok_or("no document open")?;
|
||||
let document = json!({"uid": st.uid, "epoch": st.identity_epoch});
|
||||
let contents = st.doc.clone();
|
||||
let mut fields = Map::new();
|
||||
for k in DIAGONAL_KEYS {
|
||||
fields.insert(k.into(), cur[k].clone());
|
||||
}
|
||||
fields.insert("seed".into(), Value::Object(fields.clone()));
|
||||
for k in DIAGONAL_KEYS {
|
||||
if let Some(v) = params.get(k) {
|
||||
fields.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
fields.insert("document".into(), document);
|
||||
fields.insert("cells".into(), json!({"story": cur["story"], "table": cur["table"], "rows": cur["rows"], "cols": cur["cols"]}));
|
||||
let mut d = Dialog::new("diagonalLines", Value::Object(fields));
|
||||
d.contents = Some(contents);
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// Where the document a Diagonal Lines dialog opened in is now.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum DiagonalLinesDocument {
|
||||
/// Active and unchanged since the dialog opened.
|
||||
Ready,
|
||||
/// Open, but another document is active.
|
||||
Inactive,
|
||||
/// Active, but edited since the dialog opened: the saved cell range may name other cells.
|
||||
Changed,
|
||||
/// Closed or reverted.
|
||||
Gone,
|
||||
}
|
||||
|
||||
/// An edit gives the document new contents, and a selection change keeps them. The dialog holds
|
||||
/// the contents it opened with, so no new contents can take their address while it is open.
|
||||
fn diagonal_lines_document(app: &DesignApp, d: &Dialog) -> DiagonalLinesDocument {
|
||||
let saved = d.fields.get("document");
|
||||
let get = |k: &str| saved.and_then(|s| s.get(k)).and_then(Value::as_u64);
|
||||
let (Some(uid), Some(epoch), Some(contents)) = (get("uid"), get("epoch"), d.contents.as_ref()) else {
|
||||
return DiagonalLinesDocument::Gone;
|
||||
};
|
||||
let Some(i) = app.session.documents().iter().position(|st| st.uid == uid && st.identity_epoch == epoch) else {
|
||||
return DiagonalLinesDocument::Gone;
|
||||
};
|
||||
if app.session.active_index() != Some(i) {
|
||||
DiagonalLinesDocument::Inactive
|
||||
} else if !std::sync::Arc::ptr_eq(&app.session.documents()[i].doc, contents) {
|
||||
DiagonalLinesDocument::Changed
|
||||
} else {
|
||||
DiagonalLinesDocument::Ready
|
||||
}
|
||||
}
|
||||
|
||||
/// Cell Options › Diagonal Lines: the four line buttons, the Line Stroke fields and Draw.
|
||||
fn diagonal_lines(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let lang = app.ui.language.clone();
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
for (name, label) in DIAGONAL_LINES {
|
||||
let on = d.fields.get("lines").and_then(Value::as_str) == Some(name);
|
||||
let text = crate::i18n::tr(&lang, label).to_string();
|
||||
let (r, resp) = ui.allocate_exact_size(egui::vec2(32.0, 32.0), egui::Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, &text));
|
||||
let resp = resp.on_hover_text(&text);
|
||||
if resp.clicked() {
|
||||
d.fields.insert("lines".into(), json!(name));
|
||||
}
|
||||
// Enter on a focused line button picks that line and leaves the dialog open.
|
||||
if resp.has_focus() {
|
||||
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
|
||||
}
|
||||
let p = ui.painter();
|
||||
p.rect_filled(r, 2.0, if resp.hovered() { t.hover } else { t.input });
|
||||
let cell = r.shrink(7.0);
|
||||
p.rect_stroke(cell, 0.0, egui::Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside);
|
||||
let ink = egui::Stroke::new(1.5, if on { t.accent } else { t.icon });
|
||||
if matches!(name, "topLeft" | "crossed") {
|
||||
p.line_segment([cell.left_top(), cell.right_bottom()], ink);
|
||||
}
|
||||
if matches!(name, "topRight" | "crossed") {
|
||||
p.line_segment([cell.right_top(), cell.left_bottom()], ink);
|
||||
}
|
||||
let rim = if on { egui::Stroke::new(2.0, t.accent) } else { egui::Stroke::new(1.0, t.field_border) };
|
||||
p.rect_stroke(r, 2.0, rim, egui::StrokeKind::Inside);
|
||||
}
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Line Stroke")).font(semibold(12.0)));
|
||||
let values = Value::Object(d.fields.clone());
|
||||
if let Some((k, v)) = crate::panels::cell_stroke::stroke_fields(app, ui, "diagonal_lines", &values) {
|
||||
d.fields.insert(k.into(), v);
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
egui::Grid::new("diagonal_draw").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
crate::rtl::label(ui, crate::i18n::tr(&lang, "Draw:"));
|
||||
let shown = match d.fields.get("inFront").and_then(Value::as_bool) {
|
||||
Some(true) => crate::i18n::tr(&lang, "Diagonal In Front"),
|
||||
Some(false) => crate::i18n::tr(&lang, "Content In Front"),
|
||||
None => "",
|
||||
}
|
||||
.to_string();
|
||||
craft_ui::ComboBox::from_id_salt("diagonal_draw_order").selected_text(crate::rtl::widget(ui, &shown)).width(140.0).show_ui(ui, |ui| {
|
||||
for (front, label) in [(true, "Diagonal In Front"), (false, "Content In Front")] {
|
||||
let text = crate::i18n::tr(&lang, label);
|
||||
if ui.selectable_label(shown == text, crate::rtl::widget(ui, text)).clicked() {
|
||||
d.fields.insert("inFront".into(), json!(front));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply the Diagonal Lines fields that differ from the cells' values, as one `table.setCell`
|
||||
/// on the cells the dialog opened for, in the document it opened in.
|
||||
fn confirm_diagonal_lines(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {
|
||||
match diagonal_lines_document(app, d) {
|
||||
DiagonalLinesDocument::Ready => {}
|
||||
DiagonalLinesDocument::Inactive => return Err("Diagonal Lines: the document the dialog opened in is not the active document".into()),
|
||||
DiagonalLinesDocument::Changed => return Err("Diagonal Lines: the document changed while the dialog was open".into()),
|
||||
DiagonalLinesDocument::Gone => return Err("Diagonal Lines: the document the dialog opened in was closed or reverted".into()),
|
||||
}
|
||||
let Some(Value::Object(cells)) = d.fields.get("cells") else {
|
||||
return Err("Diagonal Lines: the dialog has no target cells".into());
|
||||
};
|
||||
let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
|
||||
let mut diagonal = Map::new();
|
||||
for k in DIAGONAL_KEYS {
|
||||
if let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && !same_cell_value(seed.get(k), k, v)) {
|
||||
diagonal.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
if diagonal.is_empty() {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let mut params = cells.clone();
|
||||
params.insert("diagonal".into(), Value::Object(diagonal));
|
||||
app.run("table.setCell", Value::Object(params))
|
||||
}
|
||||
|
||||
/// Delete absolute pages `pages` as the Pages panel and Layout › Pages › Delete Page do: when
|
||||
/// they hold objects, InDesign's warning asks first, unless it was told not to.
|
||||
pub fn delete_pages(app: &mut DesignApp, pages: Vec<usize>) -> Result<Value, String> {
|
||||
@@ -4578,6 +4753,7 @@ fn format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dialog) {
|
||||
fields: d.fields.get(FORMAT_EDIT).and_then(Value::as_object).cloned().unwrap_or_default(),
|
||||
unit: d.unit,
|
||||
vertical_unit: None,
|
||||
contents: None,
|
||||
};
|
||||
let base = json!({});
|
||||
let cf = CharFields { base: &base, sparse: true };
|
||||
@@ -4865,6 +5041,18 @@ fn confirm_part1(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
|
||||
}
|
||||
r
|
||||
}
|
||||
"diagonalLines" => {
|
||||
// On an error the dialog stays open to be corrected, unless the document it opened
|
||||
// in was closed, reverted or edited.
|
||||
let r = confirm_diagonal_lines(app, &d);
|
||||
if let Err(e) = &r {
|
||||
app.status(e.clone());
|
||||
if matches!(diagonal_lines_document(app, &d), DiagonalLinesDocument::Ready | DiagonalLinesDocument::Inactive) {
|
||||
app.ui.dialog = Some(d);
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
"textFrameOptions" => {
|
||||
// On an error the dialog stays open to be corrected.
|
||||
let mut d = d;
|
||||
@@ -5445,7 +5633,7 @@ fn confirm_part5(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
|
||||
json!({"path": d.s("path"), "removeStyles": d.b("removeStyles"), "styleConflicts": d.s("styleConflicts"), "styleMap": d.fields.get("map").cloned().unwrap_or(json!({}))}),
|
||||
),
|
||||
"fittingOptions" => {
|
||||
let m = |k: &str| d.fields.get(k).and_then(Value::as_str).and_then(|s| parse_measure(s, Unit::Points).ok()).unwrap_or(0.0);
|
||||
let m = |k: &str| d.m(k).unwrap_or(0.0);
|
||||
app.run(
|
||||
"object.fittingOptions",
|
||||
json!({"autoFit": d.b("autoFit"), "fitting": d.s("fitting"), "align": d.n("align").unwrap_or(4.0) as u64,
|
||||
@@ -7693,16 +7881,21 @@ fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, su
|
||||
fn char_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, opts: &[(Value, &str)]) {
|
||||
let cur = cf.get(d, key);
|
||||
let shown = opts.iter().find(|o| o.0 == cur).map_or("", |o| crate::i18n::tr(lang, o.1));
|
||||
craft_ui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(140.0).show_ui(ui, |ui| {
|
||||
if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {
|
||||
cf.set(d, key, Value::Null);
|
||||
}
|
||||
for (v, label) in opts {
|
||||
if ui.selectable_label(*v == cur, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
|
||||
cf.set(d, key, v.clone());
|
||||
craft_ui::ComboBox::from_id_salt(("cs", key))
|
||||
.selected_text(crate::rtl::widget(ui, shown))
|
||||
.width(140.0)
|
||||
.show_ui(ui, |ui| {
|
||||
if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {
|
||||
cf.set(d, key, Value::Null);
|
||||
}
|
||||
}
|
||||
});
|
||||
for (v, label) in opts {
|
||||
if ui.selectable_label(*v == cur, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
|
||||
cf.set(d, key, v.clone());
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.accessible_name(setting_label(lang, key));
|
||||
}
|
||||
|
||||
/// An on/off attribute; for a character style a third, mixed state leaves it unset (clicks go
|
||||
@@ -7729,6 +7922,42 @@ fn char_swatch(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, d
|
||||
char_choice(lang, ui, d, cf, key, &opts);
|
||||
}
|
||||
|
||||
/// Load styles once per popup opening, including when the selected family is missing.
|
||||
fn font_style_combo(
|
||||
ui: &mut egui::Ui,
|
||||
fonts: &designcraft_fonts::ScopedFonts<'_>,
|
||||
scope: u32,
|
||||
family: &str,
|
||||
style: &str,
|
||||
d: &mut Dialog,
|
||||
cf: &CharFields,
|
||||
) -> egui::Response {
|
||||
let key = ui.make_persistent_id(("pssty_styles", scope));
|
||||
let frame = ui.ctx().cumulative_frame_nr();
|
||||
let shown = craft_ui::ComboBox::from_id_salt("pssty").selected_text(style).width(200.0).show_ui(ui, |ui| {
|
||||
let cached = ui.data(|data| data.get_temp::<(String, u64, Vec<String>)>(key));
|
||||
let styles = if let Some((_, _, styles)) = cached.filter(|(f, last, _)| f == family && last.saturating_add(1) >= frame) {
|
||||
styles
|
||||
} else {
|
||||
let _ = fonts.face(family, style);
|
||||
fonts.styles(family)
|
||||
};
|
||||
ui.data_mut(|data| data.insert_temp(key, (family.to_string(), frame, styles.clone())));
|
||||
if cf.sparse && ui.selectable_label(style.is_empty(), " ").clicked() {
|
||||
cf.set(d, "fontStyle", Value::Null);
|
||||
}
|
||||
for s in styles {
|
||||
if ui.selectable_label(s == style, &s).clicked() {
|
||||
cf.set(d, "fontStyle", json!(s));
|
||||
}
|
||||
}
|
||||
});
|
||||
if shown.inner.is_none() {
|
||||
ui.data_mut(|data| data.remove::<(String, u64, Vec<String>)>(key));
|
||||
}
|
||||
shown.response
|
||||
}
|
||||
|
||||
/// Basic Character Formats: font, size, leading, kerning, tracking, case, position and the
|
||||
/// underline, strikethrough, ligatures and no-break switches.
|
||||
fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {
|
||||
@@ -7738,7 +7967,7 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo
|
||||
let menu = crate::panels::font_menu(app);
|
||||
// Two columns, as InDesign's: the font, then Size | Leading, Kerning | Tracking, Case | Position.
|
||||
egui::Grid::new("psc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));
|
||||
let name = crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));
|
||||
let fam = cf.get(d, "fontFamily").as_str().unwrap_or("").to_string();
|
||||
let shown = if fam.is_empty() { "—".to_string() } else { crate::panels::font_label(app, &menu, &fam) };
|
||||
let picked = craft_ui::ComboBox::from_id_salt("psfam")
|
||||
@@ -7755,35 +7984,25 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo
|
||||
crate::panels::font_menu_header(app, ui, &menu, &fam, 200.0)
|
||||
},
|
||||
crate::panels::font_menu_list,
|
||||
)
|
||||
.inner
|
||||
.flatten();
|
||||
if let Some(f) = picked {
|
||||
);
|
||||
picked.response.labelled_by(name.id);
|
||||
if let Some(f) = picked.inner.flatten() {
|
||||
cf.set(d, "fontFamily", json!(f.family));
|
||||
if let Some(style) = f.style {
|
||||
cf.set(d, "fontStyle", json!(style));
|
||||
}
|
||||
}
|
||||
ui.end_row();
|
||||
crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));
|
||||
let name = crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));
|
||||
let sty = cf.get(d, "fontStyle").as_str().unwrap_or("").to_string();
|
||||
if cf.sparse && fam.is_empty() {
|
||||
// No family to list styles of: type the style ("Italic" in whatever font the text has).
|
||||
let mut s = sty.clone();
|
||||
if ui.add(egui::TextEdit::singleline(&mut s).desired_width(200.0)).changed() {
|
||||
if ui.add(egui::TextEdit::singleline(&mut s).desired_width(200.0)).labelled_by(name.id).changed() {
|
||||
cf.set(d, "fontStyle", if s.trim().is_empty() { Value::Null } else { json!(s) });
|
||||
}
|
||||
} else {
|
||||
craft_ui::ComboBox::from_id_salt("pssty").selected_text(&sty).width(200.0).show_ui(ui, |ui| {
|
||||
if cf.sparse && ui.selectable_label(sty.is_empty(), " ").clicked() {
|
||||
cf.set(d, "fontStyle", Value::Null);
|
||||
}
|
||||
for s in fonts.styles(&fam) {
|
||||
if ui.selectable_label(s == sty, &s).clicked() {
|
||||
cf.set(d, "fontStyle", json!(s));
|
||||
}
|
||||
}
|
||||
});
|
||||
font_style_combo(ui, &fonts, crate::panels::font_scope(app), &fam, &sty, d, cf).labelled_by(name.id);
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
@@ -8354,6 +8573,9 @@ const PREVIEW_FAILED: &str = "previewFailed";
|
||||
/// edited.
|
||||
fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, current: &Value) {
|
||||
let cur = |d: &Dialog, k: &str| d.fields.get(&format!("{prefix}{k}")).cloned().unwrap_or_else(|| current[k].clone());
|
||||
// The spacing table keeps its own grid: its columns are only as wide as the percent fields.
|
||||
// The rows below (a wide menu, composer buttons, long checkboxes) sit outside it, so they
|
||||
// cannot stretch its columns and push Desired and Maximum off-screen.
|
||||
egui::Grid::new("psj").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
ui.label("");
|
||||
crate::rtl::label(ui, crate::i18n::tr(lang, "Minimum"));
|
||||
@@ -8377,6 +8599,8 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu
|
||||
d.fields.insert(format!("{prefix}autoLeading"), json!(auto_leading_typed(n)));
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let single_label = crate::rtl::label(ui, crate::i18n::tr(lang, "Single Word Justification:"));
|
||||
let single = cur(d, "singleWordJustify");
|
||||
// Mixed (null) shows blank until a choice is made.
|
||||
@@ -8399,7 +8623,8 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu
|
||||
})
|
||||
.response
|
||||
.labelled_by(single_label.id);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
crate::rtl::label(ui, crate::i18n::tr(lang, "Composer:"));
|
||||
let composer = cur(d, "composer");
|
||||
// Mixed (null) selects neither; a Japanese composer keeps its kind.
|
||||
@@ -8411,20 +8636,20 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu
|
||||
if ui.selectable_label(known && single, crate::rtl::widget(ui, crate::i18n::tr(lang, "Single-line Composer"))).clicked() {
|
||||
d.fields.insert(format!("{prefix}composer"), json!(single_line));
|
||||
}
|
||||
ui.end_row();
|
||||
for (label, key, text, default) in [
|
||||
("Insert Kashidas:", "kashidas", "In justified Arabic text", true),
|
||||
("Korean Line Breaks:", "koreanCharBreaks", "Between syllables (not only at spaces)", false),
|
||||
] {
|
||||
});
|
||||
for (label, key, text, default) in [
|
||||
("Insert Kashidas:", "kashidas", "In justified Arabic text", true),
|
||||
("Korean Line Breaks:", "koreanCharBreaks", "Between syllables (not only at spaces)", false),
|
||||
] {
|
||||
ui.horizontal(|ui| {
|
||||
crate::rtl::label(ui, crate::i18n::tr(lang, label));
|
||||
let v = cur(d, key);
|
||||
let mut on = v.as_bool().unwrap_or(default);
|
||||
if ui.add(egui::Checkbox::new(&mut on, crate::rtl::widget(ui, crate::i18n::tr(lang, text))).indeterminate(v.is_null())).changed() {
|
||||
d.fields.insert(format!("{prefix}{key}"), json!(on));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(e) = d.fields.get("justifyError").and_then(Value::as_str) {
|
||||
ui.add_space(6.0);
|
||||
crate::rtl::label(ui, egui::RichText::new(e).color(ui.visuals().error_fg_color));
|
||||
@@ -10311,3 +10536,246 @@ fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, nam
|
||||
d.fields.insert(edit_key, json!(text));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod variable_style_regression {
|
||||
use super::*;
|
||||
#[test]
|
||||
#[ignore = "requires the pinned Bricolage fixture; see docs/testing-variable-fonts.md"]
|
||||
fn named_instance_style_widget_and_api_agree() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let path = std::env::var_os("DESIGNCRAFT_TEST_VARIABLE_FONT").expect("set DESIGNCRAFT_TEST_VARIABLE_FONT");
|
||||
let db = designcraft_fonts::FontDb::global();
|
||||
db.add_font(std::fs::read(path).unwrap());
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("style.paragraph.create", json!({"name":"Base VF", "chars":{"fontFamily":"Bricolage Grotesque", "fontStyle":"Regular"}})).unwrap();
|
||||
app.run("style.paragraph.create", json!({"name":"UI VF", "basedOn":"Base VF"})).unwrap();
|
||||
app.run("style.paragraph.create", json!({"name":"API VF", "basedOn":"Base VF"})).unwrap();
|
||||
let base = json!({"fontFamily":"Bricolage Grotesque", "fontStyle":"Regular"});
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.with_size(egui::vec2(1000.0, 800.0))
|
||||
.build_ui_state(
|
||||
move |ui, state: &mut (DesignApp, Dialog)| {
|
||||
basic_character_formats(&mut state.0, ui, &mut state.1, &CharFields { base: &base, sparse: false });
|
||||
},
|
||||
(app, Dialog::new("paragraphStyleOptions", json!({"name":"UI VF"}))),
|
||||
);
|
||||
h.run_steps(3);
|
||||
{
|
||||
let (app, d) = h.state_mut();
|
||||
let before = app.session.doc().unwrap().doc.clone();
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
d.fields.insert("preview".into(), json!(true));
|
||||
d.fields.insert("c.fontStyle".into(), json!("SemiBold"));
|
||||
style_options_preview(app, d);
|
||||
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("UI VF").1.font_style, "SemiBold");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
|
||||
d.fields.insert("preview".into(), json!(false));
|
||||
style_options_preview(app, d);
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
d.fields.insert("preview".into(), json!(true));
|
||||
style_options_preview(app, d);
|
||||
app.ui.dialog = Some(d.clone());
|
||||
cancel(app);
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
d.fields.remove(PREVIEWED);
|
||||
d.fields.insert("preview".into(), json!(true));
|
||||
style_options_preview(app, d);
|
||||
app.ui.dialog = Some(d.clone());
|
||||
confirm(app).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
app.run("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("UI VF").1.font_style, "SemiBold");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
d.fields.remove(PREVIEWED);
|
||||
d.fields.remove("c.fontStyle");
|
||||
d.fields.insert("preview".into(), json!(false));
|
||||
}
|
||||
h.run_steps(3);
|
||||
let mut current = "Regular";
|
||||
for selected in ["SemiBold", "Bold", "Regular"] {
|
||||
h.get_by_value(current).click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label(selected).click();
|
||||
h.run_steps(3);
|
||||
let (app, d) = h.state_mut();
|
||||
assert_eq!(d.fields["c.fontStyle"], selected);
|
||||
assert!(!d.fields.contains_key("c.fontFamily"), "inherited family remains inherited");
|
||||
confirm_paragraph_style_options(app, d).unwrap();
|
||||
app.run("style.paragraph.edit", json!({"name":"API VF","chars":{"fontStyle":selected}})).unwrap();
|
||||
let styles = &app.session.doc().unwrap().doc.styles;
|
||||
assert_eq!(styles.para("UI VF").unwrap().chars, styles.para("API VF").unwrap().chars);
|
||||
assert_eq!(styles.resolve_para_style("UI VF").1.font_style, selected);
|
||||
assert_eq!(styles.para("UI VF").unwrap().based_on.as_deref(), Some("Base VF"));
|
||||
current = selected;
|
||||
let native = app.run("file.serialize", json!({})).unwrap();
|
||||
app.run("file.openBytes", json!({"name":"vf.designcraft","base64":native["base64"]})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("UI VF").1.font_style, selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod variable_cold_style_regression {
|
||||
use super::*;
|
||||
#[test]
|
||||
#[ignore = "requires a fresh process with the pinned Bricolage fixture catalogued; see docs/testing-variable-fonts.md"]
|
||||
fn cold_style_combo_contains_named_instances() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let fonts = designcraft_fonts::FontDb::global();
|
||||
assert!(
|
||||
!fonts.styles("Bricolage Grotesque").contains(&"SemiBold".into()),
|
||||
"run in a fresh process with the test font catalogued but not loaded"
|
||||
);
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
let base = json!({"fontFamily":"Bricolage Grotesque", "fontStyle":"Regular"});
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.with_size(egui::vec2(1000.0, 800.0))
|
||||
.build_ui_state(
|
||||
move |ui, state: &mut (DesignApp, Dialog)| {
|
||||
basic_character_formats(&mut state.0, ui, &mut state.1, &CharFields { base: &base, sparse: false });
|
||||
},
|
||||
(app, Dialog::new("paragraphStyleOptions", json!({}))),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_value("Regular").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label("SemiBold").is_some(), "the cold Style combo must offer named instances");
|
||||
h.get_by_label("SemiBold").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().1.fields["c.fontStyle"], "SemiBold");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod synthetic_variable_style_regression {
|
||||
use super::*;
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
|
||||
#[test]
|
||||
fn paragraph_style_formats_select_a_synthetic_named_instance() {
|
||||
let family = "Synthetic Paragraph Wiring";
|
||||
designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::variable_font(family).unwrap());
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("style.paragraph.create", json!({"name":"Synthetic UI", "chars":{"fontFamily":family,"fontStyle":"Regular"}})).unwrap();
|
||||
let base = json!({"fontFamily":family,"fontStyle":"Regular"});
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.with_size(egui::vec2(1000.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, state: &mut (DesignApp, Dialog)| {
|
||||
basic_character_formats(&mut state.0, ui, &mut state.1, &CharFields { base: &base, sparse: false });
|
||||
},
|
||||
(app, Dialog::new("paragraphStyleOptions", json!({"name":"Synthetic UI"}))),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_value("Regular").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("SemiBold").click();
|
||||
h.run_steps(3);
|
||||
let (app, d) = h.state_mut();
|
||||
confirm_paragraph_style_options(app, d).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("Synthetic UI").1.font_style, "SemiBold");
|
||||
}
|
||||
#[test]
|
||||
fn cold_style_popup_discovers_instances_and_selects_them() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let family = "Synthetic Cold Style";
|
||||
std::fs::write(dir.path().join("variable.ttf"), designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
|
||||
let db = designcraft_fonts::FontDb::with_font_dirs(vec![dir.path().to_owned()]);
|
||||
assert_eq!(db.styles(family), ["Regular"]);
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.build_ui_state(
|
||||
|ui, d: &mut Dialog| {
|
||||
let style = d.fields.get("c.fontStyle").and_then(Value::as_str).unwrap_or("Regular").to_string();
|
||||
font_style_combo(ui, &db.scoped(0), 0, family, &style, d, &CharFields { base: &Value::Null, sparse: false })
|
||||
.accessible_name("Font Style".to_owned());
|
||||
},
|
||||
Dialog::new("paragraphStyleOptions", json!({})),
|
||||
);
|
||||
h.run_steps(3);
|
||||
assert_eq!(db.styles(family), ["Regular"], "closed popup must not preload the font");
|
||||
h.get_by_value("Regular").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(db.styles(family), ["Regular", "SemiBold"]);
|
||||
h.get_by_label("SemiBold").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().fields["c.fontStyle"], "SemiBold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_family_styles_are_cached_until_the_popup_reopens() {
|
||||
for retry in ["reopen", "hidden", "scope"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let family = "Synthetic Missing Style";
|
||||
let path = dir.path().join("variable.ttf");
|
||||
std::fs::write(&path, designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
|
||||
let db = designcraft_fonts::FontDb::with_font_dirs(vec![dir.path().to_owned()]);
|
||||
assert_eq!(db.styles(family), ["Regular"]);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.build_ui_state(
|
||||
|ui, state: &mut (Dialog, bool, u32)| {
|
||||
if state.1 {
|
||||
font_style_combo(
|
||||
ui,
|
||||
&db.scoped(state.2),
|
||||
state.2,
|
||||
family,
|
||||
"Regular",
|
||||
&mut state.0,
|
||||
&CharFields { base: &Value::Null, sparse: false },
|
||||
)
|
||||
.accessible_name("Font Style".to_owned());
|
||||
}
|
||||
},
|
||||
(Dialog::new("paragraphStyleOptions", json!({})), true, 0),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_value("Regular").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label("SemiBold").is_none());
|
||||
std::fs::write(&path, designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(db.styles(family), ["Regular"], "an open popup must not retry the missing font every frame");
|
||||
match retry {
|
||||
"hidden" => {
|
||||
h.state_mut().1 = false;
|
||||
h.run_steps(3);
|
||||
h.state_mut().1 = true;
|
||||
}
|
||||
"scope" => h.state_mut().2 = 1,
|
||||
_ => {
|
||||
egui::Popup::close_all(&h.ctx);
|
||||
h.run_steps(3);
|
||||
h.get_by_value("Regular").click();
|
||||
}
|
||||
}
|
||||
h.run_steps(3);
|
||||
if h.query_by_label("SemiBold").is_none() {
|
||||
h.get_by_value("Regular").click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
assert!(h.query_by_label("SemiBold").is_some(), "{retry} retries the now-readable font");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,7 +267,7 @@ pub fn open_layer_options(app: &mut DesignApp, id: Option<u64>) -> Result<(), St
|
||||
let id = id.map_or(st.active_layer, designcraft_doc::LayerId);
|
||||
let l = st.doc.layer(id).ok_or("no such layer")?;
|
||||
let f = json!({"id": l.id.0, "name": l.name, "rgb": l.color, "visible": l.visible, "locked": l.locked, "printable": l.printable,
|
||||
"showGuides": l.show_guides, "suppressWrapWhenHidden": l.suppress_wrap_when_hidden});
|
||||
"showGuides": l.show_guides, "lockGuides": l.lock_guides, "suppressWrapWhenHidden": l.suppress_wrap_when_hidden});
|
||||
app.ui.dialog = Some(Dialog::new("layerSettings", f));
|
||||
Ok(())
|
||||
}
|
||||
@@ -302,11 +302,14 @@ pub fn layer_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
// As InDesign's: the layer's options on the left, its guides' on the right.
|
||||
egui::Grid::new("layer_flags").num_columns(2).spacing([16.0, 6.0]).show(ui, |ui| {
|
||||
check(ui, d, "visible", tr(lang, "Show Layer"));
|
||||
check(ui, d, "locked", tr(lang, "Lock Layer"));
|
||||
ui.end_row();
|
||||
check(ui, d, "showGuides", tr(lang, "Show Guides"));
|
||||
ui.end_row();
|
||||
check(ui, d, "locked", tr(lang, "Lock Layer"));
|
||||
check(ui, d, "lockGuides", tr(lang, "Lock Guides"));
|
||||
ui.end_row();
|
||||
check(ui, d, "printable", tr(lang, "Print Layer"));
|
||||
ui.end_row();
|
||||
});
|
||||
@@ -316,7 +319,7 @@ pub fn layer_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
|
||||
pub fn confirm_layer_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut p = json!({"id": d.fields.get("id").cloned().unwrap_or(Value::Null), "name": d.s("name"), "color": d.fields.get("rgb").cloned().unwrap_or(Value::Null)});
|
||||
for k in ["visible", "locked", "printable", "showGuides", "suppressWrapWhenHidden"] {
|
||||
for k in ["visible", "locked", "printable", "showGuides", "lockGuides", "suppressWrapWhenHidden"] {
|
||||
p[k] = json!(d.b(k));
|
||||
}
|
||||
app.run("layer.set", p)
|
||||
@@ -433,4 +436,22 @@ mod tests {
|
||||
let l = doc.layers.iter().find(|l| l.name == "Artwork").expect("renamed");
|
||||
assert!(!l.printable);
|
||||
}
|
||||
|
||||
/// The course's chapter 32: Layer Options has InDesign's Lock Guides, beside Lock Layer.
|
||||
#[test]
|
||||
fn layer_options_lock_the_layers_guides() {
|
||||
let mut app = app();
|
||||
app.run("layer.new", json!({"name": "Grid"})).unwrap();
|
||||
let mut h = harness(app, crate::panels::layers::show);
|
||||
double_click(&mut h, "Grid");
|
||||
let (lock, guides) = (h.get_by_label("Lock Layer").rect(), h.get_by_label("Lock Guides").rect());
|
||||
assert!((lock.center().y - guides.center().y).abs() < 2.0 && guides.left() > lock.right(), "Lock Guides is beside Lock Layer");
|
||||
h.get_by_label("Lock Guides").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(3);
|
||||
let doc = &h.state().session.active().unwrap().doc;
|
||||
let l = doc.layers.iter().find(|l| l.name == "Grid").unwrap();
|
||||
assert!(l.lock_guides && !l.locked);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,6 +413,46 @@ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges
|
||||
assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_options_ok_edits_nothing_when_the_picked_stroke_type_is_the_cells() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app.run("table.select", json!({"what": "table"})).unwrap();
|
||||
app.run("app.cellOptionsDialog", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
assert_eq!(d.fields["seed"]["type"], json!({"kind": "solid"}));
|
||||
// The Type list picks a stroke type by name.
|
||||
d.fields.insert("type".into(), json!("solid"));
|
||||
let (undo, revision) = {
|
||||
let st = app.session.active().unwrap();
|
||||
(st.history.undo.len(), st.revision)
|
||||
};
|
||||
confirm(&mut app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((st.history.undo.len(), st.revision), (undo, revision), "no edit and no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_options_edge_change_reseeds_a_picked_stroke_type_that_was_the_cells() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app.run("table.select", json!({"what": "table"})).unwrap();
|
||||
app.run("table.setCell", json!({"stroke": {"type": "dotted", "edges": "innerHorizontal"}})).unwrap();
|
||||
app.run("app.cellOptionsDialog", json!({})).unwrap();
|
||||
let mut d = app.ui.dialog.take().unwrap();
|
||||
cell_options_edges_changed(&mut app, &mut d, &[true, true, true, true, false, false]);
|
||||
assert_eq!(d.fields["seed"]["type"], json!({"kind": "solid"}));
|
||||
// Solid picked by name for the outer edges is what they show; the inner horizontal edges
|
||||
// chosen next show their own type.
|
||||
d.fields.insert("type".into(), json!("solid"));
|
||||
cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);
|
||||
assert_eq!(d.fields["type"], json!({"kind": "dotted"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
@@ -440,6 +480,222 @@ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed()
|
||||
assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_dialog_draws_and_applies_its_values_but_not_a_mixed_one() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
app.run("table.setCell", json!({"row": 0, "col": 0, "diagonal": {"color": "[Paper]"}})).unwrap();
|
||||
app.run("table.select", json!({"what": "table"})).unwrap();
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
let ctx = dialog_context("");
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0));
|
||||
// The first frame sizes the window without painting it.
|
||||
dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
for shown in ["Line Stroke", "Weight:", "Draw:", "Diagonal In Front"] {
|
||||
visible_label(&labels, screen, shown);
|
||||
}
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.id, "diagonalLines");
|
||||
assert_eq!((&d.fields["lines"], &d.fields["color"], &d.fields["inFront"]), (&json!("none"), &Value::Null, &json!(true)));
|
||||
// The fourth line button, in the row above Line Stroke, is Crossed Diagonal Lines.
|
||||
let caption = visible_label(&labels, screen, "Line Stroke");
|
||||
let gap = ctx.global_style().spacing.item_spacing;
|
||||
let crossed = egui::pos2(caption.left() + 3.0 * (32.0 + gap.x) + 16.0, caption.top() - 10.0 - gap.y - 16.0);
|
||||
click_dialog(&mut app, &ctx, screen, crossed);
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
assert_eq!(d.fields["lines"], json!("crossed"));
|
||||
d.fields.insert("inFront".into(), json!(false));
|
||||
d.fields.insert("weight".into(), json!(0.5));
|
||||
confirm(&mut app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
|
||||
assert!(
|
||||
t.cells
|
||||
.iter()
|
||||
.all(|c| c.diagonal.lines == designcraft_doc::DiagonalLines::Crossed && !c.diagonal.in_front && c.diagonal.stroke.weight == 0.5)
|
||||
);
|
||||
let colors: Vec<_> = t.cells.iter().map(|c| c.diagonal.stroke.color.as_str()).collect();
|
||||
assert_eq!(colors, ["[Paper]", "[Black]", "[Black]", "[Black]"], "a mixed value is left as it is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_options_menu_items_need_a_table_target() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
let items = ["app.cellOptionsDialog", "app.diagonalLinesDialog"];
|
||||
for id in items {
|
||||
assert!(!crate::menus::menu_enabled(&app, id), "{id} without a table");
|
||||
}
|
||||
app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
for id in items {
|
||||
assert!(crate::menus::menu_enabled(&app, id), "{id} in a table");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_on_a_diagonal_line_button_picks_it_and_leaves_the_dialog_open() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
app.run("table.select", json!({"what": "table"})).unwrap();
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
let ctx = dialog_context("");
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0));
|
||||
dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
// Tab past the title bar and the first line button to Diagonal Line from Top Left to Bottom
|
||||
// Right, then press Enter.
|
||||
for _ in 0..3 {
|
||||
dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Tab)]);
|
||||
dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
}
|
||||
dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Enter)]);
|
||||
dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
let d = app.ui.dialog.as_ref().expect("Enter on a line button leaves the dialog open");
|
||||
assert_eq!(d.fields["lines"], json!("topLeft"));
|
||||
let st = app.session.active().unwrap();
|
||||
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
|
||||
assert!(t.cells.iter().all(|c| c.diagonal.lines == designcraft_doc::DiagonalLines::None), "nothing is applied yet");
|
||||
// Enter with no line button focused still confirms.
|
||||
ctx.memory_mut(|m| {
|
||||
if let Some(id) = m.focused() {
|
||||
m.surrender_focus(id);
|
||||
}
|
||||
});
|
||||
dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Enter)]);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
let st = app.session.active().unwrap();
|
||||
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
|
||||
assert!(t.cells.iter().all(|c| c.diagonal.lines == designcraft_doc::DiagonalLines::TopLeft));
|
||||
}
|
||||
|
||||
/// A document holding a 2×2 table with cell (0, 0) selected; returns the table id.
|
||||
fn table_document_for_diagonals(app: &mut DesignApp) -> u64 {
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
|
||||
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
|
||||
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
|
||||
tid
|
||||
}
|
||||
|
||||
/// The diagonal lines of the cells of table `tid` in document `doc`, row by row.
|
||||
fn diagonal_lines_of(app: &DesignApp, doc: usize, tid: u64) -> Vec<designcraft_doc::DiagonalLines> {
|
||||
let st = &app.session.documents()[doc];
|
||||
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
|
||||
t.cells.iter().map(|c| c.diagonal.lines).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_dialog_applies_to_the_cells_and_document_it_opened_for() {
|
||||
use designcraft_doc::DiagonalLines::{Crossed, None as No, TopRight};
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
let a = table_document_for_diagonals(&mut app);
|
||||
// The selection moves to another cell while the dialog is open: OK still edits cell (0, 0).
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
|
||||
confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(diagonal_lines_of(&app, 0, a), [Crossed, No, No, No]);
|
||||
// Another document with a table selection becomes active: OK is refused and changes neither
|
||||
// document, and the dialog stays open.
|
||||
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
let b = table_document_for_diagonals(&mut app);
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("topRight"));
|
||||
assert!(confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_some(), "the dialog stays open while its document is open");
|
||||
assert_eq!(diagonal_lines_of(&app, 1, b), [No; 4]);
|
||||
assert_eq!(diagonal_lines_of(&app, 0, a), [Crossed, No, No, No]);
|
||||
// Back in the first document, OK applies there.
|
||||
app.run("file.activate", json!({"index": 0})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(diagonal_lines_of(&app, 0, a), [TopRight, No, No, No]);
|
||||
// A row is added above the target cell while the dialog is open: the document changed and the
|
||||
// saved range would name another cell, so OK is refused, nothing changes and the dialog closes.
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
|
||||
app.run("table.insertRowAbove", json!({})).unwrap();
|
||||
assert!(confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_none(), "a dialog whose table changed closes");
|
||||
// The new row takes the formatting of the row below it.
|
||||
assert_eq!(diagonal_lines_of(&app, 0, a), [TopRight, No, TopRight, No, No, No]);
|
||||
// The first document is closed while the dialog is open: OK is refused and the dialog closes.
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
|
||||
app.run("file.close", json!({"index": 0})).unwrap();
|
||||
assert!(confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_none(), "a dialog whose document was closed closes");
|
||||
assert_eq!(diagonal_lines_of(&app, 0, b), [No; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_dialog_is_refused_when_new_contents_reuse_the_old_address() {
|
||||
use designcraft_doc::DiagonalLines::None as No;
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
let tid = table_document_for_diagonals(&mut app);
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
|
||||
// A row is added above the target cell, and the edit is undone: the contents the dialog
|
||||
// opened with are back, and the undo stack no longer holds them.
|
||||
app.run("table.insertRowAbove", json!({})).unwrap();
|
||||
let edited = (*app.session.active().unwrap().doc).clone();
|
||||
app.session.execute("edit.undo", &json!({})).unwrap();
|
||||
// The edited contents are written in place when nothing else holds the old contents, at the
|
||||
// address an allocation that reuses freed memory would give them. The saved cell range now
|
||||
// names the new row.
|
||||
let st = app.session.active_mut().unwrap();
|
||||
*std::sync::Arc::make_mut(&mut st.doc) = edited;
|
||||
assert!(confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_none(), "a dialog whose table changed closes");
|
||||
assert_eq!(diagonal_lines_of(&app, 0, tid), [No; 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_lines_dialog_ok_edits_nothing_when_the_picked_stroke_type_is_the_cells() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
table_document_for_diagonals(&mut app);
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
assert_eq!(d.fields["seed"]["type"], json!({"kind": "solid"}));
|
||||
// The Type list picks a stroke type by name.
|
||||
d.fields.insert("type".into(), json!("solid"));
|
||||
let (undo, revision) = {
|
||||
let st = app.session.active().unwrap();
|
||||
(st.history.undo.len(), st.revision)
|
||||
};
|
||||
confirm(&mut app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((st.history.undo.len(), st.revision), (undo, revision), "no edit and no undo step");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn diagonal_lines_dialog_is_refused_after_its_document_is_reverted() {
|
||||
use designcraft_doc::DiagonalLines::None as No;
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
let tid = table_document_for_diagonals(&mut app);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
app.run("file.saveAs", json!({"path": dir.path().join("diagonal.designcraft")})).unwrap();
|
||||
app.run("table.setCell", json!({"row": 1, "col": 1, "text": "unsaved"})).unwrap();
|
||||
app.run("app.diagonalLinesDialog", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
|
||||
app.session.execute("file.revert", &json!({})).unwrap();
|
||||
// The reverted document holds the same table; a selection in it does not let OK through.
|
||||
let story = app.session.active().unwrap().doc.stories.iter().find(|(_, s)| s.tables.contains_key(&tid)).map(|(k, _)| k.0).unwrap();
|
||||
app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();
|
||||
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
|
||||
assert!(confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_none(), "a dialog whose document was reverted closes");
|
||||
assert_eq!(diagonal_lines_of(&app, 0, tid), [No; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferences_ok_saves_a_story_editor_size_that_loads_back() {
|
||||
// `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`.
|
||||
@@ -1253,6 +1509,39 @@ fn paragraph_style_options_justification_sets_auto_leading_and_single_word_justi
|
||||
assert_eq!((para.auto_leading, para.single_word_justify), (Some(1.0), Some(designcraft_doc::Align::Right)));
|
||||
}
|
||||
|
||||
/// Paragraph Style Options › Justification fits at the normal dialog width: the spacing table
|
||||
/// keeps its own narrow columns (the wide Single Word Justification menu must not stretch
|
||||
/// them), so Minimum/Desired sit close together and Maximum stays in view with no horizontal
|
||||
/// scrolling.
|
||||
#[test]
|
||||
fn paragraph_style_options_justification_fits_without_horizontal_scrolling() {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("style.paragraph.create", json!({"name": "Headline"})).unwrap();
|
||||
app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Headline", "section": "justify"})));
|
||||
let ctx = dialog_context("en");
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));
|
||||
for _ in 0..3 {
|
||||
dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
}
|
||||
let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
|
||||
let rect_of =
|
||||
|text: &str| labels.iter().find(|(t, _, _)| t.trim() == text).map(|(_, r, _)| *r).unwrap_or_else(|| panic!("{text} is painted: {labels:?}"));
|
||||
let (minimum, desired) = (rect_of("Minimum"), rect_of("Desired"));
|
||||
// Left edge to left edge of the two header labels. With the 130 pt Single Word menu sharing
|
||||
// the grid's column, column 1 stretches and this distance measures ~130+; with the spacing
|
||||
// table in its own grid it is ~70. The bound sits comfortably between the two.
|
||||
let gap = desired.min.x - minimum.min.x;
|
||||
assert!(gap < 100.0, "Minimum/Desired headers {gap:.1} pt apart: {minimum:?} {desired:?}");
|
||||
// The whole section stays inside the dialog: Maximum and every control label are painted
|
||||
// unclipped on screen (no horizontal scrolling needed to reach them).
|
||||
visible_label(&labels, screen, "Maximum");
|
||||
visible_label(&labels, screen, "Single Word Justification:");
|
||||
visible_label(&labels, screen, "Composer:");
|
||||
visible_label(&labels, screen, "Insert Kashidas:");
|
||||
visible_label(&labels, screen, "Korean Line Breaks:");
|
||||
}
|
||||
|
||||
fn command_app(id: &str, fields: Value) -> DesignApp {
|
||||
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));
|
||||
|
||||
@@ -1948,6 +1948,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Continue from Previous Number", "المتابعة من الرقم السابق"),
|
||||
("Start At", "البدء عند"),
|
||||
("Strokes and Fills…", "الحدود والتعبئة…"),
|
||||
("Diagonal Lines…", "الخطوط القطرية…"),
|
||||
("No Diagonal Lines", "بلا خطوط قطرية"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "خط قطري من أعلى اليسار إلى أسفل اليمين"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "خط قطري من أعلى اليمين إلى أسفل اليسار"),
|
||||
("Crossed Diagonal Lines", "خطوط قطرية متقاطعة"),
|
||||
("Line Stroke", "حد الخط"),
|
||||
("Draw:", "الرسم:"),
|
||||
("Diagonal In Front", "القطري في الأمام"),
|
||||
("Content In Front", "المحتوى في الأمام"),
|
||||
("Cell Stroke", "حد الخلية"),
|
||||
("Cell Fill", "تعبئة الخلية"),
|
||||
("Cell edges", "حواف الخلية"),
|
||||
|
||||
@@ -1962,6 +1962,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Fancy", "Verziert"),
|
||||
("Gap Tint:", "Lückenfarbton:"),
|
||||
("Strokes and Fills…", "Konturen und Flächen …"),
|
||||
("Diagonal Lines…", "Diagonale Linien …"),
|
||||
("No Diagonal Lines", "Keine diagonalen Linien"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "Diagonale Linie von links oben nach rechts unten"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "Diagonale Linie von rechts oben nach links unten"),
|
||||
("Crossed Diagonal Lines", "Gekreuzte diagonale Linien"),
|
||||
("Line Stroke", "Linienkontur"),
|
||||
("Draw:", "Zeichnen:"),
|
||||
("Diagonal In Front", "Diagonale im Vordergrund"),
|
||||
("Content In Front", "Inhalt im Vordergrund"),
|
||||
("Cell Stroke", "Zellkontur"),
|
||||
("Cell Fill", "Zellfläche"),
|
||||
("Cell edges", "Zellkanten"),
|
||||
|
||||
@@ -142,6 +142,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Generate Index", "Générer l'index"),
|
||||
("Generate Live Caption", "Générer une légende dynamique"),
|
||||
("Get Cell Stroke", "Obtenir le contour de cellule"),
|
||||
("Get Cell Diagonal Lines", "Obtenir les lignes diagonales de cellule"),
|
||||
("Get Tabs", "Obtenir les tabulations"),
|
||||
("Global Light", "Lumière globale"),
|
||||
("Grab bag", "Liste"),
|
||||
|
||||
@@ -2008,6 +2008,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Continue from Previous Number", "Continua dal numero precedente"),
|
||||
("Start At", "Inizia da"),
|
||||
("Strokes and Fills…", "Tracce e riempimenti…"),
|
||||
("Diagonal Lines…", "Linee diagonali…"),
|
||||
("No Diagonal Lines", "Nessuna linea diagonale"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "Linea diagonale dall'angolo superiore sinistro a quello inferiore destro"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "Linea diagonale dall'angolo superiore destro a quello inferiore sinistro"),
|
||||
("Crossed Diagonal Lines", "Linee diagonali incrociate"),
|
||||
("Line Stroke", "Traccia linea"),
|
||||
("Draw:", "Disegna:"),
|
||||
("Diagonal In Front", "Diagonale in primo piano"),
|
||||
("Content In Front", "Contenuto in primo piano"),
|
||||
("Cell Stroke", "Traccia cella"),
|
||||
("Cell Fill", "Riempimento cella"),
|
||||
("Cell edges", "Bordi cella"),
|
||||
|
||||
@@ -2171,6 +2171,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Bounding Box (Visible Layers Only)", "バウンディングボックス(表示レイヤーのみ)"),
|
||||
("Bounding Box (All Layers)", "バウンディングボックス(すべてのレイヤー)"),
|
||||
("Strokes and Fills…", "線と塗り…"),
|
||||
("Diagonal Lines…", "斜線…"),
|
||||
("No Diagonal Lines", "斜線なし"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "左上から右下への斜線"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "右上から左下への斜線"),
|
||||
("Crossed Diagonal Lines", "交差する斜線"),
|
||||
("Line Stroke", "斜線の線"),
|
||||
("Draw:", "描画:"),
|
||||
("Diagonal In Front", "斜線を前面へ"),
|
||||
("Content In Front", "内容を前面へ"),
|
||||
("Cell Stroke", "セルの線"),
|
||||
("Cell Fill", "セルの塗り"),
|
||||
("Cell edges", "セルの境界線"),
|
||||
|
||||
@@ -2066,6 +2066,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Clear Recent Files", "ბოლო ფაილების სიის გასუფთავება"),
|
||||
("Transparency…", "გამჭვირვალობა…"),
|
||||
("Strokes and Fills…", "კონტურები და შევსებები…"),
|
||||
("Diagonal Lines…", "დიაგონალური ხაზები…"),
|
||||
("Show/Hide Document Grid", "დოკუმენტის ბადის ჩვენება/დამალვა"),
|
||||
("% of all commits", "ყველა კომიტის %"),
|
||||
("(Paragraph Font)", "(აბზაცის შრიფტი)"),
|
||||
|
||||
@@ -1554,6 +1554,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Continue from Previous Number", "Continuar do número anterior"),
|
||||
("Start At", "Iniciar em"),
|
||||
("Strokes and Fills…", "Traçados e preenchimentos…"),
|
||||
("Diagonal Lines…", "Linhas diagonais…"),
|
||||
("No Diagonal Lines", "Sem linhas diagonais"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "Linha diagonal do canto superior esquerdo ao inferior direito"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "Linha diagonal do canto superior direito ao inferior esquerdo"),
|
||||
("Crossed Diagonal Lines", "Linhas diagonais cruzadas"),
|
||||
("Line Stroke", "Traçado da linha"),
|
||||
("Draw:", "Desenhar:"),
|
||||
("Diagonal In Front", "Diagonal à frente"),
|
||||
("Content In Front", "Conteúdo à frente"),
|
||||
("Cell Stroke", "Traçado da célula"),
|
||||
("Cell Fill", "Preenchimento da célula"),
|
||||
("Cell edges", "Bordas da célula"),
|
||||
|
||||
@@ -2050,6 +2050,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Fancy", "Dekorativ"),
|
||||
("Gap Tint:", "Färgton för mellanrum:"),
|
||||
("Strokes and Fills…", "Konturer och fyllningar…"),
|
||||
("Diagonal Lines…", "Diagonala linjer…"),
|
||||
("No Diagonal Lines", "Inga diagonala linjer"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "Diagonal linje från övre vänstra till nedre högra hörnet"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "Diagonal linje från övre högra till nedre vänstra hörnet"),
|
||||
("Crossed Diagonal Lines", "Korsade diagonala linjer"),
|
||||
("Line Stroke", "Linjekontur"),
|
||||
("Draw:", "Rita:"),
|
||||
("Diagonal In Front", "Diagonal i förgrunden"),
|
||||
("Content In Front", "Innehåll i förgrunden"),
|
||||
("Cell Stroke", "Cellkontur"),
|
||||
("Cell Fill", "Cellfyllning"),
|
||||
("Cell edges", "Cellkanter"),
|
||||
|
||||
@@ -4843,6 +4843,36 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[
|
||||
("Start At", ["Beginnen bei", "Commencer à", "Empezar en", "開始番号", "起始编号"]),
|
||||
// Cell strokes.
|
||||
("Strokes and Fills…", ["Konturen und Flächen …", "Contours et fonds…", "Trazos y rellenos…", "線と塗り…", "描边和填色…"]),
|
||||
("Diagonal Lines…", ["Diagonale Linien …", "Lignes diagonales…", "Líneas diagonales…", "斜線…", "对角线…"]),
|
||||
("No Diagonal Lines", ["Keine diagonalen Linien", "Aucune ligne diagonale", "Sin líneas diagonales", "斜線なし", "无对角线"]),
|
||||
(
|
||||
"Diagonal Line from Top Left to Bottom Right",
|
||||
[
|
||||
"Diagonale Linie von links oben nach rechts unten",
|
||||
"Ligne diagonale du coin supérieur gauche au coin inférieur droit",
|
||||
"Línea diagonal de la esquina superior izquierda a la inferior derecha",
|
||||
"左上から右下への斜線",
|
||||
"从左上到右下的对角线",
|
||||
],
|
||||
),
|
||||
(
|
||||
"Diagonal Line from Top Right to Bottom Left",
|
||||
[
|
||||
"Diagonale Linie von rechts oben nach links unten",
|
||||
"Ligne diagonale du coin supérieur droit au coin inférieur gauche",
|
||||
"Línea diagonal de la esquina superior derecha a la inferior izquierda",
|
||||
"右上から左下への斜線",
|
||||
"从右上到左下的对角线",
|
||||
],
|
||||
),
|
||||
(
|
||||
"Crossed Diagonal Lines",
|
||||
["Gekreuzte diagonale Linien", "Lignes diagonales croisées", "Líneas diagonales cruzadas", "交差する斜線", "交叉对角线"],
|
||||
),
|
||||
("Line Stroke", ["Linienkontur", "Contour de ligne", "Trazo de línea", "斜線の線", "线条描边"]),
|
||||
("Draw:", ["Zeichnen:", "Dessin :", "Dibujar:", "描画:", "绘制:"]),
|
||||
("Diagonal In Front", ["Diagonale im Vordergrund", "Diagonale au premier plan", "Diagonal delante", "斜線を前面へ", "对角线置前"]),
|
||||
("Content In Front", ["Inhalt im Vordergrund", "Contenu au premier plan", "Contenido delante", "内容を前面へ", "内容置前"]),
|
||||
("Cell Stroke", ["Zellkontur", "Contour de cellule", "Trazo de celda", "セルの線", "单元格描边"]),
|
||||
("Cell Fill", ["Zellfläche", "Fond de cellule", "Relleno de celda", "セルの塗り", "单元格填色"]),
|
||||
("Cell edges", ["Zellkanten", "Bords de cellule", "Bordes de celda", "セルの境界線", "单元格边缘"]),
|
||||
|
||||
@@ -1976,6 +1976,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
|
||||
("Continue from Previous Number", "Продовжити з попереднього номера"),
|
||||
("Start At", "Почати з"),
|
||||
("Strokes and Fills…", "Обведення та заливки…"),
|
||||
("Diagonal Lines…", "Діагональні лінії…"),
|
||||
("No Diagonal Lines", "Без діагональних ліній"),
|
||||
("Diagonal Line from Top Left to Bottom Right", "Діагональна лінія з верхнього лівого кута в нижній правий"),
|
||||
("Diagonal Line from Top Right to Bottom Left", "Діагональна лінія з верхнього правого кута в нижній лівий"),
|
||||
("Crossed Diagonal Lines", "Перехресні діагональні лінії"),
|
||||
("Line Stroke", "Обведення лінії"),
|
||||
("Draw:", "Малювати:"),
|
||||
("Diagonal In Front", "Діагональ попереду"),
|
||||
("Content In Front", "Вміст попереду"),
|
||||
("Cell Stroke", "Обведення клітинки"),
|
||||
("Cell Fill", "Заливка клітинки"),
|
||||
("Cell edges", "Краї клітинки"),
|
||||
|
||||
@@ -33,7 +33,8 @@ pub use quick_apply::{QuickItem, command_search, palette, quick_apply_items};
|
||||
pub use run::run_ui;
|
||||
pub(crate) use run::save_then;
|
||||
pub use state::{
|
||||
checked, default_shortcut, enabled, menu_enabled, native_menu_enabled, shortcut_label, shortcut_of, shortcut_text, tool_shortcut_label,
|
||||
checked, default_shortcut, enabled, menu_enabled, native_key_equivalent, native_menu_enabled, shortcut_label, shortcut_of, shortcut_text,
|
||||
tool_shortcut_label,
|
||||
};
|
||||
pub use tables::{CLASSIC_GROUPS, MENUS, TYPOGRAPHY_GROUPS, WORKSPACE_OPEN_PANELS, WORKSPACES, workspace_open_panel};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -244,6 +244,7 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"app.cellOptionsDialog" => crate::dialogs::open_cell_options(app),
|
||||
"app.diagonalLinesDialog" => crate::dialogs::open_diagonal_lines(app),
|
||||
"window.hideMenuItem" => {
|
||||
let Some(item) = p.get("item").and_then(Value::as_str) else { return Some(Err("missing item".into())) };
|
||||
let hide = p.get("hidden").and_then(Value::as_bool).unwrap_or(true);
|
||||
@@ -269,13 +270,17 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
|
||||
"app.fittingOptions" => {
|
||||
let g = app.session.active().and_then(|d| d.selection.items.first().and_then(|id| d.doc.item(*id)).and_then(|it| it.graphic().cloned()));
|
||||
let Some(g) = g else { return Some(Err("select a frame with a placed graphic".into())) };
|
||||
let unit = app.session.active().map(|d| d.doc.settings.horizontal_units).unwrap_or(designcraft_geom::Unit::Picas);
|
||||
let fitting = serde_json::to_value(g.auto_fit).unwrap_or(json!("none"));
|
||||
let c = |v: f64| json!(designcraft_geom::format_measure(v, designcraft_geom::Unit::Points));
|
||||
app.ui.dialog = Some(crate::dialogs::Dialog::new(
|
||||
let c = |v: f64| json!(designcraft_geom::format_measure(v, unit));
|
||||
let mut dialog = crate::dialogs::Dialog::new(
|
||||
"fittingOptions",
|
||||
json!({"autoFit": g.auto_fit != designcraft_doc::Fitting::None, "fitting": fitting, "align": g.fit_align,
|
||||
"cropTop": c(g.crop[0]), "cropLeft": c(g.crop[1]), "cropBottom": c(g.crop[2]), "cropRight": c(g.crop[3])}),
|
||||
));
|
||||
);
|
||||
dialog.unit = unit;
|
||||
dialog.vertical_unit = Some(unit);
|
||||
app.ui.dialog = Some(dialog);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"app.userDictionary" => {
|
||||
|
||||
@@ -52,6 +52,21 @@ pub fn shortcut_of(app: &DesignApp, id: &str) -> Option<String> {
|
||||
crate::keys::shortcut(&app.keymap, &craft_keymap::CommandRef::new(id))
|
||||
}
|
||||
|
||||
/// Whether the macOS menu bar can carry a shortcut ("Cmd+Shift+]") as an item's key equivalent.
|
||||
/// It needs Cmd, Ctrl or Option; modifier-less shortcuts stay in the app so typing works. Option
|
||||
/// (with or without Shift) on a letter, digit, symbol or Space types a character on macOS, so the
|
||||
/// window takes that key before the bar sees it: such a shortcut stays in the app too, or it would
|
||||
/// run nowhere (#2710).
|
||||
pub fn native_key_equivalent(sc: &str) -> bool {
|
||||
let Ok(binding) = craft_keymap::Binding::parse(sc) else { return false };
|
||||
let chord = binding.trigger.chord;
|
||||
let (mods, key) = (chord.mods, chord.key);
|
||||
if mods.cmd || mods.ctrl {
|
||||
return true;
|
||||
}
|
||||
mods.alt && !(key.is_letter() || key.is_digit() || key.is_symbol() || key == craft_keymap::Key::Space)
|
||||
}
|
||||
|
||||
/// The shortcut a menu row shows: its own binding (a panel's), else its command's.
|
||||
pub fn shortcut_label(app: &DesignApp, id: &str, params: &Value) -> Option<String> {
|
||||
let cmd = crate::keys::command_ref(id, params);
|
||||
@@ -169,6 +184,9 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool {
|
||||
if matches!(id, "app.justificationDialog" | "app.hyphenationDialog") {
|
||||
return enabled(app, "type.para");
|
||||
}
|
||||
if matches!(id, "app.cellOptionsDialog" | "app.diagonalLinesDialog") {
|
||||
return enabled(app, "table.setCell");
|
||||
}
|
||||
if id == "app.graphicCell" {
|
||||
return enabled(app, "table.placeGraphic");
|
||||
}
|
||||
|
||||
@@ -437,6 +437,7 @@ pub const MENUS: &[(&str, &[&str])] = &[
|
||||
"-",
|
||||
">Cell Options",
|
||||
"ui:app.cellOptionsDialog",
|
||||
"ui:app.diagonalLinesDialog",
|
||||
"<",
|
||||
"-",
|
||||
">Insert",
|
||||
|
||||
@@ -986,6 +986,32 @@ fn fitting_has_indesigns_shortcuts() {
|
||||
assert!((width(&app) - 200.0).abs() < 1e-6, "fitted: {}", width(&app));
|
||||
}
|
||||
|
||||
/// Frame Fitting Options shows and reads its crop amounts in the document's ruler unit (#2812).
|
||||
#[test]
|
||||
fn fitting_options_follow_the_ruler_units() {
|
||||
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();
|
||||
let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
|
||||
let f = app.run("frame.create", json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("file.place", json!({"base64": designcraft_engine::cmd::base64_encode(&png), "name": "a.png", "frame": f})).unwrap();
|
||||
app.run("selection.set", json!({"ids": [f]})).unwrap();
|
||||
run_ui(&mut app, "app.fittingOptions", &json!({})).unwrap().unwrap();
|
||||
let d = app.ui.dialog.as_ref().expect("Frame Fitting Options dialog");
|
||||
assert_eq!(d.id, "fittingOptions");
|
||||
assert_eq!(d.unit, designcraft_geom::Unit::Millimeters, "a bare number means the ruler unit");
|
||||
for k in ["cropTop", "cropLeft", "cropBottom", "cropRight"] {
|
||||
assert!(d.s(k).contains("mm"), "{k} is prefilled in millimetres, got {:?}", d.s(k));
|
||||
}
|
||||
// A bare number typed in a crop field is millimetres, not points.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("cropTop".into(), json!("2"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let it = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone();
|
||||
let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("placed graphic") };
|
||||
let want = 2.0 * designcraft_geom::units::PT_PER_MM;
|
||||
assert!((g.crop[0] - want).abs() < 1e-6, "cropTop 2 means 2 mm ({} pt), got {}", want, g.crop[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_and_presentation_hide_floating_panels_too() {
|
||||
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
@@ -1793,6 +1819,40 @@ fn cmd_plus_zooms_the_canvas_not_the_window() {
|
||||
assert!(zooms_out(&mut app, egui::Key::Num9), "the second binding runs in the app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_shortcut_the_mac_menu_bar_cannot_take_runs_in_the_app() {
|
||||
use egui::{Key, Modifiers};
|
||||
// ⌥⇧P types ∏ on macOS, so the window takes the key before the menu bar sees it (#2710):
|
||||
// the bar carries no such key equivalent, and the app runs it.
|
||||
assert!(!crate::menus::native_key_equivalent("Alt+Shift+P"));
|
||||
assert!(!crate::menus::native_key_equivalent("Alt+1"));
|
||||
assert!(!crate::menus::native_key_equivalent("Alt+Space"));
|
||||
assert!(!crate::menus::native_key_equivalent("Shift+P"));
|
||||
for sc in ["Cmd+Shift+P", "Ctrl+P", "Cmd+Alt+P", "Alt+Shift+F11", "Alt+PageDown"] {
|
||||
assert!(crate::menus::native_key_equivalent(sc), "{sc}");
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap();
|
||||
app.run("selection.set", json!({"ids": [frame["id"]]})).unwrap();
|
||||
run_ui(&mut app, "window.setShortcut", &json!({"id": "type.fillWithPlaceholder", "shortcut": "Alt+Shift+P"})).unwrap().unwrap();
|
||||
// The macOS menu bar, as `NativeMenu` builds it.
|
||||
app.native_menu = true;
|
||||
for id in ["type.fillWithPlaceholder", "view.zoomIn"] {
|
||||
let sc = shortcut_of(&app, id).unwrap();
|
||||
if crate::menus::native_key_equivalent(&sc) {
|
||||
app.native_shortcuts.insert(id.to_string(), sc);
|
||||
}
|
||||
}
|
||||
assert!(app.native_shortcuts.contains_key("view.zoomIn"));
|
||||
assert_eq!(app.session.tool_id(), "selection");
|
||||
native_frame(&mut app, &ctx, vec![], None);
|
||||
native_frame(&mut app, &ctx, vec![], None);
|
||||
press(&mut app, &ctx, Key::P, Modifiers::ALT | Modifiers::SHIFT);
|
||||
assert!(!story_text(&app, &frame["story"]).is_empty(), "⌥⇧P fills the selected frame with placeholder text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_quick_apply_shortcut_opens_it_without_running_an_entry() {
|
||||
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
|
||||
@@ -146,6 +146,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
|
||||
None,
|
||||
"{} — Cell Options › Strokes and Fills of the target cells: edge proxy, stroke weight, type, colour, tint, gap colour, gap tint, and cell fill (table.setCell)",
|
||||
),
|
||||
(
|
||||
"app.diagonalLinesDialog",
|
||||
"Diagonal Lines…",
|
||||
None,
|
||||
"{} — Cell Options › Diagonal Lines of the target cells: the line type, its weight, type, color, tint, gap color and gap tint, and Draw (table.setCell {diagonal})",
|
||||
),
|
||||
("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),
|
||||
("app.rubyDialog", "Ruby…", None, "{} — the reading set over the selected text"),
|
||||
(
|
||||
|
||||
@@ -63,13 +63,15 @@ fn regular(styles: &[String]) -> String {
|
||||
styles.iter().find(|s| *s == "Regular").or(styles.first()).cloned().unwrap_or_else(|| "Regular".into())
|
||||
}
|
||||
|
||||
fn meta(ui: &Ui, fonts: &designcraft_fonts::ScopedFonts<'static>, scope: u32, family: &str) -> FamilyMeta {
|
||||
fn meta(ui: &Ui, fonts: &designcraft_fonts::ScopedFonts<'_>, scope: u32, family: &str) -> FamilyMeta {
|
||||
let key = egui::Id::unique(("font_meta", family, scope));
|
||||
if let Some(m) = ui.data(|d| d.get_temp::<FamilyMeta>(key)) {
|
||||
return m;
|
||||
}
|
||||
let styles = fonts.styles(family);
|
||||
let kind = fonts.face(family, ®ular(&styles)).kind();
|
||||
// Loading a catalogued variable font discovers its named instances.
|
||||
let styles = fonts.styles(family);
|
||||
let m = FamilyMeta { styles, kind };
|
||||
ui.data_mut(|d| d.insert_temp(key, m.clone()));
|
||||
m
|
||||
@@ -730,3 +732,116 @@ mod preview_cache_tests {
|
||||
assert!(c.get(key(Previews::CAP + 39)).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod variable_catalog_regression {
|
||||
#[test]
|
||||
#[ignore = "requires the pinned Bricolage fixture; see docs/testing-variable-fonts.md"]
|
||||
fn cold_family_menu_contains_named_instances() {
|
||||
let path = std::env::var_os("DESIGNCRAFT_TEST_VARIABLE_FONT").expect("set DESIGNCRAFT_TEST_VARIABLE_FONT");
|
||||
let path = std::path::PathBuf::from(path);
|
||||
let db = Box::leak(Box::new(designcraft_fonts::FontDb::with_font_dirs(vec![path.parent().unwrap().to_owned()])));
|
||||
let fonts = db.scoped(0);
|
||||
assert!(!fonts.styles("Bricolage Grotesque").contains(&"SemiBold".into()), "the fixture must be catalogued but not loaded");
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |root| {
|
||||
egui::CentralPanel::default().show(root, |ui| {
|
||||
let first = super::meta(ui, &fonts, 0, "Bricolage Grotesque");
|
||||
assert!(
|
||||
first.styles.contains(&"SemiBold".into()),
|
||||
"cold menu cached {:?}, live styles {:?}",
|
||||
first.styles,
|
||||
fonts.styles("Bricolage Grotesque")
|
||||
);
|
||||
let second = super::meta(ui, &fonts, 0, "Bricolage Grotesque");
|
||||
assert_eq!(first.styles, second.styles);
|
||||
});
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
|
||||
// Exercise the family menu's actual style-row selection too.
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
designcraft_fonts::FontDb::global().add_font(std::fs::read(&path).unwrap());
|
||||
let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
let menu: Vec<_> =
|
||||
designcraft_fonts::FontDb::global().scoped(0).family_infos().into_iter().filter(|f| f.family == "Bricolage Grotesque").collect();
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.with_size(egui::vec2(1000.0, 800.0))
|
||||
.build_ui_state(
|
||||
move |ui, state: &mut (crate::DesignApp, Option<super::FontPick>)| {
|
||||
let key = egui::Id::unique("font_menu_state");
|
||||
let mut st: super::MenuState = ui.data(|d| d.get_temp(key)).unwrap_or_default();
|
||||
st.expanded.insert("Bricolage Grotesque".into());
|
||||
ui.data_mut(|d| d.insert_temp(key, st));
|
||||
let m = super::font_menu_header(&mut state.0, ui, &menu, "Bricolage Grotesque", 560.0);
|
||||
if let Some(pick) = super::font_menu_list(ui, m) {
|
||||
state.1 = Some(pick);
|
||||
}
|
||||
},
|
||||
(app, None),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_label("SemiBold").click();
|
||||
h.run_steps(3);
|
||||
let pick = h.state().1.as_ref().expect("a style row was picked");
|
||||
assert_eq!(pick.family, "Bricolage Grotesque");
|
||||
assert_eq!(pick.style.as_deref(), Some("SemiBold"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod synthetic_variable_catalog_regression {
|
||||
#[test]
|
||||
fn family_menu_selects_a_synthetic_named_instance() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let family = "Synthetic Menu Wiring";
|
||||
let db = designcraft_fonts::FontDb::global();
|
||||
db.add_font(designcraft_fonts::testing::variable_font(family).unwrap());
|
||||
let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
|
||||
let menu: Vec<_> = db.scoped(0).family_infos().into_iter().filter(|f| f.family == family).collect();
|
||||
let mut h = Harness::builder()
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx, "");
|
||||
})
|
||||
.with_size(egui::vec2(1000.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, state: &mut (crate::DesignApp, Option<super::FontPick>)| {
|
||||
let key = egui::Id::unique("font_menu_state");
|
||||
let mut st: super::MenuState = ui.data(|d| d.get_temp(key)).unwrap_or_default();
|
||||
st.expanded.insert(family.into());
|
||||
ui.data_mut(|d| d.insert_temp(key, st));
|
||||
let m = super::font_menu_header(&mut state.0, ui, &menu, family, 560.0);
|
||||
if let Some(pick) = super::font_menu_list(ui, m) {
|
||||
state.1 = Some(pick);
|
||||
}
|
||||
},
|
||||
(app, None),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_label("SemiBold").click();
|
||||
h.run_steps(3);
|
||||
let pick = h.state().1.as_ref().expect("the real Family menu selected a style");
|
||||
assert_eq!(pick.family, family);
|
||||
assert_eq!(pick.style.as_deref(), Some("SemiBold"));
|
||||
}
|
||||
#[test]
|
||||
fn cold_family_menu_discovers_and_caches_named_instances() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let family = "Synthetic Cold Menu";
|
||||
std::fs::write(dir.path().join("variable.ttf"), designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
|
||||
let db = designcraft_fonts::FontDb::with_font_dirs(vec![dir.path().to_owned()]);
|
||||
let fonts = db.scoped(0);
|
||||
assert_eq!(fonts.styles(family), ["Regular"]);
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let first = super::meta(ui, &fonts, 0, family);
|
||||
assert_eq!(first.styles, ["Regular", "SemiBold"]);
|
||||
let second = super::meta(ui, &fonts, 0, family);
|
||||
assert_eq!(first.styles, second.styles);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,8 +293,16 @@ const LAYOUT_COL_MIN: f32 = 96.0;
|
||||
/// A spread's label under its thumbnails, as InDesign's: one name for a single page, "2–3" for
|
||||
/// pages numbered on in one section (an en dash), and the names apart ("2, 1", "8, A") when a section starts
|
||||
/// inside the spread.
|
||||
/// The names read left to right as the thumbnails are drawn, so a spread bound right to left
|
||||
/// lists its second page first.
|
||||
pub(crate) fn spread_label(app: &DesignApp, doc: &designcraft_doc::Document, first: usize, n: usize) -> String {
|
||||
let names: Vec<String> = (first..first + n).map(|abs| app.session.page_label(abs)).collect();
|
||||
let mut order: Vec<usize> = (first..first + n).collect();
|
||||
// In the order the thumbnails are drawn: by each page's x (a right-to-left pair shows its second page on the left).
|
||||
if let Some(sp) = doc.page_loc(first).and_then(|(si, _)| doc.spreads.get(si)) {
|
||||
let x = |abs: usize| sp.pages.get(abs.saturating_sub(first)).map_or(0.0, |p| p.x);
|
||||
order.sort_by(|&a, &b| x(a).total_cmp(&x(b)));
|
||||
}
|
||||
let names: Vec<String> = order.into_iter().map(|abs| app.session.page_label(abs)).collect();
|
||||
let starts = |abs: usize| abs == 0 || doc.sections.iter().any(|s| s.start == abs);
|
||||
match (names.first(), names.last()) {
|
||||
(Some(a), Some(b)) if names.len() > 1 => {
|
||||
@@ -1306,6 +1314,26 @@ mod spread_label_tests {
|
||||
assert_eq!(labels(&app), ["1", "2–3", "4–5", "6–7", "8–9"]);
|
||||
}
|
||||
|
||||
/// Bound right to left, a spread's label follows the document's reading order: the left
|
||||
/// page first ("3–2", not "2–3"), and a section inside a spread lists its pages left to
|
||||
/// right. Left-to-right labels are unchanged. A spread of more pages, drawn in document
|
||||
/// order, lists its names in that order, apart while a section still starts inside it.
|
||||
#[test]
|
||||
fn rtl_binding_labels_spreads_in_visual_left_to_right_order() {
|
||||
let mut app = app();
|
||||
assert_eq!(labels(&app), ["1", "2–3", "4–5", "6–7", "8–9"]);
|
||||
app.run("layout.documentSetup", json!({"binding": "rightToLeft"})).unwrap();
|
||||
assert_eq!(labels(&app), ["1", "3–2", "5–4", "7–6", "9–8"]);
|
||||
app.run("layout.section", json!({"page": 3, "startNumber": 1})).unwrap();
|
||||
let got = labels(&app);
|
||||
assert_eq!(got[1], "1, 2");
|
||||
assert_eq!(got[2], "3–2");
|
||||
app.run("layout.pages.toSpread", json!({"page": 4, "spread": 1})).unwrap();
|
||||
// Three pages, drawn in document order: 2, 3 and 4 are numbered 2, 1 and 2, and the
|
||||
// section that starts on page 3 stays inside the spread, so the names stay apart.
|
||||
assert_eq!(labels(&app)[1], "2, 1, 2");
|
||||
}
|
||||
|
||||
/// Labels navigate to document spreads, including when parent editing was active.
|
||||
#[test]
|
||||
fn the_panel_shows_spread_labels_and_a_click_on_one_goes_to_its_spread() {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user