mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-21 13:34:19 -06:00
Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2df2d64cd | ||
|
|
b3f31666d3 | ||
|
|
68f758928e | ||
|
|
840efd03fb | ||
|
|
8e8ab631fd | ||
|
|
8a9d04eeb1 | ||
|
|
266407e840 | ||
|
|
c817cc95c6 | ||
|
|
ff0823f40d | ||
|
|
211f62231d | ||
|
|
9144b9bfda | ||
|
|
a61cef5d45 | ||
|
|
739491f5c7 | ||
|
|
8377ea8e8f | ||
|
|
4357166531 | ||
|
|
5d871d0519 | ||
|
|
ae2d2b43d6 | ||
|
|
cd23034f65 | ||
|
|
b2306fe5ef | ||
|
|
646fbc7cd5 | ||
|
|
4a347e070a | ||
|
|
3bf4c05461 | ||
|
|
7b26a94193 | ||
|
|
ace000b4a4 | ||
|
|
7adbdc574c | ||
|
|
f77eef9cb6 | ||
|
|
a2f41d728e | ||
|
|
9fe9bd5042 | ||
|
|
83c3b5890b | ||
|
|
f472620ac0 | ||
|
|
5467f998a0 | ||
|
|
78dfa8f648 | ||
|
|
82f0c467be | ||
|
|
837a610133 | ||
|
|
de977bcde6 | ||
|
|
4ba0595760 | ||
|
|
6854bd1fb3 | ||
|
|
4356771236 | ||
|
|
cdf146cabd | ||
|
|
54e3e1cf34 | ||
|
|
97c13a2990 | ||
|
|
fe8a8a838c | ||
|
|
2bd6f372c5 | ||
|
|
8a1f101c46 | ||
|
|
42f8559b97 | ||
|
|
bf8b37759c | ||
|
|
1ed889c24c | ||
|
|
6a7af0d679 | ||
|
|
ce6e4094d5 | ||
|
|
9088ed777d | ||
|
|
cc90520b9d | ||
|
|
a95b065c2b | ||
|
|
84026f98b2 | ||
|
|
5f228a0e24 | ||
|
|
b354e0f870 | ||
|
|
86352d5cf3 | ||
|
|
3e776e4c7d | ||
|
|
a9a1aa36a2 | ||
|
|
bc0e51ee4d | ||
|
|
ed66198574 | ||
|
|
d53a740be1 | ||
|
|
e9750c5cb7 | ||
|
|
3d5a153e3d | ||
|
|
7bff3b53e9 | ||
|
|
0909b15eae | ||
|
|
52d17a91df | ||
|
|
323cf78232 | ||
|
|
e6e8c61dbf | ||
|
|
42a5df5f94 | ||
|
|
1d150004f7 | ||
|
|
0aefd4d025 | ||
|
|
235a38c665 | ||
|
|
3bf7a5dbbe | ||
|
|
e40199bf6f | ||
|
|
e2f94ecef9 | ||
|
|
7ccfd4caef | ||
|
|
7b3b6f8041 | ||
|
|
f8c66d0692 | ||
|
|
fecb717f99 | ||
|
|
aba890e8a6 | ||
|
|
0cc92c9744 | ||
|
|
b02baeba43 | ||
|
|
3c77297b83 | ||
|
|
60415e055c | ||
|
|
0db15a1d5e | ||
|
|
33afe69094 | ||
|
|
669d5df0b1 | ||
|
|
953f43baed | ||
|
|
acf5eb8727 | ||
|
|
bd188c19d8 | ||
|
|
56a28f33b7 | ||
|
|
cd4ab71552 | ||
|
|
6272c9a4da | ||
|
|
172e56f12e | ||
|
|
b66122f718 | ||
|
|
4e1b6a71ab | ||
|
|
b2ec73926f | ||
|
|
7f90fd0bf1 | ||
|
|
4388fba5b2 | ||
|
|
c341669dbd | ||
|
|
a4d28e2586 |
+5
-1
@@ -1 +1,5 @@
|
||||
craft-i18n.rev text eol=lf
|
||||
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
|
||||
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
|
||||
* text=auto
|
||||
|
||||
craft-i18n.rev text eol=lf
|
||||
@@ -18,4 +18,7 @@ jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets: inherit
|
||||
|
||||
Generated
+349
-100
@@ -155,13 +155,28 @@ version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-no-stdlib 2.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -210,15 +225,6 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -523,6 +529,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -614,9 +626,9 @@ version = "8.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"brotli-decompressor",
|
||||
"alloc-no-stdlib 2.0.4",
|
||||
"alloc-stdlib 0.2.4",
|
||||
"brotli-decompressor 5.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -625,8 +637,18 @@ version = "5.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"alloc-no-stdlib 2.0.4",
|
||||
"alloc-stdlib 0.2.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "6.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib 3.0.0",
|
||||
"alloc-stdlib 0.3.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1022,17 +1044,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
@@ -1048,7 +1070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1068,7 +1090,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
@@ -1079,7 +1101,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1122,6 +1144,19 @@ name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
"craft-mime",
|
||||
"craft-wordmodel",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
@@ -1145,19 +1180,83 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-jpeg",
|
||||
"craft-metadata",
|
||||
"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-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
"craft-mime",
|
||||
"craft-wordmodel",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
"craft-wordmodel",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1165,10 +1264,58 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
"craft-metafile",
|
||||
"craft-wordmodel",
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
"craft-xml",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1185,7 +1332,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1230,7 +1377,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1240,6 +1387,29 @@ dependencies = [
|
||||
"image",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1#6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -1284,7 +1454,7 @@ dependencies = [
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip 9.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1329,7 +1499,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -1340,10 +1510,35 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
"md-5",
|
||||
"miniz_oxide 0.9.1",
|
||||
"sha1 0.10.7",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
"craft-sheet",
|
||||
"craft-xml",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1352,11 +1547,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=75c70fa6a786240eb853e6267e25fc445f510cd0#75c70fa6a786240eb853e6267e25fc445f510cd0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1484,17 +1679,6 @@ version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dify"
|
||||
version = "0.8.0"
|
||||
@@ -1906,6 +2090,22 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
"half",
|
||||
"lebe",
|
||||
"miniz_oxide 0.8.9",
|
||||
"multiversion",
|
||||
"rayon-core",
|
||||
"smallvec",
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2954,6 +3154,7 @@ dependencies = [
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -3102,6 +3303,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -3185,6 +3392,12 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
|
||||
[[package]]
|
||||
name = "lebe"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -3273,6 +3486,16 @@ version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -3344,6 +3567,28 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
|
||||
dependencies = [
|
||||
"multiversion-macros",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion-macros"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -4287,6 +4532,15 @@ version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
@@ -5564,6 +5818,12 @@ dependencies = [
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-features"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -7010,16 +7270,17 @@ dependencies = [
|
||||
name = "wordcraft-cli"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-zip",
|
||||
"image",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-engine",
|
||||
"wordcraft-fonts",
|
||||
"wordcraft-geom",
|
||||
"wordcraft-mcp",
|
||||
"wordcraft-render",
|
||||
"wordcraft-zotero",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7060,15 +7321,15 @@ dependencies = [
|
||||
"cfb",
|
||||
"craft-docx",
|
||||
"craft-wordmodel",
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"image",
|
||||
"log",
|
||||
"proptest",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-geom",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7079,7 +7340,9 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-font-catalog",
|
||||
"craft-font-store",
|
||||
"craft-mime",
|
||||
"craft-proof",
|
||||
"craft-zip",
|
||||
"encoding_rs",
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
@@ -7102,14 +7365,13 @@ dependencies = [
|
||||
"wordcraft-pdf",
|
||||
"wordcraft-render",
|
||||
"zeroize",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-fonts"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"brotli-decompressor 5.0.3",
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
"log",
|
||||
@@ -7123,35 +7385,38 @@ dependencies = [
|
||||
name = "wordcraft-formats"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"cfb",
|
||||
"chardetng",
|
||||
"chrono",
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
"craft-image-codecs",
|
||||
"craft-latex",
|
||||
"craft-markdown",
|
||||
"craft-math",
|
||||
"craft-metafile",
|
||||
"craft-mime",
|
||||
"craft-odf",
|
||||
"craft-ods",
|
||||
"craft-rtf",
|
||||
"craft-sheet",
|
||||
"craft-wordmodel",
|
||||
"craft-xls",
|
||||
"craft-xlsx",
|
||||
"craft-zip",
|
||||
"encoding_rs",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
"proptest",
|
||||
"quick-xml 0.41.0",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-docx",
|
||||
"wordcraft-geom",
|
||||
"wordcraft-metafile",
|
||||
"zeroize",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-geom"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1)",
|
||||
"image",
|
||||
"serde",
|
||||
]
|
||||
@@ -7160,6 +7425,7 @@ dependencies = [
|
||||
name = "wordcraft-layout"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-metafile",
|
||||
"craft-proof",
|
||||
"image",
|
||||
"js-sys",
|
||||
@@ -7173,7 +7439,6 @@ dependencies = [
|
||||
"wordcraft-doc",
|
||||
"wordcraft-fonts",
|
||||
"wordcraft-geom",
|
||||
"wordcraft-metafile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7188,19 +7453,12 @@ dependencies = [
|
||||
"wordcraft-render",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-metafile"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-pdf"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-metafile",
|
||||
"craft-pdf",
|
||||
"hayro-cmap",
|
||||
"hayro-interpret",
|
||||
@@ -7214,13 +7472,13 @@ dependencies = [
|
||||
"wordcraft-fonts",
|
||||
"wordcraft-geom",
|
||||
"wordcraft-layout",
|
||||
"wordcraft-metafile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-render"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-metafile",
|
||||
"image",
|
||||
"log",
|
||||
"vello_cpu",
|
||||
@@ -7228,7 +7486,6 @@ dependencies = [
|
||||
"wordcraft-fonts",
|
||||
"wordcraft-geom",
|
||||
"wordcraft-layout",
|
||||
"wordcraft-metafile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7242,6 +7499,7 @@ dependencies = [
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
"craft-zip",
|
||||
"egui",
|
||||
"egui_extras",
|
||||
"egui_kittest",
|
||||
@@ -7261,7 +7519,6 @@ dependencies = [
|
||||
"wordcraft-render",
|
||||
"wordcraft-zotero",
|
||||
"zbus",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7333,7 +7590,7 @@ version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "200a7b806377b65f1ff9a985874332f15357c87e5dd7855f35f06dade95b8b3d"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"brotli-decompressor 5.0.3",
|
||||
"bytes",
|
||||
"flate2",
|
||||
]
|
||||
@@ -7693,20 +7950,6 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
@@ -7735,24 +7978,21 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zopfli"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"crc32fast",
|
||||
"log",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-core"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-inflate"
|
||||
version = "0.2.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.5.15"
|
||||
@@ -7762,6 +8002,15 @@ dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpegxl"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
|
||||
dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.15.0"
|
||||
|
||||
+23
-8
@@ -36,7 +36,7 @@ wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-metafile = { path = "crates/metafile" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -66,16 +66,29 @@ wuff = "0.2.9"
|
||||
# `forbid(unsafe_code)` in its default build, no_std-capable (builds for wasm), BSD-3-Clause/MIT.
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "bmp", "tiff"] }
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6ef2c053dfa758a9e292ff6ce4398bcd84aab1a1", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
# 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-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -110,6 +123,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
|
||||
@@ -124,7 +124,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
|
||||
| **References** | Table of contents, footnotes and endnotes, citations and bibliography (APA, MLA, Chicago, IEEE), captions, table of figures, cross-references, index, table of authorities |
|
||||
| **Review** | Spelling and grammar with suggestions (English and Polish, by each run's language), thesaurus, word count, comments in margin balloons or a pane, track changes, accept/reject, compare documents, restrict editing, accessibility checker, document inspector |
|
||||
| **Mailings** | Mail merge from CSV, merge fields, address block, greeting line, rules, preview, finish to a document; envelopes and labels |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) or Slovenščina (follows the system language by default) |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) Slovenščina or Bosanski (follows the system language by default) |
|
||||
| **Files** | .docx read/write, legacy 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
|
||||
|
||||
The honest picture, area by area, is in [ROADMAP.md](ROADMAP.md), the
|
||||
|
||||
+15
-1
File diff suppressed because one or more lines are too long
@@ -24,5 +24,6 @@ sys-locale = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
|
||||
@@ -35,10 +35,11 @@ USAGE:
|
||||
--strict writes nothing and exits 3 if a character on the
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] --cmd 'id={json}' [--cmd …]
|
||||
[--save OUT] [--print] [--author NAME]
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
@@ -64,11 +63,11 @@ fn uncovered() -> char {
|
||||
}
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 90, 200, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn pic(rid: &str) -> String {
|
||||
@@ -106,7 +105,7 @@ fn package(document: &str, document_rels: &str, extra: &[(&str, &[u8])]) -> Vec<
|
||||
r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{REL}/officeDocument" Target="word/document.xml"/></Relationships>"#
|
||||
);
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/octet-stream"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
let mut parts: Vec<(&str, &[u8])> = vec![
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", rels.as_bytes()),
|
||||
@@ -115,10 +114,9 @@ fn package(document: &str, document_rels: &str, extra: &[(&str, &[u8])]) -> Vec<
|
||||
];
|
||||
parts.extend_from_slice(extra);
|
||||
for (name, bytes) in parts {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -369,8 +369,11 @@ mod tests {
|
||||
|
||||
impl Conn {
|
||||
fn open(port: u16) -> Self {
|
||||
Self::open_within(port, Duration::from_secs(5))
|
||||
}
|
||||
fn open_within(port: u16, read_timeout: Duration) -> Self {
|
||||
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
s.set_read_timeout(Some(read_timeout)).unwrap();
|
||||
Self(BufReader::new(s.try_clone().unwrap()), s)
|
||||
}
|
||||
fn send(&mut self, line: &str) {
|
||||
@@ -388,7 +391,24 @@ mod tests {
|
||||
/// The server closed the connection.
|
||||
fn closed(&mut self) -> bool {
|
||||
let mut r = String::new();
|
||||
matches!(self.0.read_line(&mut r), Ok(0))
|
||||
closed_by_peer(self.0.read_line(&mut r))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
|
||||
/// which is how Windows can deliver a close when the writer had nothing to read back (the
|
||||
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
|
||||
/// not UTF-8, leaves the connection open.
|
||||
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
|
||||
match read {
|
||||
Ok(n) => n == 0,
|
||||
Err(e) => matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::ConnectionAborted
|
||||
| std::io::ErrorKind::NotConnected
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,13 +493,29 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closure_errors_mean_the_peer_closed() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert!(closed_by_peer(Ok(0)), "end of stream");
|
||||
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
|
||||
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
|
||||
}
|
||||
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
|
||||
// Not UTF-8, a timeout or a would-block leave the socket open.
|
||||
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
|
||||
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_connection_is_closed() {
|
||||
let (port, rx) = boot_with(Duration::from_millis(300));
|
||||
let mut quiet = Conn::open(port);
|
||||
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
|
||||
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
|
||||
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
|
||||
let t0 = Instant::now();
|
||||
assert!(quiet.closed());
|
||||
assert!(t0.elapsed() < Duration::from_secs(3));
|
||||
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
|
||||
// After an authorised request the connection may stay idle.
|
||||
let mut busy = Conn::open(port);
|
||||
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1e515422afdda2f317af430c1f9d68a5f83935b4
|
||||
e56d26244bbac099bfd42e23fb12f78a4be418a7
|
||||
|
||||
@@ -94,8 +94,8 @@ pub use settings::{
|
||||
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
|
||||
THEME_COLORS, Watermark, Zoom, ZoomFit,
|
||||
};
|
||||
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
|
||||
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
|
||||
pub(crate) use text_walk::walk_between;
|
||||
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
|
||||
|
||||
/// A document.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
|
||||
}
|
||||
|
||||
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
|
||||
pub(crate) const PARA_WALK_DEPTH: usize = 16;
|
||||
pub const PARA_WALK_DEPTH: usize = 16;
|
||||
|
||||
/// The note and text box stories an object shows, for `Document::reachable`.
|
||||
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
|
||||
|
||||
@@ -12,16 +12,16 @@ workspace = true
|
||||
craft-docx = { workspace = true }
|
||||
craft-wordmodel = { workspace = true }
|
||||
wordcraft-doc = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-doc = { workspace = true, features = ["test-support"] }
|
||||
wordcraft-geom = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
base64 = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
log = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
image = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
|
||||
+6
-27
@@ -19,39 +19,18 @@ pub(crate) const KIND: &str = "wordcraft-fit-v1";
|
||||
/// Serialize `fit` as the custom XML store.
|
||||
pub(crate) fn write(fit: &FitState) -> Result<Vec<u8>, DocxError> {
|
||||
let json = serde_json::to_string(fit).map_err(|e| DocxError::Xml(e.to_string()))?;
|
||||
let esc_json = quick_xml::escape::escape(&json);
|
||||
let esc_json = craft_xml::esc(&json);
|
||||
Ok(format!(r#"<?xml version="1.0" encoding="UTF-8"?><{ROOT} xmlns="{NS}" kind="{KIND}"><fitState>{}</fitState></{ROOT}>"#, esc_json).into_bytes())
|
||||
}
|
||||
|
||||
/// Read the state from a custom XML part's bytes, if it is ours.
|
||||
pub(crate) fn read_from_bytes(bytes: &[u8]) -> Option<FitState> {
|
||||
let mut reader = quick_xml::Reader::from_reader(bytes);
|
||||
let mut buf = Vec::new();
|
||||
let mut is_our_kind = false;
|
||||
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Ok(quick_xml::events::Event::Start(ref e)) => {
|
||||
let name = e.local_name();
|
||||
if name.as_ref() == ROOT.as_bytes() {
|
||||
for attr in e.attributes().flatten() {
|
||||
if attr.key.local_name().as_ref() == b"kind" && attr.value.as_ref() == KIND.as_bytes() {
|
||||
is_our_kind = true;
|
||||
}
|
||||
}
|
||||
} else if name.as_ref() == b"fitState" && is_our_kind {
|
||||
let text = reader.read_text(e.to_end().name()).ok()?;
|
||||
let s = std::str::from_utf8(text.as_ref()).ok()?;
|
||||
let unescaped = quick_xml::escape::unescape(s).ok()?;
|
||||
return serde_json::from_str(&unescaped).ok();
|
||||
}
|
||||
}
|
||||
Ok(quick_xml::events::Event::Eof) | Err(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
buf.clear();
|
||||
let root = craft_xml::parse(bytes).ok()?;
|
||||
if root.local() != ROOT || root.attr("kind") != Some(KIND) {
|
||||
return None;
|
||||
}
|
||||
None
|
||||
let text = root.child_text("fitState")?;
|
||||
serde_json::from_str(text.as_ref()).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Bounded conversion between craft-wordmodel and WordCraft's document model.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_docx::DocxError;
|
||||
@@ -29,24 +30,29 @@ where
|
||||
// From Shared Model -> WordCraft Document
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn blocks_from_shared(source: craft_wordmodel::Blocks) -> Result<wordcraft_doc::Blocks, DocxError> {
|
||||
type GraphicCache = HashMap<usize, Arc<wordcraft_doc::graphic::Graphic>>;
|
||||
|
||||
fn blocks_from_shared(source: craft_wordmodel::Blocks, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Blocks, DocxError> {
|
||||
source
|
||||
.into_iter()
|
||||
.map(|block| {
|
||||
let block = Arc::try_unwrap(block).unwrap_or_else(|shared| (*shared).clone());
|
||||
block_value_from_shared(block).map(Arc::new)
|
||||
block_value_from_shared(block, graphics).map(Arc::new)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn block_value_from_shared(source: craft_wordmodel::Block) -> Result<wordcraft_doc::Block, DocxError> {
|
||||
fn block_value_from_shared(source: craft_wordmodel::Block, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Block, DocxError> {
|
||||
match source {
|
||||
craft_wordmodel::Block::Para(paragraph) => paragraph_value_from_shared(paragraph).map(wordcraft_doc::Block::Para),
|
||||
craft_wordmodel::Block::Table(table) => table_value_from_shared(table).map(wordcraft_doc::Block::Table),
|
||||
craft_wordmodel::Block::Para(paragraph) => paragraph_value_from_shared(paragraph, graphics).map(wordcraft_doc::Block::Para),
|
||||
craft_wordmodel::Block::Table(table) => table_value_from_shared(table, graphics).map(wordcraft_doc::Block::Table),
|
||||
}
|
||||
}
|
||||
|
||||
fn paragraph_value_from_shared(source: craft_wordmodel::para::Paragraph) -> Result<wordcraft_doc::para::Paragraph, DocxError> {
|
||||
fn paragraph_value_from_shared(
|
||||
source: craft_wordmodel::para::Paragraph,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::Paragraph, DocxError> {
|
||||
let craft_wordmodel::para::Paragraph { text, runs, props, mark, objects, section, .. } = source;
|
||||
let mut paragraph = wordcraft_doc::para::Paragraph::new();
|
||||
paragraph.text = text;
|
||||
@@ -54,12 +60,15 @@ fn paragraph_value_from_shared(source: craft_wordmodel::para::Paragraph) -> Resu
|
||||
runs.into_iter().map(|run| Ok(wordcraft_doc::para::Run { len: run.len, props: convert(run.props)? })).collect::<Result<_, DocxError>>()?;
|
||||
paragraph.props = convert(props)?;
|
||||
paragraph.mark = convert(mark)?;
|
||||
paragraph.objects = objects.into_iter().map(object_value_from_shared).collect::<Result<_, _>>()?;
|
||||
paragraph.objects = objects.into_iter().map(|o| object_value_from_shared(o, graphics)).collect::<Result<_, _>>()?;
|
||||
paragraph.section = section.map(|section| convert(*section).map(Box::new)).transpose()?;
|
||||
Ok(paragraph)
|
||||
}
|
||||
|
||||
fn object_value_from_shared(source: craft_wordmodel::para::InlineObject) -> Result<wordcraft_doc::para::InlineObject, DocxError> {
|
||||
fn object_value_from_shared(
|
||||
source: craft_wordmodel::para::InlineObject,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::InlineObject, DocxError> {
|
||||
use craft_wordmodel::para::InlineObject as Source;
|
||||
use wordcraft_doc::para::InlineObject as Target;
|
||||
|
||||
@@ -74,49 +83,70 @@ fn object_value_from_shared(source: craft_wordmodel::para::InlineObject) -> Resu
|
||||
fx: convert(fx)?,
|
||||
ole: ole.map(|o| convert(Arc::try_unwrap(o).unwrap_or_else(|s| (*s).clone())).map(Arc::new)).transpose()?,
|
||||
}),
|
||||
Source::Graphic { w, h, alt, float, graphic } => {
|
||||
let key = Arc::as_ptr(&graphic) as usize;
|
||||
let graphic = if let Some(cached) = graphics.get(&key) {
|
||||
Arc::clone(cached)
|
||||
} else {
|
||||
let converted: Arc<wordcraft_doc::graphic::Graphic> = Arc::new(convert(Arc::try_unwrap(graphic).unwrap_or_else(|s| (*s).clone()))?);
|
||||
graphics.insert(key, Arc::clone(&converted));
|
||||
converted
|
||||
};
|
||||
Ok(Target::Graphic { w, h, alt, float: convert(float)?, graphic })
|
||||
}
|
||||
Source::Group { w, h, float, ch_w, ch_h, children, canvas } => Ok(Target::Group {
|
||||
w,
|
||||
h,
|
||||
float: convert(float)?,
|
||||
ch_w,
|
||||
ch_h,
|
||||
children: children.into_iter().map(group_child_value_from_shared).collect::<Result<_, _>>()?,
|
||||
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
canvas: canvas.map(convert).transpose()?,
|
||||
}),
|
||||
other => convert(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn group_child_value_from_shared(source: craft_wordmodel::para::GroupChild) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj)? })
|
||||
fn group_child_value_from_shared(
|
||||
source: craft_wordmodel::para::GroupChild,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
|
||||
}
|
||||
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
Ok(wordcraft_doc::table::Table {
|
||||
props: convert(source.props)?,
|
||||
grid: source.grid,
|
||||
rows: source.rows.into_iter().map(row_value_from_shared).collect::<Result<_, _>>()?,
|
||||
rows: source.rows.into_iter().map(|r| row_value_from_shared(r, graphics)).collect::<Result<_, _>>()?,
|
||||
controls: convert(source.controls)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn row_value_from_shared(source: craft_wordmodel::table::Row) -> Result<wordcraft_doc::table::Row, DocxError> {
|
||||
fn row_value_from_shared(source: craft_wordmodel::table::Row, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Row, DocxError> {
|
||||
Ok(wordcraft_doc::table::Row {
|
||||
props: convert(source.props)?,
|
||||
cells: source.cells.into_iter().map(cell_value_from_shared).collect::<Result<_, _>>()?,
|
||||
cells: source.cells.into_iter().map(|c| cell_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
controls: convert(source.controls)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_value_from_shared(source: craft_wordmodel::table::Cell) -> Result<wordcraft_doc::table::Cell, DocxError> {
|
||||
Ok(wordcraft_doc::table::Cell { props: convert(source.props)?, blocks: blocks_from_shared(source.blocks)?, controls: convert(source.controls)? })
|
||||
fn cell_value_from_shared(source: craft_wordmodel::table::Cell, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Cell, DocxError> {
|
||||
Ok(wordcraft_doc::table::Cell {
|
||||
props: convert(source.props)?,
|
||||
blocks: blocks_from_shared(source.blocks, graphics)?,
|
||||
controls: convert(source.controls)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn part_value_from_shared(source: craft_wordmodel::Part) -> Result<wordcraft_doc::Part, DocxError> {
|
||||
Ok(wordcraft_doc::Part { kind: convert(source.kind)?, blocks: blocks_from_shared(source.blocks)?, body: convert(source.body)? })
|
||||
fn part_value_from_shared(source: craft_wordmodel::Part, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Part, DocxError> {
|
||||
Ok(wordcraft_doc::Part { kind: convert(source.kind)?, blocks: blocks_from_shared(source.blocks, graphics)?, body: convert(source.body)? })
|
||||
}
|
||||
|
||||
fn glossary_value_from_shared(source: craft_wordmodel::BuildingBlock) -> Result<wordcraft_doc::BuildingBlock, DocxError> {
|
||||
fn glossary_value_from_shared(
|
||||
source: craft_wordmodel::BuildingBlock,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::BuildingBlock, DocxError> {
|
||||
Ok(wordcraft_doc::BuildingBlock {
|
||||
name: source.name,
|
||||
gallery: source.gallery,
|
||||
@@ -126,7 +156,7 @@ fn glossary_value_from_shared(source: craft_wordmodel::BuildingBlock) -> Result<
|
||||
style: source.style,
|
||||
types: source.types,
|
||||
behaviors: source.behaviors,
|
||||
blocks: blocks_from_shared(source.blocks)?,
|
||||
blocks: blocks_from_shared(source.blocks, graphics)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -138,7 +168,7 @@ fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Res
|
||||
target.part_names = source.part_names;
|
||||
target.media_parts = source.media_parts;
|
||||
for item in source.list {
|
||||
target.push(convert(item)?);
|
||||
target.list.push(convert(item)?);
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
@@ -176,10 +206,11 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
..
|
||||
} = source;
|
||||
|
||||
let mut graphics = GraphicCache::new();
|
||||
let mut document = wordcraft_doc::Document::new();
|
||||
document.body = blocks_from_shared(body)?;
|
||||
document.body = blocks_from_shared(body, &mut graphics)?;
|
||||
document.last_section = convert(last_section)?;
|
||||
document.parts = parts.into_iter().map(|(id, part)| Ok((id, part_value_from_shared(part)?))).collect::<Result<_, DocxError>>()?;
|
||||
document.parts = parts.into_iter().map(|(id, part)| Ok((id, part_value_from_shared(part, &mut graphics)?))).collect::<Result<_, DocxError>>()?;
|
||||
document.styles = Arc::new(convert((*styles).clone())?);
|
||||
document.numbering = Arc::new(convert((*numbering).clone())?);
|
||||
document.comments = convert(comments)?;
|
||||
@@ -192,7 +223,7 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
document.endnote_separators = convert(endnote_separators)?;
|
||||
document.media = media;
|
||||
document.passthrough = passthrough;
|
||||
document.glossary = glossary.into_iter().map(glossary_value_from_shared).collect::<Result<_, _>>()?;
|
||||
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
|
||||
document.missing_pictures = missing_pictures_from_shared(missing_pictures)?;
|
||||
document.fit_state = fit_state;
|
||||
Ok(document)
|
||||
@@ -344,7 +375,7 @@ fn missing_pictures_to_shared(source: &wordcraft_doc::MissingPictures) -> Result
|
||||
target.part_names = source.part_names.clone();
|
||||
target.media_parts = source.media_parts.clone();
|
||||
for item in &source.list {
|
||||
target.push(convert_ref(item)?);
|
||||
target.list.push(convert_ref(item)?);
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Alternative format chunks (`w:altChunk`, ECMA-376 §17.17.2.1): content in another format that
|
||||
//! is brought in where the chunk stands. All markup here is synthetic.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::{Block, Document, InlineObject, StoryRef};
|
||||
use wordcraft_docx::{AltChunk, ReadOptions, read, read_with};
|
||||
|
||||
@@ -46,12 +44,11 @@ fn package_styled(body: &str, chunk: Option<(&str, &str, &[u8])>, styles: Option
|
||||
}
|
||||
types.push_str(r#"<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#);
|
||||
files.push(("[Content_Types].xml".into(), types.into_bytes()));
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in files {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(&bytes).unwrap();
|
||||
zw.add(&name, &bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
const CHUNK: &str = r#"<w:altChunk r:id="rIdC"/>"#;
|
||||
@@ -144,12 +141,11 @@ fn package_with_stories(body: &str, stories: &[(&str, &str, String)], chunk: Opt
|
||||
if let Some(c) = chunk {
|
||||
files.push(("word/afchunk.docx".into(), c.to_vec()));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in files {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(&bytes).unwrap();
|
||||
zw.add(&name, &bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A paragraph `text` that comment `id` (in the file) is anchored around.
|
||||
@@ -395,17 +391,16 @@ fn inner_with_dropped_pictures(n: usize, external: bool) -> Vec<u8> {
|
||||
(0..n).map(image).collect::<String>()
|
||||
);
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", ROOT_RELS.as_bytes()),
|
||||
("word/document.xml", doc.as_bytes()),
|
||||
("word/_rels/document.xml.rels", rels.as_bytes()),
|
||||
] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A picture the chunk's own reader dropped is the file's too (#6005), named by the chunk part.
|
||||
|
||||
@@ -2,18 +2,15 @@
|
||||
//! complex-script font, size, bold and italic, and the bidi language. Fixtures are hand-written
|
||||
//! from ECMA-376 Part 1 §17.3.1.6 (bidi), §17.3.2 (run properties).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::{Align, CharProps, ParaProps};
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A package whose body is `body`.
|
||||
@@ -31,10 +28,9 @@ fn paras(d: &Document) -> Vec<&Paragraph> {
|
||||
|
||||
/// `word/document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Persian text with a ZWNJ (نیمفاصله), Persian digits, Latin and punctuation.
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
//! direction changes and marks the right-to-left pieces `w:rtl`, as Word does with text typed
|
||||
//! in a right-to-left paragraph.
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::props::CharProps;
|
||||
@@ -14,10 +13,9 @@ use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
/// `word/document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The runs of the first paragraph of `xml`: (has `w:rtl`, text with `w:br` as `\n`).
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! `thinThickThinLargeGap`, ECMA-376 Part 1 §17.18.2 ST_Border) on paragraphs, table cells and
|
||||
//! pages: written back as read, not as a single line. Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::BorderStyle;
|
||||
|
||||
const LINES: [(&str, BorderStyle); 9] = [
|
||||
@@ -23,19 +21,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn side(name: &str, val: &str) -> String {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
//! Original partial-cell-margin fixture (ECMA-376 §17.4.69).
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
fn fixture() -> Vec<u8> {
|
||||
let document = r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl><w:tblPr><w:tblCellMar><w:top w:w="55" w:type="dxa"/><w:left w:w="45" w:type="dxa"/><w:bottom w:w="55" w:type="dxa"/><w:right w:w="55" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="4320"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcMar><w:left w:w="0" w:type="dxa"/></w:tcMar></w:tcPr><w:p><w:r><w:t>Point</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>"#;
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(document.as_bytes()).unwrap();
|
||||
zip.finish().unwrap().into_inner()
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
zip.add("word/document.xml", document.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -19,9 +17,8 @@ fn partial_margin_stays_partial() {
|
||||
let reopened = wordcraft_docx::read(&bytes).unwrap();
|
||||
let cell = &reopened.body[0].as_table().unwrap().rows[0].cells[0];
|
||||
assert_eq!(cell.props.resolved_margins([6.0, 7.0, 8.0, 9.0]), [6.0, 0.0, 8.0, 9.0]);
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let margins = xml.split("<w:tcMar>").nth(1).unwrap().split("</w:tcMar>").next().unwrap();
|
||||
assert!(margins.contains("<w:left w:w=\"0\""));
|
||||
assert!(!margins.contains("<w:top"));
|
||||
|
||||
@@ -2,18 +2,15 @@
|
||||
//! `w:ind` `w:firstLineChars`, `w:hangingChars`, `w:leftChars` and `w:rightChars`, in hundredths
|
||||
//! of a character. Fixtures are hand-written.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::Document;
|
||||
use wordcraft_doc::props::ParaProps;
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A package whose body is `body`.
|
||||
@@ -44,9 +41,9 @@ fn character_indents_read_and_round_trip() {
|
||||
// Hostile values are clamped or dropped.
|
||||
assert_eq!((p[3].indent_first_chars, p[3].indent_left_chars), (Some(1584.0), None));
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let _z_bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for attr in [r#"w:firstLineChars="200""#, r#"w:leftChars="150""#, r#"w:rightChars="50""#, r#"w:hangingChars="100""#, r#"w:firstLineChars="0""#] {
|
||||
assert!(xml.contains(attr), "{attr} missing: {xml}");
|
||||
}
|
||||
@@ -71,9 +68,9 @@ fn automatic_spacing_reads_and_round_trips() {
|
||||
assert_eq!((rp.space_before, rp.space_after, rp.before_auto), (14.0, 14.0, true), "automatic spacing is 14 pt");
|
||||
assert_eq!(d.styles.resolve_para(&p[2]).space_after, 5.0);
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let _z_bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for attr in [r#"w:beforeAutospacing="1""#, r#"w:afterAutospacing="1""#, r#"w:beforeAutospacing="0""#] {
|
||||
assert!(xml.contains(attr), "{attr} missing");
|
||||
}
|
||||
@@ -90,9 +87,8 @@ fn adjust_right_indent_is_preserved() {
|
||||
assert_eq!(props(&d).iter().map(|p| p.adjust_right_indent).collect::<Vec<_>>(), [Some(false), Some(true), None]);
|
||||
for _ in 0..2 {
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out.clone())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:adjustRightInd w:val="0""#), "explicit false was lost: {xml}");
|
||||
assert!(xml.contains("<w:adjustRightInd/>"), "explicit true was lost: {xml}");
|
||||
let tags = ["<w:adjustRightInd", "<w:snapToGrid", "<w:spacing", "<w:ind"];
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! multi-paragraph results, and custom document properties round-trip. All markup here is
|
||||
//! synthetic, written from ECMA-376.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::{CharProps, Document, InlineObject, Path, StoryRef};
|
||||
use wordcraft_docx::{read, write};
|
||||
@@ -16,12 +14,11 @@ const CITE_B: &str = r#""citationItems":[{"id":7,"uris":["http://zotero.org/user
|
||||
const BIBL: &str = r#" ADDIN ZOTERO_BIBL {"uncited":[],"omitted":[],"custom":[]} CSL_BIBLIOGRAPHY "#;
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn fld(kind: &str) -> String {
|
||||
@@ -129,10 +126,9 @@ fn count(xml: &str, kind: &str) -> usize {
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -174,9 +170,8 @@ fn custom_property_bookmark_links_survive_saves_and_value_edits() {
|
||||
let before = d.custom_props.clone();
|
||||
for _ in 0..2 {
|
||||
let out = write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&out)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("docProps/custom.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("docProps/custom.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"linkTarget="OriginalBookmark""#), "{xml}");
|
||||
assert!(xml.contains(r#"linkTarget="RawBookmark""#), "{xml}");
|
||||
assert_eq!(xml.matches("linkTarget=").count(), 2, "unlinked properties stay unlinked");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Independent complex-script formatting through style inheritance and DOCX round trips.
|
||||
//! Synthetic packages, written here; no external documents or installed fonts are needed.
|
||||
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_doc::{Document, Paragraph, Run};
|
||||
|
||||
@@ -13,17 +12,16 @@ fn package(run: &str, defaults: &str, styles: &str, paragraph_style: &str) -> Ve
|
||||
r#"<w:document {ns}><w:body><w:p><w:pPr>{paragraph_style}<w:bidi/></w:pPr><w:r><w:rPr>{run}</w:rPr><w:t>שָׁלוֹם ABC 123</w:t></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let styles = format!("<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults>{styles}</w:styles>");
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, data) in [
|
||||
("_rels/.rels", root),
|
||||
("word/_rels/document.xml.rels", rels),
|
||||
("word/document.xml", document.as_str()),
|
||||
("word/styles.xml", styles.as_str()),
|
||||
] {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(data.as_bytes()).unwrap();
|
||||
z.add(name, data.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn paragraph(d: &Document) -> &Paragraph {
|
||||
@@ -180,9 +178,14 @@ fn split_runs_add_no_phantom_tracked_formatting() {
|
||||
let run = r#"<w:sz w:val="24"/><w:rPrChange w:id="7" w:author="Synthetic Author" w:date="2026-10-11T00:00:00Z"><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrChange>"#;
|
||||
let d = wordcraft_docx::read(&package(run, "", "", "")).unwrap();
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("word/document.xml").unwrap(), &mut xml)
|
||||
.unwrap();
|
||||
let xml = String::from_utf8(
|
||||
craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 })
|
||||
.unwrap()
|
||||
.read("word/document.xml", 16 << 20)
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let runs: Vec<&str> = xml.split("<w:r>").skip(1).map(|r| r.split("</w:r>").next().unwrap()).collect();
|
||||
assert!(runs.len() >= 2, "the mixed run is split: {xml}");
|
||||
assert!(runs.iter().any(|r| r.contains("<w:rtl/>")), "{xml}");
|
||||
|
||||
@@ -136,18 +136,14 @@ fn the_controls_are_written_where_they_were() {
|
||||
|
||||
/// The names of the parts of a package, in the order they are in it.
|
||||
fn part_names(bytes: &[u8]) -> Vec<String> {
|
||||
let z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip");
|
||||
z.file_names().map(str::to_string).collect()
|
||||
let z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).expect("zip");
|
||||
z.names().map(|n| n.into_owned()).collect()
|
||||
}
|
||||
|
||||
/// The body of the document part of a package.
|
||||
fn document_body(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip");
|
||||
let mut xml = String::new();
|
||||
{
|
||||
use std::io::Read;
|
||||
z.by_name("word/document.xml").expect("the document part").read_to_string(&mut xml).expect("read");
|
||||
}
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).expect("zip");
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).expect("read").expect("the document part")).expect("utf8");
|
||||
let rest = xml.split_once("<w:body>").expect("the body").1;
|
||||
let body = rest.split_once("</w:body>").expect("the end of the body").0;
|
||||
format!("<w:body>{body}</w:body>")
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! All markup here is synthetic, written from ECMA-376 §17.5.2 and the [MS-DOCX] `w14`/`w15`
|
||||
//! extensions.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::control::{ControlKind, ControlLock, ListItem};
|
||||
use wordcraft_doc::{Block, ContentControl, Document, StoryRef};
|
||||
use wordcraft_docx::{read, write};
|
||||
@@ -13,12 +11,11 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn t(s: &str) -> String {
|
||||
@@ -90,10 +87,9 @@ fn form() -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn controls(d: &Document) -> Vec<ContentControl> {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Original synthetic custom XML stores, written from the public OOXML package contract.
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use wordcraft_doc::{Path, StoryRef};
|
||||
|
||||
const REL_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
|
||||
@@ -36,22 +35,19 @@ fn fixture() -> BTreeMap<String, Vec<u8>> {
|
||||
}
|
||||
|
||||
fn zip(parts: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, bytes) in parts {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(bytes).unwrap();
|
||||
z.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut parts = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let mut bytes = Vec::new();
|
||||
f.read_to_end(&mut bytes).unwrap();
|
||||
for name in names {
|
||||
let bytes = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(parts.insert(name, bytes).is_none(), "duplicate ZIP entry");
|
||||
}
|
||||
parts
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! The document default font size (`w:docDefaults/w:rPrDefault/w:rPr/w:sz`) across a save and
|
||||
//! reopen. An unset default is resolved as `DEFAULT_FONT_SIZE`; the writer must say so, because
|
||||
//! the reader reads an omitted size as 10 pt.
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::Document;
|
||||
use wordcraft_doc::props::{CharProps, DEFAULT_FONT_SIZE};
|
||||
@@ -9,10 +8,9 @@ fn resolved(d: &Document) -> f32 {
|
||||
d.styles.resolve_char(None, &CharProps::default()).size
|
||||
}
|
||||
fn styles_xml(bytes: &[u8]) -> String {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
archive.by_name("word/styles.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
xml
|
||||
let mut archive = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(archive.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
fn defaults(xml: &str) -> &str {
|
||||
xml.split("<w:docDefaults>").nth(1).unwrap().split("</w:docDefaults>").next().unwrap()
|
||||
@@ -47,12 +45,11 @@ fn a_file_that_omits_the_default_size_is_still_read_as_ten_points() {
|
||||
let doc = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>x</w:t></w:r></w:p></w:body></w:document>"#;
|
||||
let styles = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults></w:styles>"#;
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, body) in [("_rels/.rels", root), ("word/document.xml", doc), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles)] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(body.as_bytes()).unwrap();
|
||||
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let d = wordcraft_docx::read(&zw.finish().unwrap().into_inner()).unwrap();
|
||||
let d = wordcraft_docx::read(&zw.finish().unwrap()).unwrap();
|
||||
assert_eq!(d.styles.default_chr.size, Some(10.0));
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Original nested-picture controls. No native output or external assets are embedded.
|
||||
use std::{io::Write, sync::Arc};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::para::{Anchor, CanvasStyle, Float, GroupChild, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
use wordcraft_doc::{Document, InlineObject, Paragraph, PartKind, Pos, StoryRef, TextBody, para_block};
|
||||
@@ -71,7 +71,7 @@ fn check_box(doc: &Document) {
|
||||
assert_eq!(doc.media[media].as_slice(), BLUE_PNG);
|
||||
}
|
||||
fn package(xml: &str) -> Vec<u8> {
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let docrels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdIsolationRect" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/isolation-blue.png"/></Relationships>"#;
|
||||
let types = br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
@@ -82,10 +82,9 @@ fn package(xml: &str) -> Vec<u8> {
|
||||
("word/_rels/document.xml.rels", docrels.as_slice()),
|
||||
("word/media/isolation-blue.png", BLUE_PNG),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn model_nested_picture_roundtrip() {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! East Asian language attribute of a run (`w:lang/@w:eastAsia`, ISO/IEC 29500-1 §17.3.2.20).
|
||||
//! Verifies that saving DOCX documents preserves the East Asian language of `w:lang`.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
@@ -17,19 +15,17 @@ fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
|
||||
));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in &parts {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn run(text: &str, rpr: &str) -> String {
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! two lines in one and horizontal in vertical are read and saved again. Fixtures are
|
||||
//! hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::{CombineBrackets, EastAsianLayout};
|
||||
|
||||
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
@@ -20,19 +18,17 @@ fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
|
||||
));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in &parts {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn run(text: &str, rpr: &str) -> String {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Emphasis marks (`w:em`, ISO/IEC 29500-1 §17.3.2.12: Font › Emphasis mark) are read and
|
||||
//! saved again, in their place in `w:rPr`. Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::EmphasisMark;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -10,12 +8,11 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in [("_rels/.rels", root.to_string()), ("word/document.xml", doc)] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn marks(d: &wordcraft_doc::Document) -> Vec<Option<EmphasisMark>> {
|
||||
@@ -39,9 +36,8 @@ fn emphasis_marks_are_read_and_saved() {
|
||||
let want = [EmphasisMark::Dot, EmphasisMark::Comma, EmphasisMark::Circle, EmphasisMark::UnderDot, EmphasisMark::None].map(Some);
|
||||
assert_eq!(marks(&d), want);
|
||||
let saved = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
// In its place: after w:cs, before w:lang.
|
||||
assert!(xml.contains(r#"<w:cs/><w:em w:val="underDot"/><w:lang"#), "{xml}");
|
||||
assert_eq!(marks(&wordcraft_docx::read(&saved).unwrap()), want);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Hand-written minimal WordprocessingML fixtures (written for these tests from the spec).
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::fill::Fill;
|
||||
@@ -13,12 +12,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm
|
||||
const ROOT_RELS: &str = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
|
||||
pub fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn rels(list: &[(&str, &str, &str)]) -> String {
|
||||
@@ -1483,10 +1481,9 @@ fn word_watermark_survives_save() {
|
||||
};
|
||||
assert_eq!(headers(&d2), headers(&d));
|
||||
assert_eq!(headers(&d2)[0], vec!["Header label".to_string(), "Second line".to_string()]);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
for name in ["word/header1.xml", "word/header2.xml"] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
let xml = String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<v:shape ").count(), 1, "{name}");
|
||||
}
|
||||
|
||||
@@ -1662,14 +1659,12 @@ fn chart_docx() -> Vec<u8> {
|
||||
|
||||
/// The entries of a zip, by name.
|
||||
fn unzip(bytes: &[u8]) -> std::collections::BTreeMap<String, Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
out.insert(f.name().to_string(), b);
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
out.insert(name, b);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -2174,9 +2169,8 @@ fn formatting_revisions_round_trip() {
|
||||
|
||||
// Written back: each change is the last child of its parent, and reads back the same.
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for (tag, parent) in [
|
||||
("w:rPrChange", "</w:rPr></w:rPrChange></w:rPr>"),
|
||||
("w:pPrChange", "</w:pPr></w:pPrChange></w:pPr>"),
|
||||
@@ -2432,10 +2426,9 @@ fn note_separators_and_continuation_notice_round_trip() {
|
||||
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let part = |name: &str| {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&out)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let notes = part("word/footnotes.xml");
|
||||
for (kind, id) in [("separator", "-1"), ("continuationSeparator", "0"), ("continuationNotice", "1")] {
|
||||
@@ -2558,13 +2551,12 @@ fn includepicture_keeps_its_embedded_picture() {
|
||||
let bytes = docx(&format!("<w:p>{field}</w:p><w:sectPr/>"), &[("rIdPic", "image", "media/picture.png")], &[]);
|
||||
let bytes = {
|
||||
// `docx` takes text parts; add the picture bytes as a binary part.
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut entries: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut v = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut v).unwrap();
|
||||
entries.push((f.name().to_string(), v));
|
||||
for name in names {
|
||||
let v = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
entries.push((name, v));
|
||||
}
|
||||
entries.push(("word/media/picture.png".into(), png.to_vec()));
|
||||
zip(&entries.iter().map(|(n, v)| (n.as_str(), v.as_slice())).collect::<Vec<_>>())
|
||||
@@ -2678,9 +2670,8 @@ fn rounded_rectangle_corners_are_read_and_saved() {
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
assert_eq!(corners(&d), expected);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 3565"/></a:avLst></a:prstGeom>"#), "{xml}");
|
||||
assert_eq!(corners(&wordcraft_docx::read(&bytes).unwrap()), expected);
|
||||
}
|
||||
@@ -2745,9 +2736,8 @@ fn arrowheads_keep_their_kind_and_size() {
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
assert_eq!(ends(&d), expected);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<a:headEnd type="stealth" w="sm" len="lg"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:tailEnd type="diamond" w="lg" len="sm"/>"#), "{xml}");
|
||||
assert_eq!(ends(&wordcraft_docx::read(&bytes).unwrap()), expected);
|
||||
@@ -2870,9 +2860,8 @@ fn vml_preset_shape_survives_saving() {
|
||||
r##"<w:p><w:r><w:pict>{VML_RIGHT_ARROW_TYPE}<v:shape type="#_x0000_t13" style="width:120pt;height:40pt" fillcolor="#ffa500"/></w:pict></w:r></w:p>"##
|
||||
);
|
||||
let saved = wordcraft_docx::write(&read_body(&body)).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"prst="rightArrow""#), "{xml}");
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert!(
|
||||
@@ -2898,9 +2887,8 @@ fn vml_preset_shape_survives_saving() {
|
||||
fn vml_nearest_preset_shape_survives_saving() {
|
||||
let body = r##"<w:p><w:r><w:pict><v:shape type="#_x0000_t66" style="width:60pt;height:20pt" fillcolor="#ffa500"/></w:pict></w:r></w:p>"##;
|
||||
let saved = wordcraft_docx::write(&read_body(body)).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"prst="leftArrow""#), "{xml}");
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert!(
|
||||
@@ -3047,9 +3035,8 @@ fn drawingml_shapes_survive_saving() {
|
||||
let again = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(shapes(&again), read, "every shape survives saving");
|
||||
assert_eq!(part_text_box(&again), "Floating text box");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes[..], craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<wps:wsp>").count(), 7);
|
||||
for p in presets.iter().chain(&["straightConnector1"]) {
|
||||
assert!(xml.contains(&format!(r#"<a:prstGeom prst="{p}">"#)), "{p} is written");
|
||||
@@ -4044,20 +4031,19 @@ fn hyperlink_with_empty_target_is_no_link() {
|
||||
let bytes = docx(body, &[("rId2", "hyperlink", "https://x"), ("rId3", "hyperlink", "mailto:a@example.com")], &[]);
|
||||
// Blank the first target and mark the mailto one external (the helper only does that for http).
|
||||
let bytes = {
|
||||
let mut zr = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut zr = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = zr.names().map(|n| n.into_owned()).collect();
|
||||
let mut entries = Vec::new();
|
||||
for i in 0..zr.len() {
|
||||
let mut f = zr.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
if f.name() == "word/_rels/document.xml.rels" {
|
||||
for name in names {
|
||||
let mut buf = zr.read(&name, 16 << 20).unwrap().unwrap();
|
||||
if name == "word/_rels/document.xml.rels" {
|
||||
buf = String::from_utf8(buf)
|
||||
.unwrap()
|
||||
.replace("Target=\"https://x\"", "Target=\"\"")
|
||||
.replace("a@example.com\"", "a@example.com\" TargetMode=\"External\"")
|
||||
.into_bytes();
|
||||
}
|
||||
entries.push((f.name().to_string(), buf));
|
||||
entries.push((name, buf));
|
||||
}
|
||||
let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (n.as_str(), b.as_slice())).collect();
|
||||
zip(&refs)
|
||||
@@ -4575,7 +4561,7 @@ fn shape_gradients_and_transparency_are_read_and_survive_saving() {
|
||||
rot_with_shape: false,
|
||||
flip: GradientFlip::Xy,
|
||||
}))),
|
||||
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, Rgb(0x20, 0x40, 0x60), 0.0)], lin(90.0, false), true)),
|
||||
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, Rgb(44, 92, 140), 0.0)], lin(90.0, false), true)),
|
||||
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, black, 0.0)], centre, true)),
|
||||
None,
|
||||
];
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
//! edited. Hand-written fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::{Block, BuildingBlock, CharProps, Document, Paragraph, para_block};
|
||||
@@ -15,22 +14,20 @@ const GLOSSARY_REL: &str = "http://schemas.openxmlformats.org/officeDocument/200
|
||||
const GLOSSARY_CT: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//! `styles.xml` doesn't write `w:outlineLvl` (some producers leave it out). Word for Windows,
|
||||
//! opening such a file, reports `OutlineLevel` 1 and 2 for "heading 1" and "heading 2" (whatever
|
||||
//! their style ids) and body text for a custom style.
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::Paragraph;
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
@@ -12,14 +11,13 @@ fn package(styles: &str, body: &str) -> Vec<u8> {
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}"><w:body>{body}</w:body></w:document>"#);
|
||||
let styles = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="{W}">{styles}</w:styles>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, body) in
|
||||
[("_rels/.rels", root), ("word/document.xml", doc.as_str()), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles.as_str())]
|
||||
{
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(body.as_bytes()).unwrap();
|
||||
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn para(style: &str, text: &str) -> String {
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! (`w:gridBefore`/`w:wBefore`, `w:gridAfter`/`w:wAfter`) through a round trip (#1174). All
|
||||
//! markup here is synthetic, written from ECMA-376 §17.16.17 and §17.4.14-17.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::Block;
|
||||
use wordcraft_docx::{read, write};
|
||||
|
||||
@@ -12,19 +10,17 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn resaved(body: &str) -> String {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! OpenType ligatures (`w14:ligatures`, [MS-DOCX]) in document defaults, styles and runs.
|
||||
//! Synthetic packages, written here; no external documents are needed.
|
||||
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::Ligatures;
|
||||
use wordcraft_doc::{Document, Paragraph};
|
||||
|
||||
@@ -15,17 +14,16 @@ fn package(defaults: &str, style: &str, run: &str) -> Vec<u8> {
|
||||
let styles = format!(
|
||||
r#"<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="character" w:styleId="Fancy"><w:name w:val="Fancy"/><w:rPr>{style}</w:rPr></w:style></w:styles>"#
|
||||
);
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, data) in [
|
||||
("_rels/.rels", root),
|
||||
("word/_rels/document.xml.rels", rels),
|
||||
("word/document.xml", document.as_str()),
|
||||
("word/styles.xml", styles.as_str()),
|
||||
] {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(data.as_bytes()).unwrap();
|
||||
z.add(name, data.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn paragraph(d: &Document) -> &Paragraph {
|
||||
@@ -68,10 +66,9 @@ fn unknown_ligature_values_are_ignored() {
|
||||
fn no_ligatures_element_without_a_value() {
|
||||
let d = wordcraft_docx::read(&package("", "", "")).unwrap();
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
for name in ["word/document.xml", "word/styles.xml"] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
let xml = String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(!xml.contains("ligatures"), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm
|
||||
const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn doc_zip(document_xml: &[u8]) -> Vec<u8> {
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
//! Pictures dropped at open are recorded for strict export (#6005): a missing part, an external
|
||||
//! target and a link-only picture (ECMA-376 Part 1 §20.1.8.13 `a:blip` `r:embed`/`r:link`).
|
||||
//! Original synthetic packages; nothing is fetched, the reader has no network code.
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::{Document, InlineObject, MissingPictureReason};
|
||||
|
||||
const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:v="urn:schemas-microsoft-com:vml""#;
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn blip(attrs: &str) -> String {
|
||||
@@ -32,10 +31,9 @@ fn package(body: &str, doc_rels: &str, header: Option<(&str, &str)>, extra: &[(&
|
||||
);
|
||||
let drels = format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{doc_rels}{hdr_rel}</Relationships>"#);
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/octet-stream"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
let mut put = |name: &str, bytes: &[u8]| {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
};
|
||||
put("[Content_Types].xml", types.as_bytes());
|
||||
put("_rels/.rels", rels.as_bytes());
|
||||
@@ -51,7 +49,7 @@ fn package(body: &str, doc_rels: &str, header: Option<(&str, &str)>, extra: &[(&
|
||||
for (n, b) in extra {
|
||||
put(n, b);
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
fn image_rel(id: &str, target: &str, external: bool) -> String {
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! saved, even when it holds a single paragraph (ECMA-376 §17.5.2.29-30; [MS-DOCX] `w15`
|
||||
//! repeating sections, which must wrap whole paragraphs or rows). All markup here is synthetic.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::{ContentControl, Document, StoryRef};
|
||||
use wordcraft_docx::{read, write};
|
||||
|
||||
@@ -13,19 +11,17 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn t(s: &str) -> String {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! and extended properties. Hand-written fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
@@ -12,22 +11,20 @@ const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relati
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
//! A picture's hyperlink (#5267): Word keeps it on the drawing (`wp:docPr/a:hlinkClick`,
|
||||
//! ECMA-376 Part 1 §20.4.2.5) rather than in a `w:hyperlink` around the run. Original
|
||||
//! synthetic packages; the 2×2 picture is generated in code.
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::{CharProps, Document, InlineObject, Pos};
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// An inline picture's run; `link` goes into its `wp:docPr`.
|
||||
@@ -28,7 +27,7 @@ fn package(body: &str) -> Vec<u8> {
|
||||
let doc_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdPic" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/square.png"/><Relationship Id="rIdWeb" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/picture" TargetMode="External"/><Relationship Id="rIdRun" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/run" TargetMode="External"/></Relationships>"#;
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let png = png();
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, bytes) in [
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", rels.as_bytes()),
|
||||
@@ -36,10 +35,9 @@ fn package(body: &str) -> Vec<u8> {
|
||||
("word/_rels/document.xml.rels", doc_rels.as_bytes()),
|
||||
("word/media/square.png", png.as_slice()),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
/// The link on each picture of the first paragraph, in order.
|
||||
@@ -53,10 +51,9 @@ fn picture_links(doc: &Document) -> Vec<Option<String>> {
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -109,19 +106,16 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() {
|
||||
// The drawing's link alone (as Word writes it) reads back the same.
|
||||
let without_run_link = xml.replace(&format!(r#"<w:hyperlink r:id="{rid}" w:history="1">"#), "").replacen("</w:hyperlink>", "", 1);
|
||||
assert_ne!(without_run_link, xml);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = craft_zip::Writer::new();
|
||||
for name in names {
|
||||
let mut data = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
if name == "word/document.xml" {
|
||||
data = without_run_link.clone().into_bytes();
|
||||
}
|
||||
out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
out.write_all(&data).unwrap();
|
||||
out.add(&name, &data, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let edited = out.finish().unwrap().into_inner();
|
||||
let edited = out.finish().unwrap();
|
||||
assert_eq!(picture_links(&wordcraft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string()));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Positional tabs (`w:ptab`, ECMA-376 Part 1 §17.3.3.23). Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::InlineObject;
|
||||
use wordcraft_doc::para::{PTabAlign, PTabBase};
|
||||
use wordcraft_doc::props::TabLeader;
|
||||
@@ -11,19 +9,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn ptab(relative_to: &str, alignment: &str, leader: &str) -> String {
|
||||
|
||||
@@ -2,28 +2,27 @@
|
||||
//! (ECMA-376 Part 1 §17.15.1.69–70) are kept on save and honoured by the writer. Synthetic
|
||||
//! fixtures written for these tests from the spec; the names are made up.
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;
|
||||
const RT: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
|
||||
|
||||
fn zip(entries: &[(&str, String)]) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, text) in entries {
|
||||
z.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(text.as_bytes()).unwrap();
|
||||
z.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, String> {
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut parts = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut s = String::new();
|
||||
if f.read_to_string(&mut s).is_ok() {
|
||||
parts.insert(f.name().to_string(), s);
|
||||
for name in names {
|
||||
if let Ok(Some(bytes)) = z.read(&name, 16 << 20)
|
||||
&& let Ok(s) = String::from_utf8(bytes)
|
||||
{
|
||||
parts.insert(name, s);
|
||||
}
|
||||
}
|
||||
parts
|
||||
|
||||
@@ -63,7 +63,11 @@ fn para_runs(runs: &[(&str, CharProps)]) -> Paragraph {
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut out,
|
||||
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
@@ -324,9 +328,8 @@ fn tracked_style_definition_change_round_trips() {
|
||||
});
|
||||
d.body = vec![para_block(Paragraph::with_text("x", CharProps::default()))];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/styles.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains("<w:pPrChange") && xml.contains("<w:rPrChange"), "{xml}");
|
||||
assert!(!xml.contains("stylePrChange"), "CT_Style has no such element: {xml}");
|
||||
drop(zip);
|
||||
@@ -748,9 +751,8 @@ fn note_options_round_trip_per_section() {
|
||||
assert!(sections[1].1.footnote_pr.is_empty() && sections[1].1.endnote_pr.is_empty());
|
||||
assert_eq!(r.note_options(sections[0].1, false).num_start, 7);
|
||||
assert_eq!(r.note_options(sections[1].1, false).num_start, 4);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let at = |s: &str| xml.find(s).unwrap_or_else(|| panic!("{s} missing"));
|
||||
assert!(
|
||||
at("<w:footnotePr><w:numFmt w:val=\"lowerRoman\"/><w:numStart w:val=\"7\"/><w:numRestart w:val=\"eachSect\"/></w:footnotePr>")
|
||||
@@ -773,9 +775,8 @@ fn note_never_references_itself() {
|
||||
d.body = vec![para_block(p)];
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/footnotes.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/footnotes.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(!xml.contains("<w:footnoteReference"), "a footnote cites itself: {xml}");
|
||||
assert_eq!(xml.matches("<w:footnoteRef/>").count(), 1, "{xml}");
|
||||
|
||||
@@ -840,13 +841,12 @@ fn word_note_mark_round_trips_once() {
|
||||
let mut doc = d;
|
||||
for pass in 0..2 {
|
||||
let bytes = wordcraft_docx::write(&doc).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
for (file, mark, reference, style) in [
|
||||
("word/footnotes.xml", "<w:footnoteRef/>", "<w:footnoteReference", "FootnoteReference"),
|
||||
("word/endnotes.xml", "<w:endnoteRef/>", "<w:endnoteReference", "EndnoteReference"),
|
||||
] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name(file).unwrap(), &mut xml).unwrap();
|
||||
let xml = String::from_utf8(zip.read(file, 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches(mark).count(), 1, "pass {pass}: {xml}");
|
||||
assert!(!xml.contains(reference), "pass {pass}: a note cites itself: {xml}");
|
||||
assert!(xml.contains(&format!(r#"<w:rStyle w:val="{style}"/></w:rPr>{mark}"#)), "pass {pass}: {xml}");
|
||||
@@ -894,9 +894,8 @@ fn toc_field_wraps_its_entries() {
|
||||
let d = doc_with(blocks);
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let sdt = xml.find("<w:sdt>").expect("TOC content control");
|
||||
assert!(xml.contains(r#"<w:docPartGallery w:val="Table of Contents"/>"#), "{xml}");
|
||||
let (begin, fend) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap());
|
||||
@@ -933,9 +932,8 @@ fn cell_text_direction_round_trips() {
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:textDirection w:val="btLr"/>"#), "{xml}");
|
||||
assert_eq!(xml.matches("w:textDirection").count(), 2, "horizontal cells write nothing: {xml}");
|
||||
@@ -988,9 +986,8 @@ fn toc_field_skips_nested_stories() {
|
||||
d.body = vec![para_block(head), para_block(last), para_block(Paragraph::with_text("Body", CharProps::default()))];
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let boxes: Vec<(usize, usize)> = xml.match_indices("<w:txbxContent>").map(|(a, _)| (a, a + xml[a..].find("</w:txbxContent>").unwrap())).collect();
|
||||
assert_eq!(boxes.len(), 2, "{xml}");
|
||||
let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i));
|
||||
@@ -1054,9 +1051,8 @@ fn tracked_equations_round_trip() {
|
||||
p.insert_object(end, InlineObject::Equation { linear: "z=1".into(), display: false, math: Default::default() }, &plain).unwrap();
|
||||
d.body = vec![para_block(p.clone())];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:ins w:id="1" w:author="Alice" w:date="2026-05-01T10:00:00Z"><m:oMath>"#), "ins directly encloses inline math: {xml}");
|
||||
assert!(
|
||||
xml.contains(r#"<w:del w:id="2" w:author="Bob" w:date="2026-05-02T10:00:00Z"><m:oMathPara>"#),
|
||||
@@ -1119,9 +1115,8 @@ fn tracked_paragraph_marks_round_trip() {
|
||||
let last = Paragraph::with_text("plain", CharProps::default());
|
||||
d.body = vec![para_block(split), para_block(joined), para_block(last)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:rPr><w:ins w:id="#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:rPr><w:del w:id="#), "{xml}");
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
@@ -1165,10 +1160,9 @@ fn fields_and_special_chars_round_trip() {
|
||||
|
||||
/// The `document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// #877: a field begin marker's `w:dirty` (the cached result is stale; Word refreshes it on
|
||||
@@ -1446,9 +1440,8 @@ fn drawing_canvas_round_trips() {
|
||||
p.insert_object(end, canvas, &CharProps::default()).unwrap();
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains("wordprocessingCanvas") && xml.contains("<wpc:wpc>") && xml.contains("<wpc:bg>") && xml.contains("<wpc:whole>"), "{xml}");
|
||||
let r = wordcraft_docx::read(&bytes).unwrap();
|
||||
let got = paras(&r);
|
||||
@@ -1494,9 +1487,8 @@ fn rotated_drawing_canvas_round_trips() {
|
||||
let end = p.len();
|
||||
p.insert_object(end, canvas(square), &CharProps::default()).unwrap();
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(
|
||||
xml.contains(r#"<wpc:extLst><a:ext uri="urn:wordcraft:canvas-xfrm"><a:xfrm rot="1800000" flipH="1"/></a:ext></wpc:extLst></wpc:wpc>"#),
|
||||
"{xml}"
|
||||
@@ -1524,9 +1516,8 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
|
||||
assert_eq!(r.settings.compat_mode, mode);
|
||||
if allow {
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
// CT_Compat requires the boolean option before compatSetting.
|
||||
assert!(xml.find("<w:allowSpaceOfSameStyleInTable").unwrap() < xml.find("<w:compatSetting").unwrap());
|
||||
}
|
||||
@@ -1557,15 +1548,13 @@ fn attached_template_and_link_styles_round_trip() {
|
||||
d.settings.mirror_margins = true;
|
||||
d.settings.track_changes = true;
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let at = |tag: &str| xml.find(tag).unwrap_or_else(|| panic!("{tag} missing: {xml}"));
|
||||
assert!(at("<w:mirrorMargins") < at("<w:attachedTemplate"));
|
||||
assert!(at("<w:attachedTemplate") < at("<w:linkStyles"));
|
||||
assert!(at("<w:linkStyles") < at("<w:trackRevisions"));
|
||||
let mut rels = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/_rels/settings.xml.rels").unwrap(), &mut rels).unwrap();
|
||||
let rels = String::from_utf8(zip.read("word/_rels/settings.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(rels.contains("relationships/attachedTemplate") && rels.contains("TargetMode=\"External\""), "{rels}");
|
||||
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
@@ -1583,10 +1572,9 @@ fn attached_template_and_link_styles_round_trip() {
|
||||
#[test]
|
||||
fn zoom_round_trips() {
|
||||
let settings = |bytes: &[u8]| {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let plain = wordcraft_docx::write(&Document::new()).unwrap();
|
||||
let xml = settings(&plain);
|
||||
@@ -1649,10 +1637,9 @@ fn settings_core_theme_round_trip() {
|
||||
}
|
||||
|
||||
fn part_xml(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Header parts in the document, by id.
|
||||
@@ -2047,9 +2034,8 @@ fn char_border_written_between_u_and_shd() {
|
||||
let c =
|
||||
CharProps { border: Some(Border::single(0.5)), underline: Some(Underline::Single), shading: Some(Rgb(0xFF, 0xFF, 0)), ..Default::default() };
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![para_runs(&[("x", c)])])).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let bdr = r#"<w:bdr w:val="single" w:sz="4" w:space="0" w:color="auto"/>"#;
|
||||
assert_eq!(xml.matches(bdr).count(), 1, "{xml}");
|
||||
let at = xml.find(bdr).unwrap();
|
||||
@@ -2146,9 +2132,8 @@ fn ink_and_freeforms_round_trip_as_custom_geometry() {
|
||||
}
|
||||
let d = doc_with(vec![p]);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<a:custGeom>").count(), 3, "{xml}");
|
||||
assert!(xml.contains(r#"<a:path w="762000" h="254000" fill="none"><a:moveTo><a:pt x="12700" y="12700"/></a:moveTo><a:lnTo>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:alpha val="50000"/>"#) && xml.contains(r#"cap="rnd""#), "{xml}");
|
||||
@@ -2188,9 +2173,8 @@ fn shape_effects_round_trip() {
|
||||
let mut p = Paragraph::with_text("x", CharProps::default());
|
||||
p.insert_object(1, shape, &CharProps::default()).unwrap();
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(
|
||||
xml.contains(
|
||||
r#"<a:outerShdw blurRad="50800" dist="38100" dir="8100000" algn="tr" rotWithShape="0"><a:srgbClr val="203040"><a:alpha val="40000"/>"#
|
||||
@@ -2281,9 +2265,8 @@ fn rotation_and_flips_round_trip() {
|
||||
}
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<a:xfrm rot="1800000">"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:xfrm rot="5400000" flipH="1">"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:xfrm rot="18930000" flipV="1">"#), "{xml}");
|
||||
@@ -2334,9 +2317,8 @@ fn rotated_group_and_shadow_rotation_round_trip() {
|
||||
let mut p = Paragraph::with_text("g", CharProps::default());
|
||||
p.insert_object(1, group, &CharProps::default()).unwrap();
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<wpg:grpSpPr><a:xfrm rot="8100000" flipH="1">"#), "{xml}");
|
||||
assert!(xml.contains(r#"rotWithShape="1""#) && xml.contains(r#"rotWithShape="0""#), "{xml}");
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
@@ -2440,9 +2422,8 @@ fn a_corporate_author_round_trips() {
|
||||
..Default::default()
|
||||
});
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
|
||||
let mut item_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("customXml/item1.xml").unwrap(), &mut item_xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes[..], craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let item_xml = String::from_utf8(zip.read("customXml/item1.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(item_xml.contains("<b:Author><b:Author><b:Corporate>World Health Organization</b:Corporate></b:Author><b:Editor>"), "{item_xml}");
|
||||
assert!(item_xml.contains("<b:Corporate>Harbor Guild, Inc.</b:Corporate>"), "{item_xml}");
|
||||
assert!(!item_xml.contains("<b:Last>Rivera</b:Last>"), "the corporate author takes the person authors' place: {item_xml}");
|
||||
@@ -2452,23 +2433,20 @@ fn a_corporate_author_round_trips() {
|
||||
}
|
||||
|
||||
fn assert_bibliography_parts(bytes: &[u8]) {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
assert!(zip.by_name("customXml/item1.xml").is_ok());
|
||||
assert!(zip.by_name("customXml/itemProps1.xml").is_ok());
|
||||
assert!(zip.by_name("customXml/_rels/item1.xml.rels").is_ok());
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
assert!(zip.contains("customXml/item1.xml"));
|
||||
assert!(zip.contains("customXml/itemProps1.xml"));
|
||||
assert!(zip.contains("customXml/_rels/item1.xml.rels"));
|
||||
|
||||
let mut rels_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("_rels/.rels").unwrap(), &mut rels_xml).unwrap();
|
||||
let rels_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(rels_xml.contains("relationships/customXml"), "{rels_xml}");
|
||||
assert!(rels_xml.contains("Target=\"customXml/item1.xml\""), "{rels_xml}");
|
||||
|
||||
let mut ct_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut ct_xml).unwrap();
|
||||
let ct_xml = String::from_utf8(zip.read("[Content_Types].xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(ct_xml.contains("PartName=\"/customXml/item1.xml\""), "{ct_xml}");
|
||||
assert!(ct_xml.contains("PartName=\"/customXml/itemProps1.xml\""), "{ct_xml}");
|
||||
|
||||
let mut item_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("customXml/item1.xml").unwrap(), &mut item_xml).unwrap();
|
||||
let item_xml = String::from_utf8(zip.read("customXml/item1.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_bibliography_types(&item_xml);
|
||||
assert_bibliography_people(&item_xml);
|
||||
assert_bibliography_details(&item_xml);
|
||||
@@ -2596,9 +2574,8 @@ fn wrap_polygons_round_trip() {
|
||||
}
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<wp:wrapPolygon edited="1"><wp:start x="-300" y="0"/><wp:lineTo x="21600" y="1200"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<wp:lineTo x="-300" y="0"/></wp:wrapPolygon>"#), "closed: {xml}");
|
||||
let r = unstacked(wordcraft_docx::read(&bytes).expect("read"));
|
||||
@@ -2635,9 +2612,8 @@ fn enclosed_characters_round_trip_in_words_structure() {
|
||||
}
|
||||
let doc = doc_with(vec![p]);
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:instrText xml:space="preserve"> eq \o\ac(○</w:instrText>"#), "{xml}");
|
||||
assert!(!xml.contains("separate") && !xml.contains("enlarge"), "{xml}");
|
||||
// Shrink text at 11 pt: the character at 7.5 pt (half-points 15), raised.
|
||||
@@ -2670,9 +2646,8 @@ fn ruby_phonetic_guide_round_trips_as_w_ruby() {
|
||||
p.insert_object(5, ruby.clone(), &bold).unwrap();
|
||||
let d = doc_with(vec![p]);
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for part in [
|
||||
r#"<w:rubyAlign w:val="distributeSpace"/><w:hps w:val="11"/><w:hpsRaise w:val="20"/><w:hpsBaseText w:val="22"/><w:lid w:val="ja-JP"/>"#,
|
||||
"<w:rt><w:r>",
|
||||
@@ -2717,9 +2692,8 @@ fn wrap_text_sides_round_trip() {
|
||||
}
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for tag in [
|
||||
r#"<wp:wrapSquare wrapText="left"/>"#,
|
||||
r#"<wp:wrapTight wrapText="right">"#,
|
||||
@@ -2784,9 +2758,8 @@ fn alt_text_title_and_decorative_round_trip_for_every_object() {
|
||||
t.props.description = Some("Prices by year".into());
|
||||
d.body = vec![para_block(p), Arc::new(Block::Table(t))];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"{C183D7F6-B498-43B3-948B-1728B52AA6E4}"><adec:decorative xmlns:adec="http://schemas.microsoft.com/office/drawing/2017/decorative" val="1"/>"#), "{xml}");
|
||||
assert!(
|
||||
xml.contains(r#"<w:tblLook "#) && xml.contains(r#"<w:tblCaption w:val="Prices"/><w:tblDescription w:val="Prices by year"/></w:tblPr>"#),
|
||||
@@ -2865,9 +2838,8 @@ fn warps_and_glued_connectors_round_trip() {
|
||||
|
||||
// Hostile: an unknown warp, a huge adjust value, a glue to a missing shape.
|
||||
let xml = wordcraft_docx::write(&r).unwrap();
|
||||
let mut pkg = zip::ZipArchive::new(std::io::Cursor::new(xml)).unwrap();
|
||||
let mut doc_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut pkg.by_name("word/document.xml").unwrap(), &mut doc_xml).unwrap();
|
||||
let mut pkg = craft_zip::Archive::open(&xml, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let doc_xml = String::from_utf8(pkg.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let doc_xml = doc_xml
|
||||
.replace("prst=\"textArchUp\"", "prst=\"textNotAWarp\"")
|
||||
.replace("a:stCxn id=\"5\" idx=\"3\"", "a:stCxn id=\"404\" idx=\"99999999999\"");
|
||||
@@ -2880,29 +2852,29 @@ fn warps_and_glued_connectors_round_trip() {
|
||||
|
||||
/// `zip` with part `name` replaced by `data`.
|
||||
fn replace_part(zip_bytes: &[u8], name: &str, data: &[u8]) -> Vec<u8> {
|
||||
let mut src = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).unwrap();
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..src.len() {
|
||||
let mut f = src.by_index(i).unwrap();
|
||||
let n = f.name().to_string();
|
||||
out.start_file(n.as_str(), zip::write::SimpleFileOptions::default()).unwrap();
|
||||
let mut src = craft_zip::Archive::open(zip_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = src.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = craft_zip::Writer::new();
|
||||
for n in names {
|
||||
if n == name {
|
||||
std::io::Write::write_all(&mut out, data).unwrap();
|
||||
out.add(&n, data, craft_zip::Compression::Deflated).unwrap();
|
||||
} else {
|
||||
std::io::copy(&mut f, &mut out).unwrap();
|
||||
let bytes = src.read(&n, 16 << 20).unwrap().unwrap();
|
||||
out.add(&n, &bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
}
|
||||
out.finish().unwrap().into_inner()
|
||||
out.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A texture or picture page background (`v:background/v:fill`) survives a save (#999): the image
|
||||
/// part, its relationship and the fill attributes.
|
||||
#[test]
|
||||
fn page_background_picture_round_trips() {
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 150, 100, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let png = wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 150, 100, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = Document::new();
|
||||
d.settings.page_color = Some(Rgb(0xFF, 0xFF, 0xCC));
|
||||
d.media.insert("paper.png".into(), Arc::new(png.clone()));
|
||||
@@ -2932,9 +2904,8 @@ fn drop_cap_options_round_trip() {
|
||||
margin.props.drop_cap_margin = Some(true);
|
||||
let d = doc_with(vec![dropped, margin]);
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"w:dropCap="drop" w:lines="2" w:hSpace="120""#), "{xml}");
|
||||
assert!(xml.contains(r#"w:dropCap="margin" w:lines="4""#), "{xml}");
|
||||
assert!(xml.contains(r#"w:ascii="Liberation Mono""#), "the letter's font on its run: {xml}");
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
//! Row-level table property exceptions (`w:tblPrEx` in `w:tr`, ECMA-376 Part 1 §17.4.61).
|
||||
//! Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn row(ex: &str, text: &str) -> String {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Run and style properties that must survive repeated DOCX saves.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str, styles: &str) -> Vec<u8> {
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
@@ -9,24 +7,22 @@ fn docx(body: &str, styles: &str) -> Vec<u8> {
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}<w:sectPr/></w:body></w:document>"#
|
||||
);
|
||||
let styles = format!(r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#);
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, xml) in [
|
||||
("_rels/.rels", root.to_string()),
|
||||
("word/document.xml", document),
|
||||
("word/_rels/document.xml.rels", rels.to_string()),
|
||||
("word/styles.xml", styles),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(xml.as_bytes()).unwrap();
|
||||
zip.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip.by_name(name).unwrap().read_to_string(&mut xml).unwrap();
|
||||
xml
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(zip.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
//! Section form protection (`w:formProt` in `w:sectPr`, ECMA-376 Part 1 §17.6.6). Fixtures are
|
||||
//! hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Section line numbering (`w:lnNumType` in `w:sectPr`, ECMA-376 Part 1 §17.6.8).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::section::{LineNumberRestart, LineNumbering};
|
||||
|
||||
/// Builds a minimal in-memory DOCX package archive containing the given XML body.
|
||||
@@ -10,20 +8,18 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// Extracts the `word/document.xml` content string from a serialized DOCX package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// #6209: `<w:lnNumType>` without `w:countBy` leaves line numbering off, as Word does.
|
||||
|
||||
@@ -1,25 +1,21 @@
|
||||
//! Section printer, note and chapter-number metadata survives DOCX and native JSON saves.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="w15"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
//! Section page-number settings (`w:pgNumType` in `w:sectPr`, ECMA-376 Part 1 §17.6.12).
|
||||
//! Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Section text direction (`w:textDirection` in `w:sectPr`, ECMA-376 Part 1 §17.6.20). Fixtures
|
||||
//! are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -10,16 +8,15 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
|
||||
let mut bytes = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut bytes = craft_zip::Writer::new();
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let document_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
@@ -31,17 +28,15 @@ fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
|
||||
("word/document.xml", doc.as_bytes()),
|
||||
("word/styles.xml", styles.as_bytes()),
|
||||
] {
|
||||
bytes.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
bytes.write_all(value).unwrap();
|
||||
bytes.add(name, value, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
bytes.finish().unwrap().into_inner()
|
||||
bytes.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -122,8 +117,8 @@ fn paragraph_style_text_direction_is_preserved_and_direct_value_overrides_it() {
|
||||
assert_eq!(xml.matches(r#"<w:pStyle w:val="Vertical"/>"#).count(), 2, "both paragraphs keep their style: {xml}");
|
||||
assert!(xml.contains(r#"<w:pStyle w:val="Vertical"/><w:textDirection w:val="lrTb"/>"#), "direct horizontal is explicit: {xml}");
|
||||
assert_eq!(xml.matches("w:textDirection").count(), 1, "only the direct paragraph writes a direction: {xml}");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
|
||||
let mut styles_xml = String::new();
|
||||
z.by_name("word/styles.xml").unwrap().read_to_string(&mut styles_xml).unwrap();
|
||||
let _z_bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let styles_xml = String::from_utf8(z.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(styles_xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "style value survives: {styles_xml}");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Section vertical alignment (`w:vAlign` in `w:sectPr`, ECMA-376 Part 1 §17.6.23, values from
|
||||
//! ST_VerticalJc). Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::section::PageVAlign;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -10,19 +8,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// #1320: "both" (Justified) reads as Justify and writes back as "both"; the others keep theirs.
|
||||
|
||||
@@ -4,29 +4,26 @@
|
||||
//! fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
//! ECMA-376 Part 1, 5th edition (`dml-wordprocessingDrawing.xsd`, Strict and Transitional): each
|
||||
//! drawing is written once and filled in with either set of namespaces.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::{Document, InlineObject, PartKind};
|
||||
|
||||
const STRICT_NS: &str = r#"xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main" xmlns:r="http://purl.oclc.org/ooxml/officeDocument/relationships" xmlns:wp="http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing" xmlns:a="http://purl.oclc.org/ooxml/drawingml/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" w:conformance="strict""#;
|
||||
@@ -33,19 +31,17 @@ const TRANSITIONAL: Names =
|
||||
Names { ns: TRANSITIONAL_NS, rels: TRANSITIONAL_RELS, shape: "wps", group: "wpg", canvas: "wpc", content: "w:txbxContent" };
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn solid(rgb: &str) -> String {
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
//! Word sizes a line by it when a list label is larger than the text, so a save that drops it
|
||||
//! moves every line after. Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::TextAlignment;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -12,19 +10,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,26 +2,22 @@
|
||||
//! `wps:txbx/@id`, `wps:linkedTxbx`). Fixtures are hand-written from ECMA-376 Part 1 §20.4
|
||||
//! (DrawingML WordprocessingML drawing) and §21.1.2.1.1 (`bodyPr`).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::props::{TextVert, VAlign};
|
||||
use wordcraft_doc::{Document, InlineObject, PartKind, TextBody, para_block};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The text boxes' stories in body order, a group's members among them
|
||||
@@ -217,7 +213,15 @@ fn picture_in_box_keeps_its_frame() {
|
||||
let outer = text_box(&mut d, "Label", body);
|
||||
let id = outer.text_box().unwrap();
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
image::RgbaImage::from_pixel(10, 4, image::Rgba([20, 40, 60, 255])).write_to(&mut bytes, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut bytes,
|
||||
&wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(10, 4, image::Rgba([20, 40, 60, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let media = d.add_media(bytes.into_inner(), "png");
|
||||
let image = InlineObject::Image {
|
||||
media: media.clone(),
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Original field-boundary fixtures from the public OOXML complex-field contract.
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::{InlineObject, Path, StoryRef};
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let xml = format!(r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, value) in [
|
||||
("word/document.xml", xml.as_str()),
|
||||
(
|
||||
@@ -13,10 +12,9 @@ fn package(body: &str) -> Vec<u8> {
|
||||
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="main" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
|
||||
),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(value.as_bytes()).unwrap();
|
||||
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
fn start(code: &str) -> String {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! A paragraph whose `w:pStyle` names a style `styles.xml` doesn't define is formatted as Normal,
|
||||
//! as in Word, not with the document defaults alone (#5077). Pandoc writes footers as
|
||||
//! `<w:pStyle w:val="Footer"/>` without defining Footer.
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::{Block, Document, PartKind};
|
||||
|
||||
@@ -20,7 +19,7 @@ fn package(normal_id: &str) -> Vec<u8> {
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="24"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="200"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="{normal_id}"><w:name w:val="Normal"/><w:pPr><w:spacing w:before="20" w:after="40" w:line="259" w:lineRule="auto"/></w:pPr><w:rPr><w:sz w:val="26"/></w:rPr></w:style></w:styles>"#
|
||||
);
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/></Relationships>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, body) in [
|
||||
("_rels/.rels", root),
|
||||
("word/document.xml", doc.as_str()),
|
||||
@@ -28,10 +27,9 @@ fn package(normal_id: &str) -> Vec<u8> {
|
||||
("word/styles.xml", styles.as_str()),
|
||||
("word/footer1.xml", footer.as_str()),
|
||||
] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(body.as_bytes()).unwrap();
|
||||
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn footer_para(d: &Document) -> &wordcraft_doc::Paragraph {
|
||||
|
||||
@@ -2,18 +2,15 @@
|
||||
//! `coordsize`/`coordorigin` give them. Fixtures are hand-written from ECMA-376 Part 4
|
||||
//! (VML, §14.1 `v:group`, `coordsize`, `coordorigin`; §14.2 shapes).
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::{Document, InlineObject, Paragraph};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A document whose body is `body`.
|
||||
|
||||
@@ -20,7 +20,11 @@ fn part_text(doc: &Document, id: Option<u32>) -> String {
|
||||
fn tiny_png_b64() -> String {
|
||||
let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([x as u8 * 100, y as u8 * 100, 50, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut out,
|
||||
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(out.into_inner());
|
||||
// Line breaks inside base64, as the formats write it.
|
||||
b64.as_bytes().chunks(20).map(|c| std::str::from_utf8(c).unwrap()).collect::<Vec<_>>().join("\n")
|
||||
|
||||
@@ -13,7 +13,11 @@ use wordcraft_docx::{XmlKind, read_xml, sniff_xml, write_wordml2003};
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut out,
|
||||
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ fn ragged_matrix_save_stays_small() {
|
||||
let mut doc = Document::new();
|
||||
doc.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let size = zip.by_name("word/document.xml").unwrap().size();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let size = zip.declared_size("word/document.xml").unwrap();
|
||||
assert!(size < 1_000_000, "document.xml is {size} bytes");
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ workspace = true
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -59,5 +60,5 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
[dev-dependencies]
|
||||
wordcraft-doc = { workspace = true, features = ["test-support"] }
|
||||
encoding_rs = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.when(has_canvas)
|
||||
.pure(),
|
||||
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
|
||||
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
|
||||
.params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#)
|
||||
.when(has_canvas),
|
||||
]
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult {
|
||||
result(&o)
|
||||
}
|
||||
|
||||
/// `canvas.member`: move, resize or remove one member; with no change, list the members.
|
||||
/// `canvas.member`: move, resize or remove one member; without index, list the members.
|
||||
fn member(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let pos = canvas_pos(s)?;
|
||||
let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else {
|
||||
|
||||
@@ -68,6 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Escape")
|
||||
.params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#)
|
||||
.pure(),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -63,7 +63,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?;
|
||||
set_accent(s, t.3[0]);
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"name": string (see design.themes)}"#),
|
||||
CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set)
|
||||
.params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#),
|
||||
CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing)
|
||||
|
||||
@@ -7,6 +7,13 @@ use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
use super::{delete_selection, find_pattern, pos_json, sel_result};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
|
||||
/// advertise a web alternative through the same registry/keymap as every other command.
|
||||
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
|
||||
fn copy_format_shortcut(web: bool) -> &'static str {
|
||||
if web { "Mod+Alt+Shift+C / Mod+Shift+C" } else { "Mod+Shift+C" }
|
||||
}
|
||||
|
||||
/// Undo several steps at once: the Undo button's list (#701). `count` is validated here and
|
||||
/// clamped to the undo depth, so hostile numbers never reach the stack.
|
||||
fn undo_to(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -134,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp"))
|
||||
.params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(
|
||||
r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#,
|
||||
),
|
||||
// Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening
|
||||
// it changes nothing, so it is its own command and never marks the document edited.
|
||||
CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| {
|
||||
@@ -165,10 +174,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
|
||||
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
|
||||
painter_pick(s);
|
||||
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
|
||||
s.painter = None;
|
||||
s.copied_format = Some(picked_format(s));
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Mod+Shift+C")
|
||||
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
|
||||
.pure(),
|
||||
CommandSpec::new("edit.pasteFormat", "Paste Formatting", "Home › Clipboard", paste_format).key("Mod+Shift+V"),
|
||||
]
|
||||
@@ -737,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let story = s.sel.focus.story;
|
||||
let results = search_full(s, story, true)?;
|
||||
let (a, b) = s.sel.ordered();
|
||||
// Replace the current match if selected, then move to the next.
|
||||
// Replace the current match if selected, then move to the next. The result says which
|
||||
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
|
||||
let mut replaced = 0;
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
|
||||
super::paste_text(s, &f.rep.unwrap_or_default())?;
|
||||
replaced = 1;
|
||||
}
|
||||
let _ = step(s, 1);
|
||||
Ok(json!({"remaining": search(s, story)?.len()}))
|
||||
let selected = match step(s, 1) {
|
||||
Ok(_) => {
|
||||
let (start, end) = s.sel.ordered();
|
||||
json!({"start": pos_json(&start), "end": pos_json(&end)})
|
||||
}
|
||||
Err(_) => Value::Null,
|
||||
};
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
@@ -825,11 +845,21 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
/// The character and paragraph formatting at the start of the selection.
|
||||
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
|
||||
let f = s.sel.ordered().0;
|
||||
// A symbol's own font isn't formatting to paint onto text.
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
|
||||
// Formatting only: not the source's hyperlink or revision marks (#5616).
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
|
||||
(chr, para)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
let (chr, para) = picked_format(s);
|
||||
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
|
||||
// and stays after the brush is used up or cancelled.
|
||||
s.copied_format = Some((chr.clone(), para.clone()));
|
||||
s.painter = Some((chr, para, false));
|
||||
}
|
||||
|
||||
@@ -845,24 +875,28 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"active": true}))
|
||||
}
|
||||
|
||||
/// Apply the format painter's formatting to the selection.
|
||||
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
|
||||
/// up (which stays for the next Paste Formatting).
|
||||
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
|
||||
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
|
||||
(Some(brush), _) => brush,
|
||||
(None, Some((chr, para))) => (chr, para, true),
|
||||
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
|
||||
};
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b {
|
||||
// No selection: apply paragraph formatting (and word formatting like Word).
|
||||
let f = s.sel.focus.clone();
|
||||
if let Some(pp) = s.doc.para_at(&f) {
|
||||
let (x, y) = pp.word_at(f.off);
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: y, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
|
||||
// Word selection includes trailing spaces; a painter click formats just the word,
|
||||
// matching the ordinary collapsed-caret formatting target.
|
||||
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
}
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
} else {
|
||||
s.doc.format_range(&a, &b, &|c| {
|
||||
let link = c.link.clone();
|
||||
*c = c.cleared().overlaid(&chr);
|
||||
c.link = link;
|
||||
})?;
|
||||
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
if a.path != b.path || a.off == 0 {
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
}
|
||||
@@ -872,3 +906,49 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shortcut_tests {
|
||||
use super::*;
|
||||
use crate::{KeyMap, Registry};
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_is_unique_and_keeps_existing_shortcuts() {
|
||||
for web in [false, true] {
|
||||
let mut commands = super::super::registry().all().to_vec();
|
||||
let copy = commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap();
|
||||
copy.shortcut = copy_format_shortcut(web);
|
||||
let registry = Registry::new(commands);
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for command in registry.all() {
|
||||
for key in command.shortcut.split(" / ").filter_map(crate::keymap::normalize) {
|
||||
assert!(seen.insert(key.clone()), "duplicate binding: {key}");
|
||||
}
|
||||
}
|
||||
let keys = KeyMap::default();
|
||||
let resolve = |key| keys.resolve(®istry, key).map(|c| c.id);
|
||||
assert_eq!(resolve("Mod+Shift+C"), Some("edit.copyFormat"));
|
||||
assert_eq!(resolve("Mod+Alt+Shift+C"), web.then_some("edit.copyFormat"));
|
||||
assert_eq!(resolve("Mod+Shift+V"), Some("edit.pasteFormat"));
|
||||
assert_eq!(resolve("Mod+Alt+Shift+V"), Some("edit.pasteText"));
|
||||
if !cfg!(target_os = "macos") {
|
||||
assert_eq!(resolve("Mod+Alt+C"), Some("text.copyright"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
|
||||
let mut commands = super::super::registry().all().to_vec();
|
||||
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
|
||||
let registry = Registry::new(commands);
|
||||
let mut keys = KeyMap::default();
|
||||
assert_eq!(keys.keys_for(®istry, "edit.copyFormat").first().map(String::as_str), Some("Mod+Alt+Shift+C"));
|
||||
assert!(keys.remove(®istry, "edit.copyFormat", "Mod+Alt+Shift+C").unwrap());
|
||||
assert!(keys.resolve(®istry, "Mod+Alt+Shift+C").is_none());
|
||||
keys.assign(®istry, "format.bold", "Mod+Alt+Shift+C").unwrap();
|
||||
let restored = KeyMap::from_value(&serde_json::to_value(&keys).unwrap());
|
||||
assert_eq!(restored.resolve(®istry, "Mod+Alt+Shift+C").map(|c| c.id), Some("format.bold"));
|
||||
assert_eq!(restored.resolve(®istry, "Mod+Shift+C").map(|c| c.id), Some("edit.copyFormat"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,6 @@ fn gallery_lists_everything() {
|
||||
|
||||
/// A session on a DOCX whose only paragraph is `<m:oMath>{math}</m:oMath>`.
|
||||
fn imported(math: &str) -> Session {
|
||||
use std::io::Write;
|
||||
let w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
let m = "http://schemas.openxmlformats.org/officeDocument/2006/math";
|
||||
let parts = [
|
||||
@@ -117,24 +116,21 @@ fn imported(math: &str) -> Session {
|
||||
),
|
||||
("word/document.xml", format!(r#"<w:document xmlns:w="{w}" xmlns:m="{m}"><w:body><w:p><m:oMath>{math}</m:oMath></w:p><w:sectPr/></w:body></w:document>"#)),
|
||||
];
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in parts {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let bytes = zw.finish().unwrap().into_inner();
|
||||
let bytes = zw.finish().unwrap();
|
||||
let mut s = Session::new(wordcraft_docx::read(&bytes).unwrap());
|
||||
s.run("equation.edit", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn document_xml(s: &Session) -> String {
|
||||
use std::io::Read;
|
||||
let bytes = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
xml
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> {
|
||||
fn set_code(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let code = p::req_str(v, "code")?.trim().to_string();
|
||||
if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) {
|
||||
return Err(CmdError::Params("bad field code".into()));
|
||||
return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into()));
|
||||
}
|
||||
let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) };
|
||||
with_field(s, &f.at, |o| match o {
|
||||
@@ -441,7 +441,10 @@ mod tests {
|
||||
s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap();
|
||||
let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default();
|
||||
assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report"));
|
||||
assert!(s.run("fields.setCode", &json!({"code": ""})).is_err());
|
||||
assert!(matches!(
|
||||
s.run("fields.setCode", &json!({"code": ""})),
|
||||
Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers"
|
||||
));
|
||||
|
||||
// A locked field keeps its result.
|
||||
s.run("fields.lock", &json!({})).unwrap();
|
||||
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(),
|
||||
CommandSpec::new("file.open", "Open", "File", open)
|
||||
.key("Mod+O / Mod+F12 / Mod+Alt+F2")
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#)
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
// to undo; it marks the document as changed itself.
|
||||
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
|
||||
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
|
||||
// No path (the command search, say): the app asks where to save, as File › Export
|
||||
@@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()}))
|
||||
}
|
||||
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved
|
||||
/// with from now on, or none.
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word packages and
|
||||
/// OpenDocument text files (.odt, .ott) are saved with from now on, or none.
|
||||
fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let password = match v.get("password") {
|
||||
Some(Value::Null) => None,
|
||||
|
||||
@@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let Some(n) = v.get(k) else { return Ok(None) };
|
||||
let n = n.as_str().map(str::trim).unwrap_or("");
|
||||
if n.is_empty() || n.len() > 128 {
|
||||
return Err(CmdError::Params(format!("bad font name `{k}`")));
|
||||
return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes")));
|
||||
}
|
||||
Ok(Some(n.to_string()))
|
||||
};
|
||||
|
||||
@@ -51,7 +51,7 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
},
|
||||
};
|
||||
if url.is_empty() || url.len() > 4096 {
|
||||
return Err(CmdError::Params("bad url".into()));
|
||||
return Err(CmdError::Params("`url` must be non-empty and at most 4096 UTF-8 bytes".into()));
|
||||
}
|
||||
let style = Some("Hyperlink".to_string());
|
||||
if s.sel.is_collapsed() {
|
||||
@@ -188,7 +188,9 @@ pub(super) fn delete_bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
pub(super) fn bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let name = p::req_str(v, "name")?.trim().to_string();
|
||||
if !bookmark_name_ok(&name) {
|
||||
return Err(CmdError::Params("bookmark names start with a letter, have no spaces and at most 40 characters".into()));
|
||||
return Err(CmdError::Params(
|
||||
"bookmark names start with a letter or underscore, contain only letters, numbers or underscores, and have at most 40 characters".into(),
|
||||
));
|
||||
}
|
||||
// Replace an existing bookmark of the same name.
|
||||
remove_bookmark(s, &name)?;
|
||||
|
||||
@@ -71,22 +71,7 @@ pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn base64_encode(b: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
|
||||
for ch in b.chunks(3) {
|
||||
let n =
|
||||
(ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32;
|
||||
for i in 0..4 {
|
||||
if i <= ch.len() {
|
||||
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub use craft_mime::transfer::base64 as base64_encode;
|
||||
|
||||
pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
|
||||
@@ -5,8 +5,7 @@ use super::*;
|
||||
#[test]
|
||||
fn a_huge_picture_width_keeps_the_size_finite() {
|
||||
let img = image::RgbaImage::from_pixel(2, 400, image::Rgba([10, 20, 30, 255]));
|
||||
let mut png = Vec::new();
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let png = wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img).clone(), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let r = s.run("insert.picture", &json!({"data": base64_encode(&png), "width": 3e38})).unwrap();
|
||||
let (w, h) = (r["width"].as_f64().unwrap(), r["height"].as_f64().unwrap());
|
||||
@@ -17,8 +16,8 @@ fn a_huge_picture_width_keeps_the_size_finite() {
|
||||
|
||||
/// A 4 × 4 RGB TIFF that says its strips are JPEG (they aren't): its header still reads.
|
||||
fn jpeg_strip_tiff() -> Vec<u8> {
|
||||
let mut t = Vec::new();
|
||||
image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut t), image::ImageFormat::Tiff).unwrap();
|
||||
let mut t =
|
||||
wordcraft_geom::picture::encode_format(&image::DynamicImage::from(image::RgbImage::new(4, 4).clone()), image::ImageFormat::Tiff).unwrap();
|
||||
assert_eq!(&t[..4], b"II*\0");
|
||||
let ifd = u32::from_le_bytes(t[4..8].try_into().unwrap()) as usize;
|
||||
let n = usize::from(u16::from_le_bytes([t[ifd], t[ifd + 1]]));
|
||||
@@ -37,8 +36,8 @@ fn tiffs_with_jpeg_strips_are_refused() {
|
||||
let e = s.run("insert.picture", &json!({"data": base64_encode(&tiff)})).unwrap_err().to_string();
|
||||
assert!(e.contains("TIFF"), "{e}");
|
||||
assert!(s.doc.media.is_empty());
|
||||
let mut plain = Vec::new();
|
||||
image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut plain), image::ImageFormat::Tiff).unwrap();
|
||||
let plain =
|
||||
wordcraft_geom::picture::encode_format(&image::DynamicImage::from(image::RgbImage::new(4, 4).clone()), image::ImageFormat::Tiff).unwrap();
|
||||
s.run("insert.picture", &json!({"data": base64_encode(&plain)})).unwrap();
|
||||
let e = s.run("picture.change", &json!({"data": base64_encode(&tiff)})).unwrap_err().to_string();
|
||||
assert!(e.contains("TIFF"), "{e}");
|
||||
@@ -416,3 +415,22 @@ fn local_civil_date_follows_the_utc_offset() {
|
||||
assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_preserves_command_payload_bytes() {
|
||||
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
|
||||
assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded);
|
||||
}
|
||||
let bytes: Vec<u8> = (0..513).map(|i| (i % 256) as u8).collect();
|
||||
for len in 0..=bytes.len() {
|
||||
let encoded = super::objects::base64_encode(&bytes[..len]);
|
||||
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
|
||||
assert!(!encoded.contains(['\r', '\n']));
|
||||
assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec()));
|
||||
}
|
||||
assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///");
|
||||
// The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding.
|
||||
assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255]));
|
||||
assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec()));
|
||||
assert_eq!(super::objects::base64_decode("!!!!"), None);
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
apply_filter(s);
|
||||
filter_result(s)
|
||||
})
|
||||
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
|
||||
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; `sort` also accepts a field name, one key object or null; array entries may also be field names; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
|
||||
.when(has_list)
|
||||
.pure(),
|
||||
CommandSpec::new("mailings.sortRecipients", "Sort Recipients", "Mailings › Start Mail Merge › Edit Recipient List", |s, v| {
|
||||
@@ -118,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
apply_filter(s);
|
||||
filter_result(s)
|
||||
})
|
||||
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (no params: the list's own order)"#)
|
||||
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (`sort` also accepts a field name, one key object or null; array entries may also be field names; no params: the list's own order)"#)
|
||||
.when(has_list)
|
||||
.pure(),
|
||||
CommandSpec::new("mailings.insertField", "Insert Merge Field", "Mailings › Write & Insert Fields", |s, v| {
|
||||
@@ -192,6 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
refresh(s);
|
||||
Ok(json!({"record": idx + 1}))
|
||||
})
|
||||
.params(r#"{"text": string}"#)
|
||||
.when(has_recipients),
|
||||
CommandSpec::new("mailings.checkErrors", "Check for Errors", "Mailings › Finish", |s, _| {
|
||||
let mut missing = Vec::new();
|
||||
|
||||
@@ -255,7 +255,7 @@ pub(super) fn parse_sort(headers: &[String], v: Option<&Value>) -> Result<Vec<So
|
||||
None | Some(Value::Null) => return Ok(Vec::new()),
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(o @ (Value::Object(_) | Value::String(_))) => vec![o.clone()],
|
||||
Some(_) => return Err(CmdError::Params("`sort` must be an array of {field, descending}".into())),
|
||||
Some(_) => return Err(CmdError::Params("`sort` must be a field name, a {field, descending} object, an array of those, or null".into())),
|
||||
};
|
||||
if arr.len() > MAX_SORT_KEYS {
|
||||
return Err(CmdError::Params(format!("at most {MAX_SORT_KEYS} sort keys")));
|
||||
|
||||
@@ -189,22 +189,19 @@ fn merge_end_to_end() {
|
||||
/// A typed list (#240) keeps its column order, and rows may be arrays in that order.
|
||||
#[test]
|
||||
fn recipients_from_a_workbook_ask_for_the_sheet_when_there_are_several() {
|
||||
use std::io::Write;
|
||||
let cell = |t: &str| format!(r#"<table:table-cell office:value-type="string"><text:p>{t}</text:p></table:table-cell>"#);
|
||||
let row = |cells: &[&str]| format!("<table:table-row>{}</table:table-row>", cells.iter().map(|c| cell(c)).collect::<String>());
|
||||
let content = format!(
|
||||
r#"<office:document-content xmlns:office="o" xmlns:table="t" xmlns:text="x"><office:body><office:spreadsheet><table:table table:name="Notes">{}</table:table><table:table table:name="Guests">{}{}{}</table:table></office:spreadsheet></office:body></office:document-content>"#,
|
||||
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Notes">{}</table:table><table:table table:name="Guests">{}{}{}</table:table></office:spreadsheet></office:body></office:document-content>"#,
|
||||
row(&["n"]),
|
||||
row(&["Name", "", "Name"]),
|
||||
row(&["Ada", "London", "A"]),
|
||||
row(&["Alan", "Wilmslow", "B"]),
|
||||
);
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, body) in [("mimetype", "application/vnd.oasis.opendocument.spreadsheet"), ("content.xml", content.as_str())] {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(body.as_bytes()).unwrap();
|
||||
}
|
||||
let data = super::super::insert::base64_encode(&z.finish().unwrap().into_inner());
|
||||
let mut z = craft_zip::Writer::new();
|
||||
z.add("mimetype", b"application/vnd.oasis.opendocument.spreadsheet", craft_zip::Compression::Stored).unwrap();
|
||||
z.add("content.xml", content.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
let data = super::super::insert::base64_encode(&z.finish().unwrap());
|
||||
let mut s = Session::new(Document::new());
|
||||
// Two sheets and none chosen: the names come back and nothing loads.
|
||||
let r = s.run("mailings.recipients", &json!({"data": data})).unwrap();
|
||||
@@ -593,8 +590,7 @@ fn recipients_from_an_xls_workbook() {
|
||||
let book = wordcraft_formats::sheet::xls_fixture(&[(
|
||||
"收件人",
|
||||
vec![row(&["姓名", "城市", "数量"]), row(&["张三", "北京", "12"]), row(&["李四", "上海", "2"])],
|
||||
)])
|
||||
.unwrap();
|
||||
)]);
|
||||
let mut s = Session::new(Document::new());
|
||||
let r = s.run("mailings.recipients", &json!({"path": "名单.xls", "data": b64(&book)})).unwrap();
|
||||
assert_eq!(r, json!({"fields": ["姓名", "城市", "数量"], "records": 2, "sheet": "收件人"}));
|
||||
|
||||
@@ -194,8 +194,7 @@ pub(super) fn adjust_media(
|
||||
e => CmdError::Failed(format!("can't decode the picture: {e}")),
|
||||
})?;
|
||||
let out = f(img)?;
|
||||
let mut png = Vec::new();
|
||||
out.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| CmdError::Failed(e.to_string()))?;
|
||||
let png = wordcraft_geom::picture::encode_png(&out).map_err(CmdError::Failed)?;
|
||||
let key = s.doc.add_media(png, "png");
|
||||
// Chain onto the ultimate original (the base's, or the current picture's when the base
|
||||
// is itself derived), so Reset Picture always finds it.
|
||||
|
||||
@@ -5,9 +5,8 @@ fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(w, h, |x, y| {
|
||||
if x > 2 && x < w - 3 && y > 2 && y < h - 3 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([255, 255, 255, 255]) }
|
||||
});
|
||||
let mut b = Vec::new();
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap();
|
||||
b
|
||||
|
||||
wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img).clone(), image::ImageFormat::Png).unwrap()
|
||||
}
|
||||
/// The laid-out area of the only picture or shape (not a text box).
|
||||
fn object_area(s: &mut Session) -> wordcraft_layout::hit::ObjectHit {
|
||||
@@ -451,8 +450,9 @@ fn remove_background_keeps_a_small_stack() {
|
||||
/// 1 × 2,000,000 picture Thick Frame asked for about 1.8 TB and aborted the process.
|
||||
#[test]
|
||||
fn picture_styles_and_borders_check_the_size_they_draw() {
|
||||
let mut thin = Vec::new();
|
||||
image::GrayImage::new(1, 2_000_000).write_to(&mut std::io::Cursor::new(&mut thin), image::ImageFormat::Png).unwrap();
|
||||
let thin =
|
||||
wordcraft_geom::picture::encode_format(&image::DynamicImage::from(image::GrayImage::new(1, 2_000_000).clone()), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.picture", &json!({"data": super::super::insert::base64_encode(&thin)})).unwrap();
|
||||
let media = s.doc.media.len();
|
||||
@@ -526,7 +526,7 @@ fn transparency_is_absolute_from_the_original() {
|
||||
let (_, o) = selected(s).unwrap();
|
||||
let InlineObject::Image { media, .. } = o else { panic!("a picture") };
|
||||
let bytes = s.doc.media.get(&media).cloned().unwrap();
|
||||
image::load_from_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>()
|
||||
wordcraft_geom::picture::decode_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>()
|
||||
};
|
||||
let alpha = |s: &Session| rgba(s).iter().map(|p| p[3]).collect::<Vec<_>>();
|
||||
let orig = rgba(&s);
|
||||
@@ -579,7 +579,7 @@ fn picture_edits_replace_the_file_corrections() {
|
||||
let (_, o) = selected(s).unwrap();
|
||||
let InlineObject::Image { media, fx, .. } = o else { panic!("a picture") };
|
||||
let bytes = s.doc.media.get(&media).cloned().unwrap();
|
||||
(media, fx, image::load_from_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>())
|
||||
(media, fx, wordcraft_geom::picture::decode_memory(&bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>())
|
||||
};
|
||||
let (orig_media, _, orig) = state(&s);
|
||||
// Transparency 50%: 50% (not 75%), the file's transparency dropped, its lum kept.
|
||||
@@ -670,7 +670,7 @@ fn picture_styles_borders_and_effects_replace_the_last_one() {
|
||||
let bitmap = |s: &Session| {
|
||||
let (_, o) = selected(s).unwrap();
|
||||
let InlineObject::Image { media, .. } = o else { panic!("a picture") };
|
||||
image::load_from_memory(&s.doc.media.get(&media).cloned().unwrap()).unwrap().to_rgba8()
|
||||
wordcraft_geom::picture::decode_memory(&s.doc.media.get(&media).cloned().unwrap()).unwrap().to_rgba8()
|
||||
};
|
||||
let after = |cmds: &[(&str, Value)]| {
|
||||
let mut s = picture();
|
||||
@@ -1274,9 +1274,9 @@ fn arrange_bounds_on_header_picture_writes_page_anchored_odt_frame() {
|
||||
assert_eq!((float.h_rel, float.v_rel), (Anchor::Page, Anchor::Page));
|
||||
assert_eq!((float.x, float.y), (0.0, 0.0));
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_formats::odt::export(&s.doc).unwrap())).unwrap();
|
||||
let mut styles = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("styles.xml").unwrap(), &mut styles).unwrap();
|
||||
let _z_bytes = wordcraft_formats::odt::export(&s.doc).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let styles = String::from_utf8(z.read("styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(styles.contains(r#"text:anchor-type="page""#), "frame should be page-anchored: {styles}");
|
||||
assert!(styles.contains(r#"svg:x="0pt""#) && styles.contains(r#"svg:y="0pt""#), "offsets should be 0pt: {styles}");
|
||||
assert!(!styles.contains(r#"text:anchor-type="paragraph""#), "frame should not be paragraph-anchored: {styles}");
|
||||
@@ -1288,9 +1288,9 @@ fn arrange_bounds_on_header_picture_writes_page_anchored_odt_frame() {
|
||||
assert_eq!((float.h_rel, float.v_rel), (Anchor::Page, Anchor::Page));
|
||||
assert_eq!((float.x, float.y), (10.0, 20.0));
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_formats::odt::export(&s.doc).unwrap())).unwrap();
|
||||
let mut styles = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("styles.xml").unwrap(), &mut styles).unwrap();
|
||||
let _z_bytes = wordcraft_formats::odt::export(&s.doc).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let styles = String::from_utf8(z.read("styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(styles.contains(r#"text:anchor-type="page""#), "{styles}");
|
||||
assert!(styles.contains(r#"svg:x="10pt""#) && styles.contains(r#"svg:y="20pt""#), "{styles}");
|
||||
}
|
||||
@@ -1325,9 +1325,9 @@ fn a_moved_body_picture_is_placed_by_its_paragraph_even_when_fixed_to_the_page()
|
||||
let hit = s.layout().object(&pos, 0).expect("laid out");
|
||||
assert!((hit.rect.x - 50.0).abs() < 1.0 && (hit.rect.y - 80.0).abs() < 1.0, "dropped: {:?}", hit.rect);
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_formats::odt::export(&s.doc).unwrap())).unwrap();
|
||||
let mut content = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("content.xml").unwrap(), &mut content).unwrap();
|
||||
let _z_bytes = wordcraft_formats::odt::export(&s.doc).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let content = String::from_utf8(z.read("content.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(content.contains(r#"text:anchor-type="paragraph""#), "body picture should export with paragraph anchor: {content}");
|
||||
assert!(!content.contains("anchor-page-number"), "{content}");
|
||||
}
|
||||
@@ -1606,7 +1606,6 @@ fn mirrored_indents_make_no_extra_column() {
|
||||
/// A Word file whose only paragraph holds a group of a rectangle and Word's own ink (with its
|
||||
/// picture fallback).
|
||||
fn group_with_word_ink() -> Vec<u8> {
|
||||
use std::io::Write;
|
||||
let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk""#;
|
||||
let rect = r#"<wps:wsp><wps:cNvPr id="2" name="Box"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr><wps:bodyPr/></wps:wsp>"#;
|
||||
let ink = r#"<mc:AlternateContent><mc:Choice Requires="wpi"><w14:contentPart bwMode="auto" r:id="rInk"><w14:nvContentPartPr><w14:cNvPr id="3" name="Ink 3"/><w14:cNvContentPartPr/></w14:nvContentPartPr><w14:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="457200"/></w14:xfrm></w14:contentPart></mc:Choice><mc:Fallback><pic:pic><pic:nvPicPr><pic:cNvPr id="3" name="Ink 3"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rPreview"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></mc:Fallback></mc:AlternateContent>"#;
|
||||
@@ -1626,14 +1625,12 @@ fn group_with_word_ink() -> Vec<u8> {
|
||||
),
|
||||
("word/ink/ink1.xml", r#"<ink xmlns="http://www.w3.org/2003/InkML"><trace>0 0, 1 1</trace></ink>"#.to_string()),
|
||||
];
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in parts {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.start_file("word/media/preview.png", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(&png(8, 4)).unwrap();
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.add("word/media/preview.png", &png(8, 4), craft_zip::Compression::Deflated).unwrap();
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn ink_members(doc: &wordcraft_doc::Document) -> usize {
|
||||
@@ -1653,7 +1650,6 @@ fn ink_members(doc: &wordcraft_doc::Document) -> usize {
|
||||
/// yet), so open → Ungroup → save → reopen keeps the ink in the group with its part.
|
||||
#[test]
|
||||
fn ungroup_refuses_a_group_holding_word_ink_and_the_ink_survives_saving() {
|
||||
use std::io::Read;
|
||||
let mut s = Session::new(wordcraft_docx::read(&group_with_word_ink()).unwrap());
|
||||
assert_eq!(ink_members(&s.doc), 1, "the fixture's ink is read into the group");
|
||||
let pos = Pos::body(0, 0);
|
||||
@@ -1666,16 +1662,14 @@ fn ungroup_refuses_a_group_holding_word_ink_and_the_ink_survives_saving() {
|
||||
let err = ungroup(&mut s, &json!({})).unwrap_err();
|
||||
assert!(matches!(err, CmdError::Disabled(_)), "{err:?}");
|
||||
let bytes = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<w14:contentPart").count(), 1, "{xml}");
|
||||
assert!(xml.contains("<mc:Fallback>"), "{xml}");
|
||||
assert_eq!(bytes, before, "the refused ungroup leaves the document unchanged");
|
||||
let names: Vec<String> = z.file_names().map(String::from).collect();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
assert_eq!(names.iter().filter(|n| n.starts_with("word/ink/")).count(), 1, "{names:?}");
|
||||
let mut rels = String::new();
|
||||
z.by_name("word/_rels/document.xml.rels").unwrap().read_to_string(&mut rels).unwrap();
|
||||
let rels = String::from_utf8(z.read("word/_rels/document.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(rels.matches("/customXml\"").count(), 1, "one ink relationship: {rels}");
|
||||
let back = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(ink_members(&back), 1);
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("file.options", "Options", "File", options)
|
||||
.params(
|
||||
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: the system locations only), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
|
||||
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
|
||||
|
||||
@@ -274,7 +274,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.quick = on;
|
||||
}
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"style": string (name or id), "value"?: bool (default true)}"#),
|
||||
// Advanced paragraph tools (#5043, as in WPS Office): conversions and cleanup over the
|
||||
// selection, or the whole document with `scope: "all"`. One undo step per command.
|
||||
CommandSpec::new("para.convertBreaks", "Convert Line Breaks to Paragraphs", "Home › Paragraph › Paragraph Tools", convert_breaks)
|
||||
|
||||
@@ -22,7 +22,7 @@ const MODES: [&str; 5] = ["none", "readOnly", "comments", "trackedChanges", "for
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("review.restrict", "Restrict Editing", "Review › Protect", restrict).params(
|
||||
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (start enforcing; "none" stops), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool, "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
|
||||
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (editing restriction; use "none" with "formatting": true for formatting-only protection), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool (true: stop protection), "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -431,7 +431,8 @@ enum HoleMode {
|
||||
/// run formatting and paragraph formatting outside the ranges `author` may edit, in every story,
|
||||
/// and the formatting of every table, row and cell that holds any of that protected content, and what
|
||||
/// reaches the whole document: page setup, the document defaults and the existing styles
|
||||
/// (applying a style may add one), the document's settings and its metadata.
|
||||
/// (applying a style may add one), the glossary's building blocks, the document's settings and
|
||||
/// its metadata.
|
||||
pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &str) -> bool {
|
||||
// Protection can't change mid-command (`protection_lifted` guards undo and redo).
|
||||
let mode = if Some("forms") == before.settings.protection.as_deref() { HoleMode::Controls } else { HoleMode::Perms(author.into()) };
|
||||
@@ -444,6 +445,7 @@ pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &st
|
||||
&& before.settings == after.settings
|
||||
&& before.core == after.core
|
||||
&& before.custom_props == after.custom_props
|
||||
&& before.glossary == after.glossary
|
||||
&& comments_unchanged(before, after)
|
||||
&& lists_unchanged(before, after)
|
||||
&& sources_unchanged(before, after)
|
||||
|
||||
@@ -428,6 +428,23 @@ fn the_post_check_compares_the_settings_and_the_metadata() {
|
||||
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged document isn't unchanged");
|
||||
}
|
||||
|
||||
/// The glossary's building blocks reach the whole document, so the post-check compares them.
|
||||
#[test]
|
||||
fn the_post_check_compares_the_glossary() {
|
||||
use wordcraft_doc::{BuildingBlock, CharProps, Paragraph};
|
||||
let mut before = Document::from_text("Some text.");
|
||||
before.glossary.push(BuildingBlock {
|
||||
name: "g".into(),
|
||||
blocks: vec![wordcraft_doc::para_block(Paragraph::with_text("Block", Default::default()))],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged glossary is unchanged");
|
||||
let mut after = before.clone();
|
||||
after.glossary[0].blocks[0] =
|
||||
wordcraft_doc::para_block(Paragraph::with_text("Block", CharProps { lang: Some("fr-FR".into()), ..Default::default() }));
|
||||
assert!(!super::outside_unchanged(&before, &after, "someone"), "a relanguaged building block is a change");
|
||||
}
|
||||
|
||||
/// Read only, no exceptions: going to a header the document doesn't have doesn't create
|
||||
/// one, and loading or filtering recipients doesn't rewrite the merge fields' shown results
|
||||
/// (both used to change the document from a non-mutating command, #1327).
|
||||
|
||||
@@ -56,7 +56,7 @@ fn docx_styleref_header_shows_each_page_s_chapter() {
|
||||
);
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdH" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/><Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, text) in [
|
||||
("_rels/.rels", root),
|
||||
("word/document.xml", body.as_str()),
|
||||
@@ -64,10 +64,9 @@ fn docx_styleref_header_shows_each_page_s_chapter() {
|
||||
("word/header1.xml", header.as_str()),
|
||||
("word/styles.xml", styles.as_str()),
|
||||
] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
std::io::Write::write_all(&mut zw, text.as_bytes()).unwrap();
|
||||
zw.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let bytes = zw.finish().unwrap().into_inner();
|
||||
let bytes = zw.finish().unwrap();
|
||||
let headers = |s: &mut Session| -> Vec<String> {
|
||||
s.layout()
|
||||
.pages
|
||||
@@ -714,12 +713,11 @@ fn output_numbers_text_box_captions_where_their_boxes_are_anchored() {
|
||||
let body: String = paras.iter().map(|p| format!("<w:p>{p}</w:p>")).collect();
|
||||
let document = format!("<w:document {ns}><w:body>{body}<w:sectPr/></w:body></w:document>");
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, text) in [("_rels/.rels", root), ("word/document.xml", document.as_str())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
std::io::Write::write_all(&mut zw, text.as_bytes()).unwrap();
|
||||
zw.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let s = Session::new(crate::io::open_bytes("boxes.docx", &zw.finish().unwrap().into_inner()).unwrap());
|
||||
let s = Session::new(crate::io::open_bytes("boxes.docx", &zw.finish().unwrap()).unwrap());
|
||||
let out = crate::cmd::references::output_fields(&s.doc).expect("fresh numbers");
|
||||
// The SEQ and REF results in reading order, text boxes where they are anchored.
|
||||
let mut results = Vec::new();
|
||||
@@ -774,12 +772,11 @@ fn output_shows_references_to_bookmarks_outside_the_body() {
|
||||
("word/endnotes.xml", endnotes),
|
||||
("word/comments.xml", comments),
|
||||
];
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, text) in &files {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
std::io::Write::write_all(&mut zw, text.as_bytes()).unwrap();
|
||||
zw.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let s = Session::new(crate::io::open_bytes("stories.docx", &zw.finish().unwrap().into_inner()).unwrap());
|
||||
let s = Session::new(crate::io::open_bytes("stories.docx", &zw.finish().unwrap()).unwrap());
|
||||
let out = crate::cmd::references::output_fields(&s.doc).expect("fresh references");
|
||||
let mut results = Vec::new();
|
||||
for path in out.para_paths(StoryRef::Body) {
|
||||
|
||||
@@ -67,13 +67,15 @@ pub fn toc_instr(v: &Value) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// A TOC entry: the paragraph it points at, its level (0-based), its text, and the leading page
|
||||
/// breaks of that paragraph (its page is where the text after them lands).
|
||||
/// A TOC entry: the paragraph it points at, its level (0-based), its text, the leading page
|
||||
/// breaks of that paragraph (its page is where the text after them lands), and, for a number
|
||||
/// followed by a tab, how far the heading's text starts after where its number starts.
|
||||
struct TocEntry {
|
||||
path: Path,
|
||||
level: u8,
|
||||
text: String,
|
||||
lead: usize,
|
||||
number_gap: Option<f32>,
|
||||
}
|
||||
|
||||
/// The headings of the body, in document order, as (body block, level 1–9, text, leading page
|
||||
@@ -117,9 +119,13 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
.and_then(|n| counters.next_label(&s.doc.numbering, n.num, n.level))
|
||||
.filter(|(label, def)| !label.is_empty() && !matches!(def.format, NumFormat::Bullet | NumFormat::None))
|
||||
.map(|(label, def)| match def.suffix {
|
||||
LevelSuffix::Tab => format!("{label}\t"),
|
||||
LevelSuffix::Space => format!("{label} "),
|
||||
LevelSuffix::Nothing => label,
|
||||
LevelSuffix::Tab => {
|
||||
let start = def.indent - def.hanging;
|
||||
let gap = def.tab.filter(|t| *t > start).unwrap_or(def.indent) - start;
|
||||
(format!("{label}\t"), Some(gap).filter(|g| g.is_finite() && *g > 0.0))
|
||||
}
|
||||
LevelSuffix::Space => (format!("{label} "), None),
|
||||
LevelSuffix::Nothing => (label, None),
|
||||
});
|
||||
let style = p.props.style.as_deref().unwrap_or("Normal");
|
||||
if style.starts_with("TOC") {
|
||||
@@ -144,8 +150,9 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
if let Some(l) = by_style.or(by_outline).or(if hidden { None } else { by_heading }) {
|
||||
let t = p.plain_text().replace(['\u{000C}', '\n', '\t'], " ").trim().to_string();
|
||||
if !t.is_empty() {
|
||||
let text = number.map_or_else(|| t.clone(), |n| format!("{n}{t}"));
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead });
|
||||
let text = number.as_ref().map_or_else(|| t.clone(), |(n, _)| format!("{n}{t}"));
|
||||
let number_gap = number.as_ref().and_then(|(_, g)| *g);
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead, number_gap });
|
||||
}
|
||||
}
|
||||
if let Some(id) = &tc {
|
||||
@@ -159,7 +166,7 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
let l = c.arg('l').and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
|
||||
let text = c.args.first().map(|t| t.trim().to_string()).unwrap_or_default();
|
||||
if (id.is_empty() || *id == kind) && (tc_levels.0..=tc_levels.1).contains(&l) && !text.is_empty() {
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off });
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off, number_gap: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -595,6 +602,16 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
para.mark = CharProps::default();
|
||||
if e.text.contains('\t') {
|
||||
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
|
||||
// Without a stop for the number (LibreOffice's Contents styles have only the page
|
||||
// number's right stop), its tab would run to the page number: the entry gets a
|
||||
// left stop as far after its indent as the heading's text is after its number.
|
||||
let style = s.doc.styles.resolve_para(¶.props);
|
||||
let has_stop =
|
||||
style.tabs.iter().any(|t| t.pos < width - 1.0 && matches!(t.align, TabAlign::Left | TabAlign::Center | TabAlign::Decimal));
|
||||
if let (None, false, Some(gap)) = (¶.props.tabs, has_stop, e.number_gap) {
|
||||
let pos = style.indent_left.max(0.0) + gap;
|
||||
para.props.tabs = (pos < width - 1.0).then(|| vec![TabStop { pos, align: TabAlign::Left, leader: TabLeader::None }]);
|
||||
}
|
||||
}
|
||||
if show_page && sep.contains('\t') {
|
||||
let right = TabStop { pos: width - 0.5, align: TabAlign::Right, leader };
|
||||
|
||||
@@ -28,12 +28,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("review.newComment", "New Comment", "Review › Comments", new_comment).key(super::mac_or("Mod+Alt+A / Mod+Alt+M", "Mod+Alt+M")).params(r#"{"text": string}"#),
|
||||
CommandSpec::new("review.reply", "Reply", "Review › Comments", reply)
|
||||
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
|
||||
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
|
||||
sel_result(s)
|
||||
})
|
||||
.params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
|
||||
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
|
||||
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
|
||||
|
||||
@@ -28,7 +28,7 @@ const ITEMS: &str = r#"[string | {"text": string, "level"?: 0-7, "color"?: RRGGB
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("insert.smartArt", "SmartArt", "Insert › Illustrations", insert).params(
|
||||
CommandSpec::new("insert.smartArt", "Diagram", "Insert › Illustrations", insert).params(
|
||||
r#"{"layout"?: "basicList|process|cycle|hierarchy|pyramid|radial|matrix|venn", "items"?: [string | {"text": string, "level"?: 0-7, "color"?: RRGGBB}], "colors"?: "accent1…accent6|colorful", "width"?: pt, "height"?: pt} (no items: sample items for the layout)"#,
|
||||
),
|
||||
CommandSpec::new("smartArt.items", "Edit Items", "SmartArt Design › Create Graphic", |s, v| {
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let below = p::bool(v, "below").unwrap_or(false);
|
||||
edit(s, move |g| {
|
||||
if g.items.len() >= MAX_ITEMS {
|
||||
return Err(CmdError::Failed(format!("a SmartArt graphic holds at most {MAX_ITEMS} items")));
|
||||
return Err(CmdError::Failed(format!("a diagram holds at most {MAX_ITEMS} items")));
|
||||
}
|
||||
let Some(last) = g.items.len().checked_sub(1) else {
|
||||
g.items.push(SmartArtItem::new(text.clone(), 0));
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.params(r#"{"layout": "basicList|process|cycle|hierarchy|pyramid|radial|matrix|venn"}"#)
|
||||
.when(has_smart_art),
|
||||
CommandSpec::new("smartArt.colors", "Change Colors", "SmartArt Design › SmartArt Styles", |s, v| {
|
||||
CommandSpec::new("smartArt.colors", "Change Colors", "SmartArt Design › Diagram Styles", |s, v| {
|
||||
let colors = colors_of(v)?.ok_or_else(|| CmdError::Params(format!("`variant` is required: {COLORS}")))?;
|
||||
edit(s, move |g| {
|
||||
g.colors = colors;
|
||||
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.params(r#"{"variant": "accent1|accent2|accent3|accent4|accent5|accent6|colorful"} (the items' own colours are dropped)"#)
|
||||
.when(has_smart_art),
|
||||
CommandSpec::new("smartArt.itemColor", "Item Color", "SmartArt Design › SmartArt Styles", |s, v| {
|
||||
CommandSpec::new("smartArt.itemColor", "Item Color", "SmartArt Design › Diagram Styles", |s, v| {
|
||||
let i = index(v, "index")?;
|
||||
let color = match v.get("color") {
|
||||
None | Some(Value::Null) => None,
|
||||
@@ -174,9 +174,9 @@ fn has_smart_art(s: &Session) -> Option<&'static str> {
|
||||
match selected(s) {
|
||||
Some((_, InlineObject::Graphic { graphic, .. })) if graphic.smart_art.is_some() => None,
|
||||
Some((_, InlineObject::Graphic { graphic, .. })) if graphic.kind == GraphicKind::Diagram => {
|
||||
Some("this SmartArt was made in another program: WordCraft shows it but can't edit it")
|
||||
Some("this diagram was made in another program: WordCraft shows it but can't edit it")
|
||||
}
|
||||
_ => Some("select a SmartArt graphic first"),
|
||||
_ => Some("select a diagram first"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,9 +299,9 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
/// Change the selected graphic's model with `f`, then lay it out again at its size.
|
||||
fn edit(s: &mut Session, f: impl Fn(&mut SmartArtSpec) -> Result<(), CmdError>) -> CmdResult {
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("select a SmartArt graphic first".into()))?;
|
||||
let InlineObject::Graphic { w, h, graphic, .. } = obj else { return Err(CmdError::Disabled("select a SmartArt graphic first".into())) };
|
||||
let mut spec = graphic.smart_art.as_deref().cloned().ok_or_else(|| CmdError::Disabled("this SmartArt graphic can't be edited".into()))?;
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("select a diagram first".into()))?;
|
||||
let InlineObject::Graphic { w, h, graphic, .. } = obj else { return Err(CmdError::Disabled("select a diagram first".into())) };
|
||||
let mut spec = graphic.smart_art.as_deref().cloned().ok_or_else(|| CmdError::Disabled("this diagram can't be edited".into()))?;
|
||||
f(&mut spec)?;
|
||||
let next = Arc::new(smart_art_graphic(spec, &s.doc.settings.theme_colors, w, h));
|
||||
let out = json!({"smartArt": next.smart_art.as_deref()});
|
||||
|
||||
@@ -9,9 +9,10 @@ use wordcraft_doc::props::{HeightRule, VMerge};
|
||||
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
|
||||
use wordcraft_doc::{Block, Cell, Path, Pos, StoryRef, Table, para_block};
|
||||
use wordcraft_geom::Rect;
|
||||
use wordcraft_layout::{DocLayout, Placed};
|
||||
use wordcraft_layout::DocLayout;
|
||||
|
||||
use super::sel_result;
|
||||
use super::table_resize::Reach;
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
/// A drag shorter than this (points) both ways isn't a rectangle.
|
||||
@@ -29,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#"{"page": n, "x0": pt, "y0": pt, "x1": pt, "y1": pt, "story"?: StoryRef} (a pen stroke in page points, 0-based page: a rectangle at least 12 pt each way outside any table inserts a one-cell table of that size at the paragraph under its start; a straight vertical or horizontal line inside a table splits the cells it crosses there. In the app the button turns the pen on.)"#,
|
||||
),
|
||||
CommandSpec::new("table.eraser", "Eraser", "Table Layout › Draw", eraser).params(
|
||||
r#"{"page": n, "x": pt, "y": pt} (removes the border between two cells within 4 pt of the point: cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
|
||||
r#"{"page": n, "x": pt, "y": pt, "story"?: StoryRef} (removes the border between two cells within 4 pt of the point, of a table in `story` (default: the caret's; a header's or footer's while one is edited): cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -55,16 +56,12 @@ struct CellBox {
|
||||
cell: usize,
|
||||
}
|
||||
|
||||
fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
|
||||
let Some(pg) = l.pages.get(page) else { return Vec::new() };
|
||||
pg.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Cell { rect, table, row, cell, story, .. } => {
|
||||
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
/// The table cells on a page the pen and eraser reach ([`Reach`]: a header's and footer's while
|
||||
/// one of them is edited, #5558).
|
||||
fn cell_boxes(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
|
||||
super::table_resize::cell_boxes_in(l, page, reach)
|
||||
.into_iter()
|
||||
.map(|b| CellBox { rect: b.rect, table: b.table, story: b.story, row: b.row, cell: b.cell })
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -79,13 +76,22 @@ fn table_at(boxes: &[CellBox], x: f32, y: f32) -> Option<(StoryRef, Path)> {
|
||||
|
||||
/// Classify a pen stroke: a straight line inside a table, a rectangle outside one, else `None`.
|
||||
pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
|
||||
stroke_in(l, page, Reach::Body, x0, y0, x1, y1)
|
||||
}
|
||||
|
||||
/// [`stroke`] while `editing` is edited: across a header's or footer's tables then (#5558).
|
||||
pub fn stroke_in(l: &DocLayout, page: usize, tables: Reach, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
|
||||
stroke_among(&cell_boxes(l, page, tables), x0, y0, x1, y1)
|
||||
}
|
||||
|
||||
/// [`stroke`] across the tables of `boxes`.
|
||||
fn stroke_among(boxes: &[CellBox], x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
|
||||
if ![x0, y0, x1, y1].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (dx, dy) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
let boxes = cell_boxes(l, page);
|
||||
let (mx, my) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
if table_at(&boxes, x0, y0).is_some() || table_at(&boxes, mx, my).is_some() {
|
||||
if table_at(boxes, x0, y0).is_some() || table_at(boxes, mx, my).is_some() {
|
||||
if dy >= dx && dy >= MIN_LINE && dx <= MIN_RECT.max(dy * 0.2) {
|
||||
return Some(Stroke::Vertical { x: mx, y0: y0.min(y1), y1: y0.max(y1) });
|
||||
}
|
||||
@@ -97,6 +103,19 @@ pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) ->
|
||||
(dx >= MIN_RECT && dy >= MIN_RECT).then(|| Stroke::Rect(Rect::new(x0.min(x1), y0.min(y1), dx, dy)))
|
||||
}
|
||||
|
||||
/// The cells a pen or eraser command reaches: those of the tables its `story` (default: the
|
||||
/// caret's) reaches ([`Reach`]), and of those only `story`'s own when the command names one: a
|
||||
/// caller that names a story means its tables, not a table of another drawn there.
|
||||
fn command_boxes(s: &Session, l: &DocLayout, v: &Value, page: usize) -> Vec<CellBox> {
|
||||
let story = super::story_param(s, v);
|
||||
let boxes = cell_boxes(l, page, Reach::of(l, &s.doc, story, page));
|
||||
let named = v.get("story").and_then(|x| serde_json::from_value::<StoryRef>(x.clone()).ok());
|
||||
match named {
|
||||
Some(named) => boxes.into_iter().filter(|b| b.story == named).collect(),
|
||||
None => boxes,
|
||||
}
|
||||
}
|
||||
|
||||
fn page_param(v: &Value) -> Result<usize, CmdError> {
|
||||
p::u64(v, "page").map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| CmdError::Params("`page` (number) is required".into()))
|
||||
}
|
||||
@@ -108,10 +127,11 @@ fn draw(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if l.pages.get(page).is_none() {
|
||||
return Err(CmdError::Params(format!("no page {page}")));
|
||||
}
|
||||
match stroke(&l, page, x0, y0, x1, y1) {
|
||||
let boxes = command_boxes(s, &l, v, page);
|
||||
match stroke_among(&boxes, x0, y0, x1, y1) {
|
||||
Some(Stroke::Rect(r)) => draw_table(s, v, &l, page, (x0, y0), r),
|
||||
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &l, page, x, (y0, y1)),
|
||||
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &l, page, y, (x0, x1)),
|
||||
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &boxes, x, (y0, y1)),
|
||||
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &boxes, y, (x0, x1)),
|
||||
None => Err(CmdError::Failed(
|
||||
"draw a rectangle (at least 12 pt each way) outside a table, or a straight horizontal or vertical line across table cells".into(),
|
||||
)),
|
||||
@@ -276,13 +296,12 @@ fn hide_edge(t: &mut Table, vertical: bool, line: usize, (lo, hi): (usize, usize
|
||||
}
|
||||
|
||||
/// A vertical line at page `x`: split each crossed cell into two columns there.
|
||||
fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb): (f32, f32)) -> CmdResult {
|
||||
let boxes = cell_boxes(l, page);
|
||||
fn split_columns(s: &mut Session, boxes: &[CellBox], x: f32, (ya, yb): (f32, f32)) -> CmdResult {
|
||||
let hit = |r: &Rect| {
|
||||
let overlap = yb.min(r.bottom()) - ya.max(r.y);
|
||||
x > r.x + SNAP && x < r.right() - SNAP && overlap >= r.h * 0.5
|
||||
};
|
||||
let Some((story, tp, cells)) = crossed(&boxes, (x, (ya + yb) / 2.0), hit) else {
|
||||
let Some((story, tp, cells)) = crossed(boxes, (x, (ya + yb) / 2.0), hit) else {
|
||||
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
|
||||
};
|
||||
let Some(&(r0, c0, rect0)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
|
||||
@@ -372,13 +391,12 @@ fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb):
|
||||
|
||||
/// A horizontal line at page `y`: split the row it crosses there. Crossed cells become two;
|
||||
/// the row's other cells span both rows (a vertical merge).
|
||||
fn split_rows(s: &mut Session, l: &DocLayout, page: usize, y: f32, (xa, xb): (f32, f32)) -> CmdResult {
|
||||
let boxes = cell_boxes(l, page);
|
||||
fn split_rows(s: &mut Session, boxes: &[CellBox], y: f32, (xa, xb): (f32, f32)) -> CmdResult {
|
||||
let hit = |r: &Rect| {
|
||||
let overlap = xb.min(r.right()) - xa.max(r.x);
|
||||
y > r.y + SNAP && y < r.bottom() - SNAP && overlap >= r.w * 0.5
|
||||
};
|
||||
let Some((story, tp, cells)) = crossed(&boxes, ((xa + xb) / 2.0, y), hit) else {
|
||||
let Some((story, tp, cells)) = crossed(boxes, ((xa + xb) / 2.0, y), hit) else {
|
||||
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
|
||||
};
|
||||
let Some(&(r, c0, _)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
|
||||
@@ -459,17 +477,26 @@ pub struct EraseTarget {
|
||||
|
||||
/// The border between two cells nearest page point (`x`, `y`), within [`ERASER_REACH`].
|
||||
pub fn erase_target(l: &DocLayout, page: usize, x: f32, y: f32) -> Option<EraseTarget> {
|
||||
erase_target_in(l, page, Reach::Body, x, y)
|
||||
}
|
||||
|
||||
/// [`erase_target`] while `editing` is edited: a header's or footer's tables then (#5558).
|
||||
pub fn erase_target_in(l: &DocLayout, page: usize, tables: Reach, x: f32, y: f32) -> Option<EraseTarget> {
|
||||
erase_among(&cell_boxes(l, page, tables), x, y)
|
||||
}
|
||||
|
||||
/// [`erase_target`] among the tables of `boxes`.
|
||||
fn erase_among(boxes: &[CellBox], x: f32, y: f32) -> Option<EraseTarget> {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let boxes = cell_boxes(l, page);
|
||||
let mut best: Option<(f32, usize, EraseTarget)> = None;
|
||||
let mut offer = |d: f32, depth: usize, e: EraseTarget| {
|
||||
if d <= ERASER_REACH && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
|
||||
best = Some((d, depth, e));
|
||||
}
|
||||
};
|
||||
for a in &boxes {
|
||||
for a in boxes {
|
||||
let (ar, ab) = (a.rect.right(), a.rect.bottom());
|
||||
let same = |b: &&CellBox| b.story == a.story && b.table == a.table;
|
||||
// The border on a's right, shared with the next cell of its row.
|
||||
@@ -518,7 +545,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if l.pages.get(page).is_none() {
|
||||
return Err(CmdError::Params(format!("no page {page}")));
|
||||
}
|
||||
let e = erase_target(&l, page, x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
|
||||
let e = erase_among(&command_boxes(s, &l, v, page), x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
|
||||
let (story, tp) = (e.story, e.table.clone());
|
||||
let t = s.doc.table_mut(story, &tp)?;
|
||||
let ((r, c), (r2, c2)) = (e.first, e.second);
|
||||
@@ -581,6 +608,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use wordcraft_layout::Placed;
|
||||
|
||||
/// Each row's cell spans.
|
||||
fn shape(t: &Table) -> Value {
|
||||
|
||||
@@ -16,7 +16,7 @@ use wordcraft_doc::{Document, Path, Pos, StoryRef, Table};
|
||||
use wordcraft_geom::{Point, Rect};
|
||||
use wordcraft_layout::{DocLayout, Placed};
|
||||
|
||||
use super::table_resize::{self, CellBox, Edge, REACH, ResizeTarget};
|
||||
use super::table_resize::{self, CellBox, Edge, REACH, Reach, ResizeTarget};
|
||||
use super::{sel_result, table};
|
||||
use crate::{CellRange, CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "reach"?: pt} (a drag from the move handle past a table's top-left corner: the table floats where it's dropped, the text wrapping around it; tables in the main text only)"#,
|
||||
),
|
||||
CommandSpec::new("table.fitColumn", "AutoFit Column by Double-Clicking", "Table Layout › Cell Size", fit_column).params(
|
||||
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
|
||||
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border of a table in the caret's story: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -205,11 +205,12 @@ pub fn target_at(l: &DocLayout, doc: &Document, story: StoryRef, page: usize, x:
|
||||
return None;
|
||||
}
|
||||
let reach = clean_reach(reach);
|
||||
if table_resize::resize_target(l, doc, page, x, y, reach).is_some() {
|
||||
let tables = Reach::of(l, doc, story, page);
|
||||
if table_resize::resize_target_in(l, doc, page, x, y, reach, tables).is_some() {
|
||||
return None;
|
||||
}
|
||||
let boxes = table_resize::cell_boxes(l, page);
|
||||
table_resize::tables_on(l, doc, page)
|
||||
let boxes = table_resize::cell_boxes_in(l, page, tables);
|
||||
table_resize::tables_on_in(l, doc, page, tables)
|
||||
.into_iter()
|
||||
.filter(|g| g.story == story)
|
||||
.filter_map(|geom| {
|
||||
@@ -226,7 +227,7 @@ pub fn handle_table(l: &DocLayout, doc: &Document, story: StoryRef, page: usize,
|
||||
return None;
|
||||
}
|
||||
let pad = clean_reach(reach) / 2.0;
|
||||
table_resize::tables_on(l, doc, page)
|
||||
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page))
|
||||
.into_iter()
|
||||
.filter(|g| {
|
||||
let h = handle(g);
|
||||
@@ -242,7 +243,7 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
|
||||
let rows = doc.table(story, table).map_or(0, |t| t.rows.len());
|
||||
let has_row = |p: usize, r: usize| {
|
||||
l.pages.get(p).is_some_and(|pg| {
|
||||
pg.items.iter().any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
|
||||
pg.story_items(story).any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
|
||||
})
|
||||
};
|
||||
// A repeated header row, or a row running on to the next page, is drawn on more than one
|
||||
@@ -253,7 +254,9 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
|
||||
return (None, None);
|
||||
}
|
||||
// The table's geometry on this page that the pointer handles are drawn and grabbed from.
|
||||
let Some(g) = table_resize::tables_on(l, doc, page).into_iter().find(|g| g.story == story && g.table == *table) else {
|
||||
let Some(g) =
|
||||
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page)).into_iter().find(|g| g.story == story && g.table == *table)
|
||||
else {
|
||||
return (None, None);
|
||||
};
|
||||
(first.then(|| handle(&g)), last.then(|| g.handle()))
|
||||
@@ -298,7 +301,7 @@ pub fn cell_rects(l: &DocLayout, doc: &Document, range: &CellRange) -> Vec<(usiz
|
||||
let picked: std::collections::BTreeSet<(usize, usize)> = range.cells(t).into_iter().collect();
|
||||
let mut out = Vec::new();
|
||||
for (pi, pg) in l.pages.iter().enumerate() {
|
||||
for it in &pg.items {
|
||||
for it in pg.story_items(range.story) {
|
||||
// A vertically merged cell's box spans its rows (#640); its continuation rows'
|
||||
// `covered` boxes would shade it twice.
|
||||
if let Placed::Cell { rect, table, row, cell, story, covered: false, .. } = it
|
||||
@@ -326,7 +329,7 @@ pub fn selection_rects(l: &DocLayout, doc: &Document, a: &Pos, b: &Pos, page_hin
|
||||
let mut seen = BTreeMap::new();
|
||||
let mut cells = Vec::new();
|
||||
for (pi, pg) in l.pages.iter().enumerate() {
|
||||
for it in &pg.items {
|
||||
for it in pg.story_items(a.story) {
|
||||
// A vertically merged cell's box spans its rows (#640), as in `cell_rects`.
|
||||
if let Placed::Cell { rect, table, row, story, covered: false, .. } = it
|
||||
&& *story == a.story
|
||||
@@ -510,7 +513,7 @@ fn insert_at(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Where table `table` of `story` is first drawn: its page and top-left corner.
|
||||
pub fn corner(l: &DocLayout, story: StoryRef, table: &Path) -> Option<(usize, f32, f32)> {
|
||||
l.pages.iter().enumerate().find_map(|(pi, pg)| {
|
||||
let cells = pg.items.iter().filter_map(|it| match it {
|
||||
let cells = pg.story_items(story).filter_map(|it| match it {
|
||||
Placed::Cell { rect, table: t, story: st, .. } if *st == story && t == table => Some(*rect),
|
||||
_ => None,
|
||||
});
|
||||
@@ -565,10 +568,12 @@ fn move_drag(s: &mut Session, v: &Value) -> CmdResult {
|
||||
fn fit_column(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (page, x, y, reach) = point(v)?;
|
||||
let l = s.layout();
|
||||
let Some((target, line)) = table_resize::resize_target(&l, &s.doc, page, x, y, reach).and_then(|t| match t.edge {
|
||||
Edge::Column(line) => Some((t, line)),
|
||||
_ => None,
|
||||
}) else {
|
||||
let Some((target, line)) = table_resize::resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
|
||||
.and_then(|t| match t.edge {
|
||||
Edge::Column(line) => Some((t, line)),
|
||||
_ => None,
|
||||
})
|
||||
else {
|
||||
return Err(CmdError::Failed("there's no column border there".into()));
|
||||
};
|
||||
let t = s.doc.table(target.story, &target.table).ok_or_else(|| CmdError::Failed("there's no table there".into()))?;
|
||||
@@ -595,7 +600,7 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
|
||||
let margin = l.pages.get(page).map_or(target.right(), |pg| pg.body.right());
|
||||
let Some((outer, row, cell)) = target.table.cell() else { return margin };
|
||||
let Some(t) = doc.table(target.story, &outer) else { return margin };
|
||||
let boxes = table_resize::cell_boxes(l, page);
|
||||
let boxes = table_resize::story_cell_boxes(l, page, target.story);
|
||||
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
|
||||
return margin;
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::props::{Align, HeightRule, VMerge};
|
||||
use wordcraft_doc::table::MAX_COLS;
|
||||
use wordcraft_doc::{Cell, Document, Path, StoryRef, Table};
|
||||
use wordcraft_doc::{Cell, Document, PartKind, Path, StoryRef, Table};
|
||||
use wordcraft_geom::Rect;
|
||||
use wordcraft_layout::{DocLayout, Placed};
|
||||
|
||||
@@ -29,7 +29,7 @@ const MAX_LEN: f32 = 1584.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![CommandSpec::new("table.resizeDrag", "Resize Table by Dragging", "Table Layout › Cell Size", resize_drag).params(
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a table border or the resize handle: a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a border or the resize handle of a table in the caret's story (a header's or footer's tables while one is edited): a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
|
||||
)]
|
||||
}
|
||||
|
||||
@@ -327,17 +327,53 @@ pub(crate) struct CellBox {
|
||||
pub(crate) cell: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
|
||||
/// Which of a page's tables the pointer reaches (#5558): the body's, with its text boxes' and
|
||||
/// notes', while those are edited; a header's and footer's, with the text boxes in them, while
|
||||
/// a header or footer (or a text box in one) is, and then not the dimmed body's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Reach {
|
||||
Body,
|
||||
HeaderFooter,
|
||||
}
|
||||
|
||||
impl Reach {
|
||||
/// The reach while `editing` is edited, around `page` (where a text box's host is looked for).
|
||||
pub fn of(l: &DocLayout, doc: &Document, editing: StoryRef, page: usize) -> Reach {
|
||||
let kind = |s: StoryRef| match s {
|
||||
StoryRef::Part(id) => doc.parts.get(&id).map(|p| p.kind),
|
||||
StoryRef::Body => None,
|
||||
};
|
||||
let host = match editing {
|
||||
StoryRef::Part(id) if kind(editing) == Some(PartKind::TextBox) => l.text_box(id, page).map_or(editing, |o| o.story),
|
||||
_ => editing,
|
||||
};
|
||||
if matches!(kind(host), Some(PartKind::Header | PartKind::Footer)) { Reach::HeaderFooter } else { Reach::Body }
|
||||
}
|
||||
}
|
||||
|
||||
/// The table cells on a page that the pointer reaches ([`Reach`]).
|
||||
pub(crate) fn cell_boxes_in(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
|
||||
let Some(pg) = l.pages.get(page) else { return Vec::new() };
|
||||
pg.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Cell { rect, table, row, cell, story, .. } => {
|
||||
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
let items: Box<dyn Iterator<Item = &Placed>> = match reach {
|
||||
Reach::Body => Box::new(pg.items.iter()),
|
||||
Reach::HeaderFooter => Box::new(pg.header.iter().chain(pg.footer.iter())),
|
||||
};
|
||||
items.filter_map(cell_box).collect()
|
||||
}
|
||||
|
||||
/// The cells of `story`'s tables on a page, wherever that story is drawn.
|
||||
pub(crate) fn story_cell_boxes(l: &DocLayout, page: usize, story: StoryRef) -> Vec<CellBox> {
|
||||
let Some(pg) = l.pages.get(page) else { return Vec::new() };
|
||||
pg.story_items(story).filter_map(cell_box).filter(|b| b.story == story).collect()
|
||||
}
|
||||
|
||||
fn cell_box(it: &Placed) -> Option<CellBox> {
|
||||
match it {
|
||||
Placed::Cell { rect, table, row, cell, story, .. } => {
|
||||
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawn geometry of one table on a page, from its cells' boxes.
|
||||
@@ -403,8 +439,14 @@ fn geometry(t: &Table, boxes: &[&CellBox]) -> Option<(Vec<f32>, Vec<DrawnRow>)>
|
||||
}
|
||||
|
||||
/// Every table drawn on a page, with its geometry there (`edge` is a placeholder).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn tables_on(l: &DocLayout, doc: &Document, page: usize) -> Vec<ResizeTarget> {
|
||||
let boxes = cell_boxes(l, page);
|
||||
tables_on_in(l, doc, page, Reach::Body)
|
||||
}
|
||||
|
||||
/// Every table drawn on a page that the pointer reaches ([`Reach`]).
|
||||
pub(crate) fn tables_on_in(l: &DocLayout, doc: &Document, page: usize, reach: Reach) -> Vec<ResizeTarget> {
|
||||
let boxes = cell_boxes_in(l, page, reach);
|
||||
let mut tables: Vec<(StoryRef, &Path)> = Vec::new();
|
||||
for b in &boxes {
|
||||
if !tables.iter().any(|(s, p)| *s == b.story && **p == b.table) {
|
||||
@@ -431,11 +473,17 @@ fn on_handle(t: &ResizeTarget, x: f32, y: f32, reach: f32) -> bool {
|
||||
/// The innermost table under page point (`x`, `y`) whose resize handle is on this page, or whose
|
||||
/// handle is under the point: the one whose handle the app shows.
|
||||
pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
|
||||
table_under_in(l, doc, page, x, y, reach, Reach::Body)
|
||||
}
|
||||
|
||||
/// [`table_under`] among the tables `tables` reaches: a header's or footer's while one is edited
|
||||
/// (#5558).
|
||||
pub fn table_under_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
|
||||
tables_on(l, doc, page)
|
||||
tables_on_in(l, doc, page, tables)
|
||||
.into_iter()
|
||||
.filter(|t| t.ends_here && ((x >= t.left() && x <= t.right() && y >= t.top() && y <= t.bottom()) || on_handle(t, x, y, reach)))
|
||||
.max_by_key(|t| t.table.0.len())
|
||||
@@ -444,12 +492,18 @@ pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, r
|
||||
/// The table border or resize handle within `reach` points of page point (`x`, `y`): the
|
||||
/// nearest, and of nested tables the innermost.
|
||||
pub fn resize_target(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
|
||||
resize_target_in(l, doc, page, x, y, reach, Reach::Body)
|
||||
}
|
||||
|
||||
/// [`resize_target`] among the tables `tables` reaches: a header's or footer's while one is
|
||||
/// edited (#5558).
|
||||
pub fn resize_target_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
|
||||
let mut best: Option<(f32, usize, ResizeTarget)> = None;
|
||||
for mut target in tables_on(l, doc, page) {
|
||||
for mut target in tables_on_in(l, doc, page, tables) {
|
||||
let depth = target.table.0.len();
|
||||
let mut offer = |d: f32, edge: Edge, target: &mut ResizeTarget| {
|
||||
if d <= reach && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
|
||||
@@ -500,8 +554,8 @@ fn resize_drag(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if l.pages.get(page).is_none() {
|
||||
return Err(CmdError::Params(format!("no page {page}")));
|
||||
}
|
||||
let mut target =
|
||||
resize_target(&l, &s.doc, page, x, y, reach).ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
|
||||
let mut target = resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
|
||||
.ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
|
||||
target.limit_to_selection(s, y);
|
||||
let plan = target.plan(to_x - x, to_y - y, share);
|
||||
if plan.widths.is_none() && plan.heights.is_empty() && plan.cells.is_empty() {
|
||||
@@ -647,7 +701,11 @@ fn regrid(t: &mut Table, cols: &[f32], rows: &[(usize, Vec<f32>)]) -> Result<(),
|
||||
|
||||
/// The page x of the target table's left edge on `page`, as drawn.
|
||||
fn drawn_left(l: &DocLayout, page: usize, target: &ResizeTarget) -> Option<f32> {
|
||||
cell_boxes(l, page).iter().filter(|b| b.story == target.story && b.table == target.table).map(|b| b.rect.x).min_by(f32::total_cmp)
|
||||
story_cell_boxes(l, page, target.story)
|
||||
.iter()
|
||||
.filter(|b| b.story == target.story && b.table == target.table)
|
||||
.map(|b| b.rect.x)
|
||||
.min_by(f32::total_cmp)
|
||||
}
|
||||
|
||||
/// Make `widths` (one per grid column) the table's column widths, as drawn: no preferred table
|
||||
@@ -663,7 +721,7 @@ pub(crate) fn set_widths(t: &mut Table, widths: Vec<f32>) {
|
||||
|
||||
/// The drawn height of each of the target table's rows on `page`.
|
||||
fn drawn_heights(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget) -> Vec<(usize, f32)> {
|
||||
tables_on(l, doc, page)
|
||||
tables_on_in(l, doc, page, Reach::of(l, doc, target.story, page))
|
||||
.into_iter()
|
||||
.find(|t| t.story == target.story && t.table == target.table)
|
||||
.map(|t| t.rows.iter().map(|r| (r.row, r.bottom - r.top)).collect())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
|
||||
use wordcraft_doc::CharProps;
|
||||
|
||||
/// Options › Language › Set as default: only the saved default proofing language (what future
|
||||
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
|
||||
@@ -14,8 +15,19 @@ pub(super) fn preferred_language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Set Proofing Language: the selection's language and "do not check spelling or grammar",
|
||||
/// or (`default`) the document's default and the saved language for future blank documents;
|
||||
/// `detect` is the per-user detection preference.
|
||||
/// Nothing at all sets US English, as before.
|
||||
/// Nothing at all sets US English, as before. `scope: "document"` sets it for every story.
|
||||
pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Checked first, so a bad scope changes nothing (not even the detect preference).
|
||||
let whole_document = match v.get("scope") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::String(t)) if t == "selection" => false,
|
||||
Some(Value::String(t)) if t == "document" => true,
|
||||
Some(other) => return Err(CmdError::Params(format!("`scope` must be \"selection\" or \"document\", not {other}"))),
|
||||
};
|
||||
// Protection leaves only its exceptions editable, so the whole document can't be one.
|
||||
if whole_document && let Some(mode) = s.doc.settings.protection.as_deref() {
|
||||
return Err(CmdError::Disabled(format!("review.language: stop protection ({mode}) before changing the whole document's proofing language")));
|
||||
}
|
||||
let lang = match p::str(v, "lang") {
|
||||
Some(t) => Some(
|
||||
wordcraft_proof::lang::normalize_tag(t)
|
||||
@@ -45,20 +57,91 @@ pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if lang.is_none() && no_proof.is_none() {
|
||||
return Ok(json!({"detect": s.prefs.detect_language}));
|
||||
}
|
||||
let result = crate::cmd::format::apply(s, &|c| {
|
||||
let change = |c: &mut CharProps| {
|
||||
if let Some(l) = &lang {
|
||||
c.lang = Some(l.clone());
|
||||
}
|
||||
if let Some(np) = no_proof {
|
||||
c.no_proof = Some(np);
|
||||
}
|
||||
})?;
|
||||
};
|
||||
let result = if whole_document {
|
||||
let glossary_skipped = set_document_props(s, &change)?;
|
||||
// The same caret/selection result as the selection path (the selection is untouched).
|
||||
let mut r = sel_result(s)?;
|
||||
if let Some(m) = r.as_object_mut() {
|
||||
m.insert("scope".into(), json!("document"));
|
||||
if glossary_skipped {
|
||||
m.insert("glossarySkipped".into(), json!(true));
|
||||
}
|
||||
}
|
||||
r
|
||||
} else {
|
||||
crate::cmd::format::apply(s, &change)?
|
||||
};
|
||||
if p::bool(v, "default") == Some(true) {
|
||||
s.prefs.default_language = lang;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Apply `f` to the character formatting of every story of the document (Language dialog, "Apply
|
||||
/// to the whole document"): text and paragraph marks of the body, headers, footers, notes,
|
||||
/// comments, text boxes (all `Document::parts`), table cells, and the glossary's building blocks.
|
||||
/// The selection is untouched; formatting waiting for typing follows.
|
||||
///
|
||||
/// Glossary blocks are left alone while Track Changes and Track Formatting are both on: tracked
|
||||
/// formatting (`fmt_revisions::record`) compares only the body and the parts, so a glossary change
|
||||
/// would be an untracked edit. So those blocks keep their old language while tracking; the caller
|
||||
/// reports it (`glossarySkipped`). Returns whether the glossary was skipped.
|
||||
fn set_document_props(s: &mut Session, f: &dyn Fn(&mut CharProps)) -> Result<bool, CmdError> {
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for story in stories {
|
||||
for path in s.doc.para_paths(story) {
|
||||
let para = s.doc.para_mut(story, &path)?;
|
||||
let len = para.len();
|
||||
para.format(0, len, f)?;
|
||||
f(&mut para.mark);
|
||||
para.touch();
|
||||
}
|
||||
}
|
||||
let skipped = s.doc.settings.track_changes && s.prefs.markup.track_formatting;
|
||||
if !skipped {
|
||||
for block in &mut s.doc.glossary {
|
||||
format_blocks(&mut block.blocks, f, 0);
|
||||
}
|
||||
}
|
||||
if let Some(pend) = s.pending.as_mut() {
|
||||
f(pend);
|
||||
}
|
||||
Ok(skipped)
|
||||
}
|
||||
|
||||
/// [`set_document_props`] for a block list outside any story (depth-limited like `para_paths`).
|
||||
fn format_blocks(blocks: &mut wordcraft_doc::Blocks, f: &dyn Fn(&mut CharProps), depth: usize) {
|
||||
if depth > wordcraft_doc::PARA_WALK_DEPTH {
|
||||
return;
|
||||
}
|
||||
for blk in blocks.iter_mut() {
|
||||
match Arc::make_mut(blk) {
|
||||
wordcraft_doc::Block::Para(p) => {
|
||||
let len = p.len();
|
||||
// A range inside the paragraph can't fail; the mark is formatted regardless.
|
||||
let _ = p.format(0, len, f);
|
||||
f(&mut p.mark);
|
||||
p.touch();
|
||||
}
|
||||
wordcraft_doc::Block::Table(t) => {
|
||||
for row in &mut t.rows {
|
||||
for cell in &mut row.cells {
|
||||
format_blocks(&mut cell.blocks, f, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn macros(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(d) = v.get("define") {
|
||||
let name = d.get("name").and_then(Value::as_str).unwrap_or("Macro").to_string();
|
||||
|
||||
@@ -340,7 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.params(r#"{"format": "decimal|upperRoman|lowerLetter…", "text"?: "%1.", "start"?: n}"#),
|
||||
CommandSpec::new("review.language", "Language", "Review › Language", language).params(
|
||||
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents)}"#,
|
||||
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents), "scope"?: "selection" (default) | "document" (every run and paragraph mark of every story: body, headers, footers, notes, comments, text boxes, tables, glossary (skipped while Track Changes and Track Formatting are on); one undo step, selection unchanged; returns the caret, "scope":"document" and "glossarySkipped":true when the glossary was skipped)}"#,
|
||||
),
|
||||
CommandSpec::new("review.language.preferred", "Set as Default Language", "File › Options › Language", preferred_language)
|
||||
.params(r#"{"lang": "en-US|en-GB|pl-PL|nl-NL|…" (BCP 47)} — only the saved default proofing language, what future blank documents are written in, as Options › Language › Set as default does; the open document, the selection and the undo history don't change. Returns {"preferred": tag}."#)
|
||||
|
||||
@@ -903,3 +903,150 @@ fn inspect_removals_work_when_the_document_does_not_track_changes() {
|
||||
assert!(!text.contains("Hidden"), "the hidden text is still there: {text}");
|
||||
assert!(text.contains("Visible text."), "{text}");
|
||||
}
|
||||
|
||||
/// #3518: every run and paragraph mark of a story, as (story, path, lang, noProof) rows.
|
||||
fn proofing_rows(s: &Session) -> Vec<(StoryRef, Option<String>, Option<bool>)> {
|
||||
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
|
||||
let mut out = Vec::new();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st) {
|
||||
let Some(p) = s.doc.para(st, &path) else { continue };
|
||||
out.push((st, p.mark.lang.clone(), p.mark.no_proof));
|
||||
out.extend(p.runs.iter().map(|r| (st, r.props.lang.clone(), r.props.no_proof)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A document with its text in German in the body, a table cell, a header, a footnote, a comment
|
||||
/// and a text box, as a Word DOCX keeps a `w:lang` on each run, plus a glossary entry.
|
||||
fn multi_story_doc() -> Session {
|
||||
use wordcraft_doc::{Block, BuildingBlock, CharProps, Paragraph, PartKind, Table};
|
||||
let de = || CharProps { lang: Some("de-DE".into()), ..Default::default() };
|
||||
let blk = |t: &str| Arc::new(Block::Para(Paragraph::with_text(t, de())));
|
||||
let mut d = Document::from_text("Guten Tag");
|
||||
d.body = vec![blk("Guten Tag")];
|
||||
let mut t = Table::new(1, 2, 200.0);
|
||||
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
|
||||
c.blocks = vec![blk("Zelle")];
|
||||
}
|
||||
d.body.push(Arc::new(Block::Table(t)));
|
||||
d.body.push(blk("Ende"));
|
||||
for kind in [PartKind::Header, PartKind::Footnote, PartKind::Comment, PartKind::TextBox] {
|
||||
d.add_part(kind, vec![blk("Teil")]);
|
||||
}
|
||||
d.glossary.push(BuildingBlock { name: "g".into(), blocks: vec![blk("Baustein")], ..Default::default() });
|
||||
Session::new(d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_document_sets_every_story() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
let (sel, before) = (s.sel.clone(), s.doc.clone());
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.len() >= 10 && rows.iter().any(|r| r.1.as_deref() == Some("de-DE")));
|
||||
s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
// Runs that had their own language, the paragraph marks and the empty cell: all French.
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.iter().all(|r| r.1.as_deref() == Some("fr-FR")), "{rows:?}");
|
||||
for kind_story in s.doc.parts.keys() {
|
||||
assert!(rows.iter().any(|r| r.0 == StoryRef::Part(*kind_story)));
|
||||
}
|
||||
assert!(s.doc.plain_text(StoryRef::Body).contains("Zelle"));
|
||||
let g = &s.doc.glossary[0].blocks;
|
||||
assert_eq!(g[0].as_para().map(|p| p.runs[0].props.lang.clone()), Some(Some("fr-FR".into())));
|
||||
assert_eq!(g[0].as_para().map(|p| p.mark.lang.clone()), Some(Some("fr-FR".into())));
|
||||
// The selection stays; the document is modified.
|
||||
assert_eq!(s.sel, sel);
|
||||
assert!(s.doc != before);
|
||||
// One undo restores everything.
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc == before);
|
||||
assert_eq!(s.sel, sel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_document_no_proof_and_pending() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.language", &json!({"noProof": true, "scope": "document"})).unwrap();
|
||||
assert!(proofing_rows(&s).iter().all(|r| r.2 == Some(true)));
|
||||
// The language itself wasn't asked for and stays.
|
||||
assert!(proofing_rows(&s).iter().any(|r| r.1.as_deref() == Some("de-DE")));
|
||||
// Formatting waiting for typing follows.
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "pl-PL", "scope": "document"})).unwrap();
|
||||
assert_eq!(s.pending.as_ref().and_then(|p| p.lang.as_deref()), Some("pl-PL"));
|
||||
}
|
||||
|
||||
/// Document scope returns the caret/selection like the selection path, plus the scope.
|
||||
#[test]
|
||||
fn language_scope_document_returns_the_selection_result() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert_eq!(out["scope"], "document");
|
||||
assert_eq!(out["anchor"], crate::cmd::pos_json(&s.sel.anchor), "{out}");
|
||||
assert_eq!(out["focus"], crate::cmd::pos_json(&s.sel.focus), "{out}");
|
||||
}
|
||||
|
||||
/// Tracked formatting records only the body and parts, so while it is on the glossary (outside
|
||||
/// any story) is left alone instead of changing untracked; with tracking off it changes.
|
||||
#[test]
|
||||
fn language_scope_document_skips_glossary_while_tracking_formatting() {
|
||||
let gloss = |s: &Session| s.doc.glossary[0].blocks[0].as_para().map(|p| (p.runs[0].props.lang.clone(), p.mark.lang.clone()));
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackFormatting": true})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert_eq!(out["glossarySkipped"], true, "{out}");
|
||||
assert_eq!(gloss(&s), Some((Some("de-DE".into()), Some("de-DE".into()))));
|
||||
assert!(proofing_rows(&s).iter().all(|r| r.1.as_deref() == Some("fr-FR")));
|
||||
assert!(s.doc.revisions.iter().any(|r| r.kind == wordcraft_doc::RevisionKind::Format), "the body change is tracked");
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackFormatting": false})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert!(out.get("glossarySkipped").is_none(), "{out}");
|
||||
assert_eq!(gloss(&s), Some((Some("fr-FR".into()), Some("fr-FR".into()))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_default_scope_is_selection_only() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "fr-FR"})).unwrap();
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.iter().any(|r| r.1.as_deref() == Some("fr-FR")));
|
||||
assert!(rows.iter().filter(|r| r.1.as_deref() == Some("fr-FR")).count() < rows.len() / 2);
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "fr-FR", "scope": "selection"})).unwrap();
|
||||
assert_eq!(proofing_rows(&s), rows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_bad_scope_is_a_params_error() {
|
||||
let mut s = multi_story_doc();
|
||||
let before = s.doc.clone();
|
||||
for bad in [json!("everything"), json!(1), json!(true), json!(["document"])] {
|
||||
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": bad})).unwrap_err();
|
||||
assert!(matches!(e, CmdError::Params(_)), "{e:?}");
|
||||
}
|
||||
assert!(s.doc == before);
|
||||
assert!(s.prefs.detect_language);
|
||||
}
|
||||
|
||||
/// Document scope is refused under editing protection, before anything changes.
|
||||
#[test]
|
||||
fn language_document_scope_is_refused_under_protection() {
|
||||
for mode in ["readOnly", "comments", "forms"] {
|
||||
let mut s = multi_story_doc();
|
||||
s.doc.settings.protection = Some(mode.into());
|
||||
let before = s.doc.clone();
|
||||
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": "document"})).unwrap_err();
|
||||
assert!(matches!(e, CmdError::Disabled(_)), "{mode}: {e:?}");
|
||||
assert!(s.doc == before, "{mode}: nothing changed");
|
||||
assert!(s.prefs.detect_language, "{mode}: the detect preference is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,24 +19,24 @@ const EFFECT_PARAMS: &str = r#"{"style"?: "solid"|"outlined"|"hollow"|"gradient"
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("insert.wordArt", "WordArt", "Insert › Text", insert).params(
|
||||
r#"{"text"?: string, "style"?: WordArt style id (see format.textEffects), "transform"?: "textArchUp"|"textArchDown"|"textCircle"|"textWave1"|… (a DrawingML preset text warp)}"#,
|
||||
CommandSpec::new("insert.wordArt", "Decorative Text", "Insert › Text", insert).params(
|
||||
r#"{"text"?: string, "style"?: Decorative Text style id (see format.textEffects), "transform"?: "textArchUp"|"textArchDown"|"textCircle"|"textWave1"|… (a DrawingML preset text warp)}"#,
|
||||
),
|
||||
CommandSpec::new("format.textEffects", "Text Effects", "Home › Font", text_effects).params(EFFECT_PARAMS),
|
||||
CommandSpec::new("wordArt.style", "WordArt Styles", "Shape Format › WordArt Styles", |s, v| {
|
||||
CommandSpec::new("wordArt.style", "Decorative Text Styles", "Shape Format › Decorative Text Styles", |s, v| {
|
||||
let id = p::req_str(v, "style")?;
|
||||
text_effects(s, &json!({"style": id}))
|
||||
})
|
||||
.params(r#"{"style": "solid"|"outlined"|"hollow"|"gradient"|"shadowed"|"glowing"|"reflected"|"sunset"}"#),
|
||||
CommandSpec::new("wordArt.textFill", "Text Fill", "Shape Format › WordArt Styles", |s, v| {
|
||||
CommandSpec::new("wordArt.textFill", "Text Fill", "Shape Format › Decorative Text Styles", |s, v| {
|
||||
text_effects(s, &json!({"fill": v.get("fill").or_else(|| v.get("color")).cloned().unwrap_or(Value::Null)}))
|
||||
})
|
||||
.params(r#"{"fill": "RRGGBB"|"none"|{"gradient": ["RRGGBB", …], "angle"?: deg}|null}"#),
|
||||
CommandSpec::new("wordArt.textOutline", "Text Outline", "Shape Format › WordArt Styles", |s, v| {
|
||||
CommandSpec::new("wordArt.textOutline", "Text Outline", "Shape Format › Decorative Text Styles", |s, v| {
|
||||
text_effects(s, &json!({"outline": v.get("outline").cloned().unwrap_or_else(|| v.clone())}))
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB"|null, "width"?: pt} or {"outline": "none"|null}"#),
|
||||
CommandSpec::new("wordArt.transform", "Transform", "Shape Format › WordArt Styles", transform)
|
||||
CommandSpec::new("wordArt.transform", "Transform", "Shape Format › Decorative Text Styles", transform)
|
||||
.params(r#"{"preset": "textArchUp"|"textArchDown"|"textCircle"|"textWave1"|"textSlantUp"|"textSlantDown"|"textInflate"|"textDeflate"|"textChevron"|"textChevronInverted"|"textTriangle"|"textTriangleInverted"|… (any DrawingML preset text warp)|"none", "adj"?: n (the preset's adjust value)}"#),
|
||||
]
|
||||
}
|
||||
@@ -186,7 +186,7 @@ fn text_effects(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let theme = theme(s);
|
||||
let accent = theme.get(4).copied().unwrap_or(Rgb(0x15, 0x60, 0x82));
|
||||
let style = match p::str(v, "style") {
|
||||
Some(id) => Some(art_style(id, &theme).ok_or_else(|| CmdError::Params(format!("unknown WordArt style `{id}`")))?),
|
||||
Some(id) => Some(art_style(id, &theme).ok_or_else(|| CmdError::Params(format!("unknown decorative text style `{id}`")))?),
|
||||
None => None,
|
||||
};
|
||||
let clear = p::bool(v, "clear").unwrap_or(false);
|
||||
@@ -244,11 +244,11 @@ fn transform(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some(w)
|
||||
}
|
||||
};
|
||||
let pos = warp_target(s).ok_or_else(|| CmdError::Disabled("select a shape or WordArt first".into()))?;
|
||||
let pos = warp_target(s).ok_or_else(|| CmdError::Disabled("select a shape or decorative text first".into()))?;
|
||||
let para = s.doc.para_mut(pos.story, &pos.path)?;
|
||||
match para.object_at_mut(pos.off) {
|
||||
Some(InlineObject::Shape { extra, .. }) => extra.warp = warp.clone(),
|
||||
_ => return Err(CmdError::Disabled("select a shape or WordArt first".into())),
|
||||
_ => return Err(CmdError::Disabled("select a shape or decorative text first".into())),
|
||||
}
|
||||
para.touch();
|
||||
Ok(json!({"transform": warp.map(|w| w.preset)}))
|
||||
@@ -269,7 +269,7 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let text: String = p::str(v, "text").unwrap_or("Your text here").chars().filter(|c| !c.is_control()).take(1000).collect();
|
||||
let text = if text.trim().is_empty() { "Your text here".to_string() } else { text };
|
||||
let style = p::str(v, "style").unwrap_or("solid");
|
||||
let fx = art_style(style, &theme(s)).ok_or_else(|| CmdError::Params(format!("unknown WordArt style `{style}`")))?;
|
||||
let fx = art_style(style, &theme(s)).ok_or_else(|| CmdError::Params(format!("unknown decorative text style `{style}`")))?;
|
||||
let warp = match p::str(v, "transform") {
|
||||
None | Some("none") => None,
|
||||
Some(id) => Some(TextWarp::new(id).ok_or_else(|| CmdError::Params(format!("unknown text warp `{id}`")))?),
|
||||
|
||||
@@ -464,11 +464,11 @@ pub fn save_bytes_opts(name: &str, doc: &Document, opts: &ExportOptions) -> Resu
|
||||
}
|
||||
|
||||
/// [`save_bytes`], encrypted with `password` when there is one and the format is a Word package
|
||||
/// (other formats are copies and are written as they are).
|
||||
/// or OpenDocument text file (.odt, .ott); other formats are copies and are written as they are.
|
||||
pub fn save_bytes_with(name: &str, doc: &Document, password: Option<&str>, opts: &ExportOptions) -> Result<Vec<u8>, String> {
|
||||
let bytes = save_bytes_opts(name, doc, opts)?;
|
||||
match password {
|
||||
Some(pw) if matches!(ext_of(name).as_str(), "odt" | "ott") => wordcraft_formats::odt::encrypt(&bytes, pw),
|
||||
Some(pw) if matches!(ext_of(name).as_str(), "odt" | "ott") => wordcraft_formats::odt::encrypt(&bytes, pw).map_err(|e| e.to_string()),
|
||||
Some(pw) if can_encrypt(name) => wordcraft_docx::encrypt(&bytes, pw).map_err(|e| e.to_string()),
|
||||
_ => Ok(bytes),
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ pub struct Prefs {
|
||||
pub region: Option<String>,
|
||||
/// A folder searched for Hunspell dictionaries before the system locations (File › Options ›
|
||||
/// Language, #1063): an app started from Finder or the Dock doesn't see
|
||||
/// `WORDCRAFT_DICTIONARIES`. `None` searches the system locations only.
|
||||
/// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder.
|
||||
pub dictionaries_folder: Option<String>,
|
||||
/// The user templates folder File › New lists personal templates from and Save as Word
|
||||
/// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's
|
||||
|
||||
@@ -88,6 +88,10 @@ pub struct Session {
|
||||
pub initials: String,
|
||||
/// Format painter: copied formatting waiting to be applied (and whether it stays on).
|
||||
pub painter: Option<(CharProps, wordcraft_doc::props::ParaProps, bool)>,
|
||||
/// Formatting picked up by Copy Formatting (Mod+Shift+C): Paste Formatting applies it as often
|
||||
/// as asked, as in Word, until the next Copy Formatting. A Format Painter pick is stored here
|
||||
/// as well.
|
||||
pub copied_format: Option<(CharProps, wordcraft_doc::props::ParaProps)>,
|
||||
/// Last message for the status bar / agents.
|
||||
pub status: String,
|
||||
/// Headers/footers `insert.createHeader`/`insert.createFooter` made for a page that had none
|
||||
|
||||
@@ -259,6 +259,7 @@ impl Session {
|
||||
author: _,
|
||||
initials: _,
|
||||
painter: _,
|
||||
copied_format: _,
|
||||
// What the drawn window knows of the others: its front end sets it as it draws.
|
||||
windows: _,
|
||||
status: _,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl Session {
|
||||
author: "WordCraft User".into(),
|
||||
initials: String::new(),
|
||||
painter: None,
|
||||
copied_format: None,
|
||||
status: String::new(),
|
||||
new_header_parts,
|
||||
hf_return,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user