mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-01 22:19:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2e15cf8f8 | ||
|
|
2f6311cc37 | ||
|
|
5834dc5a19 | ||
|
|
eae2421761 | ||
|
|
40c4ebc432 | ||
|
|
86adfd34eb | ||
|
|
df28b78de9 | ||
|
|
fd0bb2fb1e | ||
|
|
b3b6c451e3 | ||
|
|
6a2bad8afa | ||
|
|
dac8c6d6c7 | ||
|
|
18b680c9aa | ||
|
|
e127a080a1 | ||
|
|
5b49d692a5 | ||
|
|
ffacc4c08c | ||
|
|
109956bb90 | ||
|
|
add4851443 | ||
|
|
9a19e09d97 | ||
|
|
6e25d482c4 | ||
|
|
94bfc29b0b | ||
|
|
cb6418dc6c | ||
|
|
5c8dba229f | ||
|
|
0aab56934b | ||
|
|
7af9748ace | ||
|
|
5f83a4727a | ||
|
|
a9d3597549 | ||
|
|
f43928324f | ||
|
|
e45c0159e8 | ||
|
|
1e02093462 | ||
|
|
3cbea099f1 | ||
|
|
fbbf9c04eb | ||
|
|
e5d9b3e7cf | ||
|
|
3292ba05d3 | ||
|
|
3f9b6a029f | ||
|
|
60b9500347 | ||
|
|
8d04d14d96 | ||
|
|
1fc34fc147 | ||
|
|
cd31095163 | ||
|
|
3ef4d1fb9a | ||
|
|
4062db0ac2 | ||
|
|
aa9c31fc69 | ||
|
|
058fd1bacd | ||
|
|
9d4d2ea01c | ||
|
|
850bbb5dbc | ||
|
|
63d5faa9b2 | ||
|
|
20cf5b45d0 | ||
|
|
097d81a41b | ||
|
|
2c7629fa7a | ||
|
|
35e24aa436 | ||
|
|
13070ca85e | ||
|
|
4b33e7b4ab | ||
|
|
daf8caada3 | ||
|
|
babb331528 | ||
|
|
056771a33a | ||
|
|
67b0428657 | ||
|
|
e5a055a310 | ||
|
|
1c814e0269 | ||
|
|
b53796d412 | ||
|
|
29320804f2 | ||
|
|
faa621104c | ||
|
|
47907a820b | ||
|
|
6528f972db | ||
|
|
8b0194bc23 | ||
|
|
718eb02b89 | ||
|
|
87410b4e3f | ||
|
|
c3ba9011a2 | ||
|
|
2c26fa58a8 | ||
|
|
ed980e4df7 | ||
|
|
98cda1ea50 | ||
|
|
116e7697a1 | ||
|
|
6eeb6d10db | ||
|
|
a8c1c228d7 | ||
|
|
4ad625eef1 | ||
|
|
63ed4daab2 | ||
|
|
74a279d5f2 | ||
|
|
fe9d560b49 | ||
|
|
f3f110b442 | ||
|
|
6d5cc9ef84 | ||
|
|
1b60773196 | ||
|
|
fee9b984eb | ||
|
|
2444e64a25 | ||
|
|
241743b4ab | ||
|
|
c2872f23c3 | ||
|
|
3b16face49 | ||
|
|
4570952069 | ||
|
|
64e430354c | ||
|
|
39af5b17ca | ||
|
|
90d8844e44 | ||
|
|
952eb57688 | ||
|
|
a3ec498f2a | ||
|
|
2c5249d13e | ||
|
|
da0370c30b | ||
|
|
b70ab1a6e7 | ||
|
|
ba1e28382d | ||
|
|
e9e8af517c | ||
|
|
4175d68be5 | ||
|
|
663de991df | ||
|
|
2a1cdbb17f | ||
|
|
8fd4951d76 | ||
|
|
1b05f9a668 | ||
|
|
21f2b938e2 | ||
|
|
8ba285cdef | ||
|
|
3cc0c16302 | ||
|
|
bbdcc7c62f | ||
|
|
aec3f50582 | ||
|
|
81b5602bf0 | ||
|
|
9c57b950b9 | ||
|
|
e4e389cdb3 | ||
|
|
3370fd1ba2 | ||
|
|
4d2649738e | ||
|
|
a4b335f6a3 | ||
|
|
52190491ff | ||
|
|
c80f51e810 | ||
|
|
85aa9cdea4 | ||
|
|
18ecff6fbb | ||
|
|
e3ed7da1be | ||
|
|
68d15dafba | ||
|
|
910a2bb312 | ||
|
|
1024fc471b | ||
|
|
81c52fecc0 | ||
|
|
a09162603d | ||
|
|
3a201c8246 | ||
|
|
d1b14504dc | ||
|
|
4262276418 | ||
|
|
825538fc8b | ||
|
|
f8d06ebb27 | ||
|
|
7188d8ae04 | ||
|
|
7591283266 | ||
|
|
cf8aea6886 | ||
|
|
f732c1a370 | ||
|
|
b574cb9638 | ||
|
|
31b622ad79 | ||
|
|
7052cfc80d | ||
|
|
23e26628ed | ||
|
|
2c33a66ca9 | ||
|
|
a21b069390 | ||
|
|
41cf3c7563 | ||
|
|
f47cd975ae | ||
|
|
2ffe707b03 | ||
|
|
e0a1346590 | ||
|
|
cf140ae600 | ||
|
|
5f2e18e1cd | ||
|
|
ae8048e3f1 | ||
|
|
40cf85c25b | ||
|
|
44787764a9 | ||
|
|
48ab796792 | ||
|
|
7658819bf7 | ||
|
|
e5780698f2 | ||
|
|
5ffd7a99f5 | ||
|
|
78c37cafa7 | ||
|
|
36553301d8 | ||
|
|
00c8ee3407 | ||
|
|
d129fa2daa | ||
|
|
c3bdcd73b4 | ||
|
|
1190fa8881 | ||
|
|
6dd027fcfa | ||
|
|
0c5804767c | ||
|
|
f7dc68d543 | ||
|
|
9710db73da | ||
|
|
70a4917973 | ||
|
|
8ae23cee29 | ||
|
|
6655ba675d | ||
|
|
01efd53aea | ||
|
|
b309af4148 | ||
|
|
9f7330664b | ||
|
|
373df5adf1 | ||
|
|
b3af58602b | ||
|
|
bfacaf3627 | ||
|
|
3d8f8144d9 | ||
|
|
92c0036d72 | ||
|
|
248dae4bd1 | ||
|
|
575c5f98df | ||
|
|
eb54d88ec0 | ||
|
|
cf9a4ff7fa | ||
|
|
8e0f42e4bc | ||
|
|
f822dcb23c | ||
|
|
1e4ed377d8 | ||
|
|
2686e20330 | ||
|
|
3e20488c15 | ||
|
|
77da439d0b | ||
|
|
2215e52aa4 | ||
|
|
e1f34a90d6 | ||
|
|
b8e46b244d | ||
|
|
3962d397e5 | ||
|
|
3e9dde7799 | ||
|
|
a04356933c | ||
|
|
896c1bbebf | ||
|
|
a4870128b5 | ||
|
|
d2ff87856f | ||
|
|
b53fc8ca6e | ||
|
|
f9f8b67c54 | ||
|
|
1f01a13dfc | ||
|
|
85fcbabcb1 | ||
|
|
e29fbdb0bf | ||
|
|
060a3333b8 | ||
|
|
2fd3b556f3 | ||
|
|
85dd93a2ba | ||
|
|
e486f7c39d | ||
|
|
68501de224 | ||
|
|
6ed1877ce6 | ||
|
|
482401f3c4 | ||
|
|
4fcf7da693 | ||
|
|
8196624e83 | ||
|
|
e9d5da31d4 | ||
|
|
aedbbc9325 | ||
|
|
5597351213 | ||
|
|
90762b0529 | ||
|
|
6be7ef10fb | ||
|
|
ee33d71173 | ||
|
|
163462338e | ||
|
|
b34a8744d0 | ||
|
|
987c41364d | ||
|
|
639a4043b8 | ||
|
|
5311069ae1 | ||
|
|
1c2f0fe65e | ||
|
|
6b107250a5 | ||
|
|
1a34583e50 | ||
|
|
3e11278a93 | ||
|
|
3fc4ef2cf4 | ||
|
|
0a2b429b05 | ||
|
|
e7e4522d0d | ||
|
|
2814dfcae9 | ||
|
|
4d79e18ae8 | ||
|
|
666b9afc5a | ||
|
|
b4f6b603ac | ||
|
|
60c4a372d5 | ||
|
|
b10c97b765 | ||
|
|
03ba9e483f | ||
|
|
52e56f8d76 | ||
|
|
37d41150e6 | ||
|
|
53b7debea5 | ||
|
|
5e8c5b3c4e | ||
|
|
b1e8ae07e7 | ||
|
|
3d2002b699 | ||
|
|
0c7b4a72f2 | ||
|
|
b78adf2def | ||
|
|
0a1f2ce7a8 | ||
|
|
7471c33fe0 | ||
|
|
a124d58e5b | ||
|
|
42c1f71b52 | ||
|
|
bf2bd69470 | ||
|
|
686f71cabb | ||
|
|
1f2b2287b6 | ||
|
|
4cf13cd178 | ||
|
|
93175f979f | ||
|
|
ff4e560e7d | ||
|
|
1be06ca323 | ||
|
|
dea3e217fa | ||
|
|
a9afeb4bfe | ||
|
|
b8b8ff6128 | ||
|
|
5ff69b8bab | ||
|
|
47ae2d495d | ||
|
|
26cdede600 | ||
|
|
45d2546b63 | ||
|
|
f2a96a21f9 | ||
|
|
17ec132c7c | ||
|
|
1059b196c1 | ||
|
|
533615620e | ||
|
|
4cb013faa1 | ||
|
|
0128e117b3 | ||
|
|
6e6cfba765 | ||
|
|
5b9010f6ad | ||
|
|
37193a14ba | ||
|
|
25ca4b0752 | ||
|
|
abe572e7fb | ||
|
|
156029fe63 | ||
|
|
7d3767ba99 | ||
|
|
3f5d8feebe | ||
|
|
48f1b6b842 | ||
|
|
b3132a0b11 | ||
|
|
086d3d0384 | ||
|
|
44086d08c8 | ||
|
|
646349d521 | ||
|
|
68cf67a6c6 | ||
|
|
2773295938 | ||
|
|
442a7226e7 | ||
|
|
d1dff91f6f |
@@ -0,0 +1,33 @@
|
||||
# Evaluates the Nix flake (no build, about a minute): `nix build` / `nix develop` stop at evaluation
|
||||
# when Cargo.lock gains something nix/package.nix can't vendor, and nothing else would notice.
|
||||
name: Nix
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
|
||||
pull_request:
|
||||
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nix-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
eval:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1
|
||||
- name: nix flake check --no-build
|
||||
run: |
|
||||
if [ -f flake.nix ]; then
|
||||
nix flake check --no-build --all-systems
|
||||
else
|
||||
echo "No flake.nix present in this repository; skipping check."
|
||||
fi
|
||||
+4
-1
@@ -10,7 +10,8 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
|---|---|---|---|---|
|
||||
| `assets/hyphenation/en-us.pat` | DesignCraft contributors (generated) | trained from the Moby list by DesignCraft's patgen | Public Domain (CC0-1.0) | Our own Liang hyphenation patterns (no TeX patterns) |
|
||||
| `assets/hyphenation/en-us.dic` | Grady Ward (Moby Hyphenator II word list); converted by DesignCraft contributors | https://www.gutenberg.org/ebooks/3204 (file `mhyph.txt`, SHA-256 `eeb30474c86b8af3469035ec1a0913e35905325ca885290db9dfed9881e230ac`), via DesignCraft | Public Domain | ~165k words with break points; drives spelling and hyphenation |
|
||||
| `assets/spelling/en-extra.txt` | WordCraft contributors | original word list written for this repository (common modern words the Moby list lacks); no other dictionary copied | MIT OR Apache-2.0 | ~220 lowercase English base forms supplementing spelling (#520) |
|
||||
| `assets/spelling/en-extra.txt` | WordCraft contributors | original word list written for this repository (common modern words the Moby list lacks); no other dictionary copied | MIT OR Apache-2.0 | ~240 lowercase English base forms supplementing spelling (#520), including British spellings (#40) |
|
||||
| `assets/spelling/ru-extra.txt` | WordCraft contributors | original word list written for this repository (common modern Russian words older Hunspell dictionaries lack, with their declension classes); no other dictionary copied | MIT OR Apache-2.0 | ~200 Russian base forms supplementing spelling; their forms are generated by `crates/proof/src/ru/extra.rs` |
|
||||
| `assets/hyphenation/pl.pat` | Hanna Kołodziejska, Bogusław Jackowski, Marek Ryćko (Polish TeX hyphenation patterns, 1987–1995); hyph-utf8 package | https://github.com/hyphenation/tex-hyphen (`hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pl.tex`, SHA-256 `83ddbbd21bc06a44bc4f4a4c49c38782e809cff5f026b764c044daa29e818843`), bundled unmodified | MIT (the file is offered under MIT or Knuth's public-domain terms; WordCraft uses MIT, whose notice is in the file's header) | 4,053 Liang patterns and 20 exception words; Polish hyphenation |
|
||||
| `assets/hyphenation/pt.pat` | Pedro J. de Rezende, J. Joao Dias Almeida, Leonardo Araujo, Aline Benevides (Portuguese TeX hyphenation patterns, 1987–2024); hyph-utf8 package | https://github.com/hyphenation/tex-hyphen (`hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pt.tex`, SHA-256 `c110a39e501db372d1d755e1c64464321a2efa7d8e9617f66001000389b941f2`), bundled unmodified | BSD 3-clause (the file's licence header names it and carries the notice) | 426 Liang patterns and 2 exception words; Portuguese hyphenation |
|
||||
| `assets/hyphenation/it.pat` | Claudio Beccari (Italian TeX hyphenation patterns, 2008–2014); hyph-utf8 package | https://github.com/hyphenation/tex-hyphen (`hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-it.tex`, SHA-256 `6ce56ed6ed2ca7c0688838e366e6595e0429f984f4fc6e96ec045cebb1e76a47`), bundled unmodified | MIT (the file is offered under LPPL 1.3+ or MIT; WordCraft uses MIT, whose notice is in the file's header) | 355 Liang patterns, no exception words; Italian hyphenation |
|
||||
@@ -75,3 +76,5 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| `crates/ui-egui/src/i18n/bg.tsv` | Dimitar Klaturov (@bulgariamitko) with Claude Code | Original translation from the English interface labels in this repository; no other product localisation or other catalog used | MIT OR Apache-2.0 | Bulgarian interface catalog |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Hungarian interface catalog |
|
||||
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | French interface catalog |
|
||||
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code | Original translation from the English interface labels in this repository; no other product localisation or other catalog used | MIT OR Apache-2.0 | Swedish interface catalog; AI-assisted, terminology and the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/hr.tsv` | Andrej Škvorc (@andrejskvorc) with Claude Code (Sonnet 5.5); proofread with Gemini | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Croatian interface catalog; reviewed and corrected in the running interface, menu by menu, by the native-speaker author, who also checked the Gemini suggestions |
|
||||
|
||||
Generated
+78
-35
@@ -693,6 +693,17 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chardetng"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"encoding_rs",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
@@ -819,6 +830,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_detect"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||
|
||||
[[package]]
|
||||
name = "core_maths"
|
||||
version = "0.1.1"
|
||||
@@ -843,6 +860,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
@@ -1184,6 +1210,20 @@ dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"core_detect",
|
||||
"multiversion_no_op",
|
||||
"rustversion",
|
||||
"scopeguard",
|
||||
"simdutf8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "endi"
|
||||
version = "1.1.1"
|
||||
@@ -1843,17 +1883,6 @@ dependencies = [
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-write"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0b3db92c4917aad24ff30d61413a9a7509ae88b27aee1ae34eff881e1d2723a"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-syntax",
|
||||
"pdf-writer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
@@ -2185,15 +2214,13 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bumpalo",
|
||||
"flate2",
|
||||
"float-cmp",
|
||||
"gif",
|
||||
"hayro-write",
|
||||
"image-webp",
|
||||
"imagesize",
|
||||
"indexmap",
|
||||
@@ -2363,6 +2390,12 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
@@ -5098,7 +5131,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"clipboard-win",
|
||||
@@ -5130,9 +5163,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-cli"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-engine",
|
||||
"wordcraft-mcp",
|
||||
@@ -5142,11 +5176,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-control-key"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-doc"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -5158,7 +5192,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-docbin"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"image",
|
||||
@@ -5166,6 +5200,7 @@ dependencies = [
|
||||
"miniz_oxide 0.8.9",
|
||||
"proptest",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"thiserror 2.0.21",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-geom",
|
||||
@@ -5173,7 +5208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-docx"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64",
|
||||
@@ -5195,8 +5230,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-engine"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"encoding_rs",
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
@@ -5221,7 +5259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-fonts"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
@@ -5234,9 +5272,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-formats"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"chardetng",
|
||||
"encoding_rs",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
"proptest",
|
||||
"quick-xml",
|
||||
@@ -5247,14 +5289,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-geom"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-layout"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"js-sys",
|
||||
@@ -5273,7 +5315,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-mcp"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde_json",
|
||||
@@ -5285,7 +5327,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-metafile"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5293,14 +5335,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-pdf"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"hayro-cmap",
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
"image",
|
||||
"js-sys",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5313,7 +5355,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-proof"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.8.9",
|
||||
@@ -5322,7 +5364,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-render"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -5336,7 +5378,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-ui-egui"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
@@ -5348,6 +5390,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"toml",
|
||||
"unicode-bidi",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-engine",
|
||||
"wordcraft-fonts",
|
||||
@@ -5361,7 +5404,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-web"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5380,7 +5423,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-zotero"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -5493,7 +5536,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+12
-3
@@ -4,10 +4,10 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/wordcraft", "apps/wordcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.90"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/wordcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
@@ -52,12 +52,17 @@ harfrust = "0.13"
|
||||
wuff = "0.2.9"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "bmp", "tiff"] }
|
||||
krilla = { version = "0.8", features = ["pdf"] }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.8"
|
||||
cfb = "0.15"
|
||||
# Legacy text encodings (GBK/GB18030, Big5, Shift_JIS, EUC-KR, single-byte code pages) for plain
|
||||
# text and CSV recipient lists (#778): encoding_rs ((Apache-2.0 OR MIT) AND BSD-3-Clause) and its
|
||||
# detector chardetng (Apache-2.0 OR MIT), both pure Rust (Firefox's).
|
||||
encoding_rs = "0.8"
|
||||
chardetng = "1"
|
||||
# Password-protected (agile-encrypted) Word documents: pure-Rust RustCrypto primitives.
|
||||
aes = "0.9"
|
||||
sha1 = "0.11"
|
||||
@@ -95,3 +100,7 @@ opt-level = 3
|
||||
lto = "thin"
|
||||
codegen-units = 16
|
||||
debug = 0
|
||||
|
||||
# Required by craft-pdf: the backend rejects writers that failed during unwinding.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8" }
|
||||
|
||||
@@ -76,6 +76,11 @@ list (author, source, license) is in ATTRIBUTION.md.
|
||||
- All UI icons are drawn in code (crates/ui-egui/src/icons.rs) and are original work, MIT OR Apache-2.0.
|
||||
|
||||
Rust dependencies (egui, eframe, vello_cpu, skrifa, harfrust, krilla, quick-xml, zip, image, …)
|
||||
are permissively licensed (MIT/Apache-2.0/BSD/ISC/Zlib) and fetched through crates.io.
|
||||
are permissively licensed (MIT/Apache-2.0/BSD/ISC/Zlib) and fetched through crates.io or pinned Git sources.
|
||||
The craft-pdf writer and Krilla 0.8.2 backend are pinned to storytold/craft-libs revision
|
||||
c3487320b2d1de657b860b3c8abb44e1f2b32bd8. The backend retains its MIT OR Apache-2.0 licensing
|
||||
and upstream bundled material; see that revision's licenses/pdf-writer/ and ATTRIBUTION.md.
|
||||
The backend patch prevents finalization during an unwind and rejects a writer after failed
|
||||
cleanup. WordCraft enables only writing; PDF import and its image decoders are not enabled.
|
||||
|
||||
No Microsoft, Adobe, Avid or Autodesk icons, images, templates or artwork are included.
|
||||
|
||||
@@ -117,7 +117,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 or Български (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, 한국어 or Svenska (follows the system language by default) |
|
||||
| **Files** | .docx read/write (opens in Word), Word 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
|
||||
@@ -188,7 +188,7 @@ covers every target starting with it (`wordcraft*=debug`). The logger is
|
||||
| L0 | `wordcraft-geom` | units and measurements |
|
||||
| L1 | `wordcraft-doc`, `wordcraft-fonts`, `wordcraft-proof` | document model and editing; fonts and shaping; spelling, grammar, hyphenation |
|
||||
| L2 | `wordcraft-layout`, `wordcraft-docx`, `wordcraft-formats` | line breaking, pagination, tables, notes, hit testing; OOXML; ODT/RTF/HTML/Markdown/TXT |
|
||||
| L3 | `wordcraft-render`, `wordcraft-pdf` | rasteriser (vello_cpu); PDF (krilla) |
|
||||
| L3 | `wordcraft-render`, `wordcraft-pdf` | rasteriser (vello_cpu); PDF ([craft-pdf](docs/shared-pdf.md), Krilla) |
|
||||
| L4 | `wordcraft-engine` | session, undo, 422 commands, Word feature catalog |
|
||||
| L5 | `wordcraft-mcp` | MCP server |
|
||||
| L6 | `wordcraft-ui-egui` | the Word-style front end (swappable) |
|
||||
@@ -289,6 +289,21 @@ to the AUR itself. Install one of them:
|
||||
| [`wordcraft`](https://aur.archlinux.org/packages/wordcraft) | The latest release, built from source with `cargo` | You prefer to build releases yourself |
|
||||
| [`wordcraft-git`](https://aur.archlinux.org/packages/wordcraft-git) | The current `main` branch, built from source | You want unreleased changes and accept an occasional broken build |
|
||||
For example `yay -S wordcraft-bin` or `paru -S wordcraft-bin`.
|
||||
|
||||
#### Community packages
|
||||
|
||||
These packages are maintained by community members, not by the WordCraft team.
|
||||
|
||||
On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the
|
||||
Linux release as `app-office/wordcraft-bin` (prebuilt) and `app-office/wordcraft` (built from source):
|
||||
|
||||
```sh
|
||||
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
|
||||
emaint sync -r snakebyte
|
||||
echo 'app-office/wordcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/wordcraft
|
||||
emerge --ask app-office/wordcraft-bin
|
||||
```
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|
||||
+220
-9
@@ -2,8 +2,8 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** trivial (progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** trivial (Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial (table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** trivial (progress log: print-area strings translated in every catalog; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below.
|
||||
|
||||
WordCraft aims for complete parity with Microsoft Word, then goes further on speed, openness and
|
||||
@@ -15,7 +15,7 @@ agent control. This page is the summary; the assessment is
|
||||
## Headline numbers (2026-10-10)
|
||||
|
||||
| Number | Value | Kind |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | Table formulas: cell references and ranges (`=B2+B3`, `=SUM(B2:C3)`), arithmetic and comparisons, IF, AND, OR, NOT, TRUE, FALSE, DEFINED and the `\#` number format; ABOVE and LEFT sum the run of numbers next to the cell as Word does; an unknown function or a syntax error is an error instead of a sum; Update Field (F9) recalculates formula fields |
|
||||
| Ribbon/menu catalog coverage | **487 / 502 (97.0%)** | measured (`cargo xtask parity` → [`docs/parity-checklist.md`](docs/parity-checklist.md)) |
|
||||
| **Feature breadth** (weighted, incl. dialog options, styles, languages beyond the ribbon) | **~80%** | estimated |
|
||||
| **Ready for real work** (full target) | **~60%** (55–63%) | estimated, additive weighted sum over the dimensions |
|
||||
@@ -109,13 +109,14 @@ Weights and evidence per area: [docs/target-app-parity.md](docs/target-app-parit
|
||||
| Indonesian | id | none | 0% |
|
||||
| Japanese | ja | partial | ~95% |
|
||||
| German | de | partial (#574) | ~95% |
|
||||
| Korean | ko | none | 0% |
|
||||
| Vietnamese | vi | none | 0% |
|
||||
| Korean | ko | partial (interface catalog; proofing unavailable) | 100% (2,463 entries) |
|
||||
| Vietnamese | vi | partial (#1434) | ~95% |
|
||||
|
||||
Also shipped: Traditional Chinese (`zh-hant`), Ukrainian (`uk`), Serbian (`sr`, `sr-latn`, #250), Russian (`ru`) and Polish (`pl`), all partial (~95%). Bulgarian (`bg`) covers everything the interface audit finds (2,419 entries). Estonian (`et`), Italian (`it`, #594) and Czech (`cs`) now have complete interface catalogs, and Turkish (`tr`) a complete 2,325-entry one (every key of the Russian catalog), all with
|
||||
system-locale selection and a saved language choice (Italian also has 51 strings none of the others had yet); Estonian, Turkish, Italian and Czech proofing are not included. Hungarian (`hu`) has a
|
||||
complete 2,419-entry catalog, also without proofing.
|
||||
Proofing: English, Polish and Portuguese (spelling, grammar, hyphenation), chosen per run from its language. Word ships
|
||||
Also shipped: Traditional Chinese (`zh-hant`), Ukrainian (`uk`), Serbian (`sr`, `sr-latn`, #250), Russian (`ru`) and Polish (`pl`), all partial (~95%). Bulgarian (`bg`) covers everything the interface audit finds (2,419 entries); Swedish (`sv`) covers that too, plus 44 newer strings no other catalog has yet (2,504 entries). Estonian (`et`), Italian (`it`, #594) and Czech (`cs`) now have complete interface catalogs, and Turkish (`tr`) a complete 2,325-entry one (every key of the Russian catalog), all with
|
||||
system-locale selection and a saved language choice (Italian also has 51 strings none of the others had yet); Estonian, Turkish and Italian proofing are not included. Hungarian (`hu`) has a
|
||||
complete 2,419-entry catalog, also without proofing. Vietnamese (`vi`, #1434) has a complete
|
||||
2,448-entry catalog, also without proofing.
|
||||
Proofing: English, Polish, Portuguese and Russian (spelling, grammar, hyphenation), plus Czech (system Hunspell spelling, generic checks), chosen per run from its language. Word ships
|
||||
30 interface languages and proofing for ~50. Detail: [docs/localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
@@ -134,7 +135,49 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
## Progress log
|
||||
|
||||
| Date | What landed |
|
||||
| 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. |
|
||||
| 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture |
|
||||
| 2026-10-12 | Fields keep `w:dirty` through DOCX saves (#877): a begin marker flagged by a generator that couldn't compute a result (pandoc-style TOC placeholders) keeps the flag on open/save — as a buffered field or a range field — so Word still refreshes it on open; computing a result (Update Field, Update Table) clears it, like Word's F9 |
|
||||
|---|---|
|
||||
| 2026-10-17 | Language dialog keeps inherited proofing language and no-proof choices (#2717). Opening and accepting unchanged no longer replaces style-derived values with English US and proofing enabled. |
|
||||
| 2026-10-14 | Consistent preferred cell widths override a stale table grid when both totals agree, for fixed and AutoFit tables. Conflicting widths, spans and percentages remain unchanged. |
|
||||
| 2026-10-14 | Legacy VML freeforms (`v:shape` with its own `path`), such as the rule lines in many older headers, are read as freeform shapes: they show on screen and in PDFs and are saved back as DrawingML custom geometry instead of vanishing |
|
||||
| 2026-10-14 | Field instructions spanning paragraphs no longer add blank lines during pagination; empty result paragraphs still take a line. |
|
||||
| 2026-10-14 | Page-break-only list paragraphs no longer print stray bullets or numbers. The next item keeps its number, matching the reference export. |
|
||||
| 2026-10-12 | Backspace at the start of the paragraph after a table nested in a cell moves into the nested table's last cell, no longer into the last cell of the table around it |
|
||||
| 2026-10-14 | Grouped `flowChartOr` shapes draw their circle and crossing spokes, as in Word |
|
||||
| 2026-10-14 | Deleting a comment removes its anchors from headers, footers, notes and text boxes too, not just the body, and deletes the whole thread below it, replies to replies included; no anchor or reply is left pointing at a deleted comment (#1345) |
|
||||
| 2026-10-14 | Legacy DOC DIB conversion checks the BMP header and copy before allocation, uses the caller's decode allowance, and caps PNG output while encoding; a BMP fallback is kept when it fits. A generated 1-pixel regression covers 57/58/512-byte limits. Resource-exhaustion consequences remain unmeasured. Related: #1334 and #1554 |
|
||||
| 2026-10-13 | Justified vertical page alignment (#1320): a section set to Justified spreads each page's paragraphs and tables from the top margin to the bottom one, as Word does, including the last page and pages ending in a manual page break. DOCX `w:vAlign="both"` opens as Justified (it showed centred) and saves back; `layout.verticalAlign` takes `justify`, and Page Setup has a Vertical alignment box |
|
||||
| 2026-10-13 | macOS shortcuts as in Word for Mac: ⌘⇧S Save As, ⌘⌥E Insert Endnote, ⌘⌥A New Comment, ⌃H Replace, ⌘⌥R collapse the ribbon |
|
||||
| 2026-10-13 | The status bar flags a proofing language whose Hunspell dictionary isn't installed (Polish, Portuguese): "Polish (no dictionary)", with a tooltip naming the dictionary and where it is looked up (#1167) |
|
||||
| 2026-10-14 | A file name that isn't valid Unicode, such as a Latin-1 `café.docx`, no longer crashes `wordcraft-cli` or the app (#1440). The app and the CLI's `convert`, `info`, `text`, `inspect`, `render`, `zotero` and `run --file` open such a file, and saving it without a new name (`run --file … --cmd file.save`, or Save in the app) writes back to it. Any other such argument is an error naming it, an output name included; the app exits with status 2 on a `--control` port that isn't valid Unicode |
|
||||
| 2026-10-13 | A picture (or shape) set to Behind Text can be dragged over the text it overlaps, whether or not it was selected first, in the body and in a header/footer. The press becomes an object drag only after the pointer moves, so an ordinary click still places the text caret in the overlapping text. The UI regression tests cover In Front of Text too |
|
||||
| 2026-10-13 | Saving to DOCX keeps the watermark: it is written as Word's own text-watermark shape in every header, and a document without headers gains one to hold it (#1290) |
|
||||
| 2026-10-13 | DOCX files with Word's text watermark (Design › Watermark, a VML text shape in the headers) show it on every page on screen and in the PDF (#1290) |
|
||||
| 2026-10-13 | Insert › Link has Word's Place in This Document: a link to a bookmark, a heading (through a hidden _Toc bookmark) or the top of the document, from the dialog's Link to: choice or `insert.link` with `bookmark`, `heading` or `top`; `link.targets` lists the places and Go To follows `_top` (#1234) |
|
||||
| 2026-10-13 | Cut copies to the system clipboard however it is run (#1265): the ribbon, the context menu and the native menu cut deleted the words without copying them (only the Cmd+X event wrote the clipboard, so Paste re-inserted the previous copy); Copy/Cut publication is centralised in one sink and every entry point is tested |
|
||||
| 2026-10-13 | Insert › Bookmark deletes bookmarks (#1236): the dialog is laid out as Word's, with Add, Delete and Go To beside the list, Sort by Name or Location and Hidden bookmarks; it opens on the bookmark around the caret, Delete and Go To keep it open, and Go To selects the bookmark's text. `insert.deleteBookmark {name}` removes both ends of a bookmark, also one across paragraphs (adding a bookmark under a name in use left such a one's end behind) |
|
||||
| 2026-10-12 | Password-protected Word 97-2003 `.doc` files open after a password prompt (XOR obfuscation, RC4, RC4 CryptoAPI; wrong passwords are rejected by the stored verifier, #1079); written from the public specs and tested on synthetic files only, AES-encrypted `.doc` files are still refused |
|
||||
| 2026-10-12 | Comments can show only for the selected text (#1055): Track Changes Options › Comments › "Only for the selected text" drops the margin column, and the comment under the caret, or the clicked one, floats beside the page (over its edge in a narrow window). The default stays "In the margin", as in Word; `review.trackingOptions {"commentDisplay"}` for agents |
|
||||
| 2026-10-12 | Clicking inside a selected comment's balloon moves the caret in its text (#1013); the click used to leave the balloon, so the caret could only be moved with the arrow keys. A press on any balloon now belongs to the balloon, not the page behind it |
|
||||
| 2026-10-12 | Page background pictures and textures (Design › Page Color › Fill Effects) are drawn (tiled or stretched) and kept on save instead of being dropped from the package (#999); PDF export paints them too |
|
||||
| 2026-10-12 | Holding a click on the ribbon or toolbar no longer scrolls the document up (#1019): a double-click in the header or footer area left a text drag running, so the next press anywhere drove the edge auto-scroll; a drag now ends with the button, wherever it's released |
|
||||
| 2026-10-12 | Tracked insertions and deletions inside a field result (a `=SUM(ABOVE)` subtotal) are kept as revisions: Accept All and Reject All act on them and a save writes the `w:del` back (#1037) |
|
||||
| 2026-10-12 | Document title opens Rename Document; the account badge opens Options › General for user name and initials. `file.rename {name}` preserves file extensions and refuses an existing destination; unsaved names become the suggested save name without changing the Title property. |
|
||||
| 2026-10-13 | Rounded rectangles (#1476): a `roundRect` keeps the corner radius its file gives it (`adj`), on screen, in PDF and when saved; all were drawn with a 16% corner |
|
||||
| 2026-10-13 | PAGEREF in headers and footers (#1477): "Page X of Y" with Y a page reference to a bookmark at each letter's end shows each letter's own total instead of the result stored in the file |
|
||||
| 2026-10-13 | Replace All respects locked content controls with Track Changes on or off; it refuses the entire batch before editing when any match would change locked content or remove a control locked against deletion |
|
||||
| 2026-10-14 | File › Print translated in all 18 interface languages — printer list, duplex, grayscale, discovery/submission feedback and print commands (18 strings that shipped English-only with the craft-print integration; written from the English meaning, pending native-speaker review like the rest of the catalogs) |
|
||||
| 2026-10-14 | All Caps and Small Caps draw ß as SS, as Word does (#1581): "Straße" in All Caps reads STRASSE, not STRASE, and other letters whose capital is two characters (ff, ʼn) draw in full. The ß is still one character: the caret never stops between the two S, and a click on them lands before or after it |
|
||||
| 2026-10-13 | Windows Magnifier follows the caret onto a new line: after Enter or Shift+Enter the view moves to the empty line at once, instead of staying on the line above until two more letters are typed (#1119) |
|
||||
| 2026-10-13 | A window too big for its screen shrinks to fit when it opens (#1215): on a laptop screen the first window reached under the taskbar or past the screen edge, with the end of the scroll bar, so dragging the scroll bar stopped where the pointer met the edge. A window saved that size is fitted on its next launch too |
|
||||
| 2026-10-14 | `layout.pageSetup` with a `section` checks its values like Margins, Size and Columns (#1582): non-finite numbers and margins that leave no room for text are refused with nothing changed; page sides, column count and gap, header/footer distances and line-numbering values are clamped to the same ranges |
|
||||
| 2026-10-13 | `wordcraft --control` checks its port (#1426): a missing port, one outside 1–65535 or one that isn't a number prints an error naming it and exits with status 2, instead of starting without the control channel (and dropping `WORDCRAFT_CONTROL_PORT`); a flag right after it, such as `--sample` or `--version`, is read as a flag rather than as the port |
|
||||
| 2026-10-14 | Text wrap (#1376): in the narrow strip beside a square-wrapped picture, a word that doesn't fit moves on whole to the next row; it used to be split across the strip ("docu" / "mentazione") |
|
||||
| 2026-10-14 | DOCX files with legacy VML preset shapes show them (#1377): Word's right arrow (`_x0000_t13`) and the other presets appear with their fill, outline and size, drawn as WordCraft draws the same DrawingML preset (the nearest shape when it has no exact one), and saving keeps them as DrawingML shapes; before, they were dropped |
|
||||
| 2026-10-14 | Lists numbered with Russian letters (`russianLower`, `russianUpper`) show а), б), в) … я), then аа), бб), as in Word, instead of 1), 2), 3); the 29-letter sequence (no ё, й, ъ or ь) was observed in Word |
|
||||
| 2026-10-14 | "Do you want to save changes?" answers from the keyboard after typing too (#1597): Save takes focus from the page when the prompt opens, so the arrow keys and Tab move between Save, Don't Save and Cancel instead of the caret behind it, and Enter answers |
|
||||
| 2026-10-12 | Text boxes from older Word files (VML) keep their internal margins, Resize shape to fit text and vertical alignment, so letterhead address blocks and form headers sit where Word puts them instead of 7 pt in and 4 pt down. Hidden drawings stay hidden (they were drawn as empty boxes) and are kept on save |
|
||||
| 2026-10-13 | Word's privacy options are kept and honoured when saving .docx (#1062): with Remove personal information, comments and tracked changes are saved by "Author" and the file has no creator or last-modified-by; with Remove date and time, they are saved without dates. The open document keeps the real names and dates; `file.privacyOptions` sets both |
|
||||
| 2026-10-13 | A selected comment balloon's Delete, Reply and Resolve buttons work again (#1085): pressing them no longer counts as a click on the page that closes the balloon first, so a new empty comment, or any other, can be deleted from its balloon |
|
||||
@@ -146,25 +189,73 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-13 | Dragging a Square-wrapped shape or picture on a multi-column page wraps the text of the column it lands in around it, and its old place closes up (#884) |
|
||||
| 2026-10-13 | Pagination with footnotes follows Word (#1116): a paragraph ending on a page with footnotes keeps its space after above the separator, otherwise its last lines move to the next page with the note; pages without notes are unchanged |
|
||||
| 2026-10-13 | Interface size means what it says (#822): a chosen size is absolute, as in PhotoCraft and PdfCraft, so "100%" is one screen pixel per point even where the system reports 200 % (a bare window manager on X11, where winit guesses the scale from the monitor's DPI). The new default, Auto, keeps the system's display scale and its menu entry shows the size it draws at; sizes run 75–300 %. A saved size from before stays the same if it was the default (now Auto) and becomes absolute otherwise |
|
||||
| 2026-10-14 | Copied text keeps its formatting in other programs (#1523): Copy and Cut put HTML beside the plain text on the system clipboard for every selection, not only one holding an equation, so a browser, mail client or another word processor pastes bold, italic, fonts and sizes. RTF on the clipboard is not written yet |
|
||||
| 2026-10-13 | Copying an equation also puts MathML in HTML on the clipboard beside the linear text like `y=2x_s` (#816; Word/LibreOffice paste not yet verified; OMML is #1297). HTML export writes equations as MathML too, and opening or pasting HTML with MathML gives equations back |
|
||||
| 2026-10-13 | The Equation tab's galleries, structure buttons and symbols keep the theme's colours on Windows: their pictures share a few textures written in place (no wipe of pictures already on screen, room for the built-ins at high display scales), instead of hundreds of small textures freed in bulk, which on DirectX 12 showed inverted, red or teal tiles (#1002) |
|
||||
| 2026-10-13 | `file.close` over the control channel or MCP bridge no longer quits and discards unsaved changes (#1268): it returns an error unless the document is saved or `{"force": true}` is passed; the user's Save / Don't Save / Cancel prompt is unchanged |
|
||||
| 2026-10-14 | Text copied out of an exported PDF reads as shown (#1473): All Caps and Small Caps text comes out in capitals, as from Word's PDFs, and plain text after it keeps its own case (before, a capital first drawn for a lowercase letter made later capitals extract lowercase) |
|
||||
| 2026-10-14 | Web: Save in the "save changes?" prompt before New or Open now waits for the browser's save picker: the new or opened document replaces yours only once the file is written and closed. Cancelling the picker, or a write that fails, keeps your document open with its edits and undo, still unsaved, and the prompt comes back with the reason; a save that ends after another document has replaced it no longer runs the New/Open on that one or marks it unsaved, and New/Open while a picker save is still in flight ask first (#1315) |
|
||||
| 2026-10-13 | Closing with unsaved changes → Save that can't write the file (no permission, locked by another app, folder gone) now says so plainly instead of looking like Cancel: the prompt comes back with the reason in it ("Couldn't save … so it is still open and nothing was lost") for Save again, Don't Save or Cancel, the status bar says it too, and `ui.saveChanges` returns that error; the same for a Save As from the prompt; the document stays open with its edits (#1445) |
|
||||
| 2026-10-14 | File › Info › Inspect Document finds hidden text the way Word does (#1344): hidden by direct formatting, a character style or a paragraph style, in the body, headers, footers, footnotes and endnotes, comments and text boxes, and Remove All deletes all of it (and nothing visible) in one undo step, whole hidden paragraphs and the notes of hidden references included. The result lists anything it couldn't reach (`residual`), so a sanitised file is never reported clean by mistake |
|
||||
| 2026-10-14 | ODT files keep their tracked changes (gap 19): insertions and deletions made in LibreOffice open as revisions with their author and date, deleted paragraph breaks and text inserted then deleted included, so Accept All and Reject All give the right text; saving to ODT writes them back, and the Track Changes setting goes both ways |
|
||||
| 2026-10-14 | RTF keeps tracked changes (gap 19): insertions and deletions open as tracked changes with their authors and dates (`\revtbl`, `\revised`, `\deleted`, `\revdttm`) instead of plain text, so deleted text no longer reappears as normal text; saving to RTF writes them back, and Accept All / Reject All work after reopening |
|
||||
| 2026-10-14 | Alignment guides: moving a picture, shape or text box snaps its edges or centre to the page's edges and centre, the margins and the other floating objects on the page, with a thin line across the page for each guide while dragging; Alt moves freely; File › Options › Advanced › Editing turns them off (`ui.alignmentGuides`). Our own design: Word for Mac shows no guides |
|
||||
| 2026-10-14 | ODT files open with their sections (#1379): a paragraph that switches to another page style starts a new section on a new page, with that page's size, orientation, margins and columns and, when the file asks, page numbering restarting; a two-column `text:section` becomes a continuous two-column section. Before, the whole document was one portrait section, so landscape pages, columns and restarts were lost on open and on save to DOCX |
|
||||
| 2026-10-14 | Hebrew and Arabic in exported PDFs copy and search as whole words (#1383): right-to-left glyphs are written left to right as they appear, the order Chrome and Edge (PDFium) and poppler read text back from (checked by hand), instead of in reading order, which they reversed (`שלום` came back as `םולש`, Arabic in pieces). Lam-alef stays whole and vowel marks follow their letters, though Chrome and poppler can still break a fully vowelled word with spaces. The page looks the same. Readers that take glyphs strictly in file order get only plain Hebrew runs right, through `/ReversedChars`; screen readers are unverified |
|
||||
| 2026-10-14 | HTML import (#1381): header cells (`<th>`) are bold unless their own CSS says otherwise, and `text-align` on a cell, its row, row group or table aligns the cell's paragraphs (a paragraph's own alignment wins), so `wordcraft-cli convert page.html out.docx` writes the bold header and `w:jc` right-aligned cells. HTML, Markdown and plain text, which give no page size, open on the region's paper (A4 in Italy, Letter in the US) like a new blank document, in the app and in `wordcraft-cli`; documents with their own page size keep it |
|
||||
| 2026-10-14 | Custom page sizes (#1433): Layout › Size ends with More Paper Sizes…, which opens Page Setup's new Paper group — a Paper size list (the named sizes, or Custom size) and Width and Height in the measurement unit; OK sets the size only when it changed, and a wider-than-tall size comes out landscape. `layout.size` now clamps each side to Word's 0.1"–22" and refuses a page the margins don't fit (the margins rule: 36 pt of text room), and Page Setup checks the size and margins together before applying either |
|
||||
| 2026-10-13 | Highlighted text reads on a dark page (View › Switch Modes, #1252): highlights and character shading are dimmed, keeping their hue (yellow turns a dim olive, as in Word), and the text on them is drawn light (coloured text below 4.5:1 is drawn white, and underlines and strikethroughs follow the same rule), instead of white text on bright yellow; light page, print and exports unchanged |
|
||||
| 2026-10-13 | Full screen (#980): F11, or View › Window › Full Screen, fills the screen with the window (⌃⌘F on macOS); F11 again or Escape gives back the window as it was. Next Field, which Word puts on F11, keeps Word's Alt+F1 and Alt+Shift+F1 (and Shift+F11). The web app leaves full screen to the browser's own F11 |
|
||||
| 2026-10-13 | Double-clicking the top or bottom margin of a page creates its header or footer when it has none and puts the caret in it, as in Word (#960): the one that page shows (different first page, odd and even pages), only in Print Layout; one left empty is taken away again when you leave it, so nothing empty is saved. `insert.editHeader`/`insert.editFooter` take `{"page"}` for agents |
|
||||
| 2026-10-13 | Alt+numpad character codes, as in Word on Windows (#961): hold Alt, type a decimal code, release Alt — `0233` → é (Windows-1252), `233` → Θ (OEM code page 437; 850 in Western European locales and English outside the US), codes above 255 are Unicode (`8364` → €). Not on macOS; `text.typeCode` for agents |
|
||||
| 2026-10-13 | Review › Language and the status bar's language menu offer Set Proofing Language… again (#860): the Language dialog marks text as French, German or any of 29 languages and Set As Default makes it the document's language; Language Preferences… opens Options › Language. Text in a language outside the short list shows by name in the status bar and checked in the menu. Spelling and grammar remain English, Polish and Portuguese; text in other languages gets no marks |
|
||||
| 2026-10-12 | A list label moves with its text when the paragraph is centred or aligned to the end (it stayed at the margin), in left-to-right and right-to-left paragraphs (#1159) |
|
||||
| 2026-10-13 | A paragraph that ends with a page break keeps its space after on the page before, as in Word: the next page no longer starts up to a line too low, and a page break before right after it no longer leaves a blank page |
|
||||
| 2026-10-13 | Tables break across pages like Word's: a cell without its own margins lines up with its neighbours, exact row heights include the bottom margin, and a row whose margin doesn't fit at a page bottom is split with widow control instead of moving to the next page whole |
|
||||
| 2026-10-13 | Equation parsers are hardened (#1456): deeply chained input (`x^1^1…`, `a/a/…`, `\sum\sum…`) no longer builds a tree thousands of levels deep that overflows small stacks, `\text{…}` is escaped in LaTeX output so it reads back unchanged, and runs merge inside every structure. |
|
||||
| 2026-10-13 | A WMF with a million object records opens in milliseconds instead of a second, and a large polygon or a small crop of a large bitmap no longer builds a second full-size copy while it is read (#1463) |
|
||||
| 2026-10-13 | PDF export (#1474): a horizontal or vertical line inside a group (a divider in a grouped box) is drawn, as on screen; it was left out because it has no height |
|
||||
| 2026-10-14 | A paragraph that runs on into the next column or onto the next page wraps around the shapes there (#1374): its continued lines are broken again for that column's wrap areas instead of running through a shape there (or around one left on the page before); the lines before, and the paragraph's own floating objects, stay where they were. Paragraphs with nothing new to wrap around are not laid out again |
|
||||
| 2026-10-13 | A PAGE field in the body shows the number of the page it is actually on (#1352): after a page break inside its paragraph, or when the paragraph runs over onto the next page, it no longer repeats the first page's number; the rest of the paragraph is broken again for the wider number (page 9 to 10). Only paragraphs with PAGE fields are laid out again |
|
||||
| 2026-10-14 | RTF import keeps sections (#1378): a file with portrait and landscape parts, a two-column stretch or a page-numbering restart opens with one section each, as in Word, instead of one landscape section for the whole document. Each keeps its page size and orientation, margins, header/footer distance, columns, break type (continuous, next page, odd/even, column), page-number restart, start and format, title page and its own headers and footers; a section without its own links to the previous one's |
|
||||
| 2026-10-14 | The system Save As dialog's file-type list names every format (Word Document, PDF, OpenDocument Text, Rich Text Format…) instead of one "Documents" entry, with the document's own format first (#1399) |
|
||||
| 2026-10-14 | Colour emoji show on the page (#1269): 🧠, ✅ and other emoji were blank on screen and in `render_page` (only PDF export had them). Glyphs from colour fonts are now drawn in the font's own colours: bitmap emoji (Apple Color Emoji, Noto Color Emoji) and COLR fonts (Segoe UI Emoji, newer Noto builds, with gradients). A dark page doesn't invert them, the same as pictures |
|
||||
| 2026-10-14 | `.doc` tables keep their cell shading (#1380), from Word 97 through Word 365, so a dark header row with white text is readable again, and lose the extra empty column at the right of every row; a table no longer takes the previous table's columns, borders or alignment. Rows merged across the table (a legend) come with #1123 |
|
||||
| 2026-10-12 | On the web, pasting a picture while a comment, the Find box, a dialog field or the Backstage has the keyboard no longer inserts it into the document; it inserts once only when the page is the edit target (#1349) |
|
||||
| 2026-10-14 | Table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls (#1329): with tracking on, Delete Table, Rows, Columns and Cells mark the cells' text deleted and keep the table (like Word), and Change Case is a tracked deletion and insertion, so Reject All restores the original; all of them refuse to delete a control locked against deletion or change content locked against editing |
|
||||
| 2026-10-14 | Draw: Ink to Shape recognises arrows. A line and a V-shaped head drawn in one stroke (shaft first or head first, any direction) becomes a straight arrow connector with the head at the tip, in the stroke's colour and width; a lone V, a line with one barb and scribbles stay as they are. Our own recogniser: Word for Mac has no Ink to Shape to compare. Two-stroke arrows and arrows with a closed triangle head not yet. |
|
||||
| 2026-10-12 | A DOCX hyperlink whose relationship has an empty target (as LibreOffice writes) is no link (#1005): no "Ctrl+Click to follow link" tooltip over the text, which keeps its Hyperlink style |
|
||||
| 2026-10-12 | Table eraser beside vertically merged cells (#1039): the border between two cells merged down the same rows merges them into one cell that stays merged down those rows; a border whose two sides can't make one rectangle is hidden on both sides along the whole edge instead of refused |
|
||||
| 2026-10-13 | Styles gallery for DOCX files that mark no style `w:qFormat` (LibreOffice) shows Word's usual quick styles: Normal, No Spacing, Headings, Title, Subtitle… (#1238) |
|
||||
| 2026-10-13 | Pictures can be cropped on the page: Picture Format › Crop shows black crop handles; dragging one trims that side (a corner, two) while the picture keeps its scale and the visible part stays put, dragging back out restores it, and the cropped-away part shows under a dark dim. Esc, Enter, a click outside or Crop again keep the crop; each drag is one undo step |
|
||||
| 2026-10-13 | Table Layout › Cell Size: the Height and Width boxes apply to every row and column the selection covers (a selected table changed only its last row and column), and to the caret's row and column without a selection (#1242) |
|
||||
| 2026-10-12 | Forms protection: filling content controls under `w:edit="forms"` (#1077) — entries and typing inside fillable controls run, every other edit rolls back ("only the editable regions of this protected document can change"); `review.restrict` reports `formFields`; Find Next Region covers form fields (pane button shows for forms documents); a save/reopen keeps the protection, the filled values and the password guard |
|
||||
| 2026-10-12 | RTF import now uses the RTF spec's defaults where a file names none (#902): no space before or after paragraphs, single line spacing, and the `\deff` default font, instead of WordCraft's Normal style; RTF files that relied on the old defaults open tighter, like in Word |
|
||||
| 2026-10-12 | `--help` and `-h` print the usage and exit (#968): `wordcraft --help` lists the app's options without opening a window (it used to try to open a file named `--help`), and `wordcraft-cli <command> --help` works for every command instead of failing with `unknown option --help` |
|
||||
| 2026-10-11 | Right-clicking a table cell offers the table's commands, and as in Word they follow the selection: with the caret in a cell Insert, Delete Cells, Split Cells, Text Direction and Table Properties…; with several cells Merge Cells instead of Split; with whole columns or rows Delete Columns or Rows, Merge Cells and Distribute Rows and Columns; with the whole table Delete Table, Distribute, AutoFit and Insert Caption…. A right-click beside selected cells moves the caret there instead of keeping them |
|
||||
| 2026-10-11 | Drags, Shift+arrows and Shift+click over table cells select whole cells, as in Word: from one cell into another the rectangle between them (bold, alignment and Delete leave the other cells alone), into or out of a table whole rows; extending again goes on from where the selection started |
|
||||
| 2026-10-11 | More of the table mouse: arrows above a column, left of a row and along a cell's left edge select it (a drag selects more; a selected column is edited cell by cell, numbering it makes one list), "+" buttons beside the borders insert a row or column, the move handle past the top-left corner selects the table or drags it to float where it's dropped, and a double-click on a column border fits the column; Select Column in the ribbon; `table.selectAt`, `table.insertAt`, `table.moveDrag`, `table.fitColumn` and `table.selectColumn` for agents |
|
||||
| 2026-10-12 | Table fixes (#971): a double-click on a nested table's column border fits the column within the cell around the table (it could run out to the page's right margin); a selection from text into or across a table shades the whole cells of the rows it takes, not just their letters; Shift+Right at the end of a cell's text selects that cell first, as in Word, and the next press takes the next cell too |
|
||||
| 2026-10-12 | AutoCorrect keys its built-in English replacement list by language (#835): Polish, Croatian, Bosnian and Serbian `i` ("and") is no longer turned into `I`; English and untagged text unchanged |
|
||||
| 2026-10-12 | Ribbon groups fit above their labels: View › Show splits its four check boxes into two columns (Hide White Space, #645, had pushed the fourth onto the "Show" label), Developer › Controls loses the gaps that ran into its label, and Layout › Paragraph (#654) no longer trips a debug assertion and sits 2.5 pt higher; a test draws every tab in every language and fails on any group taller than the ribbon |
|
||||
| 2026-10-12 | Down and Up from the start of a line beside a table go into it (#1007): the caret, left of the first cell's text there, used to skip the whole table to the paragraph beyond it; it now lands in the cell under it or the nearest one, as in Word |
|
||||
| 2026-10-12 | Window caption: a non-Latin file name is drawn with a document fallback face (or the CJK UI font), instead of `?` |
|
||||
| 2026-10-12 | Comments: Arabic, Hebrew and other non-Latin comment text and author names are drawn with a document fallback face (or the CJK UI font) in the balloons and Comments pane, instead of boxes; read-only balloons show right-to-left text in reading order, set against the right edge |
|
||||
| 2026-10-13 | Word 365 cover pages (#743): shapes placed relative to the page's height now sit where Word puts them (they were at the top of the column), and a freeform drawn back to its start without being closed is filled, so the cover's coloured panel and its white title show |
|
||||
| 2026-10-12 | 32-bit Windows starts on OpenGL. DirectX 12 graphics pipeline creation returns "The parameter is incorrect" and the app exited before the window appeared |
|
||||
| 2026-10-12 | New documents follow the system region (#838): A4 and centimetres outside the US (Letter in the CLDR Letter territories, inches in the US), lengths written with the region's decimal separator (`2,54 cm`) and typed with either; an explicit Measurement units choice wins; `file.options {"region"}` for agents |
|
||||
| 2026-10-12 | Paste from other programs keeps their formatting (#687): Ctrl+V and Home › Paste read the system clipboard's HTML (and RTF on Windows and Wayland); Merge Formatting takes the destination's font and paragraph and keeps bold, italic, underline and strikethrough; Paste Special lists what the system clipboard holds (HTML, RTF, picture, text). Linux: pictures copied in a browser or Spectacle paste on KDE and other Wayland desktops (data-control clipboard), and a paste that finds nothing usable names what the clipboard holds instead of "empty" (#833) |
|
||||
| 2026-10-12 | Table style editor (#714): New/Modify Table Style edits each of the 13 table style parts (header row, total row, first/last column, odd/even bands, corner cells) with font, colour, fill, borders and cell alignment; every table using the style follows; all parts round-trip in DOCX; `table.modifyStyle` takes `part`/`parts` and per-edge borders |
|
||||
| 2026-10-12 | STYLEREF fields (#775): running headers and footers show each page's chapter title (page's first, or `\l` last, paragraph of the style, else the nearest before), style names, ids, heading levels and character styles, number switches; body STYLEREF updates with the other fields; STYLEREF in the Field dialog; PDF export follows the layout |
|
||||
| 2026-10-12 | Undo history list (#701): a ▾ beside the Quick Access Toolbar's Undo lists recent steps newest first; hovering highlights what a click undoes ("Undo 3 Actions"), and a click undoes them in one go. `edit.undoTo {count}` and `edit.undoHistory` (newest first, up to 100) for CLI and MCP |
|
||||
| 2026-10-12 | Start screen (#766): launched with nothing to open, WordCraft starts on File › Home (Blank document, templates, Recent) like Word, desktop and web; Esc leaves a blank document; File › Options › General › Start-up turns it off |
|
||||
| 2026-10-13 | No document behind the Start screen (#1129): Esc or Back from it shows an empty window (no page, ribbon greyed out but for Help) until Blank document, a template or a file is opened, as in Word; closing it asks nothing |
|
||||
| 2026-10-12 | Word 365 cover pages (#743): a freeform inside a group keeps its shape (it was drawn as a rectangle); text boxes keep their own internal margins and Resize shape to fit text, so a tight title box no longer loses its second line; both survive saving. The missing fills in the report were theme-coloured shapes, fixed by #611 |
|
||||
| 2026-10-12 | Alt+Q moves to "Tell me" command search, as in Word for Windows (#819); not on macOS, where Option+Q types a character |
|
||||
| 2026-10-12 | PDFW: PDF export uses the shared craft-pdf writer for metadata, font preparation and serialization while retaining WordCraft layout, drawing, tagging, links and font-outline retry. Writer-only builds do not enable PDF import codecs. |
|
||||
| 2026-10-12 | PDF export of long documents with many internal links (a linked table of contents) is linear: NIH's 67-page protocol template 10.6 s → 0.9 s |
|
||||
| 2026-10-12 | Keytips: Word for Windows' tab letters (File F, Design G, References S, Review R, View W, Help Y) |
|
||||
| 2026-10-13 | Keytips reach the table tabs as in Word: Alt, J, T for Table Design and Alt, J, L for Table Layout, then their controls' badges (#1183) |
|
||||
| 2026-10-12 | Table-of-contents links look like Word's: plain text, not blue and underlined (Word ignores the Hyperlink style on TOC entry links; measured in 9 cases) |
|
||||
| 2026-10-12 | Line heights like Word's: spaces and tabs never make a line taller (13 cases measured in Word for Windows); tables of contents with big tab runs were a third taller |
|
||||
| 2026-10-12 | `.doc` import: tab stops (centred titles, right-aligned dates, leaders) and sections ending at their section marks (continuous breaks, footers); EPA .doc templates now paginate like Word |
|
||||
@@ -172,17 +263,21 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | A list label makes its line taller above the baseline only, as in Word (6 cases measured in Word for Windows): Symbol bullets no longer add their deeper descent, so bulleted lists keep Word's height and page breaks |
|
||||
| 2026-10-12 | Hidden end-of-cell marks (`w:hideMark`) read, written and laid out like Word (9 cases measured in Word for Windows): a cell's empty last paragraph takes no room, so rows of such empty cells shrink to their borders |
|
||||
| 2026-10-12 | Text frames (`w:framePr`) in headers, footers, cells and text boxes: placed apart with text wrapping around them, and kept on save (a framed footer page number took a line of its own and was lost on save) |
|
||||
| 2026-10-13 | A paragraph with more than 65,536 distinct formats keeps each one (#1340): the layout numbered a paragraph's formats with 16 bits, so every run past that drew with the 65,536th format's font, size, link and tracked-change marking |
|
||||
| 2026-10-12 | List indents like Word's when a numbered style has indents of its own: the style giving the list (and styles based on it) beat the level's indents, and a paragraph with its list switched off drops the styles' indents (27 cases measured in Word for Windows); NIH's Heading 3s now sit at their 0.9" |
|
||||
| 2026-10-12 | Keep with next like Word (20 cases measured in Word for Windows): a kept paragraph moves to the next page only when it would fit on this one by itself, otherwise it breaks as usual; chains of kept paragraphs move together |
|
||||
| 2026-10-12 | An empty paragraph that only carries a continuous section break takes no room, as in Word (10 cases measured in Word for Windows): text after it follows right on and balanced columns don't count it |
|
||||
| 2026-10-12 | Floating objects positioned relative to their paragraph start above its space before, as in Word (10 cases measured in Word for Windows) |
|
||||
| 2026-10-12 | Unequal columns: text after a column break is broken for the column it lands in (NIH's SARP form had a paragraph a word or two wide) |
|
||||
| 2026-10-13 | New comments, notes, text boxes and lists in a document whose file used the largest ids (#1338): they take a free id instead of overflowing (a crash) or reusing one already taken (a new list could pick up another's definition); `Document::try_add_part` and `Numbering::try_add_list` report ids running out instead |
|
||||
| 2026-10-12 | Space before at the top of a page like Word after page breaks (32 cases measured): a paragraph ending with a page break keeps its mark with it, the next paragraph gets no space before; page break before drops it in Word 2013 mode |
|
||||
| 2026-10-12 | Automatic paragraph spacing drops between list items, as in Word (16 cases measured in Word for Windows): bulleted items that ask for automatic space before and after now touch, as in NIH's monitoring plan |
|
||||
| 2026-10-12 | Rendering like Word for Windows, found by comparing real .gov documents page by page: text is kerned only where Kerning for fonts asks for it (line breaks now match Word's), and automatic paragraph spacing (`w:beforeAutospacing`/`w:afterAutospacing`, common in pasted web text) is 14 pt, dropped at the document's and cells' edges |
|
||||
| 2026-10-12 | Keyboard context menu (#821): Shift+F10 opens the page's right-click menu below the caret; `ui.contextMenu` |
|
||||
| 2026-10-12 | The Font list no longer keeps every family it previews in memory (#848): the Font box drew each family's name in its own face by loading the whole family for good, so every trip through the list kept tens of megabytes (1.47 GB after 40 changes on macOS); entries are now drawn from a face read for the preview alone and freed (120 families previewed: +17 MB RSS instead of +411 MB); only fonts actually used load |
|
||||
| 2026-10-13 | An empty file opens (#1384): the zero-byte .docx that File Explorer's New › Microsoft Word Document makes opens as a new blank document (the region's paper, the editing language), and Save writes it back to that file instead of asking for a name |
|
||||
| 2026-10-12 | Scrolling a document with one very large table stays smooth (#811): pages are fingerprinted for the texture cache once per layout and only when shown (not every page every frame), the markup-area check is cached per revision, and textures far from the view are dropped. The issue's 1,096-page table: ~600 ms → ~2.4 ms idle frames, ~590 ms → ~4.5 ms scroll frames |
|
||||
| 2026-10-13 | Paragraph dialog over differently formatted paragraphs (#1346): a field they differ in shows blank (a check box neither on nor off, no direction picked) and OK leaves it as each paragraph has it; OK sends only the fields that changed, as one undo step, instead of giving every paragraph the caret paragraph's formatting in three undo steps |
|
||||
| 2026-10-12 | Search (#819): Alt+Q, or Alt then Q, opens the Search box from anywhere with nothing typed into it; queries match every word; `tools.search` for agents |
|
||||
| 2026-10-12 | Section breaks (#852): Layout › Breaks with text selected puts the break before the selection and keeps the text, as Word does; it used to delete it, leaving the first section empty |
|
||||
| 2026-10-12 | Find, Replace and Go To like Word (#712): Ctrl+F types into the Navigation pane's search, one tabbed Find and Replace dialog, Go To by page (absolute or relative) and bookmark; `edit.findReplace`, `edit.goto` `pageBy` |
|
||||
@@ -190,12 +285,19 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-11 | Hide White Space (#645): `view.hideWhiteSpace` (View › Show checkbox, or double-click the gap between pages) collapses margins, headers and footers between pages to a thin line in Print Layout; screen only, page count unchanged |
|
||||
| 2026-10-11 | Fonts: Palatino Linotype and Book Antiqua fall back to Palatino (macOS) or TeX Gyre Pagella / P052 / URW Palladio (Linux) before generic serif (#670) |
|
||||
|---|---|
|
||||
| 2026-10-12 | Czech proofing: cs-CZ spelling reads the installed Hunspell dictionary (`hunspell-cs` on Debian/Ubuntu), suggestions use runtime MAP/REP/TRY/KEY tables, generic repeated-word and spacing checks explain in Czech; Review › Language offers Czech/Čeština; the Czech interface writes new documents and opened TXT/Markdown in cs-CZ. Affix headers accept trailing comments. No system dictionary data or Czech hyphenation patterns bundled; parity estimates unchanged |
|
||||
| 2026-10-12 | Tables: dragging the border of one selected cell (Select Cell, or a click along its left edge) moves it in that cell's row only, as in Word, like the border of cells selected across (#962) |
|
||||
| 2026-10-13 | Korean interface catalog completed: all 2,463 entries translated; the ko-KR system locale and saved language choice select the interface. The UI prefers Korean embedded/system font faces so Hangul renders instead of boxes, and print settings and printer feedback are translated. Korean proofing remains unavailable; macOS Korean IME fixes are still pending (#163, #164) |
|
||||
| 2026-10-12 | Word default shortcuts expanded (gap #24): 140 commands bound on macOS (169 combinations), 158 on Linux/Windows (188 combinations). Bound Style Inspector (Shift+F1), Macros (Alt+F8), Strikethrough (Mod+Shift+X), Find Next (Shift+F4), Copy/Paste (Mod+Insert, Shift+Insert), Go Back (Mod+Alt+Z), File Open/Save/Save As/Print (Mod+Alt+F2, Alt+Shift+F2, Alt+F2, Mod+Alt+I), Field navigation (Alt+F1, Alt+Shift+F1), Outline show first line (Alt+Shift+L), Next Footnote (Alt+Shift+>), Link to Previous (Alt+Shift+R), AutoText (Alt+F3), Spelling on Mac (Mod+Alt+L) |
|
||||
| 2026-10-13 | Web and Draft Layout now render visible full-resolution raster tiles for exceptionally tall pages rather than downsampling the entire page into one texture; verified with a 440-paragraph headless UI reproduction |
|
||||
| 2026-10-12 | Track Changes: Accept All after a tracked deletion from the end of one paragraph into a later one no longer joins the paragraph that follows the range, and Reject All after typing into an empty paragraph keeps that paragraph (#864) |
|
||||
| 2026-10-12 | Ctrl+drag copies an object (#1014): holding Ctrl (⌘ on macOS) while dragging a picture, shape or text box leaves the original and drops a copy where you let go (text boxes get their own text); the copy is selected, the clipboard is untouched, one undo step; `arrange.copyTo` |
|
||||
| 2026-10-11 | Table border drags like Word's (#711): Ctrl shares a column border's change among the columns right of it (the table keeps its width), the table's left edge moves a left-aligned table's indent (a centred or right-aligned table keeps its alignment, as in Word), a border of cells selected across moves only in their rows, and Alt shows the column widths on the ruler |
|
||||
| 2026-10-11 | Tables on the rulers (#700): with the caret in a table the horizontal ruler marks its row's column borders and the vertical ruler its rows' bottoms; dragging a marker resizes the column (the columns right of it move along; with Shift the neighbour makes up the difference) or the row, one undo step, Escape cancels; in a cell the indents and tabs are measured from the cell |
|
||||
| 2026-10-12 | Save Changes prompt answers from the keyboard: Save has focus when it opens; arrow keys and Tab move between Save, Don't Save and Cancel; Enter answers (#861) |
|
||||
| 2026-10-12 | Builds with craft-fonts draw simplified-Chinese characters in documents from the bundled Noto Sans CJK SC (it was only used by the interface), so a CJK run gets one face covering it; fixes the FreeBSD job's `east_asian_run_uses_one_face_covering_the_whole_run` failure after #567 |
|
||||
| 2026-10-12 | Insert › Picture, drag-and-drop and paste take Windows Metafiles (`.wmf`) and Enhanced Metafiles (`.emf`) at their own frame size (#802) |
|
||||
| 2026-10-14 | A picture or icon inserted by a command (`wordcraft-cli run`, MCP, control channel) leaves the caret after it, so the next `text.newParagraph` or `text.insert` no longer deletes it, and two inserted in a row are both kept; Picture Format commands still act on it, and a picture the user inserts or pastes in the app is still selected (#965) |
|
||||
| 2026-10-12 | AutoCorrect capitals (#544): Correct TWo INitial CApitals (with exceptions), accidental cAPS LOCK, first letter of table cells; each undoable and switchable |
|
||||
| 2026-10-11 | Turkish (`tr`) interface completed (#774): 2,325 entries, every key of the Russian catalog (equation gallery, built-in style names, watermarks, paper sizes, preview tiles); the interface audit checks Turkish too |
|
||||
| 2026-10-12 | Navigation headings truncate within the resizable pane, with an ellipsis for long titles and full text on hover (#759) |
|
||||
@@ -206,7 +308,9 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-11 | Polish: interface (`pl`, the thirteenth language, every catalog key) and proofing — spelling against the installed Hunspell `pl_PL` dictionary (read at runtime, not bundled) through a new Hunspell-style affix engine, suggestions tuned for Polish, Polish grammar rules with Polish messages, TeX Polish hyphenation patterns (MIT option); proofing language per run (`w:lang`) for squiggles, F7, suggestions and hyphenation, languages without tools left unmarked; Review › Language menu and the status bar's language; a Polish interface writes new documents in Polish |
|
||||
| 2026-10-11 | German (`de`) interface (#574): 2,021 translated entries covering the full zh-hans key set, locale and saved-preference tests, bundled-font checks; no German proofing resources |
|
||||
| 2026-10-12 | Sorting and table numbers follow the text's language (#836, #837): Table › Sort, Home › Sort, the index (with its letter headings), the bibliography and the Table of Authorities use the language's alphabet (Polish `Łódź` between `Kraków` and `Zakopane`, Swedish `å ä ö` after `z`, German `ä` with `a`); table sort and formulas read `1,5` and `1 250,00` as Polish decimals and `=SUM` writes `5,75` |
|
||||
| 2026-10-14 | `.doc` notes, headers and text boxes read their text once (#1319): a story table that steps back no longer has many footnotes, endnotes, headers or text boxes copy the same text into a part each; a story starting inside an earlier one is dropped (a header or footer left empty is linked to the previous section's), so the stories together never hold more than the file's text |
|
||||
| 2026-10-11 | `.doc` import keeps pictures and drawings (#551): inline and floating pictures (PNG, JPEG, DIB, EMF, WMF), shapes, lines, groups and text boxes with position and wrap, from [MS-ODRAW] |
|
||||
| 2026-10-14 | ODT and `.doc` pictures stay within their byte budget (#1334): an ODT picture entry is inflated once however many frames point at it, and only when the size it declares fits in what is left (one inflating past that uses the budget up); a `.doc` inline picture that can't be read or doesn't fit is no longer decoded and copied again for every anchor on it, and is decoded only within what is left |
|
||||
| 2026-10-11 | Tables resize with the mouse (#217): drag a column border (the neighbour makes up the difference; Shift moves one column), a row's bottom border, or the handle past the bottom-right corner to scale the table; a dashed guide while dragging, one undo step per drag; `table.resizeDrag` for agents |
|
||||
| 2026-10-11 | Animation effects setting: File › Options › Accessibility › Animation effects (Use system setting, On, Off). With the system's animations off (Windows' Animation effects, macOS' Reduce motion, the Linux/BSD desktop's setting, a browser's reduced motion) the page no longer smooth-scrolls: wheel notches and Ctrl+wheel zoom land at once, in the document and in every list and pane, and menus and buttons don't fade; `ui.animations` for agents |
|
||||
| 2026-10-11 | Linux/BSD: Open, Save As, Export and Insert Picture work without a file chooser portal or zenity (labwc, sway…): WordCraft shows its own file browser and says how to get the system dialog; File › Open › Browse in WordCraft… is always there (#576) |
|
||||
@@ -217,8 +321,11 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-11 | File › Print: page preview, page range (all, current, selected, custom 1-3,5), odd/even, copies and collate go into the printed PDF (`file.printPdf`, `ui.print` params); printer, duplex and pages per sheet are still the system dialog's (#641, stage 1) |
|
||||
| 2026-10-11 | A vertically merged table cell (eraser on a horizontal border) lays out, shows and clicks as one cell spanning its rows (#640) |
|
||||
| 2026-10-11 | Word XML files (#548): Word XML Document (Flat OPC `.xml`) opens and saves through the DOCX reader and writer; Word 2003 XML opens (styles, lists, tables, sections, notes, comments, pictures, hyperlinks) |
|
||||
| 2026-10-14 | Open DrawingML freeform paths draw `a:tailEnd` at the final path segment |
|
||||
| 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available |
|
||||
| 2026-10-11 | Font fallback indexes which characters each installed font maps, reading each font file once (#605): text in a script no installed font covers no longer re-reads every system font per distinct character (200 such characters: 13 s → 0.2 s) |
|
||||
| 2026-10-13 | Markdown import of text full of backtick runs that never close is linear (#1336): every code span and link bracket over them searched the rest of the text for a closing run (2 MB in brackets: 17.8 s → 0.06 s) |
|
||||
| 2026-10-13 | Markdown import keeps every link in a paragraph (#1452): a `[` nothing closes, bracketed text that is not a link and each link used up the bracket scans' look-ahead budget as if they had read the rest of the paragraph, so later links were plain text; a scan now costs what it reads, and brackets it has passed are looked up |
|
||||
| 2026-10-11 | Find and Replace special characters (`^p`, `^t`, `^#`, `^&` …) and Use wildcards (ranges, counts, word anchors, groups with `\1` in Replace); `^p` finds and splits paragraphs; Special ▾ menu and search options in the dialog (#543) |
|
||||
| 2026-10-11 | Typing parity (#546): `+---+` Enter makes a table, `> ` `-> ` `=> ` arrow bullets, smileys inside words (`ok:)`), Undo right after a border line brings the characters back |
|
||||
| 2026-10-11 | Windows: DirectX 12 shaders compile with FXC, built into Windows, so the app no longer quits at launch with "Parent device is lost" when no matching `dxcompiler.dll` + `dxil.dll` pair is around (#603) |
|
||||
@@ -226,7 +333,9 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-11 | Outline view (#493): Outlining tab, outline symbols and indents, collapse/expand, Show Level, first line only, plain text; catalog 428/450 → 441/463 (95.2%) |
|
||||
| 2026-10-11 | Vertical sections (#491): Layout › Text Direction turns the section (or the cell or text box the caret is in); lines run top to bottom, right to left, ideographs upright; `w:textDirection` in `w:sectPr` read and written |
|
||||
| 2026-10-11 | File › Options in Word's panes (#485): General, Display, Proofing, Save, Language, Accessibility, Advanced, Agents; initials, individual formatting marks, spelling ignore options, custom dictionary, overtype, typing replaces selection, measurement units, recent-documents count, print options; `file.options` reads and sets them headlessly |
|
||||
| 2026-10-14 | Word XML Document (Flat OPC) reading is bounded everywhere in the file (#1353): nesting and elements are capped as the XML tree reader caps a part's, every child of the package and every part's data count against the part count and size limits (a repeated part name too), and data is checked before it's copied; base64 written as CDATA or with character references reads as the same bytes, and an entity in it is an error instead of bytes gone missing |
|
||||
| 2026-10-11 | Right-click Wrap Text submenu on pictures, shapes and text boxes: wrapping styles, Move with Text / Fix Position on Page (#513) |
|
||||
| 2026-10-14 | Text boxes in tables nested deeper than 16 survive edits (#1339): the paragraph walk behind text box pruning, copy and paste, reading order, drawing ids and note conversion goes through tables however deep they nest instead of stopping 16 tables down, so an unrelated edit no longer drops the text of a box shown only from deeper, and a copied deep table takes its boxes along |
|
||||
| 2026-10-11 | Caret animation: keys and typing glide the caret to its new place in 100 ms along the curve measured from Word for Windows, and the blink fades; clicks and scripted moves don't glide. File › Options › Advanced › Animation turns it off, kept between runs; `ui.caretAnimation` for agents |
|
||||
| 2026-10-11 | Paragraph dialog options (#512): mirror indents (`w:mirrorIndents`, laid out on even pages), same-style spacing, suppress line numbers, don't hyphenate |
|
||||
| 2026-10-11 | Screen readers can read the document canvas (#488): paragraphs, headings, lists, tables, links, pictures and the caret exposed through AccessKit |
|
||||
@@ -262,11 +371,17 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | Native saves use exclusively created sibling temporary files, synchronize before replacement and clean up on failure; existing temporary-name files/links and original files on failed saves are protected. Synthetic CLI and focused tests on macOS; no new Word parity or readiness claim. |
|
||||
| 2026-10-11 | Field codes like Word's field keys (#339): show codes (Alt+F9, Shift+F9), edit, unlink, lock and step through fields |
|
||||
| 2026-10-11 | Word's common keyboard shortcuts (#330): 101 → 125 of ~250 |
|
||||
| 2026-10-13 | Swedish (`sv`) interface: 2,504 catalog entries (every key of the reference catalog, the equation gallery, everything the interface audit finds, and 44 newer strings no catalog had yet, among them the native print settings), `sv-SE`/`sv-FI` system locales and a saved language choice; locale, catalog and bundled-font tests; AI-assisted, terminology and the running app reviewed by a native speaker; no Swedish proofing resources |
|
||||
| 2026-10-12 | Bulgarian (`bg`) interface: 2,419 catalog entries (every key of the reference catalog, the equation gallery and everything the interface audit finds), `bg-BG` system locales and a saved language choice; locale, catalog and bundled-font tests; no Bulgarian proofing resources |
|
||||
| 2026-10-13 | Croatian (`hr`) interface: 2,507 catalog entries (every key of the reference catalog, built-in style names and the equation gallery), `hr-*` system locales and a saved language choice; locale, catalog and bundled-font tests; no Croatian proofing yet |
|
||||
| 2026-10-11 | Hungarian (`hu`) interface: all 2,419 catalog entries, built-in style names translated, `hu-HU` system locales and a saved language choice; locale, catalog and bundled-font tests; no Hungarian proofing resources |
|
||||
| 2026-10-11 | Turkish (`tr`) interface: all 1,307 catalog entries, `tr-TR`/`tr-CY` system locales and a saved language choice; command search keeps Turkish dotted and dotless I apart (`italik` finds İtalik); locale, catalog, search and bundled-font tests; no Turkish proofing resources |
|
||||
| 2026-10-11 | Italian (`it`) interface (#594): 2,399 entries, feature names as Italian Word users know them, locale and saved-preference tests, bundled-font checks; no Italian proofing resources |
|
||||
| 2026-10-12 | Native drawing-level Word ink preserved through DOCX edits and repeated saves, including its InkML part and optional VML picture fallback; native ink rendering and editing remain missing |
|
||||
| 2026-10-12 | List-label line height: automatic spacing scales body text before adding label ascent overflow; AtLeast spacing keeps text descent. Original Word for Mac probes and deterministic layout tests cover symbol/decimal labels, wrapped lines, fixed/minimum spacing and inline pictures. Overall readiness unchanged; [evidence](docs/layout-parity.md#list-label-line-spacing) |
|
||||
| 2026-10-12 | Local desktop recovery: unsaved drafts and edits are snapshotted in the profile; File › Recover restores an unsaved copy or confirms discard. Full model storage includes media and opaque parts. Password sessions skip plaintext snapshots. See [recovery.md](docs/recovery.md); stability estimates remain unchanged. |
|
||||
| 2026-10-12 | Legacy table paragraph spacing: `allowSpaceOfSameStyleInTable` survives DOCX save; enabled modes 11/12/14 keep contextual same-style spacing in cells. Mode 15 and non-cell controls unchanged; measured against Word for Mac 16.113.3 |
|
||||
| 2026-10-11 | Contextual paragraph spacing: same-style first-only 12/8 pt and 10/12 pt gaps corrected to 0 pt and 2 pt in body and header layout, with per-side controls; measured against Word 16.113.3. Ordinary overlap remains #108 |
|
||||
| 2026-10-11 | Citations and bibliography in all 12 of Word's styles: Harvard, ISO 690 (author-date and numerical), Turabian, GB/T 7714, GOST (name and title sort) and SIST02 join APA, MLA, Chicago and IEEE; numbered styles count in order of first citation (#383) |
|
||||
| 2026-10-11 | Interface size setting (#475): File › Options › General scales the interface 80–200 % on top of the system display scale, kept between runs; `ui.interfaceSize` for agents |
|
||||
| 2026-10-11 | DOCX paragraph defaults: preserve omission separately from explicit empty defaults, with repeated-save and default-edit regressions |
|
||||
@@ -282,11 +397,52 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-07 | v0.1.0 released; contributor credits in About (#6) |
|
||||
| 2026-10-06 | Layout arc: wrap around floats, text boxes, page borders, line numbers, row splitting, drop caps, hyphenation, comment balloons; release pipeline for every platform; first estimate (~62% real feature parity, 120–150 h to 100%) |
|
||||
| 2026-10-05 | M0–M12 first versions: model, layout, render, engine with 200+ commands, Word-style UI, DOCX I/O, PDF and other formats, references, review, mailings, CLI, MCP, web |
|
||||
| 2026-10-12 | Mail-merge recipients (#778): legacy Excel .xls workbooks; CSV/TXT lists in GBK, Big5, Shift_JIS, UTF-16 and other encodings read correctly (plain-text import too); Edit Recipient List filters (equal, not equal, less, greater, blank, contains… joined by And/Or) and sorts, and preview, Finish & Merge and labels use only the matching records in that order (`mailings.filterRecipients`, `mailings.sortRecipients`) |
|
||||
| 2026-10-13 | The interface-translation audit runs in CI again (#1128): the size labels of Envelopes, Labels and Layout › Size are translated (`4,13 × 9,5 дюйма`) and use the region's decimal separator, and status-bar messages (table split and merge, ink replay, citations, SmartArt, Researcher, Design defaults), the Reading Mode toolbar, Go To and Search's Suggested heading are translated in every interface language, and the Read Aloud player no longer shows a speech error a frame before the status bar does, the race behind the audit's rare failure under load |
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-17 | trivial | Language dialog keeps inherited proofing language and no-proof choices (#2717); readiness estimates unchanged |
|
||||
| 2026-10-14 | trivial | Progress log: row table border exceptions |
|
||||
| 2026-10-12 | minor | Czech proofing review: short-word splits rank after deletion, NOSUGGEST excludes suggestions while accepting typed forms, affix comments apply only to headers, ratios keep spaces and repeated-word messages use Czech quotes; synthetic engine end-to-end and latency checks |
|
||||
| 2026-10-12 | minor | Czech spelling from the installed Hunspell dictionary, runtime-table suggestions and generic checks; Czech interface writes cs-CZ documents; no Czech hyphenation patterns bundled; estimates unchanged |
|
||||
| 2026-10-12 | trivial | Progress log: one selected cell's border drags in its row only (#962) |
|
||||
| 2026-10-12 | minor | Progress log: Word default shortcuts expanded to 140 commands on macOS (169 combinations) and 158 on Linux/Windows (188 combinations), addressing gap #24 |
|
||||
| 2026-10-13 | trivial | Web/Draft long-page blur fixed with visible full-resolution raster tiles |
|
||||
| 2026-10-14 | trivial | Progress log: VML freeforms read and kept on save |
|
||||
| 2026-10-14 | trivial | Progress log: consistent preferred cell widths |
|
||||
| 2026-10-14 | trivial | Field instructions spanning paragraphs no longer add blank lines during pagination; empty result paragraphs still take a line. |
|
||||
| 2026-10-14 | trivial | A list paragraph containing only a page break has no visible label; it still advances the list counter. Ordinary empty list items keep their label. |
|
||||
| 2026-10-14 | trivial | Floating-table overlap checks use visible line content; empty line-break lines no longer move a table |
|
||||
| 2026-10-14 | trivial | Progress log: deleting a comment leaves no dangling anchors or replies (#1345) |
|
||||
| 2026-10-14 | minor | Legacy DOC DIB conversion byte limits only; related #1334/#1554, stage and readiness estimates unchanged |
|
||||
| 2026-10-13 | trivial | Progress log: justified vertical page alignment (#1320) |
|
||||
| 2026-10-14 | trivial | Progress log: file names that aren't valid Unicode (#1440) |
|
||||
| 2026-10-13 | trivial | Behind Text pictures and shapes drag over overlapping text in the body and headers, selected or not, while ordinary clicks keep editing text; In Front of Text drag covered too |
|
||||
| 2026-10-13 | trivial | Progress log: the watermark written to DOCX (#1290) |
|
||||
| 2026-10-13 | trivial | Progress log: Word's text watermark read from DOCX (#1290) |
|
||||
| 2026-10-13 | trivial | Progress log: Insert Hyperlink › Place in This Document (#1234) |
|
||||
| 2026-10-13 | trivial | Progress log: Insert › Bookmark deletes and goes to bookmarks (#1236) |
|
||||
| 2026-10-12 | trivial | Progress log: an option to show only the selected text's comment (#1055) |
|
||||
| 2026-10-12 | trivial | Progress log: clicking in a comment's text moves its caret (#1013) |
|
||||
| 2026-10-12 | trivial | Progress log: a press on the ribbon no longer scrolls the document (#1019) |
|
||||
| 2026-10-12 | trivial | Progress log: Ctrl+drag copies an object (#1014) |
|
||||
| 2026-10-12 | trivial | Document title opens Rename Document; the account badge opens Options › General for user name and initials. |
|
||||
| 2026-10-13 | trivial | Progress log: rounded rectangle corners (#1476) |
|
||||
| 2026-10-13 | trivial | Progress log: PAGEREF in headers and footers (#1477) |
|
||||
| 2026-10-13 | trivial | Replace All checks content-control locks before editing; a refused batch leaves the document and undo history unchanged; existing deletion-lock rules reused, with tracked/untracked regression coverage |
|
||||
| 2026-10-14 | trivial | Progress log: print-area strings translated in every catalog |
|
||||
| 2026-10-14 | trivial | Progress log: All Caps and Small Caps draw ß as SS (#1581) |
|
||||
| 2026-10-13 | trivial | Progress log: Windows Magnifier follows the caret onto a new line (#1119) |
|
||||
| 2026-10-13 | trivial | Progress log: a window too big for its screen shrinks to fit (#1215) |
|
||||
| 2026-10-14 | trivial | Progress log: Page Setup sections are validated (#1582) |
|
||||
| 2026-10-13 | trivial | Progress log: `--control` checks its port (#1426) |
|
||||
| 2026-10-14 | trivial | Progress log: words beside a floating picture are no longer split (#1376) |
|
||||
| 2026-10-14 | trivial | Progress log: VML preset shapes (#1377) |
|
||||
| 2026-10-14 | trivial | Progress log: Russian letter list labels |
|
||||
| 2026-10-14 | trivial | Progress log: the save prompt takes the keyboard from the page (#1597) |
|
||||
| 2026-10-12 | trivial | Progress log: VML text box margins, fit and alignment; hidden drawings |
|
||||
| 2026-10-13 | trivial | Progress log: comment balloon buttons work, empty comments can be deleted (#1085) |
|
||||
| 2026-10-12 | trivial | Progress log: sample-text formulas on Enter (#1067) |
|
||||
@@ -294,14 +450,50 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-13 | trivial | Progress log: the caret contrasts with its background (#299) |
|
||||
| 2026-10-13 | trivial | Progress log: clicks on ribbon chrome keep typing in the document (#1093) |
|
||||
| 2026-10-13 | trivial | Progress log: dragged shapes wrap in their new column (#884) |
|
||||
| 2026-10-14 | trivial | Progress log: All Caps and Small Caps text extracts from PDFs as shown (#1473) |
|
||||
| 2026-10-14 | trivial | Progress log: the web's Save before New/Open waits for the save picker (#1315) |
|
||||
| 2026-10-13 | trivial | Progress log: a failed save from the close prompt says so (#1445) |
|
||||
| 2026-10-14 | trivial | Progress log: Inspect Document removes hidden text in every story (#1344) |
|
||||
| 2026-10-14 | trivial | Progress log: ODT tracked changes (gap 19) |
|
||||
| 2026-10-14 | trivial | Progress log: RTF tracked insertions and deletions (gap 19) |
|
||||
| 2026-10-14 | trivial | Progress log: alignment guides while dragging pictures and shapes |
|
||||
| 2026-10-14 | trivial | Progress log: ODT sections on import (#1379) |
|
||||
| 2026-10-14 | trivial | Progress log: right-to-left text in exported PDFs extracts as whole words (#1383) |
|
||||
| 2026-10-14 | trivial | Progress log: HTML header cells, cell alignment and region paper for opened HTML/Markdown/text (#1381) |
|
||||
| 2026-10-14 | trivial | Progress log: custom page size from More Paper Sizes… and Page Setup (#1433) |
|
||||
| 2026-10-13 | trivial | Progress log: highlighted text on a dark page (#1252) |
|
||||
| 2026-10-13 | trivial | Progress log: full screen on F11 (#980) |
|
||||
| 2026-10-13 | trivial | Progress log: interface audit back in CI (#1128) |
|
||||
| 2026-10-13 | trivial | Progress log: double-click the margin to create and edit a header or footer (#960) |
|
||||
| 2026-10-13 | trivial | Progress log: Set Proofing Language… in the Language menu (#860) |
|
||||
| 2026-10-12 | trivial | Progress log: list label follows paragraph alignment (#1159) |
|
||||
| 2026-10-13 | trivial | Progress log: space after a page break |
|
||||
| 2026-10-13 | trivial | Progress log: table row margins and splitting |
|
||||
| 2026-10-13 | trivial | Progress log: lines inside groups in PDF export (#1474) |
|
||||
| 2026-10-14 | trivial | Progress log: continued paragraphs wrap around the next column's shapes (#1374) |
|
||||
| 2026-10-13 | trivial | Progress log: PAGE fields on the pages a paragraph runs onto (#1352) |
|
||||
| 2026-10-14 | trivial | Progress log: RTF import keeps sections (#1378) |
|
||||
| 2026-10-14 | trivial | Progress log: colour emoji drawn on screen and in page renders (#1269) |
|
||||
| 2026-10-14 | trivial | Progress log: `.doc` table shading and the extra column (#1380) |
|
||||
| 2026-10-12 | trivial | Progress log: web picture paste respects the edit target (#1349) |
|
||||
| 2026-10-14 | trivial | Progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls (#1329) |
|
||||
| 2026-10-14 | trivial | Progress log: Ink to Shape recognises single-stroke arrows |
|
||||
| 2026-10-13 | trivial | Progress log: Styles gallery fallback for DOCX files without qFormat (#1238) |
|
||||
| 2026-10-13 | trivial | Progress log: crop handles on the canvas |
|
||||
| 2026-10-13 | trivial | Progress log: cell size boxes act on the whole selection (#1242) |
|
||||
| 2026-10-12 | trivial | Progress log: Accept All and Reject All keep the right paragraph marks (#864) |
|
||||
| 2026-10-12 | trivial | Progress log: `--help` for the app and every CLI subcommand (#968) |
|
||||
| 2026-10-12 | trivial | Progress log: Down and Up no longer skip a table (#1007) |
|
||||
| 2026-10-13 | trivial | Progress log: equation pictures keep the theme colours on Windows (#1002) |
|
||||
| 2026-10-12 | trivial | Progress log: table style editor (#714) |
|
||||
| 2026-10-11 | trivial | Progress log: Ctrl, Alt, left-edge and selected-cells table border drags (#711) |
|
||||
| 2026-10-11 | trivial | Progress log: table markers on the rulers (#700) |
|
||||
| 2026-10-11 | trivial | Progress log: the table context menu |
|
||||
| 2026-10-12 | trivial | Progress log: AutoFit in a nested table, whole cells shaded for a selection through a table, Shift+Right at a cell's end (#971) |
|
||||
| 2026-10-11 | trivial | Progress log: drags and Shift+arrows over table cells select whole cells |
|
||||
| 2026-10-11 | trivial | Progress log: table selection areas, insert buttons, move handle and double-click AutoFit; catalog 484/499 |
|
||||
| 2026-10-12 | trivial | Progress log: Undo history list (#701) |
|
||||
| 2026-10-14 | trivial | Progress log: Save As type list (#1399) |
|
||||
| 2026-10-12 | trivial | Progress log: Start screen at launch (#766) |
|
||||
| 2026-10-13 | trivial | Progress log: no document behind the Start screen (#1129) |
|
||||
| 2026-10-12 | trivial | Progress log: Alt+Q command search (#819); log table header fixed |
|
||||
@@ -309,9 +501,12 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | trivial | Font list previews no longer grow memory (#848) |
|
||||
| 2026-10-12 | trivial | Progress log: section break keeps the selected text (#852) |
|
||||
| 2026-10-12 | trivial | Progress log: save prompt from the keyboard (#861) |
|
||||
| 2026-10-13 | trivial | Progress log: an empty .docx opens and saves back to itself (#1384) |
|
||||
| 2026-10-12 | trivial | Progress log: craft-fonts Simplified Chinese in documents |
|
||||
| 2026-10-12 | trivial | Progress log: symbol-font text drawn as Unicode symbols (#776) |
|
||||
| 2026-10-13 | trivial | Progress log: the Paragraph dialog leaves mixed formatting alone (#1346) |
|
||||
| 2026-10-12 | trivial | Progress log: WMF and EMF pictures can be inserted (#802) |
|
||||
| 2026-10-14 | trivial | Progress log: a picture inserted by a command survives the next typing (#965) |
|
||||
| 2026-10-11 | trivial | Progress log and shipped languages: Turkish interface completed, 2,325 entries (#774) |
|
||||
| 2026-10-12 | trivial | Progress log: Navigation heading truncation (#759) |
|
||||
| 2026-10-11 | trivial | Progress log: Reading Mode implementation |
|
||||
@@ -321,12 +516,14 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | trivial | Progress log: AutoCorrect replacement list follows the text's language (#835) |
|
||||
| 2026-10-11 | trivial | Progress log: German interface (#574) |
|
||||
| 2026-10-12 | trivial | Progress log: language-aware sorting and table numbers (#836, #837) |
|
||||
| 2026-10-13 | trivial | Progress log: Word 365 cover pages, positions and closed freeforms (#743) |
|
||||
| 2026-10-12 | trivial | Progress log: Word 365 cover pages (#743) |
|
||||
| 2026-10-11 | trivial | Progress log: tables resize with the mouse (#217) |
|
||||
| 2026-10-11 | trivial | Progress log: Animation effects setting |
|
||||
| 2026-10-11 | trivial | Progress log: built-in file browser when the system file dialog is unavailable (#576) |
|
||||
| 2026-10-12 | trivial | Progress log: large-table scrolling (#811) |
|
||||
| 2026-10-11 | trivial | Progress log: security review fixes (temp files, exported link schemes) |
|
||||
| 2026-10-13 | trivial | Progress log: every distinct format in a paragraph keeps its own layout style (#1340) |
|
||||
| 2026-10-11 | trivial | Progress log: Find and Replace special characters and wildcards (#543) |
|
||||
| 2026-10-12 | minor | Desktop File > Print now discovers printers and submits PDF jobs through pinned craft-print with printer choice, copies, collation, duplex and grayscale; the upstream preview, ranges, parity and Print Markup remain available, along with browser printing and PDF export. Remaining print parity includes driver-specific tray/options and pages-per-sheet UI; physical printer fidelity needs hardware validation. |
|
||||
| 2026-10-11 | trivial | Progress log: Windows DX12 shaders compiled with FXC (#603) |
|
||||
@@ -342,6 +539,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | trivial | Progress log: selection bar in the left margin (#856) |
|
||||
| 2026-10-11 | trivial | Progress log: content controls (#381) |
|
||||
| 2026-10-11 | trivial | Progress log: Insert › Chart (#409); catalog 408/439 (92.9%) |
|
||||
| 2026-10-13 | trivial | Progress log: free part, list and comment ids after a file's largest ones (#1338) |
|
||||
| 2026-10-11 | trivial | Progress log: Line Numbers, Hyphenation, Language, Envelopes and Labels dialogs (#407) |
|
||||
| 2026-10-11 | trivial | Progress log: Alt Text pane, decorative objects, deeper accessibility checker (#386) |
|
||||
| 2026-10-11 | trivial | Progress log: Draw lasso, Add Pen, Ink to Shape, Ink Replay (#395); catalog 406/434 |
|
||||
@@ -351,6 +549,8 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-11 | trivial | Quick Access Toolbar KeyTips and persisted enable/disable setting (#620) |
|
||||
| 2026-10-11 | trivial | Progress log: mail-merge recipients from .xlsx/.xlsm/.ods (#334) |
|
||||
| 2026-10-11 | trivial | Insert › Icons landed (#309): catalog 402/434 → 403/434 (92.9%) |
|
||||
| 2026-10-13 | trivial | Progress log: Markdown backtick runs read in linear time (#1336) |
|
||||
| 2026-10-13 | trivial | Progress log: Markdown brackets no longer turn later links into text (#1452) |
|
||||
| 2026-10-11 | trivial | Enclose Characters (#297): catalog 403/434 (92.9%) |
|
||||
| 2026-10-12 | minor | Progress log: opaque custom XML store preservation, with synthetic package regressions and explicit limits |
|
||||
| 2026-10-12 | minor | Preserve imported TOC ranges and retain #538 refresh/undo/save coverage on current main; readiness unchanged |
|
||||
@@ -360,17 +560,27 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | trivial | Native saves protect existing temporary-name entries and originals on pre-replacement failure; synthetic macOS evidence, explicit durability/platform limits; readiness unchanged |
|
||||
| 2026-10-11 | trivial | Word's common keyboard shortcuts (#330): 125 of ~250 |
|
||||
| 2026-10-11 | trivial | Collapsed duplicate rows left by parallel merges |
|
||||
| 2026-10-13 | trivial | Swedish interface (`sv`): progress log and shipped languages |
|
||||
| 2026-10-12 | trivial | Bulgarian interface (`bg`): progress log and shipped languages |
|
||||
| 2026-10-13 | trivial | Croatian interface (`hr`): progress log and shipped languages |
|
||||
| 2026-10-11 | trivial | Hungarian interface (`hu`): progress log and shipped languages |
|
||||
| 2026-10-11 | trivial | Turkish interface (`tr`): progress log and shipped languages |
|
||||
| 2026-10-14 | trivial | Progress log: `.doc` notes, headers and text boxes read their text once (#1319) |
|
||||
| 2026-10-12 | minor | Native drawing-level ink and its picture fallback survive DOCX edits and repeated saves; adapted to the current graphic writer; rendering and editing InkML remain missing |
|
||||
| 2026-10-12 | minor | List-label automatic/AtLeast line-height inflation corrected; gap #4 remains open and readiness unchanged |
|
||||
| 2026-10-12 | minor | Local desktop recovery: unsaved drafts and edits are snapshotted in the profile; File › Recover restores an unsaved copy or confirms discard. Full model storage includes media and opaque parts. Password sessions skip plaintext snapshots. See [recovery.md](docs/recovery.md); stability estimates remain unchanged. |
|
||||
| 2026-10-12 | trivial | Legacy table paragraph spacing preserved; modes 11/12/14 versus 15 checked with original synthetic documents |
|
||||
| 2026-10-11 | minor | Progress log: contextual paragraph spacing in body paragraphs and headers |
|
||||
| 2026-10-11 | trivial | Progress log: eight more bibliography styles (#383) |
|
||||
| 2026-10-14 | trivial | Progress log: ODT and `.doc` pictures read once, within their byte budget (#1334) |
|
||||
| 2026-10-10 | trivial | Progress log: Draw tab ink (#307) |
|
||||
| 2026-10-10 | trivial | Draw Table and Eraser (#303): catalog 393/431 (91.2%) |
|
||||
| 2026-10-10 | trivial | Progress log: charts, SmartArt and OLE objects kept on DOCX save (#319) |
|
||||
| 2026-10-10 | trivial | Progress log: contour wrap (#354) |
|
||||
| 2026-10-14 | trivial | Progress log: text boxes in deeply nested tables kept through edits (#1339) |
|
||||
| 2026-10-10 | trivial | Progress log: free rotation and flips (#332) |
|
||||
| 2026-10-10 | trivial | Progress log: Windows OpenGL fallback without a DirectX 12 driver (#316) |
|
||||
| 2026-10-14 | trivial | Progress log: Flat OPC reading bounded everywhere in the file, CDATA base64 read (#1353) |
|
||||
| 2026-10-10 | minor | Password-protected .docx (#281): files encrypted with a password (agile encryption) open and save; File › Info › Encrypt with Password |
|
||||
| 2026-10-10 | minor | Relanded clipboard pane, table styles editor, Manage Styles, Asian typography (kinsoku), Group/Ungroup and Shape Effects (#264 #263 #270 #271 #267 #280): catalog 390/431 (90.5%) |
|
||||
| 2026-10-10 | minor | Polish interface and proofing landed: Localization 25% → 27%, Proofing 35% → 40% |
|
||||
@@ -381,3 +591,4 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-10 | major | Full re-measure; restructured to the progress-docs standard (stage banner, two numbers, dimensions, languages, upcoming, progress log); parity tables moved to `docs/target-app-parity.md`, milestones to `docs/roadmap.md` |
|
||||
| 2026-10-09 | minor | Recently landed: RTL, Ukrainian and Brazilian Portuguese |
|
||||
| 2026-10-06 | major | First honest estimate: 88% catalog, ~62% real parity, alpha ~85% of the way |
|
||||
| 2026-10-12 | trivial | Progress log: recipient filter and sort, .xls and legacy-encoding recipient lists (#778) |
|
||||
|
||||
@@ -20,3 +20,4 @@ wordcraft-render = { workspace = true }
|
||||
wordcraft-mcp = { workspace = true }
|
||||
wordcraft-zotero = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
+353
-13
@@ -3,8 +3,10 @@
|
||||
|
||||
mod automation_args;
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fmt;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -42,16 +44,72 @@ USAGE:
|
||||
running): addEditCitation, addEditBibliography,
|
||||
addNote, refresh, removeCodes, setDocPrefs
|
||||
(--cmd runs first, e.g. --cmd caret.docEnd)
|
||||
wordcraft-cli [<command>] -h | --help this help
|
||||
wordcraft-cli --version
|
||||
|
||||
Paper: documents created here, and HTML, Markdown and text files (which give no page size), use
|
||||
the system region's paper (A4, or Letter in the US and other Letter regions), read from
|
||||
LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the
|
||||
same output on every machine.
|
||||
";
|
||||
|
||||
fn open(path: &str) -> Result<Session, String> {
|
||||
let doc = wordcraft_engine::io::open_path(std::path::Path::new(path))?;
|
||||
let mut s = Session::new(doc);
|
||||
/// The subcommands, in `USAGE` order; `--help` or `-h` after any of them prints `USAGE` (#968).
|
||||
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
|
||||
fn wants_help(cmd: &str, rest: &[String]) -> bool {
|
||||
SUBCOMMANDS.contains(&cmd) && rest.iter().any(|a| a == "--help" || a == "-h")
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> Result<Session, String> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, _) = wordcraft_engine::io::open_path_in(path, None, ®ion)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The commands that open a file, and which of their arguments not starting with `--` it is (as
|
||||
/// `pos` counts). `run` opens the value of `--file`.
|
||||
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("zotero", 1)];
|
||||
|
||||
/// The arguments as text. Only the file the command opens may have a name that isn't valid Unicode,
|
||||
/// such as a Latin-1 one (#1440): it comes back as the path to open, and lossy among the arguments.
|
||||
/// Any other such argument is an error naming it.
|
||||
fn text_args<S: AsRef<OsStr>>(raw: &[S]) -> Result<(Vec<String>, Option<PathBuf>), String> {
|
||||
let args: Vec<String> = raw.iter().map(|a| a.as_ref().to_string_lossy().into_owned()).collect();
|
||||
let cmd = args.first().map(String::as_str).unwrap_or("");
|
||||
let file_at = match OPENS_FILE.iter().find(|(c, _)| *c == cmd) {
|
||||
Some((_, n)) => args.iter().enumerate().skip(1).filter(|(_, a)| !a.starts_with("--")).nth(*n).map(|(i, _)| i),
|
||||
None if cmd == "run" => args.iter().position(|a| a == "--file").map(|i| i + 1),
|
||||
None => None,
|
||||
};
|
||||
let mut file = None;
|
||||
for (i, a) in raw.iter().map(AsRef::as_ref).enumerate() {
|
||||
if a.to_str().is_none() {
|
||||
if Some(i) != file_at {
|
||||
return Err(format!("argument {} is not valid Unicode: {}", i + 1, a.to_string_lossy()));
|
||||
}
|
||||
file = Some(PathBuf::from(a));
|
||||
}
|
||||
}
|
||||
Ok((args, file))
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
let mut s = Session::new(doc);
|
||||
s.system_region = system_region();
|
||||
s
|
||||
}
|
||||
|
||||
/// The system region, read as the app reads it (locale variables, else the platform's locale).
|
||||
fn system_region() -> wordcraft_engine::Region {
|
||||
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
|
||||
fn listed_text(doc: &wordcraft_doc::Document) -> Result<String, String> {
|
||||
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
|
||||
@@ -67,6 +125,58 @@ fn arg_value(args: &[String], name: &str) -> Option<String> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
|
||||
}
|
||||
|
||||
enum OptionArg<'a> {
|
||||
Absent,
|
||||
Duplicate,
|
||||
MissingValue,
|
||||
Value(&'a str),
|
||||
}
|
||||
|
||||
fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
|
||||
let mut matches = args.iter().enumerate().filter(|(_, a)| *a == name);
|
||||
let Some((i, _)) = matches.next() else {
|
||||
return OptionArg::Absent;
|
||||
};
|
||||
if matches.next().is_some() {
|
||||
return OptionArg::Duplicate;
|
||||
}
|
||||
match args.get(i + 1) {
|
||||
None => OptionArg::MissingValue,
|
||||
Some(val) if val.starts_with("--") => OptionArg::MissingValue,
|
||||
Some(val) => OptionArg::Value(val.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
|
||||
match find_option_arg(args, "--page") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
OptionArg::Duplicate => Err(format!("{command}: duplicate --page option")),
|
||||
OptionArg::MissingValue => Err(format!("{command}: --page requires a value")),
|
||||
OptionArg::Value(val) => {
|
||||
let n = val.parse::<u64>().map_err(|_| format!("{command}: invalid --page `{val}`: not a valid integer"))?;
|
||||
if n == 0 {
|
||||
return Err(format!("{command}: invalid --page `0`: page numbers start at 1"));
|
||||
}
|
||||
Ok(Some(n))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_scale_arg(command: &str, args: &[String]) -> Result<Option<f64>, String> {
|
||||
match find_option_arg(args, "--scale") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
OptionArg::Duplicate => Err(format!("{command}: duplicate --scale option")),
|
||||
OptionArg::MissingValue => Err(format!("{command}: --scale requires a value")),
|
||||
OptionArg::Value(val) => {
|
||||
let scale = val.parse::<f64>().map_err(|_| format!("{command}: invalid --scale `{val}`: not a number"))?;
|
||||
if !scale.is_finite() || scale <= 0.0 {
|
||||
return Err(format!("{command}: invalid --scale `{val}`: scale must be a positive number"));
|
||||
}
|
||||
Ok(Some(scale))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct OptionSpec {
|
||||
name: &'static str,
|
||||
@@ -181,9 +291,16 @@ fn write_stdout(write: impl FnOnce(&mut std::io::StdoutLock<'static>) -> std::io
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<(), Failure> {
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
let (args, file) = text_args(args)?;
|
||||
// Opens the file by its real name, which its text in `args` may have lost.
|
||||
let open = |text: &str| open(file.as_deref().unwrap_or(Path::new(text)));
|
||||
let cmd = args.first().map(String::as_str).unwrap_or("");
|
||||
let rest: Vec<String> = args.iter().skip(1).cloned().collect();
|
||||
// Before options are checked or files and folders opened.
|
||||
if wants_help(cmd, &rest) {
|
||||
return write_stdout(|o| write!(o, "{USAGE}"));
|
||||
}
|
||||
let pos = |i: usize| rest.iter().filter(|a| !a.starts_with("--")).nth(i).cloned().ok_or_else(|| format!("missing argument\n\n{USAGE}"));
|
||||
match cmd {
|
||||
"convert" => {
|
||||
@@ -234,22 +351,24 @@ fn run(args: &[String]) -> Result<(), Failure> {
|
||||
"render" => {
|
||||
validate_options("render", &rest, RENDER_OPTIONS)?;
|
||||
let (i, o) = (pos(0)?, pos(1)?);
|
||||
let page = parse_page_arg("render", &rest)?.unwrap_or(1);
|
||||
let scale = parse_scale_arg("render", &rest)?.unwrap_or(2.0);
|
||||
let mut s = open(&i)?;
|
||||
let page = arg_value(&rest, "--page").and_then(|p| p.parse::<u64>().ok()).unwrap_or(1);
|
||||
let scale = arg_value(&rest, "--scale").and_then(|p| p.parse::<f64>().ok()).unwrap_or(2.0);
|
||||
let r = s.run("file.exportPng", &json!({"path": o, "page": page, "scale": scale})).map_err(|e| e.to_string())?;
|
||||
write_stdout(|o| writeln!(o, "{r}"))
|
||||
}
|
||||
"run" => {
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
let mut s = match (arg_value(&rest, "--file"), arg_value(&rest, "--template")) {
|
||||
(Some(f), _) => open(&f)?,
|
||||
(None, Some(t)) => {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
s.run("file.new", &json!({"template": t})).map_err(|e| e.to_string())?;
|
||||
s
|
||||
}
|
||||
_ => Session::new(wordcraft_doc::Document::new()),
|
||||
_ => session(wordcraft_doc::Document::new()),
|
||||
};
|
||||
if let Some(name) = arg_value(&rest, "--author") {
|
||||
set_author(&mut s, &name)?;
|
||||
@@ -274,10 +393,10 @@ fn run(args: &[String]) -> Result<(), Failure> {
|
||||
if let Some(out) = arg_value(&rest, "--save") {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = arg_value(&rest, "--page").and_then(|p| p.parse::<u64>().ok()) {
|
||||
if let Some(n) = page {
|
||||
v["page"] = json!(n);
|
||||
}
|
||||
if let Some(k) = arg_value(&rest, "--scale").and_then(|p| p.parse::<f64>().ok()) {
|
||||
if let Some(k) = scale {
|
||||
v["scale"] = json!(k);
|
||||
}
|
||||
s.run("file.exportPng", &v)
|
||||
@@ -291,7 +410,7 @@ fn run(args: &[String]) -> Result<(), Failure> {
|
||||
}
|
||||
"commands" => {
|
||||
validate_options("commands", &rest, COMMANDS_OPTIONS)?;
|
||||
let s = Session::new(wordcraft_doc::Document::new());
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
if rest.iter().any(|a| a == "--json") {
|
||||
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
|
||||
write_stdout(|o| writeln!(o, "{list}"))
|
||||
@@ -306,7 +425,7 @@ fn run(args: &[String]) -> Result<(), Failure> {
|
||||
}
|
||||
"parity" => {
|
||||
validate_options("parity", &rest, PARITY_OPTIONS)?;
|
||||
let s = Session::new(wordcraft_doc::Document::new());
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
let p = wordcraft_engine::catalog::parity(&s.registry);
|
||||
if rest.iter().any(|a| a == "--markdown") {
|
||||
write_stdout(|o| write!(o, "{}", parity_markdown(&p)))
|
||||
@@ -437,7 +556,7 @@ fn parity_markdown(p: &Value) -> String {
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
|
||||
match run(&args) {
|
||||
Ok(()) | Err(Failure::StdoutClosed) => ExitCode::SUCCESS,
|
||||
Err(Failure::Error(e)) => {
|
||||
@@ -481,6 +600,26 @@ mod tests {
|
||||
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
|
||||
for cmd in SUBCOMMANDS {
|
||||
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
|
||||
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
|
||||
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
|
||||
}
|
||||
assert!(!wants_help("frobnicate", &args(&["--help"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_exactly_the_subcommands() {
|
||||
let listed: Vec<&str> = USAGE
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
|
||||
.filter(|word| !word.starts_with(['-', '[']))
|
||||
.collect();
|
||||
assert_eq!(listed, SUBCOMMANDS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_keeps_bullet_and_number_labels() {
|
||||
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
|
||||
@@ -547,10 +686,211 @@ mod tests {
|
||||
assert!(run(&args(&["mcp", "--automation-write-root", "/definitely/not/a/folder"])).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"caf\xe9.docx".to_vec());
|
||||
let ok = |raw: Vec<OsString>| text_args(&raw).unwrap().1;
|
||||
assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
|
||||
// Every command that opens a file reaches the open with it (no such file here), so
|
||||
// `OPENS_FILE` and the commands' own arguments agree.
|
||||
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
|
||||
.iter()
|
||||
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
|
||||
.collect();
|
||||
opening.push(vec!["run".into(), "--file".into(), missing()]);
|
||||
for raw in opening {
|
||||
let e = run(&raw).unwrap_err().to_string();
|
||||
assert!(e.contains("No such file"), "{raw:?}: {e}");
|
||||
}
|
||||
for (raw, n) in [
|
||||
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
|
||||
(vec!["render".into(), "in.docx".into(), latin1()], 3),
|
||||
(vec!["run".into(), "--save".into(), latin1()], 3),
|
||||
(vec!["commands".into(), latin1()], 2),
|
||||
] {
|
||||
assert_eq!(text_args(&raw).unwrap_err(), format!("argument {n} is not valid Unicode: caf\u{FFFD}.docx"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_roots_are_an_error_with_connect() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
let e = run(&args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir])).unwrap_err().to_string();
|
||||
assert!(e.contains("--automation-read-root") && e.contains("headless"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale"])), Err("render: --scale requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "--scale", "2"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "--page", "1"])), Err("render: --scale requires a value".into()));
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "banana"])),
|
||||
Err("render: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "banana"])),
|
||||
Err("render: invalid --scale `banana`: not a number".into())
|
||||
);
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "0"])),
|
||||
Err("render: invalid --page `0`: page numbers start at 1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])),
|
||||
Err("render: invalid --page `-1`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
|
||||
Err("render: invalid --scale `0`: scale must be a positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
|
||||
Err("render: invalid --scale `-2`: scale must be a positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
|
||||
Err("render: invalid --scale `NaN`: scale must be a positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
|
||||
Err("render: invalid --scale `inf`: scale must be a positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "1", "--page", "2"])), Err("render: duplicate --page option".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "1", "--scale", "2"])),
|
||||
Err("render: duplicate --scale option".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--page"])), Err("run: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale"])), Err("run: --scale requires a value".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "--scale", "2"])),
|
||||
Err("run: --page requires a value".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "--page", "1"])),
|
||||
Err("run: --scale requires a value".into())
|
||||
);
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "banana"])),
|
||||
Err("run: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "banana"])),
|
||||
Err("run: invalid --scale `banana`: not a number".into())
|
||||
);
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "0"])),
|
||||
Err("run: invalid --page `0`: page numbers start at 1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "-1"])),
|
||||
Err("run: invalid --page `-1`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
|
||||
Err("run: invalid --scale `-1`: scale must be a positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
|
||||
Err("run: invalid --scale `NaN`: scale must be a positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
|
||||
Err("run: invalid --scale `inf`: scale must be a positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "1", "--page", "2"])),
|
||||
Err("run: duplicate --page option".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "1", "--scale", "2"])),
|
||||
Err("run: duplicate --scale option".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_and_run_valid_options_and_defaults_produce_files() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-render-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
|
||||
let docx_path = dir.join("sample.docx");
|
||||
// Create sample docx via `run --save sample.docx`
|
||||
assert!(run(&args(&["run", "--template", "sample", "--save", &docx_path.to_string_lossy()])).is_ok());
|
||||
assert!(docx_path.exists());
|
||||
|
||||
let docx_str = docx_path.to_string_lossy().into_owned();
|
||||
|
||||
// 1. render with defaults
|
||||
let out_default = dir.join("out_default.png");
|
||||
assert!(run(&args(&["render", &docx_str, &out_default.to_string_lossy()])).is_ok());
|
||||
assert!(out_default.exists());
|
||||
|
||||
// 2. render with valid --page and --scale
|
||||
let out_valid = dir.join("out_valid.png");
|
||||
assert!(run(&args(&["render", &docx_str, &out_valid.to_string_lossy(), "--page", "1", "--scale", "2"])).is_ok());
|
||||
assert!(out_valid.exists());
|
||||
|
||||
// 3. render with different flag order
|
||||
let out_reordered = dir.join("out_reordered.png");
|
||||
assert!(run(&args(&["render", &docx_str, &out_reordered.to_string_lossy(), "--scale", "1", "--page", "1"])).is_ok());
|
||||
assert!(out_reordered.exists());
|
||||
|
||||
// 4. render failure leaves no output file
|
||||
let out_invalid = dir.join("out_invalid.png");
|
||||
assert!(run(&args(&["render", &docx_str, &out_invalid.to_string_lossy(), "--page", "banana"])).is_err());
|
||||
assert!(!out_invalid.exists());
|
||||
|
||||
// 5. run --save out.png with defaults
|
||||
let run_default = dir.join("run_default.png");
|
||||
assert!(run(&args(&["run", "--file", &docx_str, "--save", &run_default.to_string_lossy()])).is_ok());
|
||||
assert!(run_default.exists());
|
||||
|
||||
// 6. run --save out.png with --page and --scale
|
||||
let run_valid = dir.join("run_valid.png");
|
||||
assert!(run(&args(&["run", "--file", &docx_str, "--save", &run_valid.to_string_lossy(), "--page", "1", "--scale", "1"])).is_ok());
|
||||
assert!(run_valid.exists());
|
||||
|
||||
// 7. run --save out.png with different flag order
|
||||
let run_reordered = dir.join("run_reordered.png");
|
||||
assert!(run(&args(&["run", "--file", &docx_str, "--scale", "1", "--page", "1", "--save", &run_reordered.to_string_lossy()])).is_ok());
|
||||
assert!(run_reordered.exists());
|
||||
|
||||
// 8. run --save out.png failure leaves no output file
|
||||
let run_invalid = dir.join("run_invalid.png");
|
||||
assert!(run(&args(&["run", "--file", &docx_str, "--save", &run_invalid.to_string_lossy(), "--scale", "banana"])).is_err());
|
||||
assert!(!run_invalid.exists());
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! `wordcraft-cli convert page.html out.docx` puts an HTML file, which gives no page size, on the
|
||||
//! system region's paper, as the app does: A4 in Italy, Letter in the US (#1381).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const HTML: &str = "<html><body><h2>Premessa</h2><table border=1><thead><tr><th>Indicatore</th><th>Valore</th></tr></thead>\
|
||||
<tbody><tr><td>Audit</td><td style=\"text-align:right;\">4</td></tr></tbody></table></body></html>";
|
||||
|
||||
/// Run the CLI in `region` with `args` (`{src}` is the sample HTML, `{out}` a JSON file it
|
||||
/// writes) and read back the page size of the JSON it saved.
|
||||
fn page_size_of(region: &str, args: &[&str]) -> (f64, f64) {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-cli-region-{region}-{}-{}", args.len(), std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (src, out) = (dir.join("page.html"), dir.join("out.json"));
|
||||
std::fs::write(&src, HTML).unwrap();
|
||||
let args: Vec<String> = args.iter().map(|a| a.replace("{src}", &src.to_string_lossy()).replace("{out}", &out.to_string_lossy())).collect();
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(&args).env("WORDCRAFT_REGION", region).env_remove("LC_ALL").output().unwrap();
|
||||
assert!(run.status.success(), "{args:?}: {}", String::from_utf8_lossy(&run.stderr));
|
||||
let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let sp = &doc["lastSection"];
|
||||
(sp["pageW"].as_f64().unwrap(), sp["pageH"].as_f64().unwrap())
|
||||
}
|
||||
|
||||
/// Convert the sample to JSON in `region` and read back the page size.
|
||||
fn page_size(region: &str) -> (f64, f64) {
|
||||
page_size_of(region, &["convert", "{src}", "{out}"])
|
||||
}
|
||||
|
||||
fn is_a4((w, h): (f64, f64)) -> bool {
|
||||
(w - 595.28).abs() < 0.01 && (h - 841.89).abs() < 0.01
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_converts_onto_the_region_paper() {
|
||||
let (w, h) = page_size("it-IT");
|
||||
assert!(is_a4((w, h)), "A4 in Italy: {w} x {h}");
|
||||
assert_eq!(page_size("en-US"), (612.0, 792.0), "Letter in the US");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_run_session_follows_the_region() {
|
||||
// `run --file`, `run --template` and a bare `run` all start a session in the system region,
|
||||
// so `file.new` gives the same paper whichever way the session began.
|
||||
for args in [
|
||||
&["run", "--cmd", "file.new", "--save", "{out}"][..],
|
||||
&["run", "--template", "blank", "--save", "{out}"][..],
|
||||
&["run", "--file", "{src}", "--cmd", "file.new", "--save", "{out}"][..],
|
||||
] {
|
||||
assert!(is_a4(page_size_of("it-IT", args)), "A4 in Italy: {args:?} gave {:?}", page_size_of("it-IT", args));
|
||||
assert_eq!(page_size_of("en-US", args), (612.0, 792.0), "Letter in the US: {args:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! `--help` or `-h` after any subcommand prints the usage and exits 0, before options are checked
|
||||
//! or files and folders opened (#968).
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
|
||||
Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
fn assert_prints_usage(args: &[&str]) {
|
||||
let out = cli(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_subcommand_prints_usage_for_help_and_h() {
|
||||
assert_prints_usage(&["--help"]);
|
||||
assert_prints_usage(&["-h"]);
|
||||
for sub in SUBCOMMANDS {
|
||||
for flag in ["--help", "-h"] {
|
||||
assert_prints_usage(&[sub, flag]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_comes_before_opening_files_and_folders() {
|
||||
assert_prints_usage(&["info", "missing.docx", "--help"]);
|
||||
assert_prints_usage(&["convert", "missing.docx", "out.pdf", "-h"]);
|
||||
assert_prints_usage(&["mcp", "--automation-read-root", "/definitely/not/a/folder", "--help"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn misspelled_options_and_unknown_commands_still_fail() {
|
||||
let out = cli(&["info", "--hepl"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
|
||||
let out = cli(&["frobnicate", "--help"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! A file name that isn't valid Unicode (`caf\xe9.txt`, Latin-1) never panics the CLI (#1440): the
|
||||
//! file a command opens opens, and any other such argument is an error naming it. Not on macOS:
|
||||
//! APFS refuses file names that aren't valid UTF-8, so the fixture can't be made there.
|
||||
#![cfg(all(unix, not(target_os = "macos")))]
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[OsString]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A temp folder holding `caf\xe9.txt`, whose text is "Bonjour".
|
||||
fn folder(name: &str) -> (PathBuf, OsString) {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-non-utf8-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join(OsString::from_vec(b"caf\xe9.txt".to_vec()));
|
||||
std::fs::write(&file, "Bonjour\n").unwrap();
|
||||
(dir, file.into_os_string())
|
||||
}
|
||||
|
||||
fn ok(out: &Output) -> String {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status);
|
||||
String::from_utf8_lossy(&out.stdout).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_a_command_opens_may_have_any_name() {
|
||||
let (dir, file) = folder("open");
|
||||
assert_eq!(ok(&cli(&["text".into(), file.clone()])).trim(), "Bonjour");
|
||||
assert!(ok(&cli(&["info".into(), file.clone()])).contains("\"words\""));
|
||||
assert!(ok(&cli(&["inspect".into(), file.clone()])).contains("Bonjour"));
|
||||
|
||||
let md = dir.join("out.md");
|
||||
ok(&cli(&["convert".into(), file.clone(), md.clone().into()]));
|
||||
assert!(std::fs::read_to_string(&md).unwrap().contains("Bonjour"));
|
||||
|
||||
let saved = dir.join("run.txt");
|
||||
ok(&cli(&["run".into(), "--file".into(), file.clone(), "--save".into(), saved.clone().into()]));
|
||||
assert!(std::fs::read_to_string(&saved).unwrap().contains("Bonjour"));
|
||||
|
||||
// Saving without a path writes back to the file under its real name, not a lossy one.
|
||||
let mut args: Vec<OsString> = vec!["run".into(), "--file".into(), file.clone()];
|
||||
for cmd in ["caret.docEnd", "text.insert={\"text\":\" encore\"}", "file.save"] {
|
||||
args.extend(["--cmd".into(), cmd.into()]);
|
||||
}
|
||||
ok(&cli(&args));
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("encore"));
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 3, "a second file was written");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_other_such_argument_is_an_error_naming_it() {
|
||||
let (dir, file) = folder("error");
|
||||
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
|
||||
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
|
||||
for (args, n) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
|
||||
] {
|
||||
let out = cli(&args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let shown = args[n - 1].to_string_lossy();
|
||||
assert!(shown.contains('\u{FFFD}'));
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out_name).exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! `wordcraft-cli run`: a picture inserted by `--cmd insert.picture` stays in the saved file when
|
||||
//! the next commands type (#965).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// A 1x1 PNG.
|
||||
const PNG: &[u8] = &[
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0,
|
||||
0x1f, 0x00, 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn typing_after_insert_picture_keeps_it_in_the_saved_file() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-cli-965-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (pic, out) = (dir.join("pic.png"), dir.join("p.docx"));
|
||||
std::fs::write(&pic, PNG).unwrap();
|
||||
let picture = format!(r#"insert.picture={{"path":{},"width":250}}"#, serde_json::json!(pic.to_string_lossy()));
|
||||
let cmds = [r#"text.insert={"text":"x"}"#, "text.newParagraph", &picture, "text.newParagraph", r#"text.insert={"text":"cap"}"#];
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.args(["run", "--template", "blank"]);
|
||||
for c in cmds {
|
||||
cli.args(["--cmd", c]);
|
||||
}
|
||||
let run = cli.arg("--save").arg(&out).output().unwrap();
|
||||
let docx = std::fs::read(&out);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(run.status.success(), "stderr: {}", String::from_utf8_lossy(&run.stderr));
|
||||
assert!(docx.unwrap().windows(11).any(|w| w == b"word/media/"), "the saved file keeps the picture");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! #866: `wordcraft-cli text` omits tracked deletions (it does not go through `document.text`).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn cli() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_omits_tracked_deletions() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-866-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("t.docx");
|
||||
let path_s = path.to_str().unwrap();
|
||||
|
||||
let make = cli()
|
||||
.args([
|
||||
"run",
|
||||
"--save",
|
||||
path_s,
|
||||
"--cmd",
|
||||
r#"text.insert={"text":"Signed by Alice Smith, Partner."}"#,
|
||||
"--cmd",
|
||||
r#"review.trackChanges={"value":true}"#,
|
||||
"--cmd",
|
||||
r#"select.text={"text":"Alice Smith, Partner"}"#,
|
||||
"--cmd",
|
||||
r#"text.insert={"text":"Bob Jones, Director"}"#,
|
||||
])
|
||||
.output()
|
||||
.expect("run");
|
||||
assert!(make.status.success(), "run failed: {}", String::from_utf8_lossy(&make.stderr));
|
||||
|
||||
let out = cli().args(["text", path_s]).output().expect("text");
|
||||
assert!(out.status.success(), "text failed: {}", String::from_utf8_lossy(&out.stderr));
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert_eq!(stdout.trim_end(), "Signed by Bob Jones, Director.");
|
||||
assert!(!stdout.contains("Alice Smith"), "{stdout}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
+136
-55
@@ -6,11 +6,12 @@ use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_ui_egui::async_saves::{AsyncSaves, SaveOutcome};
|
||||
use wordcraft_ui_egui::{Inbox, Services, WordApp};
|
||||
|
||||
const DOC_EXTS: &[&str] = &["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "rtf", "txt", "md", "html", "htm", "tex", "json", "xml"];
|
||||
const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
|
||||
const RECIPIENT_EXTS: &[&str] = &["csv", "tsv", "txt", "xlsx", "xlsm", "ods"];
|
||||
const RECIPIENT_EXTS: &[&str] = wordcraft_engine::cmd::mailings::RECIPIENT_EXTENSIONS;
|
||||
mod font_store;
|
||||
const CANVAS_ID: &str = "wordcraft_canvas";
|
||||
const LOADING_ID: &str = "wordcraft_loading";
|
||||
@@ -27,7 +28,7 @@ pub fn start() {
|
||||
return;
|
||||
};
|
||||
let dirty = Rc::new(Cell::new(false));
|
||||
let saves = Rc::new(PickerSaves::default());
|
||||
let saves = AsyncSaves::default();
|
||||
if let Err(e) = guard_unload(dirty.clone(), saves.clone()) {
|
||||
log::error!("no unsaved-changes guard: {e}");
|
||||
}
|
||||
@@ -48,7 +49,8 @@ pub fn start() {
|
||||
// Fonts the user added on an earlier visit (#582); the app notices them arrive.
|
||||
font_store::load_all(cc.egui_ctx.clone());
|
||||
let inbox: Inbox = Inbox::default();
|
||||
if let Err(e) = listen_for_pasted_pictures(inbox.clone(), cc.egui_ctx.clone()) {
|
||||
let pasted: Inbox = Inbox::default();
|
||||
if let Err(e) = listen_for_pasted_pictures(pasted.clone(), cc.egui_ctx.clone()) {
|
||||
log::error!("pasting pictures is unavailable: {e}");
|
||||
}
|
||||
// The browser's locale picks the new document's paper, the units and the
|
||||
@@ -58,13 +60,16 @@ pub fn start() {
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
let mut app = WordApp::new(session, services(inbox.clone(), cc.egui_ctx.clone(), dirty, saves.clone()));
|
||||
let messages = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut app = WordApp::new(session, services(inbox.clone(), cc.egui_ctx.clone(), dirty, saves.clone(), messages.clone()));
|
||||
// Pasted pictures wait apart from dropped files: the app inserts one only when the page is the edit target (#1349).
|
||||
app.services.pasted = Some(pasted);
|
||||
app.autosave = false;
|
||||
// No document to show: start on File › Home, as the desktop app does (#766).
|
||||
if !sample {
|
||||
app.start_screen();
|
||||
}
|
||||
Ok(Box::new(WebShell { app, inbox, saves }))
|
||||
Ok(Box::new(WebShell { app, inbox, messages }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -86,38 +91,7 @@ fn query() -> String {
|
||||
struct WebShell {
|
||||
app: WordApp,
|
||||
inbox: Inbox,
|
||||
saves: Rc<PickerSaves>,
|
||||
}
|
||||
|
||||
/// Saves the browser's save picker finishes after `download` has returned (#728). The app marks
|
||||
/// the document saved as soon as `download` returns, so a cancelled or failed picker save must
|
||||
/// mark it unsaved again, and the `beforeunload` guard keeps warning while one is in flight.
|
||||
#[derive(Default)]
|
||||
struct PickerSaves {
|
||||
/// Picker saves started and not yet written and closed.
|
||||
pending: Cell<u32>,
|
||||
/// Picker saves that didn't write the file: (name, error, or `None` when cancelled).
|
||||
unsaved: RefCell<Vec<(String, Option<String>)>>,
|
||||
}
|
||||
|
||||
impl WebShell {
|
||||
/// A picker save that didn't happen leaves the document with unsaved changes.
|
||||
fn settle_picker_saves(&mut self) {
|
||||
let unsaved = std::mem::take(&mut *self.saves.unsaved.borrow_mut());
|
||||
for (name, error) in unsaved {
|
||||
// Only a save in a format that keeps everything marked the document saved.
|
||||
if wordcraft_ui_egui::keeps_everything(&name) {
|
||||
self.app.session.dirty = true;
|
||||
}
|
||||
if let Some(error) = error {
|
||||
let msg = wordcraft_ui_egui::i18n::fmt(
|
||||
wordcraft_ui_egui::i18n::t("Couldn't download {name}: {error}"),
|
||||
&[("name", &name), ("error", &error)],
|
||||
);
|
||||
self.app.status(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
messages: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
@@ -137,7 +111,10 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
});
|
||||
}
|
||||
self.settle_picker_saves();
|
||||
let msgs = std::mem::take(&mut *self.messages.borrow_mut());
|
||||
for msg in msgs {
|
||||
self.app.status(msg);
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
}
|
||||
|
||||
@@ -157,10 +134,11 @@ const MAX_PASTED_PICTURES: u32 = 20;
|
||||
|
||||
/// Pasting a picture (#45): eframe's paste handler only reads text, so a clipboard holding just
|
||||
/// pictures (a screenshot, a browser's Copy Image) is read here and the pictures arrive through
|
||||
/// the inbox like dropped ones. A clipboard with text is left to eframe.
|
||||
/// the app's `pasted` queue, which inserts them only when the page is the edit target (#1349). A clipboard with text is left to eframe.
|
||||
fn listen_for_pasted_pictures(inbox: Inbox, ctx: egui::Context) -> Result<(), String> {
|
||||
let document = web_sys::window().and_then(|w| w.document()).ok_or("no document")?;
|
||||
let on_paste = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::ClipboardEvent)>::new(move |e: web_sys::ClipboardEvent| {
|
||||
// The target is always eframe's hidden text input while the page has focus; the app decides (#1349).
|
||||
let Some(data) = e.clipboard_data() else { return };
|
||||
if !data.get_data("text").unwrap_or_default().is_empty() {
|
||||
return;
|
||||
@@ -181,7 +159,7 @@ fn listen_for_pasted_pictures(inbox: Inbox, ctx: egui::Context) -> Result<(), St
|
||||
match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
|
||||
Ok(buf) => {
|
||||
let bytes = js_sys::Uint8Array::new(&buf).to_vec();
|
||||
// The inbox inserts files named like pictures; the engine reads the format from the bytes.
|
||||
// The engine reads the format from the bytes; the name is ignored.
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(("pasted.png".into(), bytes));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
@@ -197,9 +175,11 @@ fn listen_for_pasted_pictures(inbox: Inbox, ctx: egui::Context) -> Result<(), St
|
||||
}
|
||||
|
||||
/// `dirty` is the flag the `beforeunload` guard reads ([`guard_unload`]).
|
||||
fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: Rc<PickerSaves>) -> Services {
|
||||
fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: AsyncSaves, messages: Rc<RefCell<Vec<String>>>) -> Services {
|
||||
let open_inbox = inbox.clone();
|
||||
let save_ctx = ctx.clone();
|
||||
let font_ctx = ctx.clone();
|
||||
let font_messages = messages.clone();
|
||||
Services {
|
||||
open_async: Some(Box::new(move |purpose: &str| {
|
||||
let inbox = open_inbox.clone();
|
||||
@@ -224,6 +204,7 @@ fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: Rc<P
|
||||
})),
|
||||
// Exports ask for a name; the browser decides where the download goes.
|
||||
pick_save: Some(Box::new(|name: &str| Some(name.to_string()))),
|
||||
async_saves: Some(saves.clone()),
|
||||
download: Some(Box::new(move |path: &str, bytes: &[u8]| download(&saves, &save_ctx, path, bytes))),
|
||||
print: Some(Box::new(print_pdf)),
|
||||
inbox: Some(inbox),
|
||||
@@ -231,10 +212,112 @@ fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: Rc<P
|
||||
animations_enabled: Some(animations_enabled()),
|
||||
store_font: Some(Box::new(font_store::store)),
|
||||
forget_font: Some(Box::new(font_store::forget)),
|
||||
load_system_fonts: Some(Box::new(move || {
|
||||
load_system_fonts(font_ctx.clone(), font_messages.clone());
|
||||
})),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Most local fonts one Load System Installed Fonts installs (a designer's machine has thousands).
|
||||
const MAX_SYSTEM_FONTS: usize = 500;
|
||||
/// Most font bytes one Load System Installed Fonts reads into memory (wasm memory is small).
|
||||
const MAX_SYSTEM_FONT_BYTES: usize = 256 << 20;
|
||||
/// Most local fonts looked at, installed or not (already available, unreadable, too big).
|
||||
const MAX_SYSTEM_FONTS_TRIED: u32 = 4000;
|
||||
|
||||
/// Query the browser's Local Font Access API (`window.queryLocalFonts()`) and install the faces
|
||||
/// into the global font database, up to [`MAX_SYSTEM_FONTS`] faces and [`MAX_SYSTEM_FONT_BYTES`].
|
||||
fn load_system_fonts(ctx: egui::Context, messages: Rc<RefCell<Vec<String>>>) {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let Some(window) = web_sys::window() else {
|
||||
return;
|
||||
};
|
||||
let query_fn = match js_sys::Reflect::get(&window, &wasm_bindgen::JsValue::from_str("queryLocalFonts")) {
|
||||
Ok(val) if val.is_function() => js_sys::Function::from(val),
|
||||
_ => {
|
||||
messages.borrow_mut().push(wordcraft_ui_egui::i18n::t("Local font access is not supported by your browser.").to_string());
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let fonts_promise = match query_fn.call0(&window) {
|
||||
Ok(p) => js_sys::Promise::from(p),
|
||||
Err(e) => {
|
||||
log::warn!("queryLocalFonts call failed: {e:?}");
|
||||
messages.borrow_mut().push(wordcraft_ui_egui::i18n::t("Local font access was denied.").to_string());
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let fonts_val = match wasm_bindgen_futures::JsFuture::from(fonts_promise).await {
|
||||
Ok(val) => val,
|
||||
Err(e) => {
|
||||
log::warn!("queryLocalFonts promise rejected: {e:?}");
|
||||
messages.borrow_mut().push(wordcraft_ui_egui::i18n::t("Local font access was denied.").to_string());
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let font_list = js_sys::Array::from(&fonts_val);
|
||||
let len = font_list.length();
|
||||
let mut loaded = 0usize;
|
||||
let mut total_bytes = 0usize;
|
||||
for i in 0..len.min(MAX_SYSTEM_FONTS_TRIED) {
|
||||
if loaded >= MAX_SYSTEM_FONTS || total_bytes >= MAX_SYSTEM_FONT_BYTES {
|
||||
log::warn!("local fonts: stopped after {loaded} fonts ({total_bytes} bytes)");
|
||||
break;
|
||||
}
|
||||
let font_data = font_list.get(i);
|
||||
let Ok(blob_fn) = js_sys::Reflect::get(&font_data, &wasm_bindgen::JsValue::from_str("blob")) else {
|
||||
continue;
|
||||
};
|
||||
if !blob_fn.is_function() {
|
||||
continue;
|
||||
}
|
||||
let Ok(blob_val) = js_sys::Function::from(blob_fn).call0(&font_data) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(blob_js) = wasm_bindgen_futures::JsFuture::from(js_sys::Promise::from(blob_val)).await else {
|
||||
continue;
|
||||
};
|
||||
let Ok(blob) = blob_js.dyn_into::<web_sys::Blob>() else {
|
||||
continue;
|
||||
};
|
||||
// Skip a face too big on its own or for what is left of the budget, before reading it.
|
||||
let size = blob.size().clamp(0.0, usize::MAX as f64) as usize;
|
||||
if size > wordcraft_fonts::MAX_FONT_FILE_BYTES || total_bytes.saturating_add(size) > MAX_SYSTEM_FONT_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(array_buffer) = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await else {
|
||||
continue;
|
||||
};
|
||||
let bytes = js_sys::Uint8Array::new(&array_buffer).to_vec();
|
||||
if bytes.len() > wordcraft_fonts::MAX_FONT_FILE_BYTES {
|
||||
continue;
|
||||
}
|
||||
total_bytes = total_bytes.saturating_add(bytes.len());
|
||||
let ps_name = js_sys::Reflect::get(&font_data, &wasm_bindgen::JsValue::from_str("postscriptName"))
|
||||
.ok()
|
||||
.and_then(|v| v.as_string())
|
||||
.unwrap_or_else(|| format!("local-font-{i}"));
|
||||
let name = format!("{ps_name}.ttf");
|
||||
match wordcraft_fonts::FontDb::global().install_font(&name, &bytes) {
|
||||
Ok(_) => loaded += 1,
|
||||
Err(wordcraft_fonts::UserFontError::AlreadyAvailable(_)) => {}
|
||||
Err(e) => log::warn!("local font {name} skipped: {e}"),
|
||||
}
|
||||
}
|
||||
if loaded > 0 {
|
||||
let msg = wordcraft_ui_egui::i18n::fmt(wordcraft_ui_egui::i18n::t("Loaded {count} system fonts."), &[("count", &loaded.to_string())]);
|
||||
messages.borrow_mut().push(msg);
|
||||
} else {
|
||||
messages.borrow_mut().push(wordcraft_ui_egui::i18n::t("All system fonts are already available.").to_string());
|
||||
}
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the system has animation effects on, as the browser passes it on: off while the
|
||||
/// `prefers-reduced-motion: reduce` media query matches. `None` when the browser can't say. The
|
||||
/// query is made once and asked every frame; it follows the system's setting by itself.
|
||||
@@ -245,11 +328,11 @@ fn animations_enabled() -> Box<dyn Fn() -> Option<bool>> {
|
||||
|
||||
/// Closing, reloading or leaving the tab with unsaved changes asks first. Browsers show their own
|
||||
/// confirmation (a page can only ask for it), so there is no Save button: Cancel, then File › Save.
|
||||
fn guard_unload(dirty: Rc<Cell<bool>>, saves: Rc<PickerSaves>) -> Result<(), String> {
|
||||
fn guard_unload(dirty: Rc<Cell<bool>>, saves: AsyncSaves) -> Result<(), String> {
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let on_unload = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
|
||||
// A save still in the browser's picker hasn't written anything yet.
|
||||
if dirty.get() || saves.pending.get() > 0 {
|
||||
if dirty.get() || saves.pending() > 0 {
|
||||
e.prevent_default();
|
||||
// Older browsers ask only when `returnValue` is set.
|
||||
e.set_return_value("unsaved changes");
|
||||
@@ -262,7 +345,7 @@ fn guard_unload(dirty: Rc<Cell<bool>>, saves: Rc<PickerSaves>) -> Result<(), Str
|
||||
}
|
||||
|
||||
/// Trigger a browser save dialog or download of `bytes` named after the last component of `path`.
|
||||
fn download(saves: &Rc<PickerSaves>, ctx: &egui::Context, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
fn download(saves: &AsyncSaves, ctx: &egui::Context, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "document".into());
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
|
||||
@@ -284,7 +367,7 @@ fn download(saves: &Rc<PickerSaves>, ctx: &egui::Context, path: &str, bytes: &[u
|
||||
}
|
||||
|
||||
fn trigger_save_file_picker(
|
||||
saves: &Rc<PickerSaves>,
|
||||
saves: &AsyncSaves,
|
||||
ctx: &egui::Context,
|
||||
window: &web_sys::Window,
|
||||
picker_fn: &js_sys::Function,
|
||||
@@ -328,18 +411,19 @@ fn trigger_save_file_picker(
|
||||
let saves = saves.clone();
|
||||
let ctx = ctx.clone();
|
||||
let name = name.to_string();
|
||||
saves.pending.set(saves.pending.get().saturating_add(1));
|
||||
// The app holds back a Save Changes prompt's New/Open until this ticket ends (#1315).
|
||||
let ticket = saves.start();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// The document counts as saved only once the file is written and closed.
|
||||
let unsaved = match wasm_bindgen_futures::JsFuture::from(prom).await {
|
||||
let outcome = match wasm_bindgen_futures::JsFuture::from(prom).await {
|
||||
Ok(handle_val) => match write_file_handle(&handle_val, &bytes_vec).await {
|
||||
Ok(()) => {
|
||||
log::info!("saved {name} through the save picker");
|
||||
None
|
||||
SaveOutcome::Saved
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("couldn't write {name}: {e}");
|
||||
Some(Some(e))
|
||||
SaveOutcome::Failed(e)
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
@@ -347,17 +431,14 @@ fn trigger_save_file_picker(
|
||||
js_sys::Reflect::get(&e, &wasm_bindgen::JsValue::from_str("name")).ok().and_then(|v| v.as_string()).unwrap_or_default();
|
||||
if err_name == "AbortError" {
|
||||
log::debug!("save picker cancelled");
|
||||
Some(None)
|
||||
SaveOutcome::Cancelled
|
||||
} else {
|
||||
log::error!("showSaveFilePicker error: {e:?}");
|
||||
Some(Some(format!("{e:?}")))
|
||||
SaveOutcome::Failed(format!("{e:?}"))
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(error) = unsaved {
|
||||
saves.unsaved.borrow_mut().push((name, error));
|
||||
}
|
||||
saves.pending.set(saves.pending.get().saturating_sub(1));
|
||||
saves.finish(ticket, outcome);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
Ok(())
|
||||
|
||||
@@ -36,7 +36,7 @@ async fn open() -> Result<IdbDatabase, String> {
|
||||
let req = factory.open_with_u32(DB_NAME, 1).map_err(js)?;
|
||||
let upgrade_req = req.clone();
|
||||
let upgrade = Closure::<dyn FnMut()>::new(move || {
|
||||
if let Ok(db) = upgrade_req.result().and_then(|r| r.dyn_into::<IdbDatabase>().map_err(JsValue::from))
|
||||
if let Ok(db) = upgrade_req.result().and_then(|r| r.dyn_into::<IdbDatabase>())
|
||||
&& !db.object_store_names().contains(STORE)
|
||||
&& let Err(e) = db.create_object_store(STORE)
|
||||
{
|
||||
|
||||
@@ -36,8 +36,9 @@ winresource = "0.1"
|
||||
fmv-macos-events = "=0.1.0"
|
||||
# The system's Reduce motion setting (System Settings › Accessibility › Display), read through
|
||||
# NSWorkspace: a safe call in these bindings. Already in the build through eframe, rfd and arboard,
|
||||
# at this version; this adds only the `NSAccessibility` bindings.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication"] }
|
||||
# at this version; this adds the `NSAccessibility` bindings and, to fit the title bar around the
|
||||
# traffic lights, the window, button and view ones.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication", "NSWindow", "NSButton", "NSControl", "NSView", "NSResponder"] }
|
||||
objc2 = "0.6"
|
||||
# Closing the window must quit through NSApplication rather than by dropping the NSWindow
|
||||
# inside the AppKit run loop (see `schedule_macos_terminate`).
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
//!
|
||||
//! Everything read here comes from other programs: sizes are capped as it is read.
|
||||
//!
|
||||
//! Written here: a copy holding an equation puts HTML (the equation as MathML) beside its text
|
||||
//! (#816), for programs that read MathML (pasting into Word and LibreOffice not yet verified). arboard sets HTML with a
|
||||
//! Written here: a copy puts HTML beside its text, so other programs keep its formatting (#1523),
|
||||
//! with equations as MathML (#816; pasting into Word and LibreOffice not yet verified). arboard sets HTML with a
|
||||
//! text alternative on every desktop platform; formats of other names (Word's "Office Open XML"
|
||||
//! with OMML, #1297) it can't, so they aren't offered.
|
||||
|
||||
|
||||
@@ -484,7 +484,16 @@ mod tests {
|
||||
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "no key file after a failed bind");
|
||||
drop(taken);
|
||||
// Bound: the key file holds the key that opens the port.
|
||||
let (rx, key_file) = start(port, egui::Context::default(), Some(&dir)).unwrap();
|
||||
let mut free_port = port.wrapping_add(1).max(1024);
|
||||
let mut started = None;
|
||||
for _ in 0..100 {
|
||||
if let Some(res) = start(free_port, egui::Context::default(), Some(&dir)) {
|
||||
started = Some((res, free_port));
|
||||
break;
|
||||
}
|
||||
free_port = free_port.wrapping_add(1).max(1024);
|
||||
}
|
||||
let ((rx, key_file), port) = started.unwrap();
|
||||
let key_file = key_file.unwrap();
|
||||
assert_eq!(key_file.path(), wordcraft_control_key::key_path(&dir, port));
|
||||
let key = std::fs::read_to_string(key_file.path()).unwrap();
|
||||
|
||||
@@ -58,8 +58,11 @@ impl Launcher {
|
||||
let picking: Picking = match req {
|
||||
FileDialogRequest::Open { purpose } => Box::pin(open_filters(dialog, &purpose).pick_file()),
|
||||
FileDialogRequest::Save { name } => {
|
||||
let exts = save_exts(&name);
|
||||
Box::pin(dialog.set_file_name(name).add_filter("Documents", &exts).save_file())
|
||||
let mut dialog = dialog.set_file_name(name.clone());
|
||||
for (label, exts) in save_filters(&name) {
|
||||
dialog = dialog.add_filter(label, &exts);
|
||||
}
|
||||
Box::pin(dialog.save_file())
|
||||
}
|
||||
};
|
||||
let ctx = self.ctx.clone();
|
||||
@@ -158,9 +161,60 @@ fn save_exts(name: &str) -> Vec<String> {
|
||||
exts
|
||||
}
|
||||
|
||||
/// The "Save as type" list (#1399): one named entry per format, the suggested one first (see
|
||||
/// [`save_exts`] for why the order matters).
|
||||
///
|
||||
/// rfd doesn't report which entry the user picked, so if they choose "PDF" but leave "name.docx"
|
||||
/// in the name box, the extension in the name wins, as the format is chosen by extension.
|
||||
fn save_filters(name: &str) -> Vec<(String, Vec<String>)> {
|
||||
save_exts(name).into_iter().map(|e| (format!("{} (*.{e})", format_name(&e)), vec![e])).collect()
|
||||
}
|
||||
|
||||
/// A readable name for a save format's extension.
|
||||
fn format_name(ext: &str) -> String {
|
||||
match ext {
|
||||
"docx" => "Word Document".into(),
|
||||
"docm" => "Word Macro-Enabled Document".into(),
|
||||
"dotx" => "Word Template".into(),
|
||||
"dotm" => "Word Macro-Enabled Template".into(),
|
||||
"pdf" => "PDF".into(),
|
||||
"txt" => "Plain Text".into(),
|
||||
"md" => "Markdown".into(),
|
||||
"html" => "Web Page".into(),
|
||||
"rtf" => "Rich Text Format".into(),
|
||||
"odt" => "OpenDocument Text".into(),
|
||||
"tex" => "LaTeX".into(),
|
||||
"png" => "PNG Image".into(),
|
||||
"json" => "JSON".into(),
|
||||
"xml" => "XML".into(),
|
||||
other => other.to_ascii_uppercase(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::save_exts;
|
||||
use super::{save_exts, save_filters};
|
||||
|
||||
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
|
||||
/// every savable extension exactly once.
|
||||
#[test]
|
||||
fn save_dialog_lists_one_named_type_per_format() {
|
||||
let filters = save_filters("report.odt");
|
||||
assert_eq!(filters.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
assert_eq!(filters[0].1, vec!["odt".to_string()]);
|
||||
assert!(filters[0].0.contains("OpenDocument"), "{}", filters[0].0);
|
||||
let all: Vec<&String> = filters.iter().flat_map(|(_, e)| e).collect();
|
||||
for e in wordcraft_engine::io::SAVE_EXTS {
|
||||
assert_eq!(all.iter().filter(|x| x.as_str() == *e).count(), 1, "{e}");
|
||||
}
|
||||
assert!(filters.iter().all(|(l, e)| !l.trim().is_empty() && e.len() == 1));
|
||||
let mut labels: Vec<&String> = filters.iter().map(|(l, _)| l).collect();
|
||||
labels.sort();
|
||||
labels.dedup();
|
||||
assert_eq!(labels.len(), filters.len(), "labels are distinct");
|
||||
// Unknown names fall back to Word's format first.
|
||||
assert_eq!(save_filters("no extension")[0].1, vec!["docx".to_string()]);
|
||||
}
|
||||
|
||||
/// #689: the Save dialog's default extension is the suggested name's own format, so a file
|
||||
/// name the user types without one is saved in the document's format instead of coming back
|
||||
|
||||
+184
-12
@@ -1,6 +1,6 @@
|
||||
//! WordCraft desktop app.
|
||||
//!
|
||||
//! Usage: `wordcraft [--control <port>] [--sample] [files…]`
|
||||
//! Usage: `wordcraft [--control <port>] [--sample] [files…]`; `--help` prints `USAGE`.
|
||||
//!
|
||||
//! `--control <port>` (or `WORDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
|
||||
//! `{"id":1,"key":"…","method":"engine.execute","params":{"command":"text.insert","params":{"text":"Hi"}}}`.
|
||||
@@ -21,6 +21,8 @@ mod graphics;
|
||||
mod logging;
|
||||
mod print;
|
||||
mod region;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod traffic_lights;
|
||||
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_ui_egui::{
|
||||
@@ -28,9 +30,9 @@ use wordcraft_ui_egui::{
|
||||
window_geometry::{WindowGeometry, take_rescue},
|
||||
};
|
||||
|
||||
/// The app, the restored window geometry until the first frame has checked it, the control
|
||||
/// server's key file (removed on exit), the file dialogs the app asked for and, on macOS, the
|
||||
/// documents opened from Finder.
|
||||
/// The app, the restored window geometry (or, with none, the default: no position) until the
|
||||
/// first frame that knows the monitor has checked it, the control server's key file (removed on
|
||||
/// exit), the file dialogs the app asked for and, on macOS, the documents opened from Finder.
|
||||
struct App(
|
||||
WordApp,
|
||||
Option<WindowGeometry>,
|
||||
@@ -45,11 +47,24 @@ impl eframe::App for App {
|
||||
apple_events::poll(&self.4, &mut self.0, ctx);
|
||||
self.0.logic(ctx);
|
||||
self.3.show(frame);
|
||||
// A window that doesn't fit on its screen (the default size on a laptop) shrinks to fit
|
||||
// there, so all of the scroll bar can be dragged (#1215). Checked on the frame that first
|
||||
// knows the monitor: the off-screen check below takes the pending geometry then.
|
||||
if let Some((pos, size)) = ctx.input(|i| self.1.and_then(|g| g.fit_on_monitor(i.viewport()))) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(pos));
|
||||
}
|
||||
let prev = self.0.ui.window;
|
||||
self.0.ui.window = ctx.input(|i| WindowGeometry::track(prev, i.viewport(), i.viewport_rect().size()));
|
||||
// The first frame, once the monitor is known (as `take_rescue` waits for): maximize a
|
||||
// window that opened at its normal size so it never flashed on screen half-opened.
|
||||
let maximize = self.1.and_then(|g| g.maximize_after_open()).filter(|_| ctx.input(|i| i.viewport().monitor_size.is_some()));
|
||||
if let Some(pos) = ctx.input(|i| take_rescue(&mut self.1, i.viewport())) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(pos));
|
||||
}
|
||||
if let Some(command) = maximize {
|
||||
ctx.send_viewport_cmd(command);
|
||||
}
|
||||
// The window's close button: with unsaved changes, ask first (`WordApp::close_requested`).
|
||||
let closing = ctx.input(|i| i.viewport().close_requested());
|
||||
if closing && !self.0.close_requested() {
|
||||
@@ -189,15 +204,35 @@ fn save_prefs(app: &WordApp) {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = prefs_path() {
|
||||
if let Some(dir) = p.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
if let Some(dir) = p.parent()
|
||||
&& let Err(e) = std::fs::create_dir_all(dir)
|
||||
{
|
||||
log::warn!("preferences: cannot create {}: {e}", dir.display());
|
||||
return;
|
||||
}
|
||||
if let Ok(bytes) = serde_json::to_vec_pretty(&app.prefs()) {
|
||||
let _ = std::fs::write(&p, bytes);
|
||||
match serde_json::to_vec_pretty(&app.prefs()) {
|
||||
Ok(bytes) => {
|
||||
if let Err(e) = write_prefs(&p, &bytes) {
|
||||
log::warn!("preferences: cannot save {}: {e}", p.display());
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("preferences: cannot serialize: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a sibling temporary file and renames it over `path`, so a failed or
|
||||
/// interrupted write leaves the previous preferences in place.
|
||||
fn write_prefs(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into());
|
||||
let tmp = path.with_file_name(format!(".{name}.{}.tmp", std::process::id()));
|
||||
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path));
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
/// Native file dialogs, shown without blocking the window (`file_dialogs`, #94), File › Print
|
||||
/// through the system spooler (`print`), the system clipboard's text, formatted copies,
|
||||
/// pictures and format names (`clipboard`, #45, #584, #687, #833), the system's animation setting
|
||||
@@ -228,11 +263,59 @@ fn app_icon() -> Option<egui::IconData> {
|
||||
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
|
||||
}
|
||||
|
||||
const USAGE: &str = "\
|
||||
wordcraft — the WordCraft desktop app
|
||||
|
||||
USAGE:
|
||||
wordcraft [--sample] [--control PORT] [FILE…]
|
||||
|
||||
OPTIONS:
|
||||
--sample open the sample document
|
||||
--control PORT start the localhost control server on PORT, for agents and scripts
|
||||
(or set WORDCRAFT_CONTROL_PORT); see docs/control-protocol.md
|
||||
--version print the version
|
||||
-h, --help print this help
|
||||
";
|
||||
|
||||
/// The commit the build came from (short), or `dev`.
|
||||
fn build_sha() -> &'static str {
|
||||
option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or("dev")
|
||||
}
|
||||
|
||||
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
|
||||
/// one (#1440). A `--control` port that isn't is an error.
|
||||
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
|
||||
let (mut args, mut files) = (Vec::new(), Vec::new());
|
||||
for (i, a) in std::env::args_os().skip(1).enumerate() {
|
||||
match a.into_string() {
|
||||
Ok(a) => args.push(a),
|
||||
Err(a) if args.last().is_some_and(|p| p == "--control") => {
|
||||
// Unlike `eprintln!`, never panics.
|
||||
let (n, lossy) = (i + 1, a.to_string_lossy());
|
||||
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: argument {n} is not valid Unicode: {lossy}\n"));
|
||||
std::process::exit(2);
|
||||
}
|
||||
Err(a) => files.push(a.into()),
|
||||
}
|
||||
}
|
||||
(args, files)
|
||||
}
|
||||
|
||||
/// Open a file whose name isn't valid Unicode (#1440). `file.open` takes its path as text, so it
|
||||
/// gets the file's bytes under the lossy name, and the document then keeps the real path to save to.
|
||||
fn open_non_unicode(app: &mut WordApp, path: &std::path::Path) {
|
||||
let name = path.to_string_lossy();
|
||||
let opened = std::fs::read(path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|bytes| app.run("file.open", serde_json::json!({"path": name, "data": wordcraft_engine::cmd::insert::base64_encode(&bytes)})));
|
||||
match opened {
|
||||
// Not when it waits for a password: that open names the document itself.
|
||||
Ok(r) if r.get("pending").is_none() => app.session.path = Some(path.into()),
|
||||
Ok(_) => {}
|
||||
Err(e) => log::warn!("{name}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
@@ -240,18 +323,38 @@ fn main() -> eframe::Result {
|
||||
let mut control_port: Option<u16> = std::env::var("WORDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
|
||||
let mut files = Vec::new();
|
||||
let mut sample = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
let (args, other_files) = text_args();
|
||||
let mut bad_control: Option<Option<String>> = None;
|
||||
let mut args = args.into_iter().peekable();
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
|
||||
// A flag after `--control` stays a flag; a bad or missing port is an error (#1426).
|
||||
"--control" => {
|
||||
let port = args.next_if(|p| p.strip_prefix('-').is_none_or(|n| n.starts_with(|c: char| c.is_ascii_digit())));
|
||||
match port.as_deref().and_then(|p| p.parse::<std::num::NonZeroU16>().ok()) {
|
||||
Some(p) => control_port = Some(p.get()),
|
||||
None => bad_control = Some(port),
|
||||
}
|
||||
}
|
||||
"--sample" => sample = true,
|
||||
"--version" => {
|
||||
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
|
||||
return Ok(());
|
||||
}
|
||||
// Before the window opens (#968). Unlike `print!`, a closed stdout can't panic.
|
||||
"--help" | "-h" => {
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return Ok(());
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
// After the loop, so `--version` later on the line still wins. Unlike `eprintln!`, never panics.
|
||||
if let Some(port) = bad_control {
|
||||
let got = port.map(|p| format!(", got {p:?}")).unwrap_or_default();
|
||||
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: --control needs a port number from 1 to 65535{got}\n"));
|
||||
std::process::exit(2);
|
||||
}
|
||||
// The log file lives in the settings directory, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
@@ -328,8 +431,21 @@ fn main() -> eframe::Result {
|
||||
app.session.set_document(doc);
|
||||
}
|
||||
app.watch_desktop_theme(&cc.egui_ctx);
|
||||
if prefs_enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), std::sync::Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
app.ui.window = restored;
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(bar) = traffic_lights::title_bar() {
|
||||
log::info!("title bar: {bar:?}");
|
||||
app.mac_titlebar = bar;
|
||||
}
|
||||
let mut key_file = None;
|
||||
if let Some(port) = control_port
|
||||
&& let Some((rx, file)) = control_server::start(port, cc.egui_ctx.clone(), wordcraft_control_key::settings_dir().as_deref())
|
||||
@@ -340,7 +456,7 @@ fn main() -> eframe::Result {
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// macOS hands over later open on top of it and close it (`apple_events`).
|
||||
if files.is_empty() && !sample && control_port.is_none() {
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control_port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
for f in files {
|
||||
@@ -348,9 +464,13 @@ fn main() -> eframe::Result {
|
||||
log::warn!("{f}: {e}");
|
||||
}
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
restored,
|
||||
// With nothing restored, the window the system placed is checked all the same.
|
||||
Some(restored.unwrap_or_default()),
|
||||
key_file,
|
||||
dialogs,
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -359,3 +479,55 @@ fn main() -> eframe::Result {
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// Not on macOS: APFS refuses file names that aren't valid UTF-8, so no such file can exist there.
|
||||
#[cfg(all(test, unix, not(target_os = "macos")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
#[test]
|
||||
fn a_file_whose_name_isnt_unicode_opens_and_saves_back_to_itself() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-app-non-utf8-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join(std::ffi::OsString::from_vec(b"caf\xe9.txt".to_vec()));
|
||||
std::fs::write(&path, "Bonjour").unwrap();
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
open_non_unicode(&mut app, &path);
|
||||
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).trim(), "Bonjour");
|
||||
assert_eq!(app.session.path.as_deref(), Some(path.as_path()));
|
||||
|
||||
app.run("caret.docEnd", serde_json::json!({})).unwrap();
|
||||
app.run("text.insert", serde_json::json!({"text": " encore"})).unwrap();
|
||||
app.run("file.save", serde_json::json!({})).unwrap();
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("Bonjour encore"));
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "a second file was written");
|
||||
|
||||
// A file that can't be read is a warning, as one that fails to open by name is.
|
||||
open_non_unicode(&mut app, &dir.join(std::ffi::OsString::from_vec(b"gon\xe9.txt".to_vec())));
|
||||
assert_eq!(app.session.path.as_deref(), Some(path.as_path()));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod prefs_tests {
|
||||
use super::write_prefs;
|
||||
|
||||
#[test]
|
||||
fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-prefs-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ui.json");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
write_prefs(&path, b"new").unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
// A directory squatting on the temporary name makes the preparation step fail.
|
||||
std::fs::create_dir(dir.join(format!(".ui.json.{}.tmp", std::process::id()))).unwrap();
|
||||
assert!(write_prefs(&path, b"newer").is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ pub fn finish_pending_jobs() {
|
||||
}
|
||||
|
||||
pub fn submit() -> Submit {
|
||||
Box::new(|bytes, settings: Settings, collate| {
|
||||
Box::new(|bytes, settings: Settings, collate, options| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
|
||||
let job = craft_print::Job {
|
||||
@@ -41,7 +41,7 @@ pub fn submit() -> Submit {
|
||||
grayscale: settings.grayscale,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "WordCraft document".into(),
|
||||
..Default::default()
|
||||
options,
|
||||
};
|
||||
let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Where AppKit puts the traffic lights, so the integrated title bar fits around them (macOS).
|
||||
//!
|
||||
//! The lights' size and position change between macOS versions (they grew in macOS 26), so the
|
||||
//! title bar measures the real buttons instead of assuming the old 28 pt layout. These calls are
|
||||
//! safe in the `objc2-app-kit` bindings (our workspace forbids unsafe).
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSApplication, NSWindowButton};
|
||||
use wordcraft_ui_egui::chrome::MacTitleBar;
|
||||
|
||||
/// The title bar around the app window's traffic lights, or `None` before the window exists or
|
||||
/// when AppKit has no zoom button to measure (the caller keeps the standard layout).
|
||||
pub fn title_bar() -> Option<MacTitleBar> {
|
||||
let mtm = MainThreadMarker::new()?;
|
||||
let window = NSApplication::sharedApplication(mtm).windows().firstObject()?;
|
||||
let zoom = window.standardWindowButton(NSWindowButton::ZoomButton)?;
|
||||
// In window coordinates, which count up from the bottom.
|
||||
let frame = zoom.convertRect_toView(zoom.bounds(), None);
|
||||
let window_height = window.frame().size.height;
|
||||
let right = frame.origin.x + frame.size.width;
|
||||
let centre_from_top = window_height - (frame.origin.y + frame.size.height / 2.0);
|
||||
if !(right.is_finite() && centre_from_top.is_finite() && right > 0.0 && centre_from_top > 0.0) {
|
||||
return None;
|
||||
}
|
||||
Some(MacTitleBar::around_lights(right as f32, centre_from_top as f32, frame.size.height as f32))
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! `wordcraft --control` checks its port before the window opens (#1426).
|
||||
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn app(args: &[&str]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft"))
|
||||
.args(args)
|
||||
// With no display, an app that tries to open a window fails at once instead.
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
// A bad `--control` must not fall back to this port either.
|
||||
.env("WORDCRAFT_CONTROL_PORT", "7981")
|
||||
.env("WORDCRAFT_NO_PREFS", "1")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("wordcraft {args:?} was still running after 30 s: it started the app");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_port_is_an_error_naming_it() {
|
||||
let cases: [(&[&str], &str); 8] = [
|
||||
(&["--control", "-99999999999999999999"], ", got \"-99999999999999999999\""),
|
||||
(&["--control", "abc"], ", got \"abc\""),
|
||||
(&["--control", "79811"], ", got \"79811\""),
|
||||
(&["--control", "0"], ", got \"0\""),
|
||||
(&["--control", "-5"], ", got \"-5\""),
|
||||
(&["--control", "abc", "--control", "7981"], ", got \"abc\""),
|
||||
(&["--control"], ""),
|
||||
(&["--control", "--sample"], ""),
|
||||
];
|
||||
for (args, got) in cases {
|
||||
let out = app(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(2), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft: --control needs a port number from 1 to 65535{got}\n"), "{args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flag_after_control_is_read_as_a_flag() {
|
||||
let out = app(&["--control", "--version"]);
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(stdout.starts_with("wordcraft "), "stdout: {stdout}");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! `wordcraft --help` and `-h` print the options and exit without opening a window (#968).
|
||||
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn app(flag: &str) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft"))
|
||||
.arg(flag)
|
||||
// With no display, an app that tries to open a window fails at once instead.
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WORDCRAFT_CONTROL_PORT")
|
||||
.env("WORDCRAFT_NO_PREFS", "1")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("wordcraft {flag} was still running after 30 s: it started the app");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_h_print_the_options_and_exit() {
|
||||
for flag in ["--help", "-h"] {
|
||||
let out = app(flag);
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.status.success(), "{flag}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(stdout.starts_with("wordcraft — "), "{flag}: stdout: {stdout}");
|
||||
for option in ["--sample", "--control PORT", "--version", "-h, --help"] {
|
||||
assert!(stdout.contains(option), "{flag}: {option} missing from: {stdout}");
|
||||
}
|
||||
assert!(stderr.is_empty(), "{flag}: stderr: {stderr}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! An argument that isn't valid Unicode, such as a Latin-1 file name, never panics the app (#1440).
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn app(args: &[OsString]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft"))
|
||||
.args(args)
|
||||
// With no display, an app that tries to open a window fails at once instead.
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("WORDCRAFT_CONTROL_PORT")
|
||||
.env("WORDCRAFT_NO_PREFS", "1")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("wordcraft {args:?} was still running after 30 s: it started the app");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
/// The file opens once the window is up (`open_non_unicode`, unit-tested in `main.rs`). Not on
|
||||
/// macOS, where the app opens its window without a display variable and so keeps running.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_file_with_such_a_name_starts_the_app() {
|
||||
let out = app(&["--sample".into(), OsString::from_vec(b"caf\xe9.docx".to_vec())]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!stderr.contains("panic"), "stderr: {stderr}");
|
||||
// It went on to open the window, which fails without a display.
|
||||
assert!(stderr.contains("WinitEventLoop"), "stderr: {stderr}");
|
||||
assert_eq!(out.status.code(), Some(1), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_port_that_isnt_unicode_is_an_error_naming_it() {
|
||||
let out = app(&["--sample".into(), "--control".into(), OsString::from_vec(b"79\xe981".to_vec())]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(2), "stderr: {stderr}");
|
||||
assert_eq!(stderr, "wordcraft: argument 3 is not valid Unicode: 79\u{FFFD}81\n");
|
||||
}
|
||||
@@ -26,7 +26,12 @@ chatroom
|
||||
checkbox
|
||||
checklist
|
||||
childcare
|
||||
clamour
|
||||
clickable
|
||||
colourful
|
||||
colourisation
|
||||
colourise
|
||||
colourless
|
||||
configurable
|
||||
copyedit
|
||||
coronavirus
|
||||
@@ -54,6 +59,7 @@ ecommerce
|
||||
email
|
||||
emoji
|
||||
emoticon
|
||||
endeavour
|
||||
esports
|
||||
facebook
|
||||
favicon
|
||||
@@ -71,6 +77,7 @@ geolocation
|
||||
gigabit
|
||||
gigabyte
|
||||
github
|
||||
glamour
|
||||
globalization
|
||||
google
|
||||
groupthink
|
||||
@@ -80,6 +87,9 @@ hashtag
|
||||
healthcare
|
||||
homepage
|
||||
homeschool
|
||||
honour
|
||||
honourable
|
||||
honourably
|
||||
hotspot
|
||||
hyperlink
|
||||
hypertext
|
||||
@@ -106,6 +116,7 @@ logout
|
||||
lowercase
|
||||
makeover
|
||||
malware
|
||||
manoeuvrable
|
||||
megabyte
|
||||
megapixel
|
||||
meme
|
||||
@@ -127,6 +138,7 @@ onboard
|
||||
online
|
||||
onscreen
|
||||
outsource
|
||||
paediatric
|
||||
paralegal
|
||||
passcode
|
||||
petabyte
|
||||
@@ -139,10 +151,13 @@ podcast
|
||||
popup
|
||||
prequel
|
||||
printout
|
||||
prioritise
|
||||
prioritization
|
||||
prioritize
|
||||
privatise
|
||||
ransomware
|
||||
recyclable
|
||||
rigour
|
||||
ringtone
|
||||
roadmap
|
||||
rollout
|
||||
@@ -171,6 +186,7 @@ subfolder
|
||||
sunscreen
|
||||
superfood
|
||||
superuser
|
||||
synthesise
|
||||
tagline
|
||||
takeout
|
||||
techie
|
||||
@@ -188,6 +204,7 @@ touchpad
|
||||
touchscreen
|
||||
trackball
|
||||
trackpad
|
||||
travelogue
|
||||
upcycle
|
||||
upload
|
||||
uppercase
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# Russian spelling supplement: common words older Russian Hunspell dictionaries lack.
|
||||
# Written by WordCraft contributors (MIT OR Apache-2.0); see ATTRIBUTION.md.
|
||||
# One word per line: the base form, a TAB, then its declension, from which
|
||||
# crates/proof/src/ru/extra.rs makes every form:
|
||||
# m masculine noun ending in a consonant (маркетплейс, -а, -у, -ом, -е, -ы/-и, -ов/-ей…)
|
||||
# f feminine noun in -а (инфографика, -и, -е, -у, -ой…; genitive plural without ending)
|
||||
# fia feminine noun in -ия (интеграция, -ии, -ию, -ией, -ий…)
|
||||
# fs feminine noun in -ь (соцсеть, -и, -ью, -ей, -ям…)
|
||||
# nie neuter noun in -ие (согласие, -ия, -ию, -ием, -ий…)
|
||||
# no neuter noun in -о (юрлицо, -а, -у, -ом, -е; genitive plural without ending)
|
||||
# adj adjective or participle in -ый, -ий, -ой (бонусный, газоиспользующий)
|
||||
# ovat verb in -овать with its conjugation and participles (колеровать, администрировать)
|
||||
# = the forms themselves, space-separated (verbs, nouns with a fleeting vowel)
|
||||
# A word alone on its line doesn't decline (онлайн, медиа). Capitalized words are names and match
|
||||
# only when written with a capital.
|
||||
|
||||
# Commerce, marketing and the web
|
||||
маркетплейс m
|
||||
селлер m
|
||||
фулфилмент m
|
||||
ритейл m
|
||||
ритейлер m
|
||||
дистрибьютор m
|
||||
дропшиппинг m
|
||||
мерчандайзер m
|
||||
эквайринг m
|
||||
промокод m
|
||||
кешбэк m
|
||||
кэшбэк m
|
||||
лендинг m
|
||||
лид m
|
||||
тренд m
|
||||
бренд m
|
||||
брендбук m
|
||||
ребрендинг m
|
||||
таргетинг m
|
||||
геотаргетинг m
|
||||
ретаргетинг m
|
||||
таргетолог m
|
||||
маркетолог m
|
||||
копирайтер m
|
||||
рерайтер m
|
||||
контент m
|
||||
блогер m
|
||||
инфлюенсер m
|
||||
хештег m
|
||||
хэштег m
|
||||
репост m
|
||||
лайк m
|
||||
подкаст m
|
||||
стриминг m
|
||||
вебинар m
|
||||
чат m
|
||||
бот m
|
||||
чат-бот m
|
||||
стартап m
|
||||
франчайзинг m
|
||||
аутсорсинг m
|
||||
аутстаффинг m
|
||||
коворкинг m
|
||||
дедлайн m
|
||||
фидбэк m
|
||||
фидбек m
|
||||
кейс m
|
||||
скриншот m
|
||||
скринкаст m
|
||||
баннер m
|
||||
виджет m
|
||||
дашборд m
|
||||
сервис m
|
||||
сайт m
|
||||
скан m
|
||||
токен m
|
||||
аккаунт m
|
||||
логин m
|
||||
пароль m
|
||||
смартфон m
|
||||
гаджет m
|
||||
планшет m
|
||||
ноутбук m
|
||||
апгрейд m
|
||||
апдейт m
|
||||
бэкап m
|
||||
бэкенд m
|
||||
фронтенд m
|
||||
датасет m
|
||||
промпт m
|
||||
интерфейс m
|
||||
хостинг m
|
||||
домен m
|
||||
сниппет m
|
||||
трафик m
|
||||
юзер m
|
||||
стикер m
|
||||
чекбокс m
|
||||
инпут m
|
||||
плейсхолдер m
|
||||
тултип m
|
||||
гипсокартон m
|
||||
пеноплекс m
|
||||
праймер m
|
||||
колер m
|
||||
колорант m
|
||||
Яндекс m
|
||||
Битрикс m
|
||||
Вебвизор m
|
||||
Дзен m
|
||||
инфографика f
|
||||
аналитика f
|
||||
оплата f
|
||||
предоплата f
|
||||
постоплата f
|
||||
доплата f
|
||||
переплата f
|
||||
недоплата f
|
||||
маркировка = маркировка маркировки маркировке маркировку маркировкой маркировкою маркировок маркировкам маркировками маркировках
|
||||
отгрузка = отгрузка отгрузки отгрузке отгрузку отгрузкой отгрузкою отгрузок отгрузкам отгрузками отгрузках
|
||||
колеровка = колеровка колеровки колеровке колеровку колеровкой колеровкою колеровок колеровкам колеровками колеровках
|
||||
рассылка = рассылка рассылки рассылке рассылку рассылкой рассылкою рассылок рассылкам рассылками рассылках
|
||||
выгрузка = выгрузка выгрузки выгрузке выгрузку выгрузкой выгрузкою выгрузок выгрузкам выгрузками выгрузках
|
||||
интеграция fia
|
||||
пагинация fia
|
||||
госрегистрация fia
|
||||
геолокация fia
|
||||
монетизация fia
|
||||
кастомизация fia
|
||||
персонализация fia
|
||||
сегментация fia
|
||||
верификация fia
|
||||
валидация fia
|
||||
авторизация fia
|
||||
аутентификация fia
|
||||
оптимизация fia
|
||||
визуализация fia
|
||||
соцсеть fs
|
||||
согласие nie
|
||||
домовладение nie
|
||||
рождение nie
|
||||
паллетирование nie
|
||||
неисполнение nie
|
||||
непредоставление nie
|
||||
бонусный adj
|
||||
маркетинговый adj
|
||||
мотивационный adj
|
||||
гипоаллергенный adj
|
||||
тиксотропный adj
|
||||
сополимерный adj
|
||||
покупочный adj
|
||||
таргетированный adj
|
||||
брендированный adj
|
||||
кастомный adj
|
||||
онлайновый adj
|
||||
офлайновый adj
|
||||
колеруемый adj
|
||||
колерованный adj
|
||||
заколерованный adj
|
||||
газоиспользующий adj
|
||||
колеровать ovat
|
||||
заколеровать ovat
|
||||
администрировать ovat
|
||||
модерировать ovat
|
||||
отмодерировать ovat
|
||||
таргетировать ovat
|
||||
монетизировать ovat
|
||||
брендировать ovat
|
||||
кастомизировать ovat
|
||||
детектировать ovat
|
||||
верифицировать ovat
|
||||
валидировать ovat
|
||||
генерировать ovat
|
||||
сгенерировать ovat
|
||||
мониторить = мониторить мониторю мониторишь мониторит мониторим мониторите мониторят мониторил мониторила мониторили мониторя мониторинг
|
||||
гуглить = гуглить гуглю гуглишь гуглит гуглим гуглите гуглят гуглил гуглила гуглили
|
||||
скачивать = скачивать скачиваю скачиваешь скачивает скачиваем скачиваете скачивают скачивал скачивала скачивали скачивается скачиваются
|
||||
оценивание nie
|
||||
медучреждение nie
|
||||
юрлицо no
|
||||
учётка = учётка учётки учётке учётку учёткой учёток учёткам учётками учётках учетка учетки учетке учетку учеткой учеток учеткам учетками учетках
|
||||
перелинковка = перелинковка перелинковки перелинковке перелинковку перелинковкой перелинковок
|
||||
поклейка = поклейка поклейки поклейке поклейку поклейкой поклеек
|
||||
детекция fia
|
||||
досудебный adj
|
||||
категорийный adj
|
||||
оркестратор m
|
||||
оффер m
|
||||
трекер m
|
||||
бриф m
|
||||
гайд m
|
||||
монтажёр m
|
||||
тенант m
|
||||
мерчант m
|
||||
амбассадор m
|
||||
Роскомнадзор m
|
||||
Директ m
|
||||
Маркет m
|
||||
вовлечённость fs
|
||||
вовлеченность fs
|
||||
укрывистость fs
|
||||
# Words that don't decline
|
||||
онлайн
|
||||
офлайн
|
||||
оффлайн
|
||||
медиа
|
||||
демо
|
||||
франчайзи
|
||||
киноа
|
||||
смс
|
||||
пн
|
||||
вт
|
||||
ср
|
||||
чт
|
||||
пт
|
||||
сб
|
||||
вс
|
||||
@@ -17,6 +17,10 @@
|
||||
# To remove your names, delete your entry (or set fields empty) in a PR. The next
|
||||
# contributors.py run, and the next build, drop them.
|
||||
|
||||
[people.divyanshu2074]
|
||||
real_name = "Divyanshu Gupta"
|
||||
sync_github_name = true
|
||||
|
||||
[people.lokinmodar]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -60,6 +64,8 @@ display_name = "Ufuk Efe"
|
||||
sync_github_name = true
|
||||
|
||||
[people.GhostMitra]
|
||||
sync_github_name = true
|
||||
|
||||
[people.DevCoderMax]
|
||||
real_name = "Gleyson do Nascimento Carvalho"
|
||||
display_name = "Gleyson Carvalho"
|
||||
@@ -76,6 +82,56 @@ real_name = "Manuel Carmona"
|
||||
display_name = "manucarcor"
|
||||
[people.odedigo]
|
||||
|
||||
[people.neupaneprashant]
|
||||
real_name = "Prashant Neupane"
|
||||
[people.cyril265]
|
||||
display_name = "cyril265"
|
||||
|
||||
[people.webdevtodayjason]
|
||||
display_name = "Jason Brashear"
|
||||
sync_github_name = false
|
||||
|
||||
[people.lupant]
|
||||
sync_github_name = true
|
||||
[people.Nael-Nathanael]
|
||||
[people.Losminek]
|
||||
[people.Nghiathan13]
|
||||
|
||||
[people.leoncral]
|
||||
sync_github_name = true
|
||||
|
||||
[people.ms-youssef]
|
||||
sync_github_name = true
|
||||
|
||||
[people.finwarman]
|
||||
real_name = "Fin Warman"
|
||||
|
||||
|
||||
[people.albayazid]
|
||||
real_name = "Sazid Al Bayazid"
|
||||
|
||||
[people.switch87]
|
||||
real_name = "Gert Pellin"
|
||||
display_name = "Gert Pellin"
|
||||
|
||||
[people.tlomts-dev]
|
||||
display_name = "The Legend Of MTS Dev"
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
|
||||
[people.rbr48]
|
||||
real_name = "M S Rana"
|
||||
display_name = "Izhaan Intellect"
|
||||
|
||||
|
||||
|
||||
[people.holmbom]
|
||||
real_name = "Erik Holmbom"
|
||||
display_name = "Erik Holmbom"
|
||||
sync_github_name = false
|
||||
|
||||
[people.andrejskvorc]
|
||||
real_name = "Andrej Škvorc"
|
||||
display_name = "Andrej Škvorc"
|
||||
sync_github_name = false
|
||||
|
||||
@@ -6,7 +6,11 @@ use std::path::{Path, PathBuf};
|
||||
/// The app's settings folder (preferences, logs, key files): macOS
|
||||
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
|
||||
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
|
||||
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Connectors and the shape properties beyond fill and outline: a shape's drawing id, its text
|
||||
//! warp, and a connector's ends.
|
||||
//! warp, a rounded rectangle's corner, and a connector's ends.
|
||||
//!
|
||||
//! A connector (DrawingML `straightConnector1`, `bentConnector3`, `curvedConnector3`) is a line
|
||||
//! from its frame's top-left to its bottom-right corner (flips swap the corners). Each end may be
|
||||
@@ -34,6 +34,10 @@ pub struct ShapeExtra {
|
||||
pub arrow_start: bool,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub arrow_end: bool,
|
||||
/// A rounded rectangle's corner radius (`roundRect`'s `adj`, ECMA-376 §20.1.10.56): in
|
||||
/// 100000ths of the shorter side, at most [`MAX_CORNER`]; `None` draws [`DEFAULT_CORNER`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub corner: Option<u32>,
|
||||
}
|
||||
|
||||
fn is_zero(v: &u32) -> bool {
|
||||
@@ -49,6 +53,19 @@ impl ShapeExtra {
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest rounded-rectangle corner: half the shorter side, which makes its ends round.
|
||||
pub const MAX_CORNER: u32 = 50_000;
|
||||
|
||||
/// A rounded rectangle's corner radius without its own: 16% of the shorter side.
|
||||
pub const DEFAULT_CORNER: f32 = 0.16;
|
||||
|
||||
/// The corner radius, in points, of a `w` × `h` rounded rectangle with `corner` (see
|
||||
/// [`ShapeExtra::corner`]).
|
||||
pub fn corner_radius(corner: Option<u32>, w: f32, h: f32) -> f32 {
|
||||
let side = wordcraft_geom::finite(w).min(wordcraft_geom::finite(h)).max(0.0);
|
||||
side * corner.map_or(DEFAULT_CORNER, |c| c.min(MAX_CORNER) as f32 / 100_000.0)
|
||||
}
|
||||
|
||||
/// One glued end of a connector: the drawing id of the shape and its connection site index.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -83,6 +100,8 @@ pub fn sites(kind: ShapeKind, w: f32, h: f32) -> Vec<(f32, f32)> {
|
||||
vec![(cx, 0.0), (cx - dx, cy - dy), (0.0, cy), (cx - dx, cy + dy), (cx, h), (cx + dx, cy + dy), (w, cy), (cx + dx, cy - dy)]
|
||||
}
|
||||
ShapeKind::Triangle => vec![(cx, 0.0), (cx / 2.0, cy), (0.0, h), (cx, h), (w, h), (cx + cx / 2.0, cy)],
|
||||
// The corners, the legs' midpoints and the hypotenuse's.
|
||||
ShapeKind::RightTriangle => vec![(0.0, 0.0), (0.0, cy), (0.0, h), (cx, h), (w, h), (cx, cy)],
|
||||
ShapeKind::Line | ShapeKind::StraightConnector | ShapeKind::ElbowConnector | ShapeKind::CurvedConnector => vec![(0.0, 0.0), (w, h)],
|
||||
_ => vec![(cx, 0.0), (0.0, cy), (cx, h), (w, cy)],
|
||||
}
|
||||
@@ -237,6 +256,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_radius_follows_the_shorter_side() {
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-4;
|
||||
assert!(near(corner_radius(None, 200.0, 100.0), 16.0));
|
||||
assert!(near(corner_radius(Some(0), 200.0, 100.0), 0.0));
|
||||
assert!(near(corner_radius(Some(3_565), 100.0, 200.0), 3.565));
|
||||
assert!(near(corner_radius(Some(MAX_CORNER), 200.0, 100.0), 50.0));
|
||||
assert!(near(corner_radius(Some(u32::MAX), 200.0, 100.0), 50.0), "capped at a half-circle end");
|
||||
assert!(near(corner_radius(Some(10_000), f32::NAN, 100.0), 0.0));
|
||||
assert!(near(corner_radius(Some(10_000), -5.0, 100.0), 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_connectors_follow_their_shapes() {
|
||||
let a = ShapeExtra { id: 7, ..Default::default() };
|
||||
|
||||
@@ -490,6 +490,12 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// How many content controls allow form filling (`w:lock` content editing) across every
|
||||
/// story; 0 means a `w:edit="forms"` document has nothing left editable.
|
||||
pub fn fillable_controls(&self) -> usize {
|
||||
self.control_stories().into_iter().map(|story| self.control_ranges(story).iter().filter(|r| r.control.lock.can_edit()).count()).sum()
|
||||
}
|
||||
|
||||
/// The innermost content control holding `p`.
|
||||
pub fn control_at(&self, p: &Pos) -> Option<ControlRange> {
|
||||
let para = self.para_at(p)?;
|
||||
|
||||
+85
-22
@@ -63,37 +63,46 @@ const MAX_BOX_DEPTH: usize = 8;
|
||||
/// Most text box stories one paste may create (hostile documents can fan out).
|
||||
const MAX_PASTED_BOXES: usize = 4096;
|
||||
|
||||
/// Call `f` on every paragraph of a block (tables descended, depth-limited).
|
||||
pub(crate) fn each_para<'a>(b: &'a Block, depth: usize, f: &mut dyn FnMut(&'a Paragraph)) {
|
||||
match b {
|
||||
Block::Para(p) => f(p),
|
||||
Block::Table(t) if depth < 16 => {
|
||||
for cell in t.rows.iter().flat_map(|r| r.cells.iter()) {
|
||||
for cb in &cell.blocks {
|
||||
each_para(cb, depth + 1, f);
|
||||
}
|
||||
/// Call `f` on every paragraph of a block, in document order, however deep its tables nest. The
|
||||
/// walk keeps its own stack instead of recursing, so it is complete: a text box it doesn't reach
|
||||
/// is shown nowhere, which pruning relies on (#1339). `_depth` is unused (callers keep passing it).
|
||||
pub(crate) fn each_para<'a>(b: &'a Block, _depth: usize, f: &mut dyn FnMut(&'a Paragraph)) {
|
||||
// Most blocks are paragraphs, which need no stack.
|
||||
if let Block::Para(p) = b {
|
||||
return f(p);
|
||||
}
|
||||
let mut todo = vec![b];
|
||||
while let Some(b) = todo.pop() {
|
||||
match b {
|
||||
Block::Para(p) => f(p),
|
||||
Block::Table(t) => {
|
||||
// Last first, so they come off the stack in document order.
|
||||
let cells = t.rows.iter().rev().flat_map(|r| r.cells.iter().rev());
|
||||
todo.extend(cells.flat_map(|c| c.blocks.iter().rev()).map(|cb| &**cb));
|
||||
}
|
||||
}
|
||||
Block::Table(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn each_para_mut(b: &mut Block, depth: usize, f: &mut dyn FnMut(&mut Paragraph)) {
|
||||
match b {
|
||||
Block::Para(p) => f(p),
|
||||
Block::Table(t) if depth < 16 => {
|
||||
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
|
||||
for cb in &mut cell.blocks {
|
||||
each_para_mut(Arc::make_mut(cb), depth + 1, f);
|
||||
}
|
||||
/// [`each_para`], changing the paragraphs.
|
||||
pub(crate) fn each_para_mut(b: &mut Block, _depth: usize, f: &mut dyn FnMut(&mut Paragraph)) {
|
||||
if let Block::Para(p) = b {
|
||||
return f(p);
|
||||
}
|
||||
let mut todo = vec![b];
|
||||
while let Some(b) = todo.pop() {
|
||||
match b {
|
||||
Block::Para(p) => f(p),
|
||||
Block::Table(t) => {
|
||||
let cells = t.rows.iter_mut().rev().flat_map(|r| r.cells.iter_mut().rev());
|
||||
todo.extend(cells.flat_map(|c| c.blocks.iter_mut().rev()).map(Arc::make_mut));
|
||||
}
|
||||
}
|
||||
Block::Table(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a paragraph anywhere in `b` (also inside tables) uses paragraph or character style
|
||||
/// `id` (depth-limited like `each_para`). Table styles are the engine's `table.deleteStyle`'s job.
|
||||
/// `id` (tables to 16 levels deep). Table styles are the engine's `table.deleteStyle`'s job.
|
||||
fn uses_style(b: &Block, id: &str, depth: usize) -> bool {
|
||||
let is = |s: &Option<String>| s.as_deref() == Some(id);
|
||||
match b {
|
||||
@@ -308,7 +317,8 @@ impl Document {
|
||||
self.para_paths(a.story).into_iter().filter(|p| *p >= a.path && *p <= b.path).collect()
|
||||
}
|
||||
|
||||
/// Delete `a..b`. Returns the position where the deletion collapsed to.
|
||||
/// Delete `a..b`. Returns the position where the deletion collapsed to. On error the document
|
||||
/// is unchanged: both ends are checked before anything is deleted.
|
||||
pub fn delete_range(&mut self, a: &Pos, b: &Pos) -> Result<Pos> {
|
||||
let (a, b) = order(a, b);
|
||||
if a == b {
|
||||
@@ -317,6 +327,14 @@ impl Document {
|
||||
if a.story != b.story {
|
||||
return Err(DocError::Invalid("range spans stories".into()));
|
||||
}
|
||||
// Check both ends before the first edit, so an error never leaves the document half-deleted.
|
||||
for p in [&a, &b] {
|
||||
match self.para(p.story, &p.path) {
|
||||
Some(para) if para.clamp(p.off) == p.off => {}
|
||||
Some(_) => return Err(DocError::BadOffset(p.off)),
|
||||
None => return Err(DocError::BadPath(p.path.to_string())),
|
||||
}
|
||||
}
|
||||
// Content control markers whose partner is outside the range stay (the control is
|
||||
// emptied, not broken).
|
||||
let kept = self.kept_control_markers(&a, &b);
|
||||
@@ -389,6 +407,27 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
// From the very start of a top-level table to a top-level paragraph (Select All in a
|
||||
// document that starts with a table, #1198): the tables are covered whole and go too,
|
||||
// and the paragraphs left between join.
|
||||
if a.path.depth() > 0 && b.path.depth() == 0 && a.off == 0 {
|
||||
let ta = a.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let first = self.para_paths(a.story).into_iter().find(|q| q.0.first().is_some_and(|t| *t as usize == ta));
|
||||
if first.as_ref() == Some(&a.path) {
|
||||
let ib = b.path.last();
|
||||
let bl = self.container_mut(a.story, &b.path)?;
|
||||
let mut removed = 0;
|
||||
for i in (ta..ib).rev() {
|
||||
if matches!(bl.get(i).map(|b| &**b), Some(Block::Table(_))) {
|
||||
bl.remove(i);
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
let at = Pos { story: a.story, path: Path::top(ta), off: 0 };
|
||||
let end = Pos { story: a.story, path: Path::top(ib.saturating_sub(removed)), off: 0 };
|
||||
return self.delete_range(&at, &end);
|
||||
}
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
@@ -554,7 +593,7 @@ impl Document {
|
||||
let body = crate::TextBody { next: None, ..src.body };
|
||||
*budget -= 1;
|
||||
self.adopt_text_boxes(&mut blocks, parts, depth + 1, budget);
|
||||
let id = self.add_part(PartKind::TextBox, blocks.into_iter().map(Arc::new).collect());
|
||||
let id = self.try_add_part(PartKind::TextBox, blocks.into_iter().map(Arc::new).collect()).ok()?;
|
||||
if let Some(p) = self.parts.get_mut(&id) {
|
||||
p.body = body;
|
||||
}
|
||||
@@ -666,6 +705,30 @@ mod tests {
|
||||
assert_eq!(d.plain_text(StoryRef::Body), "Hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_range_with_bad_end_leaves_document_unchanged() {
|
||||
let mut d = doc(&["one", "two", "three"]);
|
||||
let before = d.plain_text(StoryRef::Body);
|
||||
// Missing paragraph as the second end.
|
||||
assert!(d.delete_range(&Pos::body(0, 1), &Pos::body(9, 0)).is_err());
|
||||
assert_eq!(d.plain_text(StoryRef::Body), before);
|
||||
// Offset past the end of the second paragraph.
|
||||
assert!(d.delete_range(&Pos::body(0, 1), &Pos::body(1, 99)).is_err());
|
||||
assert_eq!(d.plain_text(StoryRef::Body), before);
|
||||
// Offset inside a multi-byte character.
|
||||
let mut d = doc(&["abc", "\u{e9}x"]);
|
||||
assert!(d.delete_range(&Pos::body(0, 1), &Pos::body(1, 1)).is_err());
|
||||
assert_eq!(d.plain_text(StoryRef::Body), "abc\n\u{e9}x");
|
||||
// Range entering a table with a bad offset at its start: the cell text stays.
|
||||
let mut d = doc(&["before", "after"]);
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(Table::new(2, 1, 200.0))).unwrap();
|
||||
d.insert_text(&Pos { story: StoryRef::Body, path: Path(vec![1, 0, 0, 0]), off: 0 }, "x", &CharProps::default()).unwrap();
|
||||
let before = d.plain_text(StoryRef::Body);
|
||||
let cell = Pos { story: StoryRef::Body, path: Path(vec![1, 1, 0, 0]), off: 0 };
|
||||
assert!(d.delete_range(&Pos::body(0, 99), &cell).is_err());
|
||||
assert_eq!(d.plain_text(StoryRef::Body), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_multi() {
|
||||
let mut d = doc(&["one", "two", "three"]);
|
||||
|
||||
+180
-5
@@ -1,6 +1,7 @@
|
||||
//! Windows-1252 (the byte encoding legacy Word text pieces use) and the other single-byte Windows
|
||||
//! code pages RTF files name with `\ansicpg` or a font's `\fcharset` (Cyrillic 1251, Central
|
||||
//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai).
|
||||
//! European 1250, Greek, Turkish, Hebrew, Arabic, Baltic, Vietnamese, Thai), and Mac OS Roman
|
||||
//! (10000, RTF `\mac`).
|
||||
|
||||
/// Windows-1252 code points for 0x80..=0x9F.
|
||||
const CP1252: [u16; 32] = [
|
||||
@@ -125,11 +126,134 @@ const CP1258: [u16; 128] = [
|
||||
0x20AB, 0x00FF,
|
||||
];
|
||||
|
||||
/// Mac OS Roman (code page 10000, RTF `\mac`) code points for 0x80..=0xFF, with the euro sign at
|
||||
/// 0xDB (Mac OS 8.5 and later).
|
||||
const MAC_ROMAN: [u16; 128] = [
|
||||
0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, 0x00EA, 0x00EB,
|
||||
0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, 0x2020, 0x00B0, 0x00A2, 0x00A3,
|
||||
0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5,
|
||||
0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB,
|
||||
0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178,
|
||||
0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE,
|
||||
0x00CF, 0x00CC, 0x00D3, 0x00D4, 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD,
|
||||
0x02DB, 0x02C7,
|
||||
];
|
||||
/// IBM PC (OEM) code page 437 code points for 0x80..=0xFF (the Unicode Consortium's CP437
|
||||
/// mapping file).
|
||||
const CP437: [u16; 128] = [
|
||||
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
|
||||
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
|
||||
0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
|
||||
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
|
||||
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
|
||||
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4,
|
||||
0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2,
|
||||
0x25A0, 0x00A0,
|
||||
];
|
||||
|
||||
/// OEM code page 850 (DOS Latin-1, Western European) code points for 0x80..=0xFF (the Unicode
|
||||
/// Consortium's CP850 mapping file).
|
||||
const CP850: [u16; 128] = [
|
||||
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
|
||||
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
|
||||
0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
|
||||
0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
|
||||
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518,
|
||||
0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9,
|
||||
0x00FD, 0x00DD, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2,
|
||||
0x25A0, 0x00A0,
|
||||
];
|
||||
|
||||
/// OEM code page 852 (DOS Latin-2, Central European) code points for 0x80..=0xFF (the Unicode Consortium's CP852
|
||||
/// mapping file).
|
||||
const CP852: [u16; 128] = [
|
||||
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, 0x00C9, 0x0139,
|
||||
0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
|
||||
0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
|
||||
0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103,
|
||||
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518,
|
||||
0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170,
|
||||
0x00FD, 0x00DD, 0x0163, 0x00B4, 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159,
|
||||
0x25A0, 0x00A0,
|
||||
];
|
||||
|
||||
/// OEM code page 866 (DOS Cyrillic) code points for 0x80..=0xFF (the Unicode Consortium's CP866
|
||||
/// mapping file).
|
||||
const CP866: [u16; 128] = [
|
||||
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421,
|
||||
0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433,
|
||||
0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
|
||||
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
|
||||
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
|
||||
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B,
|
||||
0x044C, 0x044D, 0x044E, 0x044F, 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4,
|
||||
0x25A0, 0x00A0,
|
||||
];
|
||||
|
||||
/// OEM code page 737 (DOS Greek) code points for 0x80..=0xFF (the Unicode Consortium's CP737
|
||||
/// mapping file).
|
||||
const CP737: [u16; 128] = [
|
||||
0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, 0x03A1, 0x03A3,
|
||||
0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC,
|
||||
0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561,
|
||||
0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
|
||||
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518,
|
||||
0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388,
|
||||
0x0389, 0x038A, 0x038C, 0x038E, 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2,
|
||||
0x25A0, 0x00A0,
|
||||
];
|
||||
|
||||
/// OEM code page 857 (DOS Turkish; U+FFFD where the byte is unassigned) code points for 0x80..=0xFF (the Unicode Consortium's CP857
|
||||
/// mapping file).
|
||||
const CP857: [u16; 128] = [
|
||||
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, 0x00C9, 0x00E6,
|
||||
0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, 0x00E1, 0x00ED, 0x00F3, 0x00FA,
|
||||
0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1,
|
||||
0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
|
||||
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0xFFFD, 0x00CD, 0x00CE, 0x00CF, 0x2518,
|
||||
0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0xFFFD, 0x00D7, 0x00DA, 0x00DB, 0x00D9,
|
||||
0x00EC, 0x00FF, 0x00AF, 0x00B4, 0x00AD, 0x00B1, 0xFFFD, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2,
|
||||
0x25A0, 0x00A0,
|
||||
];
|
||||
|
||||
/// The glyphs the OEM code pages show for 0x01..=0x1F (smileys, card suits, arrows), as
|
||||
/// Windows' Alt+numpad entry produces them rather than the control characters.
|
||||
const OEM_GLYPHS: [u16; 31] = [
|
||||
0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195,
|
||||
0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC,
|
||||
];
|
||||
|
||||
/// The OEM code pages [`oem_byte`] decodes.
|
||||
pub const OEM_CODE_PAGES: [u16; 6] = [437, 737, 850, 852, 857, 866];
|
||||
|
||||
/// One byte of an OEM code page in [`OEM_CODE_PAGES`] (any other code page reads as 437) as a
|
||||
/// char, with the graphic glyphs for 0x01..=0x1F and 0x7F (⌂); 0x00 stays NUL.
|
||||
pub fn oem_byte(code_page: u16, b: u8) -> char {
|
||||
let table: &[u16; 128] = match code_page {
|
||||
737 => &CP737,
|
||||
850 => &CP850,
|
||||
852 => &CP852,
|
||||
857 => &CP857,
|
||||
866 => &CP866,
|
||||
_ => &CP437,
|
||||
};
|
||||
let u = match b {
|
||||
0x01..=0x1F => OEM_GLYPHS.get(usize::from(b - 1)).copied(),
|
||||
0x7F => Some(0x2302),
|
||||
0x80..=0xFF => table.get(usize::from(b - 0x80)).copied(),
|
||||
_ => Some(u16::from(b)),
|
||||
};
|
||||
u.and_then(|u| char::from_u32(u32::from(u))).unwrap_or('\u{FFFD}')
|
||||
}
|
||||
|
||||
/// The single-byte Windows code pages [`windows_byte`] decodes (1252 included).
|
||||
pub const SINGLE_BYTE_CODE_PAGES: [u16; 10] = [874, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258];
|
||||
|
||||
/// One byte of a single-byte Windows code page as a char; a code page outside
|
||||
/// [`SINGLE_BYTE_CODE_PAGES`] reads as Windows-1252.
|
||||
/// Mac OS Roman, RTF's `\mac` character set.
|
||||
pub const MAC_ROMAN_CODE_PAGE: u16 = 10000;
|
||||
|
||||
/// One byte of a single-byte code page as a char: a Windows one in [`SINGLE_BYTE_CODE_PAGES`] or
|
||||
/// Mac OS Roman ([`MAC_ROMAN_CODE_PAGE`]); any other code page reads as Windows-1252.
|
||||
pub fn windows_byte(code_page: u16, b: u8) -> char {
|
||||
let table: &[u16; 128] = match code_page {
|
||||
874 => &CP874,
|
||||
@@ -141,6 +265,7 @@ pub fn windows_byte(code_page: u16, b: u8) -> char {
|
||||
1256 => &CP1256,
|
||||
1257 => &CP1257,
|
||||
1258 => &CP1258,
|
||||
MAC_ROMAN_CODE_PAGE => &MAC_ROMAN,
|
||||
_ => return cp1252(b),
|
||||
};
|
||||
if b < 0x80 {
|
||||
@@ -149,11 +274,25 @@ pub fn windows_byte(code_page: u16, b: u8) -> char {
|
||||
table.get(usize::from(b - 0x80)).and_then(|u| char::from_u32(u32::from(*u))).unwrap_or('\u{FFFD}')
|
||||
}
|
||||
|
||||
/// Whether [`code_page_byte`] decodes `code_page`: a Windows one ([`SINGLE_BYTE_CODE_PAGES`]), an
|
||||
/// OEM (DOS) one ([`OEM_CODE_PAGES`]) or Mac OS Roman. Document formats (RTF) name all three.
|
||||
pub fn is_byte_code_page(code_page: u16) -> bool {
|
||||
SINGLE_BYTE_CODE_PAGES.contains(&code_page) || OEM_CODE_PAGES.contains(&code_page) || code_page == MAC_ROMAN_CODE_PAGE
|
||||
}
|
||||
|
||||
/// A byte of 8-bit document text in `code_page` (see [`is_byte_code_page`]) as a char. Below 0x80
|
||||
/// it is ASCII in every code page (text, so an OEM page's glyphs for control codes don't apply).
|
||||
pub fn code_page_byte(code_page: u16, b: u8) -> char {
|
||||
if b >= 0x80 && OEM_CODE_PAGES.contains(&code_page) { oem_byte(code_page, b) } else { windows_byte(code_page, b) }
|
||||
}
|
||||
|
||||
/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern
|
||||
/// European → 1250… `None` for the ANSI and default charsets (the document's code page applies),
|
||||
/// symbol fonts and the double-byte East Asian charsets.
|
||||
/// European → 1250, 77 Mac → 10000, 254 PC → 437… `None` for the ANSI and default charsets (the
|
||||
/// document's code page applies), symbol fonts and the double-byte East Asian charsets.
|
||||
pub fn charset_code_page(charset: i32) -> Option<u16> {
|
||||
Some(match charset {
|
||||
77 => MAC_ROMAN_CODE_PAGE,
|
||||
254 => 437,
|
||||
161 => 1253,
|
||||
162 => 1254,
|
||||
163 => 1258,
|
||||
@@ -180,6 +319,10 @@ mod tests {
|
||||
assert_eq!(decode(1253, &[0xC1, 0xE2]), "Αβ");
|
||||
assert_eq!(decode(1252, &[0x80, 0xE9]), "ێ");
|
||||
assert_eq!(decode(9999, &[0xE9]), "é");
|
||||
// Mac OS Roman (#1653): accents, the euro sign at 0xDB, typographic quotes.
|
||||
assert_eq!(decode(10000, &[0x80, 0x8E, 0xDB, 0xF1, 0xF2, 0xF3, 0xD2, 0xD3, 0x41]), "Äé€ÒÚÛ“”A");
|
||||
assert_eq!(charset_code_page(77), Some(10000));
|
||||
assert_eq!(charset_code_page(254), Some(437));
|
||||
assert_eq!(charset_code_page(204), Some(1251));
|
||||
assert_eq!(charset_code_page(0), None);
|
||||
for cp in SINGLE_BYTE_CODE_PAGES {
|
||||
@@ -188,4 +331,36 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #1653: one decoder for document text in any code page RTF names: Windows, DOS or Mac.
|
||||
#[test]
|
||||
fn document_text_in_windows_dos_and_mac_code_pages() {
|
||||
let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| code_page_byte(cp, b)).collect::<String>();
|
||||
assert_eq!(decode(437, &[0x82, 0xA0, 0x41, 0x01]), "éáA\u{1}", "DOS text; ASCII stays ASCII");
|
||||
assert_eq!(decode(850, &[0x9D, 0xE9]), "ØÚ");
|
||||
assert_eq!(decode(10000, &[0x8E]), "é");
|
||||
assert_eq!(decode(1251, &[0xC4]), "Д");
|
||||
for cp in [437, 850, 866, 1250, 1252, 10000] {
|
||||
assert!(is_byte_code_page(cp), "{cp}");
|
||||
}
|
||||
assert!(!is_byte_code_page(932) && !is_byte_code_page(0) && !SINGLE_BYTE_CODE_PAGES.contains(&10000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oem_code_pages() {
|
||||
let decode = |cp: u16, bytes: &[u8]| bytes.iter().map(|&b| oem_byte(cp, b)).collect::<String>();
|
||||
assert_eq!(decode(437, &[0x82, 0xE9, 0x01, 0x7F]), "éΘ☺⌂");
|
||||
assert_eq!(decode(850, &[0x9B, 0xE9]), "øÚ");
|
||||
assert_eq!(decode(852, &[0xA5, 0x88, 0xBE, 0xA9]), "ąłżę");
|
||||
assert_eq!(decode(866, &[0x8F, 0xE0, 0xA8, 0xA2, 0xA5, 0xE2, 0xF0, 0xFC]), "ПриветЁ№");
|
||||
assert_eq!(decode(737, &[0x80, 0x99, 0xE0]), "Αβω");
|
||||
assert_eq!(decode(857, &[0x8D, 0x98, 0xA6, 0x9F]), "ıİĞş");
|
||||
assert_eq!(oem_byte(857, 0xD5), '\u{FFFD}', "unassigned in 857");
|
||||
assert_eq!(decode(9999, &[0xE9]), "Θ", "unknown pages read as 437");
|
||||
for cp in OEM_CODE_PAGES {
|
||||
for b in 0..=255u8 {
|
||||
let _ = oem_byte(cp, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ fn scan(story: StoryRef, bl: &Blocks, prefix: &mut Vec<u32>, depth: usize, out:
|
||||
let path = Path(prefix.clone());
|
||||
for off in p.object_offsets() {
|
||||
match p.object_at(off) {
|
||||
Some(InlineObject::FieldStart { instr, locked }) => {
|
||||
Some(InlineObject::FieldStart { instr, locked, .. }) => {
|
||||
open.push((instr.clone(), *locked, Pos::new(story, path.clone(), off)));
|
||||
}
|
||||
Some(InlineObject::FieldEnd) => match open.pop() {
|
||||
@@ -93,6 +93,18 @@ impl Document {
|
||||
self.story(story).map(|bl| scan_story(story, bl).ranges).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `p` moved past the range-field ends right after it. A click just after a field's result
|
||||
/// lands before its end marker (the marker takes no room); typing or inserting there belongs
|
||||
/// after the field, as in Word, not in its result.
|
||||
pub fn past_field_ends(&self, p: &Pos) -> Pos {
|
||||
let Some(para) = self.para_at(p) else { return p.clone() };
|
||||
let mut off = p.off;
|
||||
while matches!(para.object_at(off), Some(InlineObject::FieldEnd)) {
|
||||
off += OBJ.len_utf8();
|
||||
}
|
||||
Pos { off, ..p.clone() }
|
||||
}
|
||||
|
||||
/// Whether any story holds a range-field marker without its partner.
|
||||
pub fn has_unbalanced_field_ranges(&self) -> bool {
|
||||
self.story_refs().into_iter().any(|s| self.story(s).is_some_and(|bl| !scan_story(s, bl).orphans.is_empty()))
|
||||
|
||||
@@ -24,7 +24,7 @@ pub struct Graphic {
|
||||
pub h: f32,
|
||||
/// Where the graphic was read from, so saving writes the original drawing itself back (not
|
||||
/// only these items). `None` for graphics made some other way.
|
||||
#[serde(skip)]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<std::sync::Arc<Embedded>>,
|
||||
/// A SmartArt graphic WordCraft can edit (one it made, or one read back exactly as it wrote
|
||||
/// it): saving writes the diagram parts from it, and the items are drawn from it. See
|
||||
@@ -41,7 +41,7 @@ pub struct Graphic {
|
||||
/// source format and the package parts that markup refers to. Never edited; WordCraft only moves
|
||||
/// and resizes the object around it. The parts themselves (bytes, content type and their own
|
||||
/// relationships) are kept in [`crate::Document::passthrough`] under their part names.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Embedded {
|
||||
/// The object's markup as a standalone XML element with its namespace declarations (DOCX:
|
||||
/// the `a:graphic` of a chart, SmartArt diagram or native ink, an ink `mc:AlternateContent`,
|
||||
@@ -52,7 +52,7 @@ pub struct Embedded {
|
||||
}
|
||||
|
||||
/// One relationship an [`Embedded`] object uses.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct EmbeddedRef {
|
||||
/// The relationship id the markup uses.
|
||||
pub id: String,
|
||||
|
||||
+131
-12
@@ -71,6 +71,27 @@ pub enum DocError {
|
||||
|
||||
pub type Result<T> = std::result::Result<T, DocError>;
|
||||
|
||||
/// A free id, `min` or more, for something new (a part, a list, a comment): one past `largest`, the
|
||||
/// largest id in use, so ids keep growing; once that would pass `u32::MAX` (a file can use any id),
|
||||
/// the lowest one `used` (every id in use) doesn't hold. `None` when every id from `min` up is taken.
|
||||
pub fn free_id(largest: Option<u32>, used: impl Iterator<Item = u32>, min: u32) -> Option<u32> {
|
||||
let Some(largest) = largest else { return Some(min) };
|
||||
if let Some(next) = largest.checked_add(1) {
|
||||
return Some(next.max(min));
|
||||
}
|
||||
let mut ids: Vec<u32> = used.filter(|&i| i >= min).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let mut want = min;
|
||||
for i in ids {
|
||||
if i > want {
|
||||
break;
|
||||
}
|
||||
want = want.checked_add(1)?;
|
||||
}
|
||||
Some(want)
|
||||
}
|
||||
|
||||
/// A block in a story. (Blocks are always behind an `Arc`, so the size difference is fine.)
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -322,6 +343,13 @@ pub struct Comment {
|
||||
pub resolved: bool,
|
||||
/// `Document::parts` id of the comment text.
|
||||
pub part: u32,
|
||||
/// Word's durable id for the comment (`w16cid:durableId`, hex), kept across saves so Word
|
||||
/// keeps tracking the same comment. `None` for comments made here: the writer assigns one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub durable_id: Option<String>,
|
||||
/// The comment's UTC timestamp from the file (`w16cex:dateUtc`); `date` is local time there.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub date_utc: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
@@ -433,6 +461,8 @@ pub struct Settings {
|
||||
/// Most consecutive lines that may end with a hyphen (`w:consecutiveHyphenLimit`); 0 = no limit.
|
||||
pub consecutive_hyphen_limit: u32,
|
||||
pub page_color: Option<Rgb>,
|
||||
/// Picture or texture page background (Design › Page Color › Fill Effects), drawn over the colour.
|
||||
pub page_picture: Option<PagePicture>,
|
||||
pub watermark: Option<Watermark>,
|
||||
/// Theme fonts (major = headings, minor = body).
|
||||
pub major_font: String,
|
||||
@@ -464,6 +494,17 @@ pub struct Settings {
|
||||
/// 2013 and later, which places a table's border at the margin rather than its text and lets
|
||||
/// justified lines shrink their spaces to fit more text.
|
||||
pub compat_mode: u32,
|
||||
/// Fonts the document's font table classes as roman (serif, `w:family w:val="roman"`): Word
|
||||
/// draws one that isn't installed in a serif face.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub roman_fonts: Vec<String>,
|
||||
/// `w:doNotUseHTMLParagraphAutoSpacing`: the space between two paragraphs is the first's space
|
||||
/// after plus the second's space before, not the larger of the two.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub sum_paragraph_spacing: bool,
|
||||
/// Keep contextual paragraph spacing inside legacy table cells (`allowSpaceOfSameStyleInTable`).
|
||||
/// Word ignores the layout override in compatibility mode 15, but the flag still round-trips.
|
||||
pub allow_space_of_same_style_in_table: bool,
|
||||
/// Drawing grid spacing in points, across and down (View › Gridlines); ECMA-376's default is 1/8 inch.
|
||||
pub grid_h: f32,
|
||||
pub grid_v: f32,
|
||||
@@ -480,6 +521,10 @@ pub struct Settings {
|
||||
pub attached_template: Option<String>,
|
||||
/// Update the document's styles from the attached template when it is opened (`w:linkStyles`).
|
||||
pub link_styles: bool,
|
||||
/// The zoom the document was saved at (`w:zoom`), restored when it is opened; `None` for 100%
|
||||
/// without a fit mode.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub zoom: Option<Zoom>,
|
||||
/// Remove personal information when saving (`w:removePersonalInformation`, ECMA-376
|
||||
/// §17.15.1.70): the saved file names comment and revision authors "Author" and leaves out
|
||||
/// the document's creator and last-modified-by. The open document keeps its real values.
|
||||
@@ -491,6 +536,24 @@ pub struct Settings {
|
||||
pub remove_date_time: bool,
|
||||
}
|
||||
|
||||
/// A saved zoom: a percentage, or a fit mode (the percentage it last came to).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Zoom {
|
||||
/// 10–500.
|
||||
pub percent: u32,
|
||||
pub fit: Option<ZoomFit>,
|
||||
}
|
||||
|
||||
/// View › Zoom's fit modes a document can be saved in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ZoomFit {
|
||||
OnePage,
|
||||
PageWidth,
|
||||
TextWidth,
|
||||
}
|
||||
|
||||
/// Word's compatibility mode for documents that don't state one.
|
||||
pub const LEGACY_COMPAT_MODE: u32 = 12;
|
||||
|
||||
@@ -503,6 +566,18 @@ pub const DEFAULT_HYPHENATION_ZONE: f32 = 18.0;
|
||||
/// ECMA-376 §17.15.1.44/45: 180 twentieths of a point when a document doesn't say.
|
||||
pub const DEFAULT_GRID: f32 = 9.0;
|
||||
|
||||
/// A picture fill for the page background (`v:background/v:fill` with an image).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct PagePicture {
|
||||
/// Key into [`Document::media`].
|
||||
pub media: String,
|
||||
/// `v:fill/@type` (`tile`, `frame`, `tile`...); tiled when `tile`, stretched to the page otherwise.
|
||||
pub fill_type: String,
|
||||
/// `o:title` of the fill (texture name), kept for round trip.
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Watermark {
|
||||
@@ -547,6 +622,7 @@ impl Default for Settings {
|
||||
hyphenate_caps: true,
|
||||
consecutive_hyphen_limit: 0,
|
||||
page_color: None,
|
||||
page_picture: None,
|
||||
watermark: None,
|
||||
major_font: styles::HEADING_FONT.into(),
|
||||
minor_font: styles::BODY_FONT.into(),
|
||||
@@ -560,12 +636,16 @@ impl Default for Settings {
|
||||
protect_formatting: false,
|
||||
protect_hash: Vec::new(),
|
||||
compat_mode: COMPAT_MODE_CURRENT,
|
||||
roman_fonts: Vec::new(),
|
||||
sum_paragraph_spacing: false,
|
||||
allow_space_of_same_style_in_table: false,
|
||||
grid_h: DEFAULT_GRID,
|
||||
grid_v: DEFAULT_GRID,
|
||||
math: None,
|
||||
bib_style: None,
|
||||
attached_template: None,
|
||||
link_styles: false,
|
||||
zoom: None,
|
||||
remove_personal_info: false,
|
||||
remove_date_time: false,
|
||||
}
|
||||
@@ -597,10 +677,10 @@ pub struct Document {
|
||||
#[serde(skip_serializing_if = "NoteSeparators::is_empty")]
|
||||
pub endnote_separators: NoteSeparators,
|
||||
/// Embedded media (images) by key.
|
||||
#[serde(skip)]
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub media: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
/// Source-format parts we keep verbatim for round-trip (e.g. custom XML), by part name.
|
||||
#[serde(skip)]
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub passthrough: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
}
|
||||
|
||||
@@ -814,19 +894,24 @@ impl Document {
|
||||
|
||||
/// The whole text of a story, paragraphs separated by `\n` (tables: cells by `\t`).
|
||||
pub fn plain_text(&self, s: StoryRef) -> String {
|
||||
self.story_text(s, false)
|
||||
self.story_text(s, TextMode::Plain)
|
||||
}
|
||||
|
||||
/// [`Self::plain_text`] as it reads on screen: symbol-font characters (Wingdings…) as their
|
||||
/// Unicode equivalents ([`Paragraph::shown_text`]).
|
||||
pub fn shown_text(&self, s: StoryRef) -> String {
|
||||
self.story_text(s, true)
|
||||
self.story_text(s, TextMode::Shown)
|
||||
}
|
||||
|
||||
fn story_text(&self, s: StoryRef, shown: bool) -> String {
|
||||
/// [`Self::plain_text`] without tracked-deleted runs. A deleted paragraph mark still yields `\n`.
|
||||
pub fn final_text(&self, s: StoryRef) -> String {
|
||||
self.story_text(s, TextMode::Final)
|
||||
}
|
||||
|
||||
fn story_text(&self, s: StoryRef, mode: TextMode) -> String {
|
||||
let mut out = String::new();
|
||||
if let Some(bl) = self.story(s) {
|
||||
text_of(bl, &mut out, 0, shown);
|
||||
text_of(bl, &mut out, 0, mode);
|
||||
}
|
||||
if out.ends_with('\n') {
|
||||
out.pop();
|
||||
@@ -893,15 +978,22 @@ impl Document {
|
||||
&mut self.last_section
|
||||
}
|
||||
|
||||
/// Allocate a new part id and insert the part.
|
||||
/// Allocate a new part id and insert the part. Part ids run out only past `u32::MAX` parts, more
|
||||
/// than memory holds; then nothing is added and the id is 0, which [`free_id`] never gives a part.
|
||||
pub fn add_part(&mut self, kind: PartKind, blocks: Blocks) -> u32 {
|
||||
let id = self.parts.keys().next_back().map(|k| k + 1).unwrap_or(1);
|
||||
self.try_add_part(kind, blocks).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// [`Document::add_part`], or an error, adding nothing, when every part id is taken.
|
||||
pub fn try_add_part(&mut self, kind: PartKind, blocks: Blocks) -> Result<u32> {
|
||||
let id = free_id(self.parts.keys().next_back().copied(), self.parts.keys().copied(), 1)
|
||||
.ok_or_else(|| DocError::Invalid("no free part id".into()))?;
|
||||
let mut part = Part { kind, blocks, body: TextBody::default() };
|
||||
if part.blocks.is_empty() {
|
||||
part.blocks.push(para_block(Paragraph::new()));
|
||||
}
|
||||
self.parts.insert(id, part);
|
||||
id
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Count words like Word's status bar (whitespace-separated tokens containing a letter or digit,
|
||||
@@ -1158,6 +1250,18 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
|
||||
/// JSON, whose run lengths may overflow, fall short or split a character.
|
||||
pub fn normalize_runs(&mut self) {
|
||||
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut Paragraph::normalize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of paragraphs in the body (all depths).
|
||||
pub fn paragraph_count(&self) -> usize {
|
||||
self.para_paths(StoryRef::Body).len()
|
||||
@@ -1307,14 +1411,29 @@ fn walk(bl: &Blocks, prefix: &mut Vec<u32>, out: &mut Vec<Path>, depth: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(bl: &Blocks, out: &mut String, depth: usize, shown: bool) {
|
||||
/// Which text of a paragraph [`text_of`] collects.
|
||||
#[derive(Clone, Copy)]
|
||||
enum TextMode {
|
||||
/// Every run, tracked deletions included ([`Paragraph::plain_text`]).
|
||||
Plain,
|
||||
/// As shown on screen ([`Paragraph::shown_text`]).
|
||||
Shown,
|
||||
/// Without tracked deletions ([`Paragraph::final_text`]).
|
||||
Final,
|
||||
}
|
||||
|
||||
fn text_of(bl: &Blocks, out: &mut String, depth: usize, mode: TextMode) {
|
||||
if depth > 16 {
|
||||
return;
|
||||
}
|
||||
for b in bl {
|
||||
match &**b {
|
||||
Block::Para(p) => {
|
||||
out.push_str(&if shown { p.shown_text() } else { p.plain_text() });
|
||||
out.push_str(&match mode {
|
||||
TextMode::Plain => p.plain_text(),
|
||||
TextMode::Shown => p.shown_text(),
|
||||
TextMode::Final => p.final_text(),
|
||||
});
|
||||
out.push('\n');
|
||||
}
|
||||
Block::Table(t) => {
|
||||
@@ -1322,7 +1441,7 @@ fn text_of(bl: &Blocks, out: &mut String, depth: usize, shown: bool) {
|
||||
let mut cells = Vec::new();
|
||||
for c in &row.cells {
|
||||
let mut s = String::new();
|
||||
text_of(&c.blocks, &mut s, depth + 1, shown);
|
||||
text_of(&c.blocks, &mut s, depth + 1, mode);
|
||||
cells.push(s.trim_end_matches('\n').replace('\n', " "));
|
||||
}
|
||||
out.push_str(&cells.join("\t"));
|
||||
|
||||
+19
-5
@@ -9,14 +9,23 @@ pub fn is_web_or_mail_link(url: &str) -> bool {
|
||||
["http", "https", "mailto"].iter().any(|s| scheme.eq_ignore_ascii_case(s))
|
||||
}
|
||||
|
||||
/// Whether a hyperlink may be written as an `href` (or Markdown destination) in an exported file:
|
||||
/// a web or email link, a bookmark (`#name`) or a relative path. Scripts (`javascript:`,
|
||||
/// `vbscript:`), `data:`, `file:` and every other scheme are refused, read the way a browser reads
|
||||
/// a URL: ASCII control characters and spaces are dropped first, so `java\nscript:` is a script.
|
||||
/// Whether a hyperlink may be written as an `href` (or Markdown destination, RTF `HYPERLINK`
|
||||
/// field, ODT `xlink:href`, LaTeX `\href`) in an exported file: a web or email link, a bookmark
|
||||
/// (`#name`) or a relative path. Scripts (`javascript:`, `vbscript:`), `data:`, `file:` and every
|
||||
/// other scheme are refused, read the way a browser reads a URL: ASCII control characters and
|
||||
/// spaces are dropped first, so `java\nscript:` is a script. A protocol-relative reference
|
||||
/// (`//host/…`) or a UNC path (`\\host\…`, or `//host` once backslashes are read as separators)
|
||||
/// names another machine — following it on Windows leaks the user's NTLM credentials — so it is
|
||||
/// refused too.
|
||||
pub fn is_safe_href(url: &str) -> bool {
|
||||
let cleaned: String = url.chars().filter(|c| !c.is_ascii_control() && *c != ' ').collect();
|
||||
// `//host` (protocol-relative) and `\\host` (UNC), with `\` read as `/` the way Windows does.
|
||||
if cleaned.replace('\\', "/").starts_with("//") {
|
||||
return false;
|
||||
}
|
||||
match scheme(url) {
|
||||
Some(s) => matches!(s.as_str(), "http" | "https" | "mailto"),
|
||||
None => !url.trim().is_empty(),
|
||||
None => !cleaned.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +82,11 @@ mod tests {
|
||||
"data:text/html,<script>alert(1)</script>",
|
||||
"file:///etc/passwd",
|
||||
"ms-msdt:/id",
|
||||
// Protocol-relative and UNC references name another machine (NTLM leak on Windows).
|
||||
"//attacker.example/share/x",
|
||||
"\\\\attacker.example\\share\\x",
|
||||
"/\\attacker.example\\x",
|
||||
" //attacker.example/x",
|
||||
"",
|
||||
] {
|
||||
assert!(!is_safe_href(bad), "{bad:?}");
|
||||
|
||||
+200
-20
@@ -340,7 +340,7 @@ fn yes() -> bool {
|
||||
|
||||
/// A row holds an equation-number mark (`#`) in a top-level run.
|
||||
pub fn has_number_mark(row: &[MNode]) -> bool {
|
||||
row.iter().any(|n| matches!(n, MNode::Run(r) if !r.lit && r.text.contains('#')))
|
||||
row.iter().any(|n| matches!(n, MNode::Run(r) if !r.lit && !r.nor && r.text.contains('#')))
|
||||
}
|
||||
|
||||
/// Integral signs (their limits default to sub/sup positions).
|
||||
@@ -499,6 +499,21 @@ fn lin_operand(a: &[MNode], s: &mut String, depth: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A script or limit operand. The parser reads a script as one letter or a number (`x_10`), so a
|
||||
/// longer run is grouped: `V_(dd)`, not `V_dd` (which reads back as V_d then d).
|
||||
fn lin_script(a: &[MNode], s: &mut String, depth: usize) {
|
||||
if let [MNode::Run(r)] = a
|
||||
&& r.text.chars().nth(1).is_some()
|
||||
&& !(r.text.starts_with(|c: char| c.is_ascii_digit()) && r.text.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
{
|
||||
s.push('(');
|
||||
s.push_str(&r.text);
|
||||
s.push(')');
|
||||
} else {
|
||||
lin_operand(a, s, depth);
|
||||
}
|
||||
}
|
||||
|
||||
fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
match n {
|
||||
MNode::Run(r) => s.push_str(&r.text),
|
||||
@@ -515,9 +530,9 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
MNode::Script { kind, base, sub, sup } => {
|
||||
if *kind == ScriptKind::Pre {
|
||||
s.push('_');
|
||||
lin_operand(sub, s, depth);
|
||||
lin_script(sub, s, depth);
|
||||
s.push('^');
|
||||
lin_operand(sup, s, depth);
|
||||
lin_script(sup, s, depth);
|
||||
s.push('▒');
|
||||
lin_operand(base, s, depth);
|
||||
return;
|
||||
@@ -525,11 +540,11 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
lin_operand(base, s, depth);
|
||||
if matches!(kind, ScriptKind::Sub | ScriptKind::SubSup) {
|
||||
s.push('_');
|
||||
lin_operand(sub, s, depth);
|
||||
lin_script(sub, s, depth);
|
||||
}
|
||||
if matches!(kind, ScriptKind::Sup | ScriptKind::SubSup) {
|
||||
s.push('^');
|
||||
lin_operand(sup, s, depth);
|
||||
lin_script(sup, s, depth);
|
||||
}
|
||||
}
|
||||
MNode::Rad { deg, deg_hide, e } => {
|
||||
@@ -548,11 +563,11 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
s.push(*chr);
|
||||
if !sub_hide && !sub.is_empty() {
|
||||
s.push('_');
|
||||
lin_operand(sub, s, depth);
|
||||
lin_script(sub, s, depth);
|
||||
}
|
||||
if !sup_hide && !sup.is_empty() {
|
||||
s.push('^');
|
||||
lin_operand(sup, s, depth);
|
||||
lin_script(sup, s, depth);
|
||||
}
|
||||
s.push('▒');
|
||||
lin_operand(e, s, depth);
|
||||
@@ -592,7 +607,7 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
MNode::Lim { upper, e, lim } => {
|
||||
lin_operand(e, s, depth);
|
||||
s.push(if *upper { '┴' } else { '┬' });
|
||||
lin_operand(lim, s, depth);
|
||||
lin_script(lim, s, depth);
|
||||
}
|
||||
MNode::Acc { chr, e } => {
|
||||
lin_operand(e, s, depth);
|
||||
@@ -701,7 +716,7 @@ pub fn math_class(c: char) -> MClass {
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge adjacent runs with the same formatting; recurse into structures.
|
||||
/// Merge adjacent runs with the same formatting; recurse into every structure.
|
||||
pub fn merge_runs(a: Arg) -> Arg {
|
||||
let mut out: Arg = Vec::with_capacity(a.len());
|
||||
for n in a {
|
||||
@@ -722,23 +737,79 @@ pub fn merge_runs(a: Arg) -> Arg {
|
||||
}
|
||||
MNode::Run(r)
|
||||
}
|
||||
MNode::Frac { kind, num, den } => MNode::Frac { kind, num: merge_runs(num), den: merge_runs(den) },
|
||||
MNode::Script { kind, base, sub, sup } => MNode::Script { kind, base: merge_runs(base), sub: merge_runs(sub), sup: merge_runs(sup) },
|
||||
MNode::Rad { deg, deg_hide, e } => MNode::Rad { deg: merge_runs(deg), deg_hide, e: merge_runs(e) },
|
||||
MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e } => {
|
||||
MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub: merge_runs(sub), sup: merge_runs(sup), e: merge_runs(e) }
|
||||
}
|
||||
MNode::Delim { beg, end, sep, grow, shp_match, elems } => {
|
||||
MNode::Delim { beg, end, sep, grow, shp_match, elems: elems.into_iter().map(merge_runs).collect() }
|
||||
}
|
||||
MNode::Func { name, e } => MNode::Func { name: merge_runs(name), e: merge_runs(e) },
|
||||
other => other,
|
||||
other => crate::math_linear::map_args(other, &merge_runs),
|
||||
};
|
||||
out.push(n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Deepest node (a leaf counts 1) the parsers wrap further. Half of [`MAX_DEPTH`]: serde_json
|
||||
/// stops reading at 128 nested containers and a node costs two (object and array).
|
||||
pub(crate) const WRAP_DEPTH: usize = MAX_DEPTH / 2;
|
||||
|
||||
/// Calls `f` with every argument of `n`.
|
||||
fn each_arg<'a>(n: &'a MNode, f: &mut impl FnMut(&'a [MNode])) {
|
||||
match n {
|
||||
MNode::Run(_) => {}
|
||||
MNode::Frac { num, den, .. } => {
|
||||
f(num);
|
||||
f(den);
|
||||
}
|
||||
MNode::Script { base, sub, sup, .. } => {
|
||||
f(base);
|
||||
f(sub);
|
||||
f(sup);
|
||||
}
|
||||
MNode::Rad { deg, e, .. } => {
|
||||
f(deg);
|
||||
f(e);
|
||||
}
|
||||
MNode::Nary { sub, sup, e, .. } => {
|
||||
f(sub);
|
||||
f(sup);
|
||||
f(e);
|
||||
}
|
||||
MNode::Delim { elems, .. } => elems.iter().for_each(|a| f(a)),
|
||||
MNode::Func { name, e } => {
|
||||
f(name);
|
||||
f(e);
|
||||
}
|
||||
MNode::Lim { e, lim, .. } => {
|
||||
f(e);
|
||||
f(lim);
|
||||
}
|
||||
MNode::Acc { e, .. }
|
||||
| MNode::Bar { e, .. }
|
||||
| MNode::BorderBox { e, .. }
|
||||
| MNode::Boxed { e }
|
||||
| MNode::GroupChr { e, .. }
|
||||
| MNode::Phant { e, .. } => f(e),
|
||||
MNode::EqArr { rows } => rows.iter().for_each(|a| f(a)),
|
||||
MNode::Matrix { rows, .. } => rows.iter().flatten().for_each(|a| f(a)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` is already nested too deeply to be wrapped in another structure. The parsers use this so
|
||||
/// `x^1^1^1…` stays shallow (a left-nested tree 10 000 deep overflows the stack in `Clone`,
|
||||
/// `Drop`, `PartialEq` and serde). Iterative, stops at the first too-deep path; costs at most the
|
||||
/// size of `n`, which the parsers' input caps bound.
|
||||
pub(crate) fn too_deep(n: &MNode) -> bool {
|
||||
let mut stack: Vec<(&MNode, usize)> = vec![(n, 1)];
|
||||
while let Some((n, d)) = stack.pop() {
|
||||
if d >= WRAP_DEPTH {
|
||||
return true;
|
||||
}
|
||||
each_arg(n, &mut |a| stack.extend(a.iter().map(|c| (c, d + 1))));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Any of `a` is too deep to be wrapped ([`too_deep`]).
|
||||
pub(crate) fn any_too_deep(a: &[MNode]) -> bool {
|
||||
a.iter().any(too_deep)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -807,6 +878,115 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
//T1
|
||||
/// Deepest nesting of `a` (a leaf counts 1), without recursion.
|
||||
fn depth_of(a: &[MNode]) -> usize {
|
||||
let mut best = 0;
|
||||
let mut stack: Vec<(&MNode, usize)> = a.iter().map(|n| (n, 1)).collect();
|
||||
while let Some((n, d)) = stack.pop() {
|
||||
best = best.max(d);
|
||||
each_arg(n, &mut |a| stack.extend(a.iter().map(|c| (c, d + 1))));
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Run `f` on a thread with a stack far below the 8 MB of a main thread (#1456).
|
||||
fn on_small_stack(f: impl FnOnce() + Send + 'static) {
|
||||
std::thread::Builder::new().stack_size(512 * 1024).spawn(f).unwrap().join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_chained_input_stays_shallow() {
|
||||
on_small_stack(|| {
|
||||
let cases: Vec<(&str, Arg)> = vec![
|
||||
("x^1^1…", parse_linear(&format!("x{}", "^1".repeat(9999)))),
|
||||
("a/a/a…", parse_linear(&format!("a{}", "/a".repeat(9999)))),
|
||||
("accents", parse_linear(&format!("x{}", "\u{302}".repeat(9999)))),
|
||||
("limits", parse_linear(&format!("x{}", "┬a".repeat(9000)))),
|
||||
("(a b)^1^1…", parse_linear(&format!("(a b){}", "^1".repeat(9000)))),
|
||||
("latex x^1^1…", crate::math_latex::parse_latex(&format!("x{}", "^1".repeat(9999)))),
|
||||
("latex \\sum…", crate::math_latex::parse_latex(&"\\sum".repeat(5000))),
|
||||
("latex \\sin x^1…", crate::math_latex::parse_latex(&format!("\\sin x{}", "^1".repeat(9000)))),
|
||||
];
|
||||
for (name, n) in cases {
|
||||
assert!(!n.is_empty(), "{name}");
|
||||
assert!(depth_of(&n) <= 70, "{name}: depth {}", depth_of(&n));
|
||||
let copy = n.clone();
|
||||
assert_eq!(copy, n, "{name}");
|
||||
let _ = to_linear(&n);
|
||||
let _ = crate::math_latex::to_latex(&n);
|
||||
let json = serde_json::to_string(&n).unwrap();
|
||||
let back: Arg = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, n, "{name}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_nesting_is_still_built() {
|
||||
// Well below the cap: scripts, fractions and operators still wrap.
|
||||
let n = parse_linear(&format!("x{}", "^1".repeat(10)));
|
||||
assert_eq!(depth_of(&n), 11, "{n:#?}");
|
||||
let n = crate::math_latex::parse_latex(r"\sum_{i}\sum_{j}a_{ij}");
|
||||
assert!(matches!(&n[0], MNode::Nary { e, .. } if matches!(e.first(), Some(MNode::Nary { .. }))), "{n:#?}");
|
||||
}
|
||||
|
||||
//T2
|
||||
#[test]
|
||||
fn latex_text_escapes_what_latex_reads_as_markup() {
|
||||
for text in ["a}b\\c", "{x}", "50% of #1", "a_b&c$d~e^f", "\\", "\\alpha", "\\{"] {
|
||||
let n = vec![MNode::Run(MRun { text: text.into(), nor: true, sty: Some(MSty::Plain), ..Default::default() })];
|
||||
let tex = crate::math_latex::to_latex(&n);
|
||||
assert_eq!(crate::math_latex::parse_latex(&tex), n, "{text:?} → {tex}");
|
||||
}
|
||||
let n = vec![MNode::Run(MRun::new("a\\b"))];
|
||||
assert_eq!(crate::math_latex::parse_latex(&crate::math_latex::to_latex(&n)), n);
|
||||
}
|
||||
|
||||
//T3
|
||||
#[test]
|
||||
fn latex_runs_merge_inside_every_structure() {
|
||||
use crate::math_latex::parse_latex;
|
||||
for (tex, lin) in [(r"\overline{ab}", "¯(ab)"), (r"\underline{ab}", "▁(ab)"), (r"\boxed{ab}", "▭(ab)"), (r"\phantom{ab}", "⟡(ab)")] {
|
||||
assert_eq!(parse_latex(tex), parse_linear(lin), "{tex}");
|
||||
}
|
||||
let n = parse_latex(r"\begin{matrix}a b&c d\\e f&g\end{matrix}");
|
||||
let MNode::Matrix { rows, .. } = &n[0] else { panic!("{n:#?}") };
|
||||
assert!(rows.iter().flatten().all(|c| c.len() == 1), "{rows:#?}");
|
||||
let n = parse_latex(r"\hat{ab}\underbrace{ab}\underset{ab}{cd}");
|
||||
let runs = |a: &Arg| a.iter().filter(|n| matches!(n, MNode::Run(_))).count();
|
||||
assert!(matches!(&n[0], MNode::Acc { e, .. } if runs(e) == 1), "{n:#?}");
|
||||
assert!(matches!(&n[1], MNode::GroupChr { e, .. } if runs(e) == 1), "{n:#?}");
|
||||
assert!(matches!(&n[2], MNode::Lim { e, lim, .. } if runs(e) == 1 && runs(lim) == 1), "{n:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_letter_scripts_round_trip() {
|
||||
// A script reads one letter or a number, so `V_dd` is V_d then d: longer scripts are grouped.
|
||||
let script = |kind, sub: &str, sup: &str| MNode::Script { kind, base: vec![run("V")], sub: parse_linear(sub), sup: parse_linear(sup) };
|
||||
for n in [
|
||||
vec![script(ScriptKind::Sub, "dd", "")],
|
||||
vec![script(ScriptKind::Sup, "", "ab")],
|
||||
vec![script(ScriptKind::SubSup, "in", "2")],
|
||||
vec![MNode::Nary {
|
||||
chr: '∑',
|
||||
lim_loc: None,
|
||||
grow: false,
|
||||
sub_hide: false,
|
||||
sup_hide: false,
|
||||
sub: vec![run("ij")],
|
||||
sup: vec![run("n")],
|
||||
e: vec![run("x")],
|
||||
}],
|
||||
vec![MNode::Lim { upper: false, e: vec![run("⟶")], lim: vec![run("yields")] }],
|
||||
] {
|
||||
assert_eq!(parse_linear(&to_linear(&n)), n, "{}", to_linear(&n));
|
||||
}
|
||||
// Numbers and single letters stay bare.
|
||||
assert_eq!(to_linear(&[script(ScriptKind::SubSup, "10", "2.5")]), "V_10^2.5");
|
||||
assert_eq!(to_linear(&[script(ScriptKind::Sub, "d", "")]), "V_d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_linear_never_panics() {
|
||||
for s in ["", "/", "^", "_", "√", "∑", "((((", "))))", "■(", "█(@@&&", "a/", "/b", "^^^__", "√(&)", "∫_^▒", "lim_", "sin"] {
|
||||
|
||||
@@ -362,6 +362,26 @@ pub fn tidy(root: &mut Arg) {
|
||||
go(root, 0);
|
||||
}
|
||||
|
||||
/// Call `f` on every run in the tree.
|
||||
pub fn each_run_mut(root: &mut Arg, f: &mut dyn FnMut(&mut MRun)) {
|
||||
fn go(a: &mut Arg, f: &mut dyn FnMut(&mut MRun), depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for n in a.iter_mut() {
|
||||
if let MNode::Run(r) = n {
|
||||
f(r);
|
||||
}
|
||||
for c in 0..child_count(n) {
|
||||
if let Some(ch) = child_mut(n, c) {
|
||||
go(ch, f, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
go(root, f, 0);
|
||||
}
|
||||
|
||||
fn merge_shallow(a: Arg) -> Arg {
|
||||
let mut out: Arg = Vec::with_capacity(a.len());
|
||||
for n in a {
|
||||
@@ -1179,6 +1199,21 @@ mod tests {
|
||||
assert!(matches!(eq[0], MNode::Frac { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_up_keeps_a_multi_letter_subscript() {
|
||||
// #1609: `dd` typed in a subscript box split into V_d and d on the next space.
|
||||
let mut eq: Arg = Vec::new();
|
||||
let p = insert_nodes(&mut eq, &MathPos::default(), parse_linear("⬚_⬚"));
|
||||
let p = insert_text(&mut eq, &p, "V", TypeStyle::default());
|
||||
let p = move_right(&eq, &p).unwrap();
|
||||
let p = insert_text(&mut eq, &p, "dd", TypeStyle::default());
|
||||
let p = move_right(&eq, &p).unwrap();
|
||||
assert_eq!(p, MathPos::new(vec![], 1));
|
||||
let built = eq.clone();
|
||||
assert_eq!(build_up(&mut eq, &p, false), None);
|
||||
assert_eq!(eq, built, "{}", lin(&eq));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_dissolves_and_removes() {
|
||||
let mut eq = parse_linear("√x");
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
//! accents, `\overbrace`/`\underbrace`, `\text`/`\mathrm`/`\mathbf`/`\mathbb`…, function names,
|
||||
//! spacing and every named symbol in [`crate::math_symbols`]. Unknown commands stay as text.
|
||||
|
||||
use crate::math::{Arg, FracKind, MAX_DEPTH, MNode, MRun, MScr, MSty, ScriptKind, is_nary_char, math_class, merge_runs};
|
||||
use crate::math::{
|
||||
Arg, FracKind, MAX_DEPTH, MNode, MRun, MScr, MSty, ScriptKind, WRAP_DEPTH, any_too_deep, is_nary_char, math_class, merge_runs, too_deep,
|
||||
};
|
||||
use crate::math_linear::{FUNCTION_NAMES, map_args};
|
||||
use crate::math_symbols::{name_of, symbol};
|
||||
|
||||
@@ -109,7 +111,7 @@ pub fn parse_latex(s: &str) -> Arg {
|
||||
p.i += 1;
|
||||
}
|
||||
let out = merge_runs(out);
|
||||
if out.iter().any(|n| matches!(n, MNode::Run(r) if r.text.contains('#'))) {
|
||||
if out.iter().any(|n| matches!(n, MNode::Run(r) if !r.nor && r.text.contains('#'))) {
|
||||
return vec![MNode::EqArr { rows: vec![out] }];
|
||||
}
|
||||
out
|
||||
@@ -147,8 +149,13 @@ impl Lp {
|
||||
Tok::Sup | Tok::Sub => {
|
||||
self.i += 1;
|
||||
let s = self.arg();
|
||||
let base = out.pop();
|
||||
out.push(script(base, tok == Tok::Sup, s));
|
||||
if out.last().is_some_and(too_deep) {
|
||||
// Too deep to wrap (`x^1^1^1…`): the operator is dropped, the script kept.
|
||||
out.extend(s);
|
||||
} else {
|
||||
let base = out.pop();
|
||||
out.push(script(base, tok == Tok::Sup, s));
|
||||
}
|
||||
}
|
||||
Tok::Cmd(ref c) if c == "limits" || c == "nolimits" || c == "displaystyle" || c == "textstyle" => {
|
||||
self.i += 1;
|
||||
@@ -171,7 +178,7 @@ impl Lp {
|
||||
}
|
||||
self.depth -= 1;
|
||||
// Big operators take the following term as their operand.
|
||||
nary_operands(out)
|
||||
nary_operands(out, self.depth)
|
||||
}
|
||||
|
||||
/// A command argument: a `{group}` or one token.
|
||||
@@ -224,10 +231,14 @@ impl Lp {
|
||||
}
|
||||
self.i += 1;
|
||||
let mut level = 0i32;
|
||||
// The previous token was a control word (`\backslash{}`: the empty braces end its name).
|
||||
let mut after_word = false;
|
||||
while let Some(t) = self.peek().cloned() {
|
||||
self.i += 1;
|
||||
let was_word = std::mem::replace(&mut after_word, matches!(&t, Tok::Cmd(c) if c.chars().all(|c| c.is_ascii_alphabetic())));
|
||||
match t {
|
||||
Tok::Close if level == 0 => break,
|
||||
Tok::Open if was_word && self.peek() == Some(&Tok::Close) => self.i += 1,
|
||||
Tok::Open => {
|
||||
level += 1;
|
||||
s.push('{');
|
||||
@@ -515,6 +526,10 @@ impl Lp {
|
||||
while let Some(t @ (Tok::Sup | Tok::Sub)) = self.peek().cloned() {
|
||||
self.i += 1;
|
||||
let s = self.arg();
|
||||
if any_too_deep(&e) {
|
||||
e.extend(s);
|
||||
continue;
|
||||
}
|
||||
let base = if e.len() == 1 { e.pop() } else { Some(group(std::mem::take(&mut e))) };
|
||||
e.push(script(base, t == Tok::Sup, s));
|
||||
}
|
||||
@@ -629,12 +644,14 @@ fn script(base: Option<MNode>, sup: bool, s: Arg) -> MNode {
|
||||
}
|
||||
|
||||
/// Big operators without an operand take the atoms after them up to a relation or binary operator.
|
||||
fn nary_operands(a: Arg) -> Arg {
|
||||
/// `depth` is how deep the operators already sit; past [`WRAP_DEPTH`] they stay without operand
|
||||
/// (`\sum\sum\sum…` must not nest once per operator).
|
||||
fn nary_operands(a: Arg, depth: usize) -> Arg {
|
||||
let mut out: Arg = Vec::with_capacity(a.len());
|
||||
let mut it = a.into_iter().peekable();
|
||||
while let Some(n) = it.next() {
|
||||
match n {
|
||||
MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e } if e.is_empty() => {
|
||||
MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e } if e.is_empty() && depth < WRAP_DEPTH => {
|
||||
let mut body = Vec::new();
|
||||
while let Some(next) = it.peek() {
|
||||
let stop = match next {
|
||||
@@ -650,8 +667,14 @@ fn nary_operands(a: Arg) -> Arg {
|
||||
body.push(x);
|
||||
}
|
||||
}
|
||||
let body = nary_operands(body);
|
||||
out.push(MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e: merge_runs(body) });
|
||||
let body = merge_runs(nary_operands(body, depth + 1));
|
||||
if any_too_deep(&body) {
|
||||
// No room to wrap the operand: it follows the operator.
|
||||
out.push(MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e });
|
||||
out.extend(body);
|
||||
} else {
|
||||
out.push(MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e: body });
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
@@ -725,6 +748,21 @@ fn chars(text: &str, s: &mut String) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text inside `\text{…}`: only what LaTeX would read as markup is escaped.
|
||||
fn text_chars(text: &str, s: &mut String) {
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'{' | '}' | '%' | '$' | '#' | '&' | '_' | '~' => {
|
||||
s.push('\\');
|
||||
s.push(c);
|
||||
}
|
||||
// `{}` ends the command name without adding a space (spaces count in text).
|
||||
'\\' => s.push_str("\\backslash{}"),
|
||||
c => s.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn delim_tex(c: Option<char>) -> String {
|
||||
match c {
|
||||
None => ".".into(),
|
||||
@@ -764,7 +802,7 @@ fn node(n: &MNode, s: &mut String, depth: usize) {
|
||||
};
|
||||
s.push_str(open);
|
||||
if r.nor {
|
||||
s.push_str(&r.text);
|
||||
text_chars(&r.text, s);
|
||||
} else {
|
||||
chars(&r.text, s);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! an operator or space; a parenthesised operand loses its parentheses). `^`/`_` with nothing
|
||||
//! before them are pre-scripts. A top-level `#` numbers the equation (`E=mc^2#(1)`).
|
||||
|
||||
use crate::math::{Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, is_nary_char, math_class, merge_runs};
|
||||
use crate::math::{Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, any_too_deep, is_nary_char, math_class, merge_runs, too_deep};
|
||||
|
||||
/// Function names set upright and applied to the following operand.
|
||||
pub const FUNCTION_NAMES: &[&str] = &[
|
||||
@@ -135,6 +135,11 @@ impl P {
|
||||
'/' | '⁄' | '∕' | '¦' => {
|
||||
self.i += 1;
|
||||
let start = operand_start(&out);
|
||||
// A numerator that is already deep stays as it is: `/` is text then.
|
||||
if out.get(start..).is_some_and(any_too_deep) {
|
||||
out.push(text(c));
|
||||
continue;
|
||||
}
|
||||
let num = strip_parens(out.drain(start..).collect());
|
||||
let den = self.operand(stops);
|
||||
let kind = match c {
|
||||
@@ -156,20 +161,34 @@ impl P {
|
||||
} else {
|
||||
self.i += 1;
|
||||
let s = self.script_operand(stops);
|
||||
let base = out.pop();
|
||||
out.push(attach_script(base, c == '^', s));
|
||||
if out.last().is_some_and(too_deep) {
|
||||
out.push(text(c));
|
||||
out.extend(s);
|
||||
} else {
|
||||
let base = out.pop();
|
||||
out.push(attach_script(base, c == '^', s));
|
||||
}
|
||||
}
|
||||
}
|
||||
'┬' | '┴' => {
|
||||
self.i += 1;
|
||||
let lim = self.script_operand(stops);
|
||||
let e = out.pop().map(|n| vec![n]).unwrap_or_default();
|
||||
out.push(MNode::Lim { upper: c == '┴', e: strip_parens(e), lim });
|
||||
if out.last().is_some_and(too_deep) {
|
||||
out.push(text(c));
|
||||
out.extend(lim);
|
||||
} else {
|
||||
let e = out.pop().map(|n| vec![n]).unwrap_or_default();
|
||||
out.push(MNode::Lim { upper: c == '┴', e: strip_parens(e), lim });
|
||||
}
|
||||
}
|
||||
c if is_combining(c) => {
|
||||
self.i += 1;
|
||||
let e = out.pop().map(|n| strip_parens(vec![n])).unwrap_or_default();
|
||||
out.push(MNode::Acc { chr: c, e });
|
||||
if out.last().is_some_and(too_deep) {
|
||||
out.push(text(c));
|
||||
} else {
|
||||
let e = out.pop().map(|n| strip_parens(vec![n])).unwrap_or_default();
|
||||
out.push(MNode::Acc { chr: c, e });
|
||||
}
|
||||
}
|
||||
'▒' | '\u{2061}' => self.i += 1,
|
||||
' ' => {
|
||||
@@ -537,25 +556,33 @@ impl P {
|
||||
}
|
||||
out.pop()
|
||||
};
|
||||
if !matches!(c, '^' | '_') && !(matches!(c, '┬' | '┴') && self.no_limits == 0) && !is_combining(c) {
|
||||
break;
|
||||
}
|
||||
// The base is already deep: the operator is text (see `too_deep`).
|
||||
let deep = if whole { any_too_deep(out) } else { out.last().is_some_and(too_deep) };
|
||||
self.i += 1;
|
||||
if deep {
|
||||
let s = if matches!(c, '^' | '_' | '┬' | '┴') { self.script_operand(stops) } else { Vec::new() };
|
||||
out.push(text(c));
|
||||
out.extend(s);
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'^' | '_' => {
|
||||
self.i += 1;
|
||||
let s = self.script_operand(stops);
|
||||
let b = base(out);
|
||||
out.push(attach_script(b, c == '^', s));
|
||||
}
|
||||
'┬' | '┴' if self.no_limits == 0 => {
|
||||
self.i += 1;
|
||||
'┬' | '┴' => {
|
||||
let lim = self.script_operand(stops);
|
||||
let b = base(out);
|
||||
out.push(MNode::Lim { upper: c == '┴', e: b.map(|n| vec![n]).unwrap_or_default(), lim });
|
||||
}
|
||||
c if is_combining(c) => {
|
||||
self.i += 1;
|
||||
_ => {
|
||||
let b = base(out);
|
||||
out.push(MNode::Acc { chr: c, e: b.map(|n| strip_parens(vec![n])).unwrap_or_default() });
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +85,7 @@ pub const SYMBOLS: &[(&str, char)] = &[
|
||||
("vee", '∨'),
|
||||
("wedge", '∧'),
|
||||
("setminus", '∖'),
|
||||
("backslash", '\\'),
|
||||
("wr", '≀'),
|
||||
("diamond", '⋄'),
|
||||
("dagger", '†'),
|
||||
|
||||
+64
-11
@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::{Align, CharProps};
|
||||
use crate::section::NumFormat;
|
||||
use crate::{DocError, free_id};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -75,6 +76,17 @@ pub struct AbstractNum {
|
||||
pub id: u32,
|
||||
pub name: Option<String>,
|
||||
pub levels: Vec<Level>,
|
||||
/// Word's list identity (`w:nsid`, 8 hex digits), which it uses to match lists across
|
||||
/// documents (paste, compare); kept from the file.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub nsid: Option<String>,
|
||||
/// The list template the definition came from (`w:tmpl`); kept from the file.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tmpl: Option<String>,
|
||||
/// `w:multiLevelType` from the file (`singleLevel`, `multilevel`, `hybridMultilevel`);
|
||||
/// `None`: derived from the levels.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub multi_level_type: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
@@ -219,20 +231,40 @@ impl Numbering {
|
||||
}
|
||||
self.abstract_of(num)?.levels.get(level as usize)
|
||||
}
|
||||
/// Create a new list of `kind`; returns the `num` id.
|
||||
/// Create a new list of `kind`; returns the `num` id. List ids run out only past `u32::MAX`
|
||||
/// lists, more than memory holds; then nothing is added and the id is 0, "no list".
|
||||
pub fn add_list(&mut self, kind: ListKind) -> u32 {
|
||||
let aid = self.abstracts.iter().map(|a| a.id + 1).max().unwrap_or(0);
|
||||
self.abstracts.push(AbstractNum { id: aid, name: None, levels: levels_for(kind) });
|
||||
let nid = self.nums.iter().map(|n| n.id + 1).max().unwrap_or(1).max(1);
|
||||
self.nums.push(Num { id: nid, abstract_id: aid, ..Default::default() });
|
||||
nid
|
||||
self.try_add_list(kind).unwrap_or(0)
|
||||
}
|
||||
/// A new `num` that restarts numbering of an existing list.
|
||||
/// [`Numbering::add_list`], or an error, adding nothing, when list ids are all taken.
|
||||
pub fn try_add_list(&mut self, kind: ListKind) -> crate::Result<u32> {
|
||||
self.try_add_levels(None, levels_for(kind))
|
||||
}
|
||||
/// A new list definition (`name`, `levels`) and a `num` for it; returns the `num` id. Both ids
|
||||
/// are [`free_id`]s, so the largest ids a file can hold don't make them collide with its lists;
|
||||
/// an error, adding nothing, when they are all taken.
|
||||
pub fn try_add_levels(&mut self, name: Option<String>, levels: Vec<Level>) -> crate::Result<u32> {
|
||||
let aid = free_id(self.abstracts.iter().map(|a| a.id).max(), self.abstracts.iter().map(|a| a.id), 0);
|
||||
let (Some(aid), Some(nid)) = (aid, self.free_num_id()) else { return Err(DocError::Invalid("no free list id".into())) };
|
||||
self.abstracts.push(AbstractNum { id: aid, name, levels, ..Default::default() });
|
||||
self.nums.push(Num { id: nid, abstract_id: aid, ..Default::default() });
|
||||
Ok(nid)
|
||||
}
|
||||
/// A `num` id no list has (`num` 0 means "no list"), `None` when they are all taken.
|
||||
fn free_num_id(&self) -> Option<u32> {
|
||||
free_id(self.nums.iter().map(|n| n.id).max(), self.nums.iter().map(|n| n.id), 1)
|
||||
}
|
||||
/// A new `num` that restarts numbering of an existing list (`None`: no such list, or list ids
|
||||
/// are all taken).
|
||||
pub fn restart(&mut self, num: u32) -> Option<u32> {
|
||||
let a = self.num(num)?.abstract_id;
|
||||
let nid = self.nums.iter().map(|n| n.id + 1).max().unwrap_or(1).max(1);
|
||||
let starts = self.abstracts.iter().find(|x| x.id == a).map(|x| x.levels.iter().enumerate().map(|(i, l)| (i as u8, l.start)).collect());
|
||||
self.nums.push(Num { id: nid, abstract_id: a, start_overrides: starts.unwrap_or_default(), ..Default::default() });
|
||||
let source = self.num(num)?;
|
||||
let a = source.abstract_id;
|
||||
let level_overrides = source.level_overrides.clone();
|
||||
let nid = self.free_num_id()?;
|
||||
// Every level starts again at its own effective start, so a level this list defines itself keeps its start.
|
||||
let levels = self.abstracts.iter().find(|x| x.id == a).map_or(0, |x| x.levels.len());
|
||||
let start_overrides = (0..levels).filter_map(|i| self.level(num, i as u8).map(|l| (i as u8, l.start))).collect();
|
||||
self.nums.push(Num { id: nid, abstract_id: a, start_overrides, level_overrides });
|
||||
Some(nid)
|
||||
}
|
||||
/// Find an existing list whose first level matches `kind`, so consecutive bullet clicks reuse it.
|
||||
@@ -256,6 +288,12 @@ pub struct Counters {
|
||||
}
|
||||
|
||||
impl Counters {
|
||||
/// The current value of each level of `num`'s list (0 for a level not counted yet).
|
||||
pub fn values(&self, numbering: &Numbering, num: u32) -> Option<[u32; 9]> {
|
||||
let abs = numbering.abstract_of(num)?;
|
||||
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
|
||||
}
|
||||
|
||||
/// Advance the counter for `num`/`level` and return the label (`"1."`, `"a)"`, `"•"`).
|
||||
pub fn next_label(&mut self, numbering: &Numbering, num: u32, level: u8) -> Option<(String, Level)> {
|
||||
let n = numbering.num(num)?;
|
||||
@@ -432,4 +470,19 @@ mod tests {
|
||||
assert_eq!(c.next_label(&n, b, 0).unwrap().0, "•");
|
||||
assert_eq!(n.find_kind(ListKind::Bullet), Some(b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_keeps_the_list_s_own_level_definitions() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
let own = Level { format: NumFormat::UpperRoman, text: "Part %1".into(), indent: 90.0, hanging: 40.0, start: 5, ..Level::default() };
|
||||
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
|
||||
num.level_overrides.push((0, own.clone()));
|
||||
}
|
||||
let r = n.restart(id).unwrap();
|
||||
assert_eq!(n.num(r).unwrap().level_overrides, vec![(0, own.clone())]);
|
||||
assert_eq!(n.level(r, 0), Some(&own));
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
|
||||
}
|
||||
}
|
||||
|
||||
+47
-23
@@ -288,7 +288,11 @@ pub enum ShapeKind {
|
||||
Rectangle,
|
||||
RoundedRectangle,
|
||||
Ellipse,
|
||||
/// Flowchart OR preset: an ellipse with horizontal and vertical spokes.
|
||||
FlowchartOr,
|
||||
Triangle,
|
||||
/// A right triangle (DrawingML's `rtTriangle`): the right angle at the bottom left.
|
||||
RightTriangle,
|
||||
Diamond,
|
||||
Line,
|
||||
Arrow,
|
||||
@@ -380,7 +384,7 @@ pub enum InlineObject {
|
||||
crop: [f32; 4],
|
||||
/// The OLE object (embedded or linked file) this picture shows, as read from a file:
|
||||
/// saving writes the object back, not only its picture. See [`crate::graphic::Embedded`].
|
||||
#[serde(skip)]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
ole: Option<std::sync::Arc<crate::graphic::Embedded>>,
|
||||
},
|
||||
/// A chart or SmartArt diagram (see [`crate::graphic`]).
|
||||
@@ -444,11 +448,20 @@ pub enum InlineObject {
|
||||
result: String,
|
||||
#[serde(default)]
|
||||
locked: bool,
|
||||
/// `w:dirty` (ECMA-376 §17.16.5.35): the cached result is stale — another program that
|
||||
/// couldn't compute it set the flag so Word refreshes the field on open. Kept through
|
||||
/// saves; cleared when WordCraft computes a result, like Word's F9.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
dirty: bool,
|
||||
/// Shows its code (`{ PAGE }`) instead of its result, the other way round from the
|
||||
/// document-wide View › Field Codes setting (`fields.toggleCode`, Shift+F9). A view
|
||||
/// toggle: never written to files.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
code: bool,
|
||||
/// A legacy form field's definition (`FORMCHECKBOX`, `FORMTEXT`, `FORMDROPDOWN`): the
|
||||
/// source's `w:ffData`, raw OOXML kept for round trip. Empty for other fields.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
form: String,
|
||||
},
|
||||
/// The start of a field whose result is ordinary content — formatted, possibly spanning
|
||||
/// paragraphs — up to the matching [`InlineObject::FieldEnd`]. Imported TOCs and citation
|
||||
@@ -458,6 +471,9 @@ pub enum InlineObject {
|
||||
instr: String,
|
||||
#[serde(default)]
|
||||
locked: bool,
|
||||
/// `w:dirty` on the begin marker, as [`InlineObject::Field::dirty`].
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
dirty: bool,
|
||||
},
|
||||
/// The end of the innermost open [`InlineObject::FieldStart`].
|
||||
FieldEnd,
|
||||
@@ -1029,32 +1045,32 @@ impl Paragraph {
|
||||
|
||||
/// Merge adjacent equal runs and drop empty ones.
|
||||
pub fn normalize(&mut self) {
|
||||
// Runs must end on character boundaries and cover the text exactly (never expected, but
|
||||
// files lie): clamp each end to the text, push it past a split character, pad the tail.
|
||||
let n = self.text.len();
|
||||
let mut end = 0usize;
|
||||
let mut out: Vec<Run> = Vec::with_capacity(self.runs.len());
|
||||
for r in self.runs.drain(..) {
|
||||
if r.len == 0 {
|
||||
let mut e = end.saturating_add(r.len).min(n);
|
||||
while !self.text.is_char_boundary(e) {
|
||||
e += 1;
|
||||
}
|
||||
if e == end {
|
||||
continue;
|
||||
}
|
||||
match out.last_mut() {
|
||||
Some(l) if l.props == r.props => l.len += r.len,
|
||||
_ => out.push(r),
|
||||
Some(l) if l.props == r.props => l.len += e - end,
|
||||
_ => out.push(Run { len: e - end, props: r.props }),
|
||||
}
|
||||
end = e;
|
||||
}
|
||||
if end < n {
|
||||
match out.last_mut() {
|
||||
Some(l) => l.len += n - end,
|
||||
None => out.push(Run { len: n, props: self.mark.clone() }),
|
||||
}
|
||||
}
|
||||
self.runs = out;
|
||||
// Repair a run list that doesn't cover the text exactly (never expected, but files lie).
|
||||
let total: usize = self.runs.iter().map(|r| r.len).sum();
|
||||
if total != self.text.len() {
|
||||
if total < self.text.len() {
|
||||
let p = self.runs.last().map(|r| r.props.clone()).unwrap_or_else(|| self.mark.clone());
|
||||
self.runs.push(Run { len: self.text.len() - total, props: p });
|
||||
} else {
|
||||
let mut keep = self.text.len();
|
||||
for r in &mut self.runs {
|
||||
r.len = r.len.min(keep);
|
||||
keep -= r.len;
|
||||
}
|
||||
self.runs.retain(|r| r.len > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete `a..b` (bytes). Objects inside are removed.
|
||||
@@ -1345,8 +1361,12 @@ mod tests {
|
||||
fn text_without_takes_ranges_in_any_order() {
|
||||
// Multi-byte chars at range edges, an object, and ranges unsorted, overlapping, nested and empty.
|
||||
let mut p = Paragraph::with_text("añb€c", CharProps::default());
|
||||
p.insert_object(3, InlineObject::Field { instr: "PAGE".into(), result: "7".into(), locked: false, code: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
p.insert_object(
|
||||
3,
|
||||
InlineObject::Field { instr: "PAGE".into(), result: "7".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let text = p.text.clone();
|
||||
let naive = |dropped: &[std::ops::Range<usize>]| {
|
||||
let mut out = String::new();
|
||||
@@ -1415,8 +1435,12 @@ mod tests {
|
||||
#[test]
|
||||
fn objects_track_text() {
|
||||
let mut p = Paragraph::with_text("ab", CharProps::default());
|
||||
p.insert_object(1, InlineObject::Field { instr: "PAGE".into(), result: "1".into(), locked: false, code: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
p.insert_object(
|
||||
1,
|
||||
InlineObject::Field { instr: "PAGE".into(), result: "1".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
p.insert_object(0, InlineObject::BookmarkStart { name: "x".into() }, &CharProps::default()).unwrap();
|
||||
assert_eq!(p.objects.len(), 2);
|
||||
assert!(matches!(p.object_at(0), Some(InlineObject::BookmarkStart { .. })));
|
||||
|
||||
+31
-1
@@ -554,6 +554,10 @@ impl TabLeader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two tab positions closer than this (points) are the same stop: `para.tabs` replaces at this
|
||||
/// tolerance, and the Tabs dialog and the ruler merge and detect no-ops with it.
|
||||
pub const TAB_POS_EPS: f32 = 0.5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TabStop {
|
||||
/// Points from the paragraph's left indent origin (the text column's left edge).
|
||||
@@ -1074,11 +1078,31 @@ pub struct RowProps {
|
||||
pub header: bool,
|
||||
/// Don't let the row break across pages.
|
||||
pub cant_split: bool,
|
||||
/// Table properties this row overrides (`w:tblPrEx`, ECMA-376 §17.4.61): width, alignment,
|
||||
/// indent, borders, shading, layout and cell margins. `Some` when the file has the element.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub exceptions: Option<Box<TableProps>>,
|
||||
/// Grid columns skipped before the row's first cell (`w:gridBefore`), and the preferred
|
||||
/// width of that gap in points (`w:wBefore`).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub grid_before: u32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub w_before: Option<f32>,
|
||||
/// Grid columns left after the row's last cell (`w:gridAfter`), and their width in points
|
||||
/// (`w:wAfter`).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub grid_after: u32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub w_after: Option<f32>,
|
||||
/// Tracked formatting change (`w:trPrChange`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fmt_change: Option<Box<PropChange<RowProps>>>,
|
||||
}
|
||||
|
||||
fn is_zero(v: &u32) -> bool {
|
||||
*v == 0
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VMerge {
|
||||
@@ -1103,11 +1127,17 @@ pub struct CellProps {
|
||||
pub vmerge: VMerge,
|
||||
pub shading: Option<Rgb>,
|
||||
pub borders: Option<Borders>,
|
||||
pub valign: VAlign,
|
||||
/// Vertical alignment (`w:vAlign`); `None` follows the table style, else top. An explicit
|
||||
/// `Top` beats the style.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub valign: Option<VAlign>,
|
||||
/// Cell margins override (top, left, bottom, right), points.
|
||||
pub margins: Option<[f32; 4]>,
|
||||
/// Which way the cell's text runs.
|
||||
pub text_direction: TextDirection,
|
||||
/// The file states the horizontal direction (`lrTb`) outright; saving writes it back.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub text_direction_set: bool,
|
||||
pub no_wrap: bool,
|
||||
/// The cell's last paragraph takes no room when it is empty (`w:hideMark`): a row of such
|
||||
/// empty cells shrinks to its borders.
|
||||
|
||||
@@ -2,7 +2,36 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::{Borders, VAlign};
|
||||
use crate::props::Borders;
|
||||
|
||||
/// How a section's text sits on its pages, top to bottom (`w:vAlign`, ECMA-376 §17.6.23,
|
||||
/// ST_VerticalJc). Table cells and text boxes use [`crate::props::VAlign`], which has no
|
||||
/// Justified.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PageVAlign {
|
||||
#[default]
|
||||
Top,
|
||||
Center,
|
||||
/// Justified (`both`): the room left on each page is shared out equally between the page's
|
||||
/// paragraphs and tables, so the text runs from the top margin to the bottom one.
|
||||
#[serde(alias = "both", alias = "justified")]
|
||||
Justify,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl PageVAlign {
|
||||
/// From a command or file value: `top|center|justify|bottom` (also `both`, `justified`,
|
||||
/// `middle`); anything else is Top.
|
||||
pub fn parse(v: &str) -> PageVAlign {
|
||||
match v {
|
||||
"center" | "middle" => PageVAlign::Center,
|
||||
"justify" | "justified" | "both" => PageVAlign::Justify,
|
||||
"bottom" => PageVAlign::Bottom,
|
||||
_ => PageVAlign::Top,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -227,7 +256,7 @@ impl NumFormat {
|
||||
NumFormat::ALL.into_iter().find(|f| f.ooxml() == s).unwrap_or(NumFormat::Decimal)
|
||||
}
|
||||
/// Format `n` (1-based). Formats WordCraft doesn't draw yet (Hebrew, Arabic, Hindi, Thai,
|
||||
/// Vietnamese, Russian, text amounts) show decimal, as do values past a sequence's end
|
||||
/// Vietnamese, text amounts) show decimal, as do values past a sequence's end
|
||||
/// (the 21st item of ①…⑳).
|
||||
pub fn format(self, n: u32) -> String {
|
||||
use crate::cjk_numbers as cjk;
|
||||
@@ -237,6 +266,8 @@ impl NumFormat {
|
||||
NumFormat::LowerRoman => roman(n),
|
||||
NumFormat::UpperLetter => letters(n).to_uppercase(),
|
||||
NumFormat::LowerLetter => letters(n),
|
||||
NumFormat::RussianUpper => russian_letters(n).to_uppercase(),
|
||||
NumFormat::RussianLower => russian_letters(n),
|
||||
NumFormat::Ordinal => format!("{n}{}", ordinal_suffix(n)),
|
||||
NumFormat::CardinalText => cardinal_text(n),
|
||||
NumFormat::OrdinalText => ordinal_text(n),
|
||||
@@ -275,8 +306,6 @@ impl NumFormat {
|
||||
| NumFormat::DecimalHalfWidth
|
||||
| NumFormat::Hex
|
||||
| NumFormat::VietnameseCounting
|
||||
| NumFormat::RussianLower
|
||||
| NumFormat::RussianUpper
|
||||
| NumFormat::Hebrew1
|
||||
| NumFormat::Hebrew2
|
||||
| NumFormat::ArabicAlpha
|
||||
@@ -354,6 +383,22 @@ pub fn letters(n: u32) -> String {
|
||||
std::iter::repeat_n(c, k as usize).collect()
|
||||
}
|
||||
|
||||
/// The 29 letters Word counts Russian lists with: а..я without ё, й, ъ and ь (ы stays).
|
||||
const RUSSIAN_LETTERS: [char; 29] =
|
||||
['а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ы', 'э', 'ю', 'я'];
|
||||
|
||||
/// Word-style Russian letters: а..я, аа..яя, ааа.. (repeated letter, as [`letters`]).
|
||||
pub fn russian_letters(n: u32) -> String {
|
||||
if n == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let len = RUSSIAN_LETTERS.len() as u32;
|
||||
let n = n.min(len * 30);
|
||||
let k = (n - 1) / len + 1;
|
||||
let c = RUSSIAN_LETTERS.get(((n - 1) % len) as usize).copied().unwrap_or('а');
|
||||
std::iter::repeat_n(c, k as usize).collect()
|
||||
}
|
||||
|
||||
const ONES: [&str; 20] = [
|
||||
"zero",
|
||||
"one",
|
||||
@@ -676,8 +721,16 @@ pub struct SectionProps {
|
||||
pub title_page: bool,
|
||||
pub page_num_start: Option<u32>,
|
||||
pub page_num_format: NumFormat,
|
||||
/// The file carries a `w:pgNumType` element that sets nothing else (no start, decimal
|
||||
/// format), so saving writes it back rather than dropping it.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub page_num_set: bool,
|
||||
pub line_numbers: Option<LineNumbering>,
|
||||
pub valign: VAlign,
|
||||
pub valign: PageVAlign,
|
||||
/// Form protection of the section (`w:formProt`, ECMA-376 §17.6.6): `Some` when the file
|
||||
/// states it. Kept so saving writes it back; editing does not act on it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub form_prot: Option<bool>,
|
||||
pub page_borders: Option<Borders>,
|
||||
/// Text direction / bidi section.
|
||||
pub rtl: bool,
|
||||
@@ -685,6 +738,9 @@ pub struct SectionProps {
|
||||
/// sections turn the page's text area (headers and footers stay horizontal).
|
||||
#[serde(skip_serializing_if = "is_horizontal")]
|
||||
pub text_direction: crate::props::TextDirection,
|
||||
/// The file states the horizontal direction (`lrTb`) outright; saving writes it back.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub text_direction_set: bool,
|
||||
/// Tracked change of the section's properties (`w:sectPrChange`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fmt_change: Option<Box<crate::props::PropChange<SectionProps>>>,
|
||||
@@ -718,11 +774,14 @@ impl Default for SectionProps {
|
||||
title_page: false,
|
||||
page_num_start: None,
|
||||
page_num_format: NumFormat::Decimal,
|
||||
page_num_set: false,
|
||||
line_numbers: None,
|
||||
valign: VAlign::Top,
|
||||
valign: PageVAlign::Top,
|
||||
form_prot: None,
|
||||
page_borders: None,
|
||||
rtl: false,
|
||||
text_direction: crate::props::TextDirection::Horizontal,
|
||||
text_direction_set: false,
|
||||
fmt_change: None,
|
||||
doc_grid: None,
|
||||
footnote_pr: NoteProps::default(),
|
||||
@@ -831,6 +890,8 @@ mod tests {
|
||||
assert_eq!(NumFormat::ChineseCountingThousand.format(101), "一百零一");
|
||||
assert_eq!(NumFormat::DecimalEnclosedCircle.format(3), "③");
|
||||
assert_eq!(NumFormat::Hebrew1.format(3), "3", "formats not drawn yet show decimal");
|
||||
assert_eq!(NumFormat::RussianLower.format(0), "");
|
||||
assert_eq!(NumFormat::RussianUpper.format(u32::MAX).chars().count(), 30);
|
||||
for f in NumFormat::ALL {
|
||||
assert_eq!(NumFormat::from_ooxml(f.ooxml()), f, "{f:?} round-trips");
|
||||
assert!(f == NumFormat::Bullet || f == NumFormat::None || !f.format(u32::MAX).is_empty(), "{f:?}");
|
||||
@@ -838,6 +899,17 @@ mod tests {
|
||||
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn russian_letters_follow_word() {
|
||||
// Word's own labels for a russianLower list: no ё, й, ъ or ь, then doubled letters.
|
||||
let labels: Vec<String> = (1..=31).map(|n| NumFormat::RussianLower.format(n)).collect();
|
||||
assert_eq!(labels.join(" "), "а б в г д е ж з и к л м н о п р с т у ф х ц ч ш щ ы э ю я аа бб");
|
||||
assert_eq!(NumFormat::RussianLower.format(59), "ааа");
|
||||
assert_eq!(NumFormat::RussianLower.format(100), "нннн");
|
||||
assert_eq!(NumFormat::RussianUpper.format(26), "Ы");
|
||||
assert_eq!(NumFormat::RussianUpper.format(36), "ЖЖ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn landscape_swaps() {
|
||||
let mut s = SectionProps { margin_left: 50.0, ..Default::default() };
|
||||
|
||||
+354
-2
@@ -3,7 +3,12 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::{Align, Border, BorderStyle, Borders, CharProps, LineSpacing, ParaProps, Rgb, TabAlign, TabLeader, TabStop, TextColor, Underline};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::props::{
|
||||
Align, Border, BorderStyle, Borders, CharProps, LineSpacing, ParaProps, Rgb, TabAlign, TabLeader, TabStop, TableLook, TextColor, Underline,
|
||||
VAlign,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -41,6 +46,10 @@ pub struct Style {
|
||||
/// (`w:locked`).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub locked: bool,
|
||||
/// The default style of its kind (`w:default`), whatever its id: localized documents call
|
||||
/// the default character, table and list styles something other than the English ids.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub default: bool,
|
||||
/// Table style: conditional formatting for header row, banding etc.
|
||||
pub table: Option<TableStyleParts>,
|
||||
}
|
||||
@@ -84,6 +93,166 @@ pub struct TableStyleParts {
|
||||
pub col_band_fill: Option<Rgb>,
|
||||
pub col_band_chr: CharProps,
|
||||
pub col_band_borders: Option<Borders>,
|
||||
/// Per-part formatting the named fields above don't carry: every field of the parts without
|
||||
/// one (even bands, corner cells), and the cell text alignment of every part. Read and write
|
||||
/// parts through [`TableStyleParts::part`] / [`TableStyleParts::set_part`].
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub regions: BTreeMap<TablePart, PartFormat>,
|
||||
}
|
||||
|
||||
/// A conditional formatting part of a table style (`w:tblStylePr/@w:type`, ECMA-376 §17.7.6).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TablePart {
|
||||
WholeTable,
|
||||
FirstRow,
|
||||
LastRow,
|
||||
FirstCol,
|
||||
LastCol,
|
||||
Band1Vert,
|
||||
Band2Vert,
|
||||
Band1Horz,
|
||||
Band2Horz,
|
||||
NeCell,
|
||||
NwCell,
|
||||
SeCell,
|
||||
SwCell,
|
||||
}
|
||||
|
||||
impl TablePart {
|
||||
/// Every part, lowest precedence first (ECMA-376 §17.7.6: whole table, bands, first/last
|
||||
/// column, first/last row, corner cells).
|
||||
pub const ALL: [TablePart; 13] = [
|
||||
TablePart::WholeTable,
|
||||
TablePart::Band1Vert,
|
||||
TablePart::Band2Vert,
|
||||
TablePart::Band1Horz,
|
||||
TablePart::Band2Horz,
|
||||
TablePart::FirstCol,
|
||||
TablePart::LastCol,
|
||||
TablePart::FirstRow,
|
||||
TablePart::LastRow,
|
||||
TablePart::NeCell,
|
||||
TablePart::NwCell,
|
||||
TablePart::SeCell,
|
||||
TablePart::SwCell,
|
||||
];
|
||||
/// The `w:type` value.
|
||||
pub fn ooxml(self) -> &'static str {
|
||||
match self {
|
||||
TablePart::WholeTable => "wholeTable",
|
||||
TablePart::FirstRow => "firstRow",
|
||||
TablePart::LastRow => "lastRow",
|
||||
TablePart::FirstCol => "firstCol",
|
||||
TablePart::LastCol => "lastCol",
|
||||
TablePart::Band1Vert => "band1Vert",
|
||||
TablePart::Band2Vert => "band2Vert",
|
||||
TablePart::Band1Horz => "band1Horz",
|
||||
TablePart::Band2Horz => "band2Horz",
|
||||
TablePart::NeCell => "neCell",
|
||||
TablePart::NwCell => "nwCell",
|
||||
TablePart::SeCell => "seCell",
|
||||
TablePart::SwCell => "swCell",
|
||||
}
|
||||
}
|
||||
pub fn from_ooxml(s: &str) -> Option<TablePart> {
|
||||
TablePart::ALL.into_iter().find(|p| p.ooxml() == s)
|
||||
}
|
||||
/// A part spanning whole rows (its left/right edges are the table's sides, `inside_v` the
|
||||
/// edges between its cells).
|
||||
pub fn is_row(self) -> bool {
|
||||
matches!(self, TablePart::FirstRow | TablePart::LastRow | TablePart::Band1Horz | TablePart::Band2Horz)
|
||||
}
|
||||
/// A part spanning whole columns (its top/bottom edges are the table's, `between` the edges
|
||||
/// between its cells).
|
||||
pub fn is_column(self) -> bool {
|
||||
matches!(self, TablePart::FirstCol | TablePart::LastCol | TablePart::Band1Vert | TablePart::Band2Vert)
|
||||
}
|
||||
fn bit(self) -> u16 {
|
||||
1 << (TablePart::ALL.iter().position(|p| *p == self).unwrap_or(0) as u16)
|
||||
}
|
||||
}
|
||||
|
||||
/// The table style parts one cell is in (always the whole table).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct PartSet(u16);
|
||||
|
||||
impl PartSet {
|
||||
/// The parts of the cell at row `ri` of `nrows`, grid column `g` spanning `span` of `ncols`,
|
||||
/// in a table with options `look` and row bands of `band_size` rows.
|
||||
pub fn of_cell(look: &TableLook, band_size: u32, (ri, nrows): (usize, usize), (g, span, ncols): (usize, usize, usize)) -> PartSet {
|
||||
let header = look.header_row && ri == 0;
|
||||
let total = look.total_row && ri + 1 == nrows && nrows > 1;
|
||||
let first_col = look.first_column && g == 0;
|
||||
let last_col = look.last_column && g.saturating_add(span) >= ncols && ncols > 1;
|
||||
let size = band_size.clamp(1, 1000) as usize;
|
||||
let row_band = look.banded_rows && !header;
|
||||
let odd_row = (ri.saturating_sub(usize::from(look.header_row)) / size).is_multiple_of(2);
|
||||
let col_band = look.banded_columns && !first_col;
|
||||
let odd_col = g.saturating_sub(usize::from(look.first_column)).is_multiple_of(2);
|
||||
let mut bits = TablePart::WholeTable.bit();
|
||||
for (on, p) in [
|
||||
(col_band && odd_col, TablePart::Band1Vert),
|
||||
(col_band && !odd_col, TablePart::Band2Vert),
|
||||
(row_band && odd_row, TablePart::Band1Horz),
|
||||
(row_band && !odd_row, TablePart::Band2Horz),
|
||||
(first_col, TablePart::FirstCol),
|
||||
(last_col, TablePart::LastCol),
|
||||
(header, TablePart::FirstRow),
|
||||
(total, TablePart::LastRow),
|
||||
(header && last_col, TablePart::NeCell),
|
||||
(header && first_col, TablePart::NwCell),
|
||||
(total && last_col, TablePart::SeCell),
|
||||
(total && first_col, TablePart::SwCell),
|
||||
] {
|
||||
if on {
|
||||
bits |= p.bit();
|
||||
}
|
||||
}
|
||||
PartSet(bits)
|
||||
}
|
||||
pub fn contains(self, p: TablePart) -> bool {
|
||||
self.0 & p.bit() != 0
|
||||
}
|
||||
/// The parts, lowest precedence first.
|
||||
pub fn iter(self) -> impl Iterator<Item = TablePart> {
|
||||
TablePart::ALL.into_iter().filter(move |p| self.contains(*p))
|
||||
}
|
||||
}
|
||||
|
||||
/// What one table style part gives its cells.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PartFormat {
|
||||
pub chr: CharProps,
|
||||
/// Cell shading.
|
||||
pub fill: Option<Rgb>,
|
||||
/// Cell borders (the whole table's are the table borders).
|
||||
pub borders: Option<Borders>,
|
||||
/// Horizontal alignment of the cells' paragraphs (`w:pPr/w:jc`).
|
||||
pub align: Option<Align>,
|
||||
/// Vertical alignment in the cells (`w:tcPr/w:vAlign`).
|
||||
pub v_align: Option<VAlign>,
|
||||
}
|
||||
|
||||
impl PartFormat {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == PartFormat::default()
|
||||
}
|
||||
/// What `patch` sets wins; borders merge edge by edge.
|
||||
pub fn overlay(&mut self, patch: &PartFormat) {
|
||||
self.chr.overlay(&patch.chr);
|
||||
self.fill = patch.fill.or(self.fill);
|
||||
self.borders = match (self.borders, patch.borders) {
|
||||
(Some(mut b), Some(p)) => {
|
||||
b.overlay(&p);
|
||||
Some(b)
|
||||
}
|
||||
(b, p) => p.or(b),
|
||||
};
|
||||
self.align = patch.align.or(self.align);
|
||||
self.v_align = patch.v_align.or(self.v_align);
|
||||
}
|
||||
}
|
||||
|
||||
impl TableStyleParts {
|
||||
@@ -120,6 +289,125 @@ impl TableStyleParts {
|
||||
self.col_band_fill = patch.col_band_fill.or(self.col_band_fill);
|
||||
self.col_band_chr.overlay(&patch.col_band_chr);
|
||||
self.col_band_borders = merge(self.col_band_borders, patch.col_band_borders);
|
||||
for (k, f) in &patch.regions {
|
||||
self.regions.entry(*k).or_default().overlay(f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Part `p`'s formatting. The whole table's text formatting is the style's own
|
||||
/// ([`Style::table_part`] adds it); its borders are the table borders.
|
||||
pub fn part(&self, p: TablePart) -> PartFormat {
|
||||
let extra = self.regions.get(&p).cloned().unwrap_or_default();
|
||||
let named = |chr: &CharProps, fill: Option<Rgb>, borders: Option<Borders>| PartFormat {
|
||||
chr: chr.clone(),
|
||||
fill,
|
||||
borders,
|
||||
align: extra.align,
|
||||
v_align: extra.v_align,
|
||||
};
|
||||
match p {
|
||||
TablePart::WholeTable => {
|
||||
PartFormat { chr: CharProps::default(), fill: self.fill, borders: self.borders, align: None, v_align: extra.v_align }
|
||||
}
|
||||
TablePart::FirstRow => named(&self.header_chr, self.header_fill, self.header_borders),
|
||||
TablePart::LastRow => {
|
||||
// The built-in top rule is the region's top edge unless its borders set one.
|
||||
let borders = match (self.total_borders, self.total_border_top) {
|
||||
(Some(mut b), top) => {
|
||||
b.top = b.top.or(top);
|
||||
Some(b)
|
||||
}
|
||||
(None, top) => top.map(|t| Borders { top: Some(t), ..Borders::default() }),
|
||||
};
|
||||
named(&self.total_chr, self.total_fill, borders)
|
||||
}
|
||||
TablePart::FirstCol => named(&self.first_col_chr, self.first_col_fill, self.first_col_borders),
|
||||
TablePart::LastCol => named(&self.last_col_chr, self.last_col_fill, self.last_col_borders),
|
||||
TablePart::Band1Vert => named(&self.col_band_chr, self.col_band_fill, self.col_band_borders),
|
||||
TablePart::Band1Horz => named(&self.band_chr, self.band_fill, self.band_borders),
|
||||
_ => extra,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace part `p`'s formatting (for the whole table only its fill, borders and vertical
|
||||
/// alignment: [`Style::set_table_part`] stores the rest).
|
||||
pub fn set_part(&mut self, p: TablePart, f: PartFormat) {
|
||||
let align_only = PartFormat { align: f.align, v_align: f.v_align, ..PartFormat::default() };
|
||||
let PartFormat { chr, fill, borders, .. } = f.clone();
|
||||
let rest = match p {
|
||||
TablePart::WholeTable => {
|
||||
self.fill = fill;
|
||||
self.borders = borders;
|
||||
PartFormat { v_align: f.v_align, ..PartFormat::default() }
|
||||
}
|
||||
TablePart::FirstRow => {
|
||||
(self.header_chr, self.header_fill, self.header_borders) = (chr, fill, borders);
|
||||
align_only
|
||||
}
|
||||
TablePart::LastRow => {
|
||||
(self.total_chr, self.total_fill) = (chr, fill);
|
||||
self.total_border_top = borders.and_then(|b| b.top);
|
||||
self.total_borders = borders.map(|b| Borders { top: None, ..b }).filter(|b| *b != Borders::default());
|
||||
align_only
|
||||
}
|
||||
TablePart::FirstCol => {
|
||||
(self.first_col_chr, self.first_col_fill, self.first_col_borders) = (chr, fill, borders);
|
||||
align_only
|
||||
}
|
||||
TablePart::LastCol => {
|
||||
(self.last_col_chr, self.last_col_fill, self.last_col_borders) = (chr, fill, borders);
|
||||
align_only
|
||||
}
|
||||
TablePart::Band1Vert => {
|
||||
(self.col_band_chr, self.col_band_fill, self.col_band_borders) = (chr, fill, borders);
|
||||
align_only
|
||||
}
|
||||
TablePart::Band1Horz => {
|
||||
(self.band_chr, self.band_fill, self.band_borders) = (chr, fill, borders);
|
||||
align_only
|
||||
}
|
||||
_ => f,
|
||||
};
|
||||
if rest.is_empty() {
|
||||
self.regions.remove(&p);
|
||||
} else {
|
||||
self.regions.insert(p, rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Style {
|
||||
/// Table style part `p` as this style alone sets it (the whole table's text formatting and
|
||||
/// paragraph alignment are the style's own).
|
||||
pub fn table_part(&self, p: TablePart) -> PartFormat {
|
||||
let mut f = self.table.as_ref().map(|t| t.part(p)).unwrap_or_default();
|
||||
if p == TablePart::WholeTable {
|
||||
f.chr = self.chr.clone();
|
||||
f.align = self.para.align;
|
||||
}
|
||||
f
|
||||
}
|
||||
/// Replace part `p` of this table style.
|
||||
pub fn set_table_part(&mut self, p: TablePart, f: PartFormat) {
|
||||
if p == TablePart::WholeTable {
|
||||
self.chr = f.chr.clone();
|
||||
self.para.align = f.align;
|
||||
}
|
||||
let mut t = self.table.take().unwrap_or_default();
|
||||
t.set_part(p, f);
|
||||
self.table = (t != TableStyleParts::default()).then_some(t);
|
||||
}
|
||||
}
|
||||
|
||||
impl TableStyleProps {
|
||||
/// Part `p` with the based-on chain merged (see [`Style::table_part`]).
|
||||
pub fn part(&self, p: TablePart) -> PartFormat {
|
||||
let mut f = self.parts.part(p);
|
||||
if p == TablePart::WholeTable {
|
||||
f.chr = self.chr.clone();
|
||||
f.align = self.para.align;
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,6 +430,10 @@ pub struct StyleSheet {
|
||||
/// the application; nonempty `default_para` is always written after spacing edits.
|
||||
pub default_para_present: bool,
|
||||
pub styles: Vec<Style>,
|
||||
/// The file's `w:latentStyles` (behaviour of built-in styles not defined in the document:
|
||||
/// gallery, priority, visibility), as XML, written back as is.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub latent_styles: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for StyleSheet {
|
||||
@@ -168,7 +460,13 @@ fn color(c: Rgb) -> Option<TextColor> {
|
||||
|
||||
impl StyleSheet {
|
||||
pub fn empty() -> Self {
|
||||
StyleSheet { default_chr: CharProps::default(), default_para: ParaProps::default(), default_para_present: true, styles: Vec::new() }
|
||||
StyleSheet {
|
||||
default_chr: CharProps::default(),
|
||||
default_para: ParaProps::default(),
|
||||
default_para_present: true,
|
||||
styles: Vec::new(),
|
||||
latent_styles: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in style set used for new documents.
|
||||
@@ -184,6 +482,7 @@ impl StyleSheet {
|
||||
},
|
||||
default_para_present: true,
|
||||
styles: Vec::new(),
|
||||
latent_styles: None,
|
||||
};
|
||||
let mut add = |st: Style| s.styles.push(st);
|
||||
add(Style { id: "Normal".into(), name: "Normal".into(), priority: Some(0), quick: true, ..p_style() });
|
||||
@@ -483,6 +782,33 @@ impl StyleSheet {
|
||||
None => self.styles.push(st),
|
||||
}
|
||||
}
|
||||
/// For a file from a producer that never writes `w:qFormat` (LibreOffice): give it Word's
|
||||
/// usual Quick Styles gallery. Each built-in style whose id or name matches a quick style of
|
||||
/// [`StyleSheet::builtin`] becomes quick (taking the built-in's priority when it has none), and
|
||||
/// the quick built-ins the file lacks are added with their linked styles. Existing ids and
|
||||
/// names are never overwritten. Callers use it only when no style in the file is quick.
|
||||
pub fn add_default_gallery(&mut self) {
|
||||
let builtin = StyleSheet::builtin();
|
||||
for q in builtin.styles.iter().filter(|s| s.quick && s.kind != StyleKind::Table) {
|
||||
let found =
|
||||
self.styles.iter().position(|s| s.id == q.id).or_else(|| self.styles.iter().position(|s| s.name.eq_ignore_ascii_case(&q.name)));
|
||||
if let Some(st) = found.and_then(|i| self.styles.get_mut(i)) {
|
||||
if st.builtin && st.kind == q.kind {
|
||||
st.quick = true;
|
||||
st.priority = st.priority.or(q.priority);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for sid in std::iter::once(q.id.as_str()).chain(q.linked.as_deref()) {
|
||||
if let Some(b) = builtin.get(sid)
|
||||
&& self.get(sid).is_none()
|
||||
&& self.find(&b.name).is_none()
|
||||
{
|
||||
self.styles.push(b.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Remove style `id` and return it. Styles based on it are rebased onto its own base, and
|
||||
/// `next` / `linked` references to it are dropped. Text that uses it is the document's to
|
||||
/// retarget ([`crate::Document::restyle`]).
|
||||
@@ -605,6 +931,32 @@ mod tests {
|
||||
assert!(g.iter().any(|s| s.id == "Heading1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_gallery_marks_and_adds_quick_builtins() {
|
||||
let b = StyleSheet::builtin();
|
||||
let mut s = StyleSheet::empty();
|
||||
let plain = |id: &str, name: &str| Style { id: id.into(), name: name.into(), builtin: true, ..Default::default() };
|
||||
s.styles.push(plain("Normal", "Normal"));
|
||||
s.styles.push(plain("Heading1", "heading 1"));
|
||||
s.styles.push(Style { priority: Some(7), ..plain("Heading2", "Heading 2") });
|
||||
s.styles.push(Style { builtin: false, ..plain("Heading3", "Heading 3") });
|
||||
s.styles.push(Style { para: ParaProps { space_after: Some(99.0), ..Default::default() }, ..plain("Custom1", "Subtitle") });
|
||||
s.add_default_gallery();
|
||||
let ids: Vec<&str> = s.gallery().iter().map(|x| x.id.as_str()).collect();
|
||||
for id in ["Normal", "NoSpacing", "Heading1", "Heading2", "Title"] {
|
||||
assert!(ids.contains(&id), "{id} in {ids:?}");
|
||||
}
|
||||
let mut bare = StyleSheet::empty();
|
||||
bare.add_default_gallery();
|
||||
assert!(bare.get("Heading1").is_some_and(|x| x.quick) && bare.get("Title").is_some(), "missing quick builtins added");
|
||||
assert_eq!(s.get("Heading2").and_then(|x| x.priority), Some(7), "file priority kept");
|
||||
assert_eq!(s.get("Heading1").and_then(|x| x.priority), b.get("Heading1").and_then(|x| x.priority));
|
||||
assert!(!s.get("Heading3").is_some_and(|x| x.quick), "custom style untouched");
|
||||
assert!(s.get("Subtitle").is_none(), "a style with that name exists: not duplicated");
|
||||
assert!(s.get("Custom1").is_some_and(|x| x.quick), "found by name only, built in: quick");
|
||||
assert_eq!(s.get("Custom1").and_then(|x| x.para.space_after), Some(99.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_serialized_styles_keep_explicit_defaults() {
|
||||
let mut value = serde_json::to_value(StyleSheet::empty()).unwrap();
|
||||
|
||||
+119
-1
@@ -90,6 +90,46 @@ fn parts_and_media() {
|
||||
assert_ne!(k1, k3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_ids_skip_taken_ones_instead_of_overflowing() {
|
||||
assert_eq!(free_id(None, std::iter::empty(), 1), Some(1));
|
||||
assert_eq!(free_id(Some(7), [3, 7].into_iter(), 1), Some(8));
|
||||
assert_eq!(free_id(Some(0), [0].into_iter(), 1), Some(1));
|
||||
// A file used the largest id: the lowest free one, not a wrapped 0 or a taken id.
|
||||
assert_eq!(free_id(Some(u32::MAX), [1, 2, 4, u32::MAX].into_iter(), 1), Some(3));
|
||||
assert_eq!(free_id(Some(u32::MAX), [u32::MAX, 1, 0, 1].into_iter(), 0), Some(2));
|
||||
// Every id from `min` up taken: none, rather than a duplicate.
|
||||
assert_eq!(free_id(Some(u32::MAX), [u32::MAX, u32::MAX - 1, u32::MAX - 2].into_iter(), u32::MAX - 2), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_and_lists_after_the_largest_ids_take_free_ones() {
|
||||
// A file can carry any ids, 0 and u32::MAX included; new ones must not overflow or replace them.
|
||||
let mut d = Document::new();
|
||||
for id in [0, 1, u32::MAX] {
|
||||
let blocks = vec![para_block(Paragraph::with_text(&id.to_string(), CharProps::default()))];
|
||||
d.parts.insert(id, Part { kind: PartKind::Header, blocks, ..Default::default() });
|
||||
}
|
||||
let parts = d.parts.clone();
|
||||
assert_eq!(d.try_add_part(PartKind::Comment, Vec::new()), Ok(2));
|
||||
assert_eq!(d.add_part(PartKind::Footer, Vec::new()), 3);
|
||||
assert!(parts.iter().all(|(k, p)| d.parts.get(k) == Some(p)));
|
||||
|
||||
let n = &mut d.numbering;
|
||||
n.add_list(ListKind::Bullet);
|
||||
n.add_list(ListKind::Bullet);
|
||||
n.abstracts[1].id = u32::MAX;
|
||||
n.nums[1].id = u32::MAX;
|
||||
n.nums[1].abstract_id = u32::MAX;
|
||||
let lists = n.clone();
|
||||
let num = n.try_add_list(ListKind::Numbered).unwrap();
|
||||
assert_eq!((num, n.num(num).map(|x| x.abstract_id)), (2, Some(1)));
|
||||
assert_eq!(n.abstract_of(num).map(|a| &a.levels), Some(&numbering::levels_for(ListKind::Numbered)));
|
||||
assert_eq!(n.restart(num), Some(3));
|
||||
assert_eq!(n.num(3).map(|x| x.abstract_id), Some(1));
|
||||
assert_eq!((&n.abstracts[..2], &n.nums[..2]), (&lists.abstracts[..], &lists.nums[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_is_shallow() {
|
||||
let d = Document::from_text("a\nb");
|
||||
@@ -241,6 +281,84 @@ fn prune_text_boxes_drops_only_unshown_ones() {
|
||||
assert_eq!(d.prune_text_boxes(), 0);
|
||||
}
|
||||
|
||||
/// `blocks` in the only cell of `levels` tables, each nested in the next.
|
||||
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
|
||||
(0..levels).fold(blocks, |inner, _| {
|
||||
let mut t = Table::new(1, 1, 100.0);
|
||||
t.rows[0].cells[0].blocks = inner;
|
||||
vec![Arc::new(Block::Table(t))]
|
||||
})
|
||||
}
|
||||
|
||||
/// A paragraph showing text box story `story` (drawing id `id`).
|
||||
fn box_para(story: u32, id: u32) -> Blocks {
|
||||
let shape = InlineObject::Shape {
|
||||
kind: para::ShapeKind::TextBox,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story: Some(story),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: connector::ShapeExtra { id, ..Default::default() },
|
||||
};
|
||||
let mut p = Paragraph::with_text("cell", CharProps::default());
|
||||
p.insert_object(0, shape, &CharProps::default()).unwrap();
|
||||
vec![para_block(p)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_boxes_shown_from_deeply_nested_tables_are_kept() {
|
||||
// #1339: the paragraph walk stopped 16 tables down, so a box shown only from deeper was taken
|
||||
// for unshown and the next edit pruned its story.
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let at_17 = d.add_part(PartKind::TextBox, para_of("17 tables down"));
|
||||
let at_40 = d.add_part(PartKind::TextBox, para_of("40 tables down"));
|
||||
let inner = d.add_part(PartKind::TextBox, para_of("deep in a box"));
|
||||
let outer = d.add_part(PartKind::TextBox, nested_tables(18, box_para(inner, 0)));
|
||||
let in_header = d.add_part(PartKind::TextBox, para_of("deep in a header"));
|
||||
let hdr = d.add_part(PartKind::Header, nested_tables(20, box_para(in_header, 0)));
|
||||
let unshown = d.add_part(PartKind::TextBox, para_of("shown nowhere"));
|
||||
d.body.extend(nested_tables(17, box_para(at_17, 0)));
|
||||
d.body.extend(nested_tables(40, box_para(at_40, 7)));
|
||||
d.body.extend(box_para(outer, 0));
|
||||
assert_eq!(d.prune_text_boxes(), 1);
|
||||
assert!(!d.parts.contains_key(&unshown));
|
||||
let kept: Vec<u32> = d.parts.keys().copied().collect();
|
||||
assert_eq!(kept, vec![at_17, at_40, inner, outer, in_header, hdr]);
|
||||
assert_eq!(d.prune_text_boxes(), 0);
|
||||
// Counted in reading order, the nested box after its own; new drawing ids above the deep one.
|
||||
let part = StoryRef::Part;
|
||||
assert_eq!(d.counted_stories(), vec![StoryRef::Body, part(at_17), part(at_40), part(outer), part(inner)]);
|
||||
assert_eq!(d.next_shape_id(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deeply_nested_table_is_copied_with_its_text_boxes() {
|
||||
// A copy takes the box 17 tables down along, so pasting it into another document shows its
|
||||
// text, not the other document's box that happens to have the same id.
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let deep = d.add_part(PartKind::TextBox, para_of("deep box"));
|
||||
d.body.extend(nested_tables(17, box_para(deep, 0)));
|
||||
let frag = d.body_fragment();
|
||||
assert_eq!(frag.parts.keys().copied().collect::<Vec<_>>(), vec![deep]);
|
||||
let mut e = Document::new();
|
||||
let own = e.add_part(PartKind::TextBox, para_of("its own box"));
|
||||
assert_eq!(own, deep, "the same id in both documents");
|
||||
e.body = box_para(own, 0);
|
||||
let end = e.end_of(StoryRef::Body);
|
||||
e.insert_fragment(&end, &frag).unwrap();
|
||||
let mut shown = Vec::new();
|
||||
e.objects_in_reading_order(&mut |o| shown.extend(o.text_box()));
|
||||
let texts: Vec<String> = shown.iter().map(|id| e.plain_text(StoryRef::Part(*id))).collect();
|
||||
assert_eq!(texts, vec!["its own box", "deep box"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_in_text_box_follow_nested_boxes_once() {
|
||||
let shape = |story| InlineObject::Shape {
|
||||
@@ -273,7 +391,7 @@ fn notes_in_text_box_follow_nested_boxes_once() {
|
||||
}
|
||||
|
||||
fn fs(instr: &str) -> InlineObject {
|
||||
InlineObject::FieldStart { instr: instr.into(), locked: false }
|
||||
InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+20
-9
@@ -59,8 +59,8 @@ impl WrapPolygon {
|
||||
|
||||
/// A shape's outline in unit coordinates (0..1 across a `w` × `h` frame), flattened to straight
|
||||
/// lines. `None` for shapes whose outline is their rectangle (rectangles, text boxes, lines,
|
||||
/// freeforms).
|
||||
pub fn shape_outline(kind: ShapeKind, w: f32, h: f32) -> Option<Vec<(f32, f32)>> {
|
||||
/// freeforms). `corner` is a rounded rectangle's (see [`crate::connector::ShapeExtra::corner`]).
|
||||
pub fn shape_outline(kind: ShapeKind, w: f32, h: f32, corner: Option<u32>) -> Option<Vec<(f32, f32)>> {
|
||||
use std::f32::consts::{FRAC_PI_2, PI, TAU};
|
||||
let pos = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0e6) } else { 0.0 };
|
||||
let (w, h) = (pos(w), pos(h));
|
||||
@@ -73,10 +73,12 @@ pub fn shape_outline(kind: ShapeKind, w: f32, h: f32) -> Option<Vec<(f32, f32)>>
|
||||
| ShapeKind::StraightConnector
|
||||
| ShapeKind::ElbowConnector
|
||||
| ShapeKind::CurvedConnector => return None,
|
||||
ShapeKind::Ellipse => (0..48).map(|i| (i as f32) * TAU / 48.0).map(|a| (0.5 + 0.5 * a.cos(), 0.5 + 0.5 * a.sin())).collect(),
|
||||
ShapeKind::Ellipse | ShapeKind::FlowchartOr => {
|
||||
(0..48).map(|i| (i as f32) * TAU / 48.0).map(|a| (0.5 + 0.5 * a.cos(), 0.5 + 0.5 * a.sin())).collect()
|
||||
}
|
||||
ShapeKind::RoundedRectangle => {
|
||||
// Corner radius as drawn: 16% of the shorter side.
|
||||
let r = 0.16 * w.min(h);
|
||||
// Corner radius as drawn.
|
||||
let r = crate::connector::corner_radius(corner, w, h);
|
||||
let (rx, ry) = if w > 0.0 && h > 0.0 { (r / w, r / h) } else { (0.0, 0.0) };
|
||||
let mut pts = Vec::new();
|
||||
for (cx, cy, a0) in [(1.0 - rx, 1.0 - ry, 0.0), (rx, 1.0 - ry, FRAC_PI_2), (rx, ry, PI), (1.0 - rx, ry, PI + FRAC_PI_2)] {
|
||||
@@ -88,6 +90,7 @@ pub fn shape_outline(kind: ShapeKind, w: f32, h: f32) -> Option<Vec<(f32, f32)>>
|
||||
pts
|
||||
}
|
||||
ShapeKind::Triangle => vec![(0.5, 0.0), (1.0, 1.0), (0.0, 1.0)],
|
||||
ShapeKind::RightTriangle => vec![(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
|
||||
ShapeKind::Diamond => vec![(0.5, 0.0), (1.0, 0.5), (0.5, 1.0), (0.0, 0.5)],
|
||||
ShapeKind::Arrow => {
|
||||
// As drawn: the head is half the height long, the shaft 40% of the height thick.
|
||||
@@ -217,18 +220,26 @@ mod tests {
|
||||
ShapeKind::Ellipse,
|
||||
ShapeKind::RoundedRectangle,
|
||||
ShapeKind::Triangle,
|
||||
ShapeKind::RightTriangle,
|
||||
ShapeKind::Diamond,
|
||||
ShapeKind::Arrow,
|
||||
ShapeKind::Star,
|
||||
ShapeKind::Heart,
|
||||
] {
|
||||
for (w, h) in [(100.0, 50.0), (0.0, 0.0), (f32::NAN, 10.0)] {
|
||||
let pts = shape_outline(kind, w, h).unwrap();
|
||||
assert!(pts.len() >= 3 && pts.len() <= MAX_DERIVED_POINTS, "{kind:?}");
|
||||
assert!(pts.iter().all(|(x, y)| (-0.001..=1.001).contains(x) && (-0.001..=1.001).contains(y)), "{kind:?}");
|
||||
for corner in [None, Some(0), Some(3_565), Some(u32::MAX)] {
|
||||
let pts = shape_outline(kind, w, h, corner).unwrap();
|
||||
assert!(pts.len() >= 3 && pts.len() <= MAX_DERIVED_POINTS, "{kind:?}");
|
||||
assert!(pts.iter().all(|(x, y)| (-0.001..=1.001).contains(x) && (-0.001..=1.001).contains(y)), "{kind:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(shape_outline(ShapeKind::Rectangle, 10.0, 10.0).is_none());
|
||||
assert!(shape_outline(ShapeKind::Rectangle, 10.0, 10.0, None).is_none());
|
||||
// The end of the bottom-right corner: in the frame's corner when the corner is square,
|
||||
// 16% of the height (8 of 100 wide) in from it by default.
|
||||
let corner_pt = |corner| shape_outline(ShapeKind::RoundedRectangle, 100.0, 50.0, corner).unwrap()[6];
|
||||
assert!(corner_pt(Some(0)).0 > 0.999 && corner_pt(Some(0)).1 > 0.999, "{:?}", corner_pt(Some(0)));
|
||||
assert!((corner_pt(None).0 - 0.92).abs() < 0.001, "{:?}", corner_pt(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -14,6 +14,7 @@ wordcraft-geom = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
image = { workspace = true }
|
||||
miniz_oxide = { workspace = true }
|
||||
sha1 = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
//! Password-protected Word 97-2003 files ([MS-DOC] §2.2.6, [MS-OFFCRYPTO] §2.3.5-2.3.7).
|
||||
//!
|
||||
//! Three schemes exist for `.doc`:
|
||||
//!
|
||||
//! * **XOR obfuscation** (`fObfuscated`): a 32-bit password verifier sits in `FibBase.lKey` and
|
||||
//! the streams are XORed with a 16-byte array derived from the password (method 2).
|
||||
//! * **RC4** (header version 1.1): `EncryptionHeader` at the start of the Table stream; the key
|
||||
//! per 512-byte block comes from MD5.
|
||||
//! * **RC4 CryptoAPI** (header version 2/3/4 . 2): like RC4 but with a SHA-1 key derivation, a
|
||||
//! key size of 40-128 bits and a variable-size header.
|
||||
//!
|
||||
//! In all three the WordDocument stream (past its first 68 bytes), the Table stream (past its
|
||||
//! header, for RC4) and the whole Data stream are transformed. The password is checked against
|
||||
//! the stored verifier before anything is decrypted, so a wrong password is reported and never
|
||||
//! yields a garbled document. Everything is written from the public specifications.
|
||||
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use crate::DocbinError;
|
||||
|
||||
/// Bytes at the start of the WordDocument stream that are stored untransformed.
|
||||
pub(crate) const FIB_PLAIN: usize = 68;
|
||||
/// RC4 re-keys every this many bytes of a stream.
|
||||
const BLOCK: usize = 512;
|
||||
/// Longest password considered (the specifications' limit for the RC4 schemes).
|
||||
const MAX_PASSWORD_CHARS: usize = 255;
|
||||
/// XOR obfuscation uses at most this many single-byte password characters.
|
||||
const MAX_XOR_PASSWORD: usize = 15;
|
||||
/// `FibBase.flags`: the document is encrypted (`fEncrypted`) / obfuscated (`fObfuscated`).
|
||||
pub(crate) const F_ENCRYPTED: u16 = 0x0100;
|
||||
pub(crate) const F_OBFUSCATED: u16 = 0x8000;
|
||||
/// `EncryptionHeaderFlags`: `fCryptoAPI`, `fExternal`, `fAES`.
|
||||
const H_CRYPTO_API: u32 = 0x04;
|
||||
const H_EXTERNAL: u32 = 0x10;
|
||||
const H_AES: u32 = 0x20;
|
||||
|
||||
fn unsupported(what: &str) -> DocbinError {
|
||||
DocbinError::Encryption(what.into())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Primitives
|
||||
|
||||
/// MD5 ([RFC 1321]); the RC4 scheme is defined on it.
|
||||
pub(crate) fn md5(data: &[u8]) -> [u8; 16] {
|
||||
const S: [u32; 64] = [
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16,
|
||||
23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
|
||||
];
|
||||
// K[i] = floor(2^32 * abs(sin(i + 1))), as the RFC defines it.
|
||||
let k: Vec<u32> = (0..64u32).map(|i| (f64::from(i + 1).sin().abs() * 4_294_967_296.0) as u32).collect();
|
||||
let (mut a0, mut b0, mut c0, mut d0) = (0x6745_2301u32, 0xefcd_ab89u32, 0x98ba_dcfeu32, 0x1032_5476u32);
|
||||
let mut msg = Vec::with_capacity(data.len() + 72);
|
||||
msg.extend_from_slice(data);
|
||||
msg.push(0x80);
|
||||
while msg.len() % 64 != 56 {
|
||||
msg.push(0);
|
||||
}
|
||||
msg.extend_from_slice(&(data.len() as u64).wrapping_mul(8).to_le_bytes());
|
||||
for chunk in msg.as_chunks::<64>().0 {
|
||||
let mut m = [0u32; 16];
|
||||
let words = chunk.as_chunks::<4>().0;
|
||||
for (w, b) in m.iter_mut().zip(words) {
|
||||
*w = u32::from_le_bytes(*b);
|
||||
}
|
||||
let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
|
||||
for i in 0..64usize {
|
||||
let (f, g) = match i / 16 {
|
||||
0 => ((b & c) | (!b & d), i),
|
||||
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
|
||||
2 => (b ^ c ^ d, (3 * i + 5) % 16),
|
||||
_ => (c ^ (b | !d), (7 * i) % 16),
|
||||
};
|
||||
let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]);
|
||||
a = d;
|
||||
d = c;
|
||||
c = b;
|
||||
b = b.wrapping_add(f.rotate_left(S[i]));
|
||||
}
|
||||
a0 = a0.wrapping_add(a);
|
||||
b0 = b0.wrapping_add(b);
|
||||
c0 = c0.wrapping_add(c);
|
||||
d0 = d0.wrapping_add(d);
|
||||
}
|
||||
let mut out = [0u8; 16];
|
||||
let (cells, _) = out.as_chunks_mut::<4>();
|
||||
for (o, v) in cells.iter_mut().zip([a0, b0, c0, d0]) {
|
||||
*o = v.to_le_bytes();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn sha1(parts: &[&[u8]]) -> Vec<u8> {
|
||||
let mut h = Sha1::new();
|
||||
for p in parts {
|
||||
h.update(p);
|
||||
}
|
||||
h.finalize().to_vec()
|
||||
}
|
||||
|
||||
/// The RC4 stream cipher.
|
||||
pub(crate) struct Rc4 {
|
||||
s: [u8; 256],
|
||||
i: u8,
|
||||
j: u8,
|
||||
}
|
||||
|
||||
impl Rc4 {
|
||||
pub(crate) fn new(key: &[u8]) -> Rc4 {
|
||||
let mut s = [0u8; 256];
|
||||
for (n, v) in s.iter_mut().enumerate() {
|
||||
*v = n as u8;
|
||||
}
|
||||
let kl = key.len().max(1);
|
||||
let mut j = 0u8;
|
||||
for i in 0..256usize {
|
||||
let k = key.get(i % kl).copied().unwrap_or(0);
|
||||
j = j.wrapping_add(s[i]).wrapping_add(k);
|
||||
s.swap(i, usize::from(j));
|
||||
}
|
||||
Rc4 { s, i: 0, j: 0 }
|
||||
}
|
||||
|
||||
fn next(&mut self) -> u8 {
|
||||
self.i = self.i.wrapping_add(1);
|
||||
self.j = self.j.wrapping_add(self.s[usize::from(self.i)]);
|
||||
self.s.swap(usize::from(self.i), usize::from(self.j));
|
||||
self.s[usize::from(self.s[usize::from(self.i)].wrapping_add(self.s[usize::from(self.j)]))]
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&mut self, data: &mut [u8]) {
|
||||
for b in data {
|
||||
*b ^= self.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16le(password: &str) -> Vec<u8> {
|
||||
password.encode_utf16().take(MAX_PASSWORD_CHARS).flat_map(u16::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
fn u16_at(d: &[u8], at: usize) -> Option<u16> {
|
||||
Some(u16::from_le_bytes(d.get(at..at.checked_add(2)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn u32_at(d: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// XOR obfuscation (method 1 key/verifier pieces, method 2 array and transform)
|
||||
|
||||
const PAD_ARRAY: [u8; 15] = [0xBB, 0xFF, 0xFF, 0xBA, 0xFF, 0xFF, 0xB9, 0x80, 0x00, 0xBE, 0x0F, 0x00, 0xBF, 0x0F, 0x00];
|
||||
const INITIAL_CODE: [u16; 15] =
|
||||
[0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3];
|
||||
const XOR_MATRIX: [u16; 105] = [
|
||||
0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09, 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF, 0x4563, 0x8AC6, 0x05AD, 0x0B5A,
|
||||
0x16B4, 0x2D68, 0x5AD0, 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40, 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5, 0x6F45,
|
||||
0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A, 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9, 0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4,
|
||||
0x7B68, 0xF6D0, 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC, 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10, 0xAA51, 0x4483,
|
||||
0x8906, 0x022D, 0x045A, 0x08B4, 0x1168, 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C, 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6,
|
||||
0x1DAD, 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC, 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4,
|
||||
];
|
||||
|
||||
/// `CreateXorKey_Method1`. `pw` is 1 to 15 bytes.
|
||||
fn xor_key(pw: &[u8]) -> u16 {
|
||||
let mut key = INITIAL_CODE.get(pw.len().wrapping_sub(1)).copied().unwrap_or(0);
|
||||
let mut current = 0x68i32;
|
||||
for &ch in pw.iter().rev() {
|
||||
let mut ch = ch;
|
||||
for _ in 0..7 {
|
||||
if ch & 0x40 != 0
|
||||
&& let Some(m) = usize::try_from(current).ok().and_then(|c| XOR_MATRIX.get(c))
|
||||
{
|
||||
key ^= m;
|
||||
}
|
||||
ch <<= 1;
|
||||
current -= 1;
|
||||
}
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
/// `CreatePasswordVerifier_Method1`.
|
||||
fn verifier_method1(pw: &[u8]) -> u16 {
|
||||
let mut v = 0u16;
|
||||
for &b in pw.iter().rev().chain(std::iter::once(&(pw.len() as u8))) {
|
||||
let i1 = u16::from(v & 0x4000 != 0);
|
||||
let i2 = v.wrapping_mul(2) & 0x7FFF;
|
||||
v = (i1 | i2) ^ u16::from(b);
|
||||
}
|
||||
v ^ 0xCE4B
|
||||
}
|
||||
|
||||
/// `CreatePasswordVerifier_Method2`: the 32-bit value stored in `FibBase.lKey`.
|
||||
pub(crate) fn xor_verifier(pw: &[u8]) -> u32 {
|
||||
(u32::from(xor_key(pw)) << 16) | u32::from(verifier_method1(pw))
|
||||
}
|
||||
|
||||
/// `CreateXorArray_Method2`.
|
||||
pub(crate) fn xor_array(pw: &[u8]) -> [u8; 16] {
|
||||
let key = (xor_verifier(pw) >> 16) as u16;
|
||||
let (high, low) = ((key >> 8) as u8, key as u8);
|
||||
let mut arr = [0u8; 16];
|
||||
for (i, slot) in arr.iter_mut().enumerate() {
|
||||
*slot = pw.get(i).copied().unwrap_or_else(|| PAD_ARRAY.get(i.saturating_sub(pw.len())).copied().unwrap_or(0));
|
||||
}
|
||||
let (pairs, _) = arr.as_chunks_mut::<2>();
|
||||
for pair in pairs {
|
||||
pair[0] = (pair[0] ^ low).rotate_right(1);
|
||||
pair[1] = (pair[1] ^ high).rotate_right(1);
|
||||
}
|
||||
arr
|
||||
}
|
||||
|
||||
/// The single-byte forms of a password the XOR scheme tries: the system-codepage form (Latin-1
|
||||
/// here) and the "low byte, or high byte when the low one is zero" form. Each is cut to 15.
|
||||
fn xor_candidates(password: &str) -> Vec<Vec<u8>> {
|
||||
let mut out: Vec<Vec<u8>> = Vec::new();
|
||||
let latin: Option<Vec<u8>> = password.chars().take(MAX_XOR_PASSWORD).map(|c| u8::try_from(u32::from(c)).ok()).collect();
|
||||
if let Some(l) = latin {
|
||||
out.push(l);
|
||||
}
|
||||
let folded: Vec<u8> = password.encode_utf16().take(MAX_XOR_PASSWORD).map(|u| if u & 0xFF == 0 { (u >> 8) as u8 } else { u as u8 }).collect();
|
||||
if !out.contains(&folded) {
|
||||
out.push(folded);
|
||||
}
|
||||
out.retain(|p| !p.is_empty());
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The cipher
|
||||
|
||||
/// How the streams of one file are transformed, once the password has been verified.
|
||||
pub(crate) enum Cipher {
|
||||
Xor { array: [u8; 16] },
|
||||
Rc4 { base: Vec<u8>, crypto_api: bool, key_len: usize, table_skip: usize },
|
||||
}
|
||||
|
||||
impl Cipher {
|
||||
/// Check `password` against the file's verifier and set up the cipher. `flags` and `lkey` come
|
||||
/// from the FIB base, `table` is the (still encrypted) Table stream.
|
||||
pub(crate) fn open(flags: u16, lkey: u32, table: &[u8], password: &str) -> Result<Cipher, DocbinError> {
|
||||
if flags & F_OBFUSCATED != 0 {
|
||||
for pw in xor_candidates(password) {
|
||||
if xor_verifier(&pw) == lkey {
|
||||
return Ok(Cipher::Xor { array: xor_array(&pw) });
|
||||
}
|
||||
}
|
||||
return Err(DocbinError::WrongPassword);
|
||||
}
|
||||
let short = || DocbinError::Malformed("the encryption header is truncated".into());
|
||||
let major = u16_at(table, 0).ok_or_else(short)?;
|
||||
let minor = u16_at(table, 2).ok_or_else(short)?;
|
||||
match (major, minor) {
|
||||
(1, 1) => Self::open_rc4(table, password),
|
||||
(2..=4, 2) => Self::open_crypto_api(table, password),
|
||||
_ => Err(unsupported(&format!("unknown encryption version {major}.{minor}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_rc4(table: &[u8], password: &str) -> Result<Cipher, DocbinError> {
|
||||
let short = || DocbinError::Malformed("the encryption header is truncated".into());
|
||||
let salt = table.get(4..20).ok_or_else(short)?;
|
||||
let enc_verifier = table.get(20..36).ok_or_else(short)?;
|
||||
let enc_hash = table.get(36..52).ok_or_else(short)?;
|
||||
let h0 = md5(&utf16le(password));
|
||||
let mut buf = Vec::with_capacity(336);
|
||||
for _ in 0..16 {
|
||||
buf.extend_from_slice(&h0[..5]);
|
||||
buf.extend_from_slice(salt);
|
||||
}
|
||||
let base = md5(&buf)[..5].to_vec();
|
||||
let cipher = Cipher::Rc4 { base, crypto_api: false, key_len: 16, table_skip: 52 };
|
||||
let mut rc4 = Rc4::new(&cipher.block_key(0));
|
||||
let mut verifier = [0u8; 16];
|
||||
verifier.copy_from_slice(enc_verifier);
|
||||
let mut hash = [0u8; 16];
|
||||
hash.copy_from_slice(enc_hash);
|
||||
rc4.apply(&mut verifier);
|
||||
rc4.apply(&mut hash);
|
||||
if md5(&verifier) != hash {
|
||||
return Err(DocbinError::WrongPassword);
|
||||
}
|
||||
Ok(cipher)
|
||||
}
|
||||
|
||||
fn open_crypto_api(table: &[u8], password: &str) -> Result<Cipher, DocbinError> {
|
||||
let short = || DocbinError::Malformed("the encryption header is truncated".into());
|
||||
let hflags = u32_at(table, 4).ok_or_else(short)?;
|
||||
if hflags & H_EXTERNAL != 0 {
|
||||
return Err(unsupported("the document uses an external encryption provider"));
|
||||
}
|
||||
if hflags & H_AES != 0 {
|
||||
return Err(unsupported("AES-encrypted .doc files are not supported"));
|
||||
}
|
||||
if hflags & H_CRYPTO_API == 0 {
|
||||
return Err(unsupported("unknown encryption header"));
|
||||
}
|
||||
let hsize = usize::try_from(u32_at(table, 8).ok_or_else(short)?).unwrap_or(usize::MAX);
|
||||
// EncryptionHeader: flags, sizeExtra, algId, algIdHash, keySize, providerType, 2 reserved
|
||||
// words and the CSP name; it starts at byte 12.
|
||||
if hsize < 32 || hsize > table.len() {
|
||||
return Err(DocbinError::Malformed("the encryption header has a bad size".into()));
|
||||
}
|
||||
let alg_id = u32_at(table, 20).ok_or_else(short)?;
|
||||
let alg_hash = u32_at(table, 24).ok_or_else(short)?;
|
||||
if !matches!(alg_id, 0 | 0x6801) {
|
||||
return Err(unsupported(&format!("encryption algorithm 0x{alg_id:X}")));
|
||||
}
|
||||
if !matches!(alg_hash, 0 | 0x8004) {
|
||||
return Err(unsupported(&format!("hash algorithm 0x{alg_hash:X}")));
|
||||
}
|
||||
let mut bits = u32_at(table, 28).ok_or_else(short)?;
|
||||
if bits == 0 {
|
||||
bits = 40;
|
||||
}
|
||||
if !(40..=128).contains(&bits) || bits % 8 != 0 {
|
||||
return Err(unsupported(&format!("a {bits}-bit key")));
|
||||
}
|
||||
let key_len = (bits / 8) as usize;
|
||||
// EncryptionVerifier: saltSize, salt[16], encryptedVerifier[16], verifierHashSize,
|
||||
// encryptedVerifierHash[20].
|
||||
let v = 12 + hsize;
|
||||
if u32_at(table, v) != Some(16) {
|
||||
return Err(DocbinError::Malformed("the encryption salt has a bad size".into()));
|
||||
}
|
||||
let salt = table.get(v + 4..v + 20).ok_or_else(short)?;
|
||||
let enc_verifier = table.get(v + 20..v + 36).ok_or_else(short)?;
|
||||
if u32_at(table, v + 36) != Some(20) {
|
||||
return Err(unsupported("a verifier hash that is not SHA-1"));
|
||||
}
|
||||
let enc_hash = table.get(v + 40..v + 60).ok_or_else(short)?;
|
||||
let mut pw = utf16le(password);
|
||||
let base = sha1(&[salt, &pw]);
|
||||
pw.fill(0);
|
||||
let cipher = Cipher::Rc4 { base, crypto_api: true, key_len, table_skip: v + 60 };
|
||||
let mut rc4 = Rc4::new(&cipher.block_key(0));
|
||||
let mut verifier = enc_verifier.to_vec();
|
||||
let mut hash = enc_hash.to_vec();
|
||||
rc4.apply(&mut verifier);
|
||||
rc4.apply(&mut hash);
|
||||
if sha1(&[&verifier]) != hash {
|
||||
return Err(DocbinError::WrongPassword);
|
||||
}
|
||||
Ok(cipher)
|
||||
}
|
||||
|
||||
/// The RC4 key of stream block `block`.
|
||||
fn block_key(&self, block: u32) -> Vec<u8> {
|
||||
match self {
|
||||
Cipher::Xor { .. } => Vec::new(),
|
||||
Cipher::Rc4 { base, crypto_api: false, .. } => md5(&[base.as_slice(), &block.to_le_bytes()].concat()).to_vec(),
|
||||
Cipher::Rc4 { base, crypto_api: true, key_len, .. } => {
|
||||
let mut k = sha1(&[base, &block.to_le_bytes()]);
|
||||
k.truncate(*key_len);
|
||||
// A 40-bit key is zero-padded to 128 bits.
|
||||
if *key_len == 5 {
|
||||
k.resize(16, 0);
|
||||
}
|
||||
k
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrypt `data` in place; its first `skip` bytes are stored untransformed.
|
||||
fn decrypt(&self, data: &mut [u8], skip: usize) {
|
||||
match self {
|
||||
Cipher::Xor { array } => {
|
||||
for (i, b) in data.iter_mut().enumerate().skip(skip) {
|
||||
let a = array[i % 16];
|
||||
// Zero bytes, and bytes equal to the array element, were left as they were.
|
||||
if *b != 0 && *b != a {
|
||||
*b ^= a;
|
||||
}
|
||||
}
|
||||
}
|
||||
Cipher::Rc4 { .. } => {
|
||||
for (n, chunk) in data.chunks_mut(BLOCK).enumerate() {
|
||||
let Ok(block) = u32::try_from(n) else { return };
|
||||
let mut rc4 = Rc4::new(&self.block_key(block));
|
||||
let start = n * BLOCK;
|
||||
// The keystream runs over the untransformed bytes too.
|
||||
let plain = skip.saturating_sub(start).min(chunk.len());
|
||||
let head = chunk.get(..plain).map(<[u8]>::to_vec).unwrap_or_default();
|
||||
rc4.apply(chunk);
|
||||
if let Some(dst) = chunk.get_mut(..plain) {
|
||||
dst.copy_from_slice(&head);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decrypt_word(&self, data: &mut [u8]) {
|
||||
self.decrypt(data, FIB_PLAIN);
|
||||
}
|
||||
|
||||
pub(crate) fn decrypt_table(&self, data: &mut [u8]) {
|
||||
let skip = match self {
|
||||
Cipher::Xor { .. } => 0,
|
||||
Cipher::Rc4 { table_skip, .. } => *table_skip,
|
||||
};
|
||||
self.decrypt(data, skip);
|
||||
}
|
||||
|
||||
pub(crate) fn decrypt_data(&self, data: &mut [u8]) {
|
||||
self.decrypt(data, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn md5_matches_the_rfc_1321_vectors() {
|
||||
assert_eq!(hex(&md5(b"")), "d41d8cd98f00b204e9800998ecf8427e");
|
||||
assert_eq!(hex(&md5(b"a")), "0cc175b9c0f1b6a831c399e269772661");
|
||||
assert_eq!(hex(&md5(b"abc")), "900150983cd24fb0d6963f7d28e17f72");
|
||||
assert_eq!(hex(&md5(b"message digest")), "f96b697d7cb7938d525a2f31aaf161d0");
|
||||
assert_eq!(
|
||||
hex(&md5(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890")),
|
||||
"57edf4a22be3c955ac49da2e2107b67a"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rc4_matches_a_published_vector() {
|
||||
let mut d = b"Plaintext".to_vec();
|
||||
Rc4::new(b"Key").apply(&mut d);
|
||||
assert_eq!(hex(&d), "bbf316e8d940af0ad3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xor_candidates_cut_to_fifteen_and_skip_empty() {
|
||||
assert!(xor_candidates("").is_empty());
|
||||
assert_eq!(xor_candidates("abcdefghijklmnopqrst")[0].len(), 15);
|
||||
// Not representable as single bytes: only the folded form remains.
|
||||
assert_eq!(xor_candidates("\u{4e2d}").len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -37,16 +37,22 @@ fn plc(table: &[u8], (fc, lcb): (u32, u32), cb: usize) -> Vec<(u32, &[u8])> {
|
||||
|
||||
/// The text box stories of a `PlcftxbxTxt` (or `PlcfHdrtxbxTxt`): (shape spid, story CP range
|
||||
/// relative to the text box subdocument).
|
||||
///
|
||||
/// The CPs of a well-formed PLC ascend, so the stories are disjoint. A story starting before
|
||||
/// the end of the last one kept (a hostile table pointing many text boxes at the same text,
|
||||
/// each read into its own part) is dropped: every subdocument CP becomes at most one story.
|
||||
pub(crate) fn textbox_stories(table: &[u8], pair: Option<(u32, u32)>) -> Vec<(u32, (u32, u32))> {
|
||||
let Some(pair) = pair else { return Vec::new() };
|
||||
let Some(blob) = table.get(pair.0 as usize..(pair.0 as usize).saturating_add(pair.1 as usize)) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut kept_to = 0u32;
|
||||
for (i, (cp, ftxbxs)) in plc(table, pair, CB_FTXBXS).iter().enumerate() {
|
||||
// The story runs to the next entry's CP (the PLC's last CP for the last entry).
|
||||
let Some(end) = blob.get((i + 1) * 4..(i + 1) * 4 + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) else { continue };
|
||||
let Some(lid) = ftxbxs.get(14..18).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) else { continue };
|
||||
if end > *cp && lid != 0 {
|
||||
if end > *cp && *cp >= kept_to && lid != 0 {
|
||||
out.push((lid, (*cp, end)));
|
||||
kept_to = end;
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -180,7 +186,8 @@ fn leaf(sp: &Sp, w: f32, h: f32, float: Float, b: &Build, pics: &mut Pictures) -
|
||||
2 => ShapeKind::RoundedRectangle,
|
||||
3 => ShapeKind::Ellipse,
|
||||
4 => ShapeKind::Diamond,
|
||||
5 | 6 => ShapeKind::Triangle,
|
||||
5 => ShapeKind::Triangle,
|
||||
6 => ShapeKind::RightTriangle,
|
||||
12 | 187 => ShapeKind::Star,
|
||||
13 | 66 | 67 | 68 | 69 => ShapeKind::Arrow,
|
||||
20 | 32 => ShapeKind::Line,
|
||||
|
||||
@@ -80,10 +80,33 @@ impl SubDocs {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the unencrypted head of a password-protected file says (see [`peek_encryption`]).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Protection {
|
||||
pub(crate) flags: u16,
|
||||
/// `FibBase.lKey`: the XOR verifier, or the size of the RC4 header in the Table stream.
|
||||
pub(crate) lkey: u32,
|
||||
pub(crate) which_tbl_stm: bool,
|
||||
}
|
||||
|
||||
/// Is the WordDocument stream that of an encrypted Word 97-2003 file? Only the first 68 bytes are
|
||||
/// stored in the clear; this reads nothing else. `None` for anything else, including streams that
|
||||
/// are too short or have a foreign magic (the full parse reports those).
|
||||
pub(crate) fn peek_encryption(word: &[u8]) -> Option<Protection> {
|
||||
if word.len() < crate::crypt::FIB_PLAIN || word.get(0..2)? != W_IDENT.to_le_bytes() {
|
||||
return None;
|
||||
}
|
||||
let flags = u16::from_le_bytes([*word.get(OFF_FLAGS)?, *word.get(OFF_FLAGS + 1)?]);
|
||||
if flags & crate::crypt::F_ENCRYPTED == 0 {
|
||||
return None;
|
||||
}
|
||||
let lkey = u32::from_le_bytes([*word.get(0x0E)?, *word.get(0x0F)?, *word.get(0x10)?, *word.get(0x11)?]);
|
||||
Some(Protection { flags, lkey, which_tbl_stm: flags & 0x0200 != 0 })
|
||||
}
|
||||
|
||||
/// The parsed FIB.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Fib {
|
||||
pub(crate) encrypted: bool,
|
||||
/// Selects 1Table (true) or 0Table (false).
|
||||
pub(crate) which_tbl_stm: bool,
|
||||
pub(crate) ccp: SubDocs,
|
||||
@@ -157,6 +180,6 @@ impl Fib {
|
||||
pairs.push(u32le(blob_off + i * 4));
|
||||
}
|
||||
|
||||
Ok(Fib { encrypted: flags & 0x0100 != 0, which_tbl_stm: flags & 0x0200 != 0, ccp: sub, pairs })
|
||||
Ok(Fib { which_tbl_stm: flags & 0x0200 != 0, ccp: sub, pairs })
|
||||
}
|
||||
}
|
||||
|
||||
+72
-18
@@ -8,12 +8,14 @@
|
||||
//! capped), so hostile input yields an error or a best-effort document, never a panic.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod crypt;
|
||||
mod drawing;
|
||||
mod fib;
|
||||
mod fkp;
|
||||
mod fmt;
|
||||
mod list;
|
||||
mod media;
|
||||
mod metadata;
|
||||
mod notes;
|
||||
mod officeart;
|
||||
mod piece;
|
||||
@@ -43,6 +45,10 @@ use table::ParaOut;
|
||||
const MAX_STREAM: u64 = 1 << 30;
|
||||
/// Most header/footer parts we create (matches the docx reader's cap).
|
||||
const MAX_PARTS: usize = 50_000;
|
||||
/// Hard ceiling on characters materialised across every story walk of one document (body,
|
||||
/// headers, notes, text boxes), whatever the file's size. The working budget is tied to the
|
||||
/// WordDocument stream (see [`read`]); this caps even a maximal stream.
|
||||
const MAX_TOTAL_CHARS: u64 = 64 << 20;
|
||||
/// `sprmCPicLocation`: the fc of a picture in the Data stream.
|
||||
const C_PIC_LOCATION: u16 = 0x6A03;
|
||||
/// `sprmPIlvl` / `sprmPIlfo`: the paragraph's list level and list.
|
||||
@@ -58,9 +64,16 @@ pub enum DocbinError {
|
||||
/// The compound file is readable but is not a Word 97-2003 document.
|
||||
#[error("not a Word 97-2003 document: {0}")]
|
||||
NotWord(String),
|
||||
/// The document is password-protected (XOR obfuscation or RC4 encryption).
|
||||
#[error("encrypted or password-protected .doc files are not supported")]
|
||||
Encrypted,
|
||||
/// The document is password-protected and no password was given.
|
||||
#[error("this document is protected with a password")]
|
||||
PasswordRequired,
|
||||
/// The password does not open the document.
|
||||
#[error("the password is incorrect")]
|
||||
WrongPassword,
|
||||
/// The document is encrypted in a way WordCraft can't read (AES, an external provider, an
|
||||
/// unknown header).
|
||||
#[error("encrypted document: {0}")]
|
||||
Encryption(String),
|
||||
/// The input exceeds a safety limit (stream size, piece count…).
|
||||
#[error("limit exceeded: {0}")]
|
||||
Limit(String),
|
||||
@@ -69,25 +82,51 @@ pub enum DocbinError {
|
||||
Malformed(String),
|
||||
}
|
||||
|
||||
/// Read a `.doc` (Word 97-2003 binary) file into a [`Document`].
|
||||
/// Is this `.doc` password-protected (XOR obfuscation, RC4 or RC4 CryptoAPI)? False for
|
||||
/// anything that is not a readable Word 97-2003 file.
|
||||
pub fn is_encrypted(bytes: &[u8]) -> bool {
|
||||
let Ok(mut comp) = cfb::CompoundFile::open(std::io::Cursor::new(bytes)) else { return false };
|
||||
stream(&mut comp, "WordDocument").is_some_and(|w| fib::peek_encryption(&w).is_some())
|
||||
}
|
||||
|
||||
/// Read a `.doc` (Word 97-2003 binary) file into a [`Document`]. A password-protected file
|
||||
/// gives [`DocbinError::PasswordRequired`]; see [`read_with_password`].
|
||||
pub fn read(bytes: &[u8]) -> Result<Document, DocbinError> {
|
||||
read_with_password(bytes, None)
|
||||
}
|
||||
|
||||
/// [`read`] for a file that may be password-protected: it is checked against the file's stored
|
||||
/// verifier ([`DocbinError::WrongPassword`] when it does not match) and then decrypted. The
|
||||
/// password is ignored for an unprotected file.
|
||||
pub fn read_with_password(bytes: &[u8], password: Option<&str>) -> Result<Document, DocbinError> {
|
||||
let mut comp = cfb::CompoundFile::open(std::io::Cursor::new(bytes)).map_err(|e| DocbinError::Container(e.to_string()))?;
|
||||
let word = stream(&mut comp, "WordDocument").ok_or_else(|| DocbinError::NotWord("no WordDocument stream".into()))?;
|
||||
let mut word = stream(&mut comp, "WordDocument").ok_or_else(|| DocbinError::NotWord("no WordDocument stream".into()))?;
|
||||
if word.len() as u64 > MAX_STREAM {
|
||||
return Err(DocbinError::Limit(format!("WordDocument stream is {} bytes", word.len())));
|
||||
}
|
||||
let fib = fib::Fib::parse(&word)?;
|
||||
if fib.encrypted {
|
||||
return Err(DocbinError::Encrypted);
|
||||
}
|
||||
let enc = fib::peek_encryption(&word);
|
||||
// The FIB names the Table stream (0Table or 1Table); fall back to whichever exists,
|
||||
// since files written by other writers sometimes carry the wrong bit.
|
||||
let named = if fib.which_tbl_stm { "1Table" } else { "0Table" };
|
||||
let other = if fib.which_tbl_stm { "0Table" } else { "1Table" };
|
||||
let table = stream(&mut comp, named).or_else(|| stream(&mut comp, other)).unwrap_or_default();
|
||||
let which = if let Some(e) = enc { e.which_tbl_stm } else { fib::Fib::parse(&word)?.which_tbl_stm };
|
||||
let named = if which { "1Table" } else { "0Table" };
|
||||
let other = if which { "0Table" } else { "1Table" };
|
||||
let mut table = stream(&mut comp, named).or_else(|| stream(&mut comp, other)).unwrap_or_default();
|
||||
if table.len() as u64 > MAX_STREAM {
|
||||
return Err(DocbinError::Limit(format!("Table stream is {} bytes", table.len())));
|
||||
}
|
||||
let mut data = stream(&mut comp, "Data").unwrap_or_default();
|
||||
if data.len() as u64 > MAX_STREAM {
|
||||
return Err(DocbinError::Limit(format!("Data stream is {} bytes", data.len())));
|
||||
}
|
||||
if let Some(e) = enc {
|
||||
// Verify the password first; only then is anything decrypted.
|
||||
let password = password.ok_or(DocbinError::PasswordRequired)?;
|
||||
let cipher = crypt::Cipher::open(e.flags, e.lkey, &table, password)?;
|
||||
cipher.decrypt_word(&mut word);
|
||||
cipher.decrypt_table(&mut table);
|
||||
cipher.decrypt_data(&mut data);
|
||||
}
|
||||
let fib = fib::Fib::parse(&word)?;
|
||||
|
||||
// The piece table locates every character in the WordDocument stream.
|
||||
let (fc_clx, lcb_clx) =
|
||||
@@ -109,12 +148,10 @@ pub fn read(bytes: &[u8]) -> Result<Document, DocbinError> {
|
||||
None => Bins::parse(&[], 0, 0)?,
|
||||
};
|
||||
|
||||
let data = stream(&mut comp, "Data").unwrap_or_default();
|
||||
if data.len() as u64 > MAX_STREAM {
|
||||
return Err(DocbinError::Limit(format!("Data stream is {} bytes", data.len())));
|
||||
}
|
||||
|
||||
let mut doc = Document::new();
|
||||
if let Some(core) = metadata::read(&mut comp) {
|
||||
doc.core = core;
|
||||
}
|
||||
doc.body.clear();
|
||||
doc.styles = fmt::stylesheet(&raw_styles, &fonts);
|
||||
doc.numbering = list::parse(&table, &fib, &fonts);
|
||||
@@ -129,6 +166,12 @@ pub fn read(bytes: &[u8]) -> Result<Document, DocbinError> {
|
||||
let hdd_base = fib.ccp.text.saturating_add(fib.ccp.ftn);
|
||||
let edn_base = hdd_base.saturating_add(fib.ccp.hdd).saturating_add(fib.ccp.atn);
|
||||
let mut pics = media::Pictures::default();
|
||||
// Every materialised character comes from at least one byte of the WordDocument stream, so a
|
||||
// legitimate document's total text (body plus every header, footnote and text box, each read
|
||||
// once) cannot exceed its stream. A hostile piece or story table that aliases the same bytes
|
||||
// many times can, so the walk is held to twice the stream's size — generous for real files,
|
||||
// tight against aliasing — and never past the absolute ceiling.
|
||||
let budget = std::cell::Cell::new((word.len() as u64).saturating_mul(2).min(MAX_TOTAL_CHARS));
|
||||
|
||||
let ctx = WalkCtx {
|
||||
word: &word,
|
||||
@@ -143,6 +186,7 @@ pub fn read(bytes: &[u8]) -> Result<Document, DocbinError> {
|
||||
marks: &[],
|
||||
drawn: &[],
|
||||
sect_ends: &[],
|
||||
budget: &budget,
|
||||
};
|
||||
|
||||
// Drawings: text box stories become parts first, then the floating shapes and pictures
|
||||
@@ -283,6 +327,10 @@ struct WalkCtx<'a> {
|
||||
/// Where sections end (main-document CPs, sorted): the section mark (0x0C) just before
|
||||
/// each ends the section's last paragraph, it isn't a page break inside it.
|
||||
sect_ends: &'a [u32],
|
||||
/// Characters still allowed across every story walk of this document. Story ranges (headers,
|
||||
/// footnotes, text boxes) are hostile and can each span a whole subdocument, so thousands of
|
||||
/// them could otherwise materialise the same text thousands of times; this bounds the total.
|
||||
budget: &'a std::cell::Cell<u64>,
|
||||
}
|
||||
|
||||
/// State while assembling one paragraph from per-CP formatting.
|
||||
@@ -356,6 +404,12 @@ fn walk(ctx: &WalkCtx, cp_start: u32, cp_end: u32, pics: &mut media::Pictures) -
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Every real character counts against the document-wide budget; once it is spent, stop
|
||||
// (a hostile file with thousands of story ranges over the same text can't multiply on).
|
||||
if ctx.budget.get() == 0 {
|
||||
break;
|
||||
}
|
||||
ctx.budget.set(ctx.budget.get() - 1);
|
||||
// A section mark (0x0C) at a section's end is that section's last paragraph mark.
|
||||
let section_mark = c == '\u{C}' && ctx.sect_ends.binary_search(&cp.saturating_add(1)).is_ok();
|
||||
match c {
|
||||
@@ -521,7 +575,7 @@ fn finish_field(pb: &mut ParaBuild, f: FieldBuild) {
|
||||
return;
|
||||
}
|
||||
pb.push('\u{FFFC}', CharProps::default());
|
||||
pb.objects.push(InlineObject::Field { instr, result: result_text, locked: false, code: false });
|
||||
pb.objects.push(InlineObject::Field { instr, result: result_text, locked: false, dirty: false, code: false, form: String::new() });
|
||||
}
|
||||
|
||||
/// `HYPERLINK "url"` / `HYPERLINK url \l "bookmark"` → the model link target
|
||||
|
||||
@@ -85,6 +85,7 @@ pub(crate) fn parse(table: &[u8], fib: &Fib, fonts: &[String]) -> Numbering {
|
||||
id: i as u32,
|
||||
name: None,
|
||||
levels: def.levels.iter().enumerate().map(|(j, l)| level_of(l, j, fonts)).collect(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if let Some((fc, lcb)) = fib.pair(pair::PLF_LFO)
|
||||
@@ -224,7 +225,7 @@ fn parse_plf_lfo(table: &[u8], fc: u32, defs: &[ListDef], numbering: &mut Number
|
||||
}
|
||||
}
|
||||
let id = numbering.abstracts.len() as u32;
|
||||
numbering.abstracts.push(AbstractNum { id, name: None, levels });
|
||||
numbering.abstracts.push(AbstractNum { id, name: None, levels, ..Default::default() });
|
||||
id
|
||||
};
|
||||
numbering.nums.push(Num { id: (i + 1) as u32, abstract_id, start_overrides, ..Default::default() });
|
||||
|
||||
+32
-19
@@ -19,12 +19,13 @@ const MAX_PICTURES: usize = 5_000;
|
||||
pub(crate) const MAX_MEDIA_BYTES: usize = 256 << 20;
|
||||
|
||||
/// The document's pictures, keyed by their location in the Data stream: anchors that share a
|
||||
/// `fc_pic` share one media entry, and the total bytes copied are capped, so a file with
|
||||
/// thousands of anchors on one huge picture costs one copy, not thousands. Pictures of the
|
||||
/// drawing layer's BLIP store are shared the same way, by store index.
|
||||
/// `fc_pic` share one media entry (or one failure), and the total bytes copied are capped, so a
|
||||
/// file with thousands of anchors on one huge picture costs one copy, not thousands. Pictures of
|
||||
/// the drawing layer's BLIP store are shared the same way, by store index.
|
||||
pub(crate) struct Pictures {
|
||||
/// fc_pic → the inline picture already materialised.
|
||||
by_fc: HashMap<u32, Inline>,
|
||||
/// fc_pic → the inline picture already materialised (`None`: unreadable or over the cap,
|
||||
/// not retried).
|
||||
by_fc: HashMap<u32, Option<Inline>>,
|
||||
/// BLIP store index → media key (`None`: unreadable, not retried).
|
||||
by_bse: HashMap<u32, Option<String>>,
|
||||
/// The media entries, merged into the document at the end.
|
||||
@@ -68,24 +69,34 @@ impl Pictures {
|
||||
/// count/byte cap is reached.
|
||||
pub(crate) fn get(&mut self, data: &[u8], fc_pic: u32) -> Option<Inline> {
|
||||
if let Some(hit) = self.by_fc.get(&fc_pic) {
|
||||
return Some(hit.clone());
|
||||
return hit.clone();
|
||||
}
|
||||
if self.by_fc.len().saturating_add(self.by_bse.len()) >= MAX_PICTURES {
|
||||
return None;
|
||||
}
|
||||
let pic = match locate(data, fc_pic)? {
|
||||
let pic = self.read(data, fc_pic);
|
||||
self.by_fc.insert(fc_pic, pic.clone());
|
||||
pic
|
||||
}
|
||||
|
||||
/// Read the inline picture at `fc_pic`: nothing is decoded or copied beyond what is left of
|
||||
/// the byte cap, and nothing at all once it is used up.
|
||||
fn read(&mut self, data: &[u8], fc_pic: u32) -> Option<Inline> {
|
||||
let room = self.limit.saturating_sub(self.total);
|
||||
if room == 0 {
|
||||
return None;
|
||||
}
|
||||
match locate(data, fc_pic, room)? {
|
||||
Found::Range(pic) => {
|
||||
let bytes = data.get(pic.range.clone())?.to_vec();
|
||||
let bytes = data.get(pic.range.clone()).filter(|b| b.len() <= room)?.to_vec();
|
||||
let key = self.insert(bytes, pic.ext, false)?;
|
||||
Inline { key, w: pic.w, h: pic.h, crop: [0.0; 4], alt: String::new() }
|
||||
Some(Inline { key, w: pic.w, h: pic.h, crop: [0.0; 4], alt: String::new() })
|
||||
}
|
||||
Found::Shape { w, h, blip, props } => {
|
||||
let key = self.insert(blip.bytes, blip.ext, blip.placeholder)?;
|
||||
Inline { key, w, h, crop: props.crop, alt: props.alt }
|
||||
Some(Inline { key, w, h, crop: props.crop, alt: props.alt })
|
||||
}
|
||||
};
|
||||
self.by_fc.insert(fc_pic, pic.clone());
|
||||
Some(pic)
|
||||
}
|
||||
}
|
||||
|
||||
/// The media key of BLIP store entry `pib` (1-based), decoding it the first time; `delay`
|
||||
@@ -148,8 +159,9 @@ enum Found {
|
||||
const MM_SHAPE: u16 = 0x0064;
|
||||
const MM_SHAPEFILE: u16 = 0x0066;
|
||||
|
||||
/// Locate the picture at `fc_pic` in the Data stream ([MS-DOC] §2.9.192 PICFAndOfficeArtData).
|
||||
fn locate(data: &[u8], fc_pic: u32) -> Option<Found> {
|
||||
/// Locate the picture at `fc_pic` in the Data stream ([MS-DOC] §2.9.192 PICFAndOfficeArtData);
|
||||
/// a shape's picture is decoded only up to `room` bytes.
|
||||
fn locate(data: &[u8], fc_pic: u32, room: usize) -> Option<Found> {
|
||||
let base = fc_pic as usize;
|
||||
let pic = data.get(base..)?;
|
||||
let lcb = u32::from_le_bytes(pic.get(0..4)?.try_into().ok()?) as usize;
|
||||
@@ -168,7 +180,7 @@ fn locate(data: &[u8], fc_pic: u32) -> Option<Found> {
|
||||
if mm == MM_SHAPEFILE {
|
||||
at = at.checked_add(1 + *pic.get(at)? as usize)?;
|
||||
}
|
||||
let (blip, props) = inline_shape(pic.get(at..end)?, data)?;
|
||||
let (blip, props) = inline_shape(pic.get(at..end)?, data, room)?;
|
||||
// The goal size is before cropping; the crop fractions take their share off it.
|
||||
let [cl, ct, cr, cb] = props.crop;
|
||||
let w = (dxa_goal / 20.0 * (1.0 - cl - cr).max(0.01) * scale(mx)).clamp(1.0, 1584.0);
|
||||
@@ -185,14 +197,15 @@ fn locate(data: &[u8], fc_pic: u32) -> Option<Found> {
|
||||
}
|
||||
|
||||
/// An `OfficeArtInlineSpContainer`: the picture shape, then the `OfficeArtFBSE` records its
|
||||
/// `pib` indexes (BLIPs embedded, or at `foDelay` in the Data stream).
|
||||
fn inline_shape(buf: &[u8], data: &[u8]) -> Option<(officeart::Blip, officeart::Props)> {
|
||||
/// `pib` indexes (BLIPs embedded, or at `foDelay` in the Data stream). `room` caps the bytes
|
||||
/// the BLIP decodes to.
|
||||
fn inline_shape(buf: &[u8], data: &[u8], room: usize) -> Option<(officeart::Blip, officeart::Props)> {
|
||||
let mut budget = 10_000usize;
|
||||
let recs = officeart::children(buf, &mut budget);
|
||||
let sp = recs.iter().find(|r| r.typ == officeart::rt::SP_CONTAINER).map(|r| officeart::shape(r.body, &mut budget))?;
|
||||
let fbses: Vec<&[u8]> = recs.iter().filter(|r| r.typ == officeart::rt::FBSE).map(|r| r.body).collect();
|
||||
let fbse = sp.props.pib.and_then(|p| fbses.get((p as usize).checked_sub(1)?)).or(fbses.first())?;
|
||||
let blip = officeart::fbse_blip(fbse, data, MAX_MEDIA_BYTES)?;
|
||||
let blip = officeart::fbse_blip(fbse, data, room)?;
|
||||
Some((blip, sp.props))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Optional document text properties from [MS-OLEPS] §2.21 and §2.25.1.
|
||||
//! Broken metadata must not prevent opening the document or allocate from unchecked sizes.
|
||||
|
||||
use std::io::{Read, Seek};
|
||||
|
||||
use wordcraft_doc::CoreProps;
|
||||
|
||||
const MAX_STREAM: u64 = 2 << 20;
|
||||
const MAX_STRING: usize = 64 << 10;
|
||||
const SUMMARY_FMTID: &[u8] = &[0xe0, 0x85, 0x9f, 0xf2, 0xf9, 0x4f, 0x68, 0x10, 0xab, 0x91, 0x08, 0x00, 0x2b, 0x27, 0xb3, 0xd9];
|
||||
|
||||
pub(crate) fn read<F: Read + Seek>(comp: &mut cfb::CompoundFile<F>) -> Option<CoreProps> {
|
||||
let stream = comp.open_stream("/\u{5}SummaryInformation").ok()?;
|
||||
if stream.len() > MAX_STREAM {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
stream.take(MAX_STREAM + 1).read_to_end(&mut bytes).ok()?;
|
||||
if bytes.len() as u64 > MAX_STREAM {
|
||||
return None;
|
||||
}
|
||||
parse(&bytes)
|
||||
}
|
||||
|
||||
fn u32_at(bytes: &[u8], offset: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(bytes.get(offset..offset.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn parse(bytes: &[u8]) -> Option<CoreProps> {
|
||||
if bytes.get(..2)? != [0xfe, 0xff] || bytes.get(28..44)? != SUMMARY_FMTID || u32_at(bytes, 24)? != 1 {
|
||||
return None;
|
||||
}
|
||||
if u16::from_le_bytes(bytes.get(2..4)?.try_into().ok()?) > 1 {
|
||||
return None;
|
||||
}
|
||||
let offset = u32_at(bytes, 44)? as usize;
|
||||
if offset < 48 || !offset.is_multiple_of(4) {
|
||||
return None;
|
||||
}
|
||||
let size = u32_at(bytes, offset)? as usize;
|
||||
let set = bytes.get(offset..offset.checked_add(size)?)?;
|
||||
let count = u32_at(set, 4)? as usize;
|
||||
if count > 4096 {
|
||||
return None;
|
||||
}
|
||||
let table_end = 8 + count * 8;
|
||||
let table = set.get(8..table_end)?;
|
||||
// Offsets are relative to the property set. Bound each value by the next property so a
|
||||
// forged string length cannot read another property's bytes as part of the title.
|
||||
let property = |id: u32| -> Option<&[u8]> {
|
||||
let entry = table.as_chunks::<8>().0.iter().find(|entry| u32_at(entry.as_slice(), 0) == Some(id))?.as_slice();
|
||||
let start = u32_at(entry, 4)? as usize;
|
||||
if start < table_end || !start.is_multiple_of(4) {
|
||||
return None;
|
||||
}
|
||||
let end = table
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.filter_map(|e| u32_at(e, 4))
|
||||
.map(|n| n as usize)
|
||||
.filter(|n| *n > start)
|
||||
.min()
|
||||
.unwrap_or(set.len())
|
||||
.min(set.len());
|
||||
set.get(start..end)
|
||||
};
|
||||
let cp = property(1)?;
|
||||
if u32_at(cp, 0)? != 2 {
|
||||
return None;
|
||||
} // VT_I2
|
||||
let codepage = u16::from_le_bytes(cp.get(4..6)?.try_into().ok()?);
|
||||
let get = |id| property(id).and_then(|value| text(value, codepage)).unwrap_or_default();
|
||||
Some(CoreProps {
|
||||
title: get(2),
|
||||
subject: get(3),
|
||||
creator: get(4),
|
||||
keywords: get(5),
|
||||
description: get(6),
|
||||
last_modified_by: get(8),
|
||||
revision: get(9).parse().unwrap_or_default(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn text(value: &[u8], codepage: u16) -> Option<String> {
|
||||
let kind = u32_at(value, 0)?;
|
||||
let count = u32_at(value, 4)? as usize;
|
||||
let size = match kind {
|
||||
30 => count, // CodePageString length is in bytes, even for code page 1200.
|
||||
31 => count.checked_mul(2)?, // UnicodeString length is in UTF-16 units.
|
||||
_ => return None,
|
||||
};
|
||||
if size > MAX_STRING {
|
||||
return None;
|
||||
}
|
||||
let bytes = value.get(8..8usize.checked_add(size)?)?;
|
||||
if kind == 31 || codepage == 1200 {
|
||||
if !bytes.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let units = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|u| *u != 0);
|
||||
Some(char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)).collect())
|
||||
} else {
|
||||
let bytes = bytes.split(|b| *b == 0).next().unwrap_or_default();
|
||||
if codepage == 65001 {
|
||||
Some(String::from_utf8_lossy(bytes).into_owned())
|
||||
} else if wordcraft_doc::encoding::SINGLE_BYTE_CODE_PAGES.contains(&codepage) {
|
||||
Some(bytes.iter().map(|b| wordcraft_doc::encoding::windows_byte(codepage, *b)).collect())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,11 @@ const MAX: usize = 10_000;
|
||||
/// Parse the note reference/story PLCs. `ref_pair`/`txt_pair` are the FIB pair indices
|
||||
/// (`(2, 3)` for footnotes, `(46, 47)` for endnotes); story ranges are relative to the
|
||||
/// note subdocument.
|
||||
///
|
||||
/// The story CPs of a well-formed PLC ascend, so the stories are disjoint. A hostile table
|
||||
/// that steps back would make many notes read the same text again (each one materialised
|
||||
/// as its own part), so a story starting before the end of the last one kept is dropped:
|
||||
/// every subdocument CP becomes at most one note.
|
||||
pub(crate) fn parse_notes(table: &[u8], fib: &crate::fib::Fib, ref_pair: usize, txt_pair: usize) -> Vec<(u32, (u32, u32))> {
|
||||
let refs = fib.pair(ref_pair).and_then(|(fc, lcb)| plc_of(table, fc, lcb, 2)).unwrap_or_default();
|
||||
let txts = fib.pair(txt_pair).and_then(|(fc, lcb)| plc_of(table, fc, lcb, 0)).unwrap_or_default();
|
||||
@@ -14,12 +19,15 @@ pub(crate) fn parse_notes(table: &[u8], fib: &crate::fib::Fib, ref_pair: usize,
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut kept_to = 0u32;
|
||||
// The reference PLC's aFtnIdx order matches the story order; pair them by index.
|
||||
for (i, &cp) in refs.iter().enumerate() {
|
||||
if let (Some(a), Some(b)) = (txts.get(i), txts.get(i + 1))
|
||||
if let (Some(&a), Some(&b)) = (txts.get(i), txts.get(i + 1))
|
||||
&& b > a
|
||||
&& a >= kept_to
|
||||
{
|
||||
out.push((cp, (*a, *b)));
|
||||
out.push((cp, (a, b)));
|
||||
kept_to = b;
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
//! and record counts are capped, and decompressed metafiles are size-limited.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
|
||||
use image::ImageEncoder;
|
||||
|
||||
use wordcraft_doc::props::Rgb;
|
||||
|
||||
@@ -138,7 +141,7 @@ pub(crate) fn blip(rec: &Rec, limit: usize) -> Option<Blip> {
|
||||
rt::BLIP_PNG => Some(Blip { bytes: data.to_vec(), ext: "png", placeholder: false }),
|
||||
rt::BLIP_JPEG | rt::BLIP_JPEG_CMYK => Some(Blip { bytes: data.to_vec(), ext: "jpeg", placeholder: false }),
|
||||
rt::BLIP_TIFF => Some(Blip { bytes: data.to_vec(), ext: "tiff", placeholder: false }),
|
||||
_ => dib_to_png(data),
|
||||
_ => dib_to_png(data, limit),
|
||||
}
|
||||
}
|
||||
rt::BLIP_EMF | rt::BLIP_WMF | rt::BLIP_PICT => {
|
||||
@@ -175,7 +178,7 @@ pub(crate) fn blip(rec: &Rec, limit: usize) -> Option<Blip> {
|
||||
/// A device-independent bitmap (BITMAPINFOHEADER + palette + pixels) as a PNG: the DIB gets
|
||||
/// the 14-byte BMP file header it lacks, is decoded with size limits and re-encoded. When the
|
||||
/// bitmap can't be decoded the BMP bytes are kept (and render as a grey placeholder).
|
||||
fn dib_to_png(dib: &[u8]) -> Option<Blip> {
|
||||
fn dib_to_png(dib: &[u8], limit: usize) -> Option<Blip> {
|
||||
let header = u32_at(dib, 0)? as usize;
|
||||
if !(12..=124).contains(&header) {
|
||||
return None;
|
||||
@@ -193,7 +196,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Blip> {
|
||||
// BI_BITFIELDS masks follow a 40-byte header.
|
||||
let masks = if header == 40 && (compression == 3 || compression == 6) { if compression == 3 { 12 } else { 16 } } else { 0 };
|
||||
let off_bits = 14usize.checked_add(header)?.checked_add(colors * entry)?.checked_add(masks)?;
|
||||
let file_size = 14usize.checked_add(dib.len())?;
|
||||
let file_size = 14usize.checked_add(dib.len()).filter(|&size| size <= limit)?;
|
||||
let mut bmp = Vec::with_capacity(file_size);
|
||||
bmp.extend_from_slice(b"BM");
|
||||
bmp.extend_from_slice(&u32::try_from(file_size).ok()?.to_le_bytes());
|
||||
@@ -205,17 +208,43 @@ fn dib_to_png(dib: &[u8]) -> Option<Blip> {
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_DIB_SIDE);
|
||||
limits.max_image_height = Some(MAX_DIB_SIDE);
|
||||
limits.max_alloc = Some(256 << 20);
|
||||
limits.max_alloc = Some((256 << 20).min(limit as u64));
|
||||
reader.limits(limits);
|
||||
let mut png = Vec::new();
|
||||
let mut png = PictureWriter { bytes: Vec::new(), limit };
|
||||
match reader.decode() {
|
||||
Ok(img) if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_ok() => {
|
||||
Some(Blip { bytes: png, ext: "png", placeholder: false })
|
||||
Ok(img)
|
||||
if image::codecs::png::PngEncoder::new(&mut png).write_image(img.as_bytes(), img.width(), img.height(), img.color().into()).is_ok() =>
|
||||
{
|
||||
Some(Blip { bytes: png.bytes, ext: "png", placeholder: false })
|
||||
}
|
||||
_ => Some(Blip { bytes: bmp, ext: "bmp", placeholder: true }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cap encoded bytes while the PNG encoder writes, before the buffer can grow.
|
||||
struct PictureWriter {
|
||||
bytes: Vec<u8>,
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
impl Write for PictureWriter {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let Some(end) = self.bytes.len().checked_add(buf.len()).filter(|&end| end <= self.limit) else {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "picture exceeds remaining media budget"));
|
||||
};
|
||||
if end > self.bytes.capacity() {
|
||||
let new_capacity = self.bytes.capacity().saturating_mul(2).max(end).min(self.limit);
|
||||
self.bytes.try_reserve_exact(new_capacity - self.bytes.len()).map_err(std::io::Error::other)?;
|
||||
}
|
||||
self.bytes.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Shapes.
|
||||
|
||||
|
||||
@@ -171,6 +171,11 @@ fn apply_section(s: &mut SectionProps, prl: &Prl) {
|
||||
/// `[cps[i], cps[i+1])`. Stories 0-5 are footnote/endnote separators; every section then owns
|
||||
/// six stories in the order even header, odd (default) header, even footer, odd (default)
|
||||
/// footer, first header, first footer. The CPs are relative to the header subdocument.
|
||||
///
|
||||
/// The CPs of a well-formed PLC ascend, so the stories are disjoint. A story starting before
|
||||
/// the end of an earlier one (a hostile table pointing many sections at the same text, each
|
||||
/// read into its own part) is left empty, like a slot linked to the previous section's:
|
||||
/// every subdocument CP becomes at most one story.
|
||||
pub(crate) fn header_stories(table: &[u8], fib: &Fib) -> Vec<(u32, u32)> {
|
||||
let Some((fc, lcb)) = fib.pair(pair::PLCF_HDD) else { return Vec::new() };
|
||||
let Some(plc) = table.get(fc as usize..(fc as usize).saturating_add(lcb as usize)) else { return Vec::new() };
|
||||
@@ -178,9 +183,12 @@ pub(crate) fn header_stories(table: &[u8], fib: &Fib) -> Vec<(u32, u32)> {
|
||||
let n = (lcb as usize / 4).min(6 + 6 * MAX_SECTIONS + 1);
|
||||
let cp_at = |i: usize| -> Option<u32> { plc.get(i * 4..i * 4 + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) };
|
||||
let mut stories = Vec::with_capacity(n);
|
||||
let mut kept_to = 0u32;
|
||||
for i in 0..n.saturating_sub(1) {
|
||||
if let (Some(a), Some(b)) = (cp_at(i), cp_at(i + 1)) {
|
||||
stories.push((a, b.max(a)));
|
||||
let b = if a < kept_to { a } else { b.max(a) };
|
||||
kept_to = kept_to.max(b);
|
||||
stories.push((a, b));
|
||||
}
|
||||
}
|
||||
stories
|
||||
|
||||
+90
-24
@@ -28,6 +28,15 @@ const T_TABLE_BORDERS_80: u16 = 0xD605;
|
||||
const T_ROW_HEIGHT: u16 = 0x9407;
|
||||
const T_DEF_TABLE: u16 = 0xD608;
|
||||
const T_DEF_TABLE_SHD_80: u16 = 0xD609;
|
||||
/// `sprmTDefTableShd` / `Shd2nd` / `Shd3rd`: 10-byte `Shd`s for cells 0-21, 22-43, 44-62.
|
||||
const T_DEF_TABLE_SHD: u16 = 0xD612;
|
||||
const T_DEF_TABLE_SHD_2ND: u16 = 0xD616;
|
||||
const T_DEF_TABLE_SHD_3RD: u16 = 0xD60C;
|
||||
/// `sprmTDefTableShdRaw` / `Raw2nd` / `Raw3rd`: the same `Shd` arrays over the same cell
|
||||
/// ranges, which Word 2007+ writes next to the above.
|
||||
const T_DEF_TABLE_SHD_RAW: u16 = 0xD670;
|
||||
const T_DEF_TABLE_SHD_RAW_2ND: u16 = 0xD671;
|
||||
const T_DEF_TABLE_SHD_RAW_3RD: u16 = 0xD672;
|
||||
const T_CANT_SPLIT_90: u16 = 0x3403;
|
||||
const T_MERGE: u16 = 0x5624;
|
||||
const T_VERT_MERGE: u16 = 0xD62B;
|
||||
@@ -49,8 +58,10 @@ pub(crate) struct RowInfo {
|
||||
pub(crate) cell_mark: bool,
|
||||
/// Table depth from `sprmPItap` (0 or 1 supported; deeper tables degrade to paragraphs).
|
||||
pub(crate) depth: u32,
|
||||
/// Column widths (points) from `sprmTDefTable`.
|
||||
pub(crate) grid: Vec<f32>,
|
||||
/// Cell-edge positions (points) from `sprmTDefTable` — [MS-DOC] defines them per row,
|
||||
/// so each row keeps its own; ascending in well-formed rows, the first edge usually 0
|
||||
/// (the row origin). Rows without a `sprmTDefTable` keep this empty.
|
||||
pub(crate) edges: Vec<f32>,
|
||||
height: Option<f32>,
|
||||
height_rule: HeightRule,
|
||||
header: bool,
|
||||
@@ -62,7 +73,9 @@ pub(crate) struct RowInfo {
|
||||
merges: Vec<(u8, u8)>,
|
||||
/// Per-cell overrides keyed by (pre-merge) cell index.
|
||||
vmerge: Vec<(u8, VMerge)>,
|
||||
shading: Vec<(u8, Rgb)>,
|
||||
/// Later entries win: the `Shd` arrays override the `Shd80` fallback before them, and an
|
||||
/// automatic `Shd` (`None`) clears it.
|
||||
shading: Vec<(u8, Option<Rgb>)>,
|
||||
widths: Vec<(u8, f32)>,
|
||||
valign: Vec<(u8, VAlign)>,
|
||||
}
|
||||
@@ -74,6 +87,12 @@ impl RowInfo {
|
||||
pub(crate) fn height(&self) -> Option<f32> {
|
||||
self.height
|
||||
}
|
||||
|
||||
/// The fill cell `i` ends up with (the last shading entry for it wins), for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn shading_of(&self, i: u8) -> Option<Rgb> {
|
||||
self.shading.iter().rfind(|(k, _)| *k == i).and_then(|(_, s)| *s)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode(papx: &[u8]) -> RowInfo {
|
||||
@@ -87,7 +106,7 @@ pub(crate) fn decode(papx: &[u8]) -> RowInfo {
|
||||
P_IN_TABLE => r.in_table = prl.operand.first().copied().unwrap_or(0) != 0,
|
||||
P_TTP => r.ttp = prl.operand.first().copied().unwrap_or(0) != 0,
|
||||
P_ITAP => r.depth = i32_of(&prl).unwrap_or(0).max(0) as u32,
|
||||
T_DEF_TABLE => r.grid = def_table_grid(prl.operand),
|
||||
T_DEF_TABLE => r.edges = def_table_edges(prl.operand),
|
||||
T_TABLE_HEADER => r.header = prl.operand.first().copied().unwrap_or(0) != 0,
|
||||
T_CANT_SPLIT | T_CANT_SPLIT_90 => r.cant_split = prl.operand.first().copied().unwrap_or(0) != 0,
|
||||
T_ROW_HEIGHT => {
|
||||
@@ -135,8 +154,8 @@ pub(crate) fn decode(papx: &[u8]) -> RowInfo {
|
||||
if let Some(rgb) = prl.operand.get(3..).and_then(shd_rgb)
|
||||
&& let [a, b, ..] = prl.operand.get(1..3).unwrap_or(&[])
|
||||
{
|
||||
for c in *a..*b {
|
||||
r.shading.push((c, rgb));
|
||||
for c in *a..(*b).min(MAX_COLS as u8) {
|
||||
r.shading.push((c, Some(rgb)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,10 +163,29 @@ pub(crate) fn decode(papx: &[u8]) -> RowInfo {
|
||||
let cells = prl.operand.get(1..).unwrap_or(&[]);
|
||||
for (i, b) in cells.as_chunks::<2>().0.iter().take(MAX_COLS).enumerate() {
|
||||
if let Some(rgb) = shd80_rgb(b) {
|
||||
r.shading.push((i as u8, rgb));
|
||||
r.shading.push((i as u8, Some(rgb)));
|
||||
}
|
||||
}
|
||||
}
|
||||
T_DEF_TABLE_SHD | T_DEF_TABLE_SHD_RAW | T_DEF_TABLE_SHD_2ND | T_DEF_TABLE_SHD_RAW_2ND | T_DEF_TABLE_SHD_3RD | T_DEF_TABLE_SHD_RAW_3RD => {
|
||||
// Each array covers its own cell range (0-21, 22-43, 44-62); extra entries
|
||||
// are ignored so an over-long array can't override the next range.
|
||||
let (first, lim) = match prl.op {
|
||||
T_DEF_TABLE_SHD_2ND | T_DEF_TABLE_SHD_RAW_2ND => (22, 44),
|
||||
T_DEF_TABLE_SHD_3RD | T_DEF_TABLE_SHD_RAW_3RD => (44, MAX_COLS),
|
||||
_ => (0, 22),
|
||||
};
|
||||
let cells = prl.operand.get(1..).unwrap_or(&[]);
|
||||
let raw = matches!(prl.op, T_DEF_TABLE_SHD_RAW | T_DEF_TABLE_SHD_RAW_2ND | T_DEF_TABLE_SHD_RAW_3RD);
|
||||
for (i, b) in cells.as_chunks::<10>().0.iter().take(lim - first).enumerate() {
|
||||
// In the Raw arrays a nil Shd (ipat 0xFFFF) means "as the table style
|
||||
// shades it", so it leaves any earlier fill alone.
|
||||
if raw && b.get(8..10) == Some(&[0xFF, 0xFF]) {
|
||||
continue;
|
||||
}
|
||||
r.shading.push(((first + i) as u8, shd_rgb(b)));
|
||||
}
|
||||
}
|
||||
T_CELL_WIDTH => {
|
||||
// cb, itcFirst, itcLim, ftsWidth (3 = twips), wWidth.
|
||||
if let [a, b, fts, w0, w1, ..] = prl.operand
|
||||
@@ -221,11 +259,11 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
if let Some((_, w)) = info.widths.iter().find(|(k, _)| *k == i) {
|
||||
c.props.width = Some(*w);
|
||||
}
|
||||
if let Some((_, s)) = info.shading.iter().find(|(k, _)| *k == i) {
|
||||
c.props.shading = Some(*s);
|
||||
if let Some((_, s)) = info.shading.iter().rfind(|(k, _)| *k == i) {
|
||||
c.props.shading = *s;
|
||||
}
|
||||
if let Some((_, v)) = info.valign.iter().find(|(k, _)| *k == i) {
|
||||
c.props.valign = *v;
|
||||
c.props.valign = Some(*v);
|
||||
}
|
||||
}
|
||||
for &(a, b) in info.merges.iter().take(MAX_COLS) {
|
||||
@@ -250,7 +288,7 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
height_rule: info.height_rule,
|
||||
header: info.header,
|
||||
cant_split: info.cant_split,
|
||||
fmt_change: None,
|
||||
..Default::default()
|
||||
},
|
||||
cells,
|
||||
controls: Default::default(),
|
||||
@@ -295,6 +333,13 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
if !is_table {
|
||||
if open {
|
||||
flush_table(&mut out, &mut rows, &mut cells, &mut cell, &grid, &props, depth_seen > 1);
|
||||
grid.clear();
|
||||
// Table props are per-table (first row carrying the sprm wins within the
|
||||
// table): reset the accumulator so one table's borders, align, indent and
|
||||
// cell margins never leak into the next (the repro's first table wrote
|
||||
// Word's default 108-twip gap, and every later table — including the
|
||||
// change history with its own 40-twip gap — inherited 5.4 pt margins).
|
||||
props = TableProps::default();
|
||||
open = false;
|
||||
depth_seen = 0;
|
||||
}
|
||||
@@ -305,8 +350,9 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
open = true;
|
||||
}
|
||||
depth_seen = depth_seen.max(info.depth);
|
||||
if !info.grid.is_empty() && grid.is_empty() {
|
||||
grid = info.grid.clone();
|
||||
if grid.is_empty() {
|
||||
// Column widths from the table's first `sprmTDefTable`.
|
||||
grid = info.edges.windows(2).take(MAX_COLS).map(|w| (w[1] - w[0]).max(0.0)).collect();
|
||||
}
|
||||
if info.borders.is_some() && props.borders.is_none() {
|
||||
props.borders = info.borders;
|
||||
@@ -318,10 +364,25 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
props.indent = info.indent;
|
||||
}
|
||||
if info.cell_mark {
|
||||
// A row-end (TTP) mark terminates the row. Word writes rows as N content
|
||||
// cells each ended by their own cell mark, followed by an empty row-end mark
|
||||
// that carries the row's TDefTable (the 3GPP change history: 8 content marks
|
||||
// + an empty TTP whose TDefTable defines itcMac = 8). When that mark ends no
|
||||
// content of its own and the TDefTable already has a column per flushed cell,
|
||||
// it is a pure row terminator, not the end of a phantom (N+1)th cell — such a
|
||||
// cell has no column (width None) and shifts every real cell's span one grid
|
||||
// column over. A TTP mark with content, or one short of the TDefTable's
|
||||
// columns, still ends a real cell (rows without a TDefTable keep today's
|
||||
// shape: the count is unknowable, so the mark always flushes).
|
||||
let row_end_only = info.ttp && p.para.text.is_empty() && cell.is_empty() && !info.edges.is_empty() && cells.len() + 1 >= info.edges.len();
|
||||
// ...but a row-end mark with no cells before it still makes a (one-cell) row.
|
||||
let row_end_only = row_end_only && !cells.is_empty();
|
||||
if !p.para.text.is_empty() {
|
||||
cell.push(para_block(p.para));
|
||||
}
|
||||
flush_cell(&mut cells, &mut cell);
|
||||
if !row_end_only {
|
||||
flush_cell(&mut cells, &mut cell);
|
||||
}
|
||||
if info.ttp {
|
||||
let row = build_row(std::mem::take(&mut cells), &info);
|
||||
rows.push(row);
|
||||
@@ -336,21 +397,23 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
out
|
||||
}
|
||||
|
||||
/// Column widths (points) from a `sprmTDefTable` operand: cb u16, itcMac u8, then itcMac+1
|
||||
/// twip boundaries followed by the TC80s (skipped).
|
||||
fn def_table_grid(operand: &[u8]) -> Vec<f32> {
|
||||
/// Cell-edge positions (points) from a `sprmTDefTable` operand: cb u16, itcMac u8, then
|
||||
/// itcMac+1 twip boundaries followed by the TC80s (skipped). Edges are returned as stored:
|
||||
/// per-row, in operand order; sorting and capping happen when the table grid is assembled.
|
||||
fn def_table_edges(operand: &[u8]) -> Vec<f32> {
|
||||
let itc = operand.get(2).copied().unwrap_or(0) as usize;
|
||||
if itc == 0 || itc > MAX_COLS {
|
||||
if itc == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut edges = Vec::with_capacity(itc + 1);
|
||||
// itcMac is a u8, so this allocation stays tiny; the loop stops at the operand's end.
|
||||
let mut edges = Vec::with_capacity((itc + 1).min(256));
|
||||
for i in 0..=itc {
|
||||
match operand.get(3 + i * 2..3 + i * 2 + 2) {
|
||||
Some(b) => edges.push(i16::from_le_bytes([b[0], b[1]]) as f32 / 20.0),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
edges.windows(2).map(|w| (w[1] - w[0]).max(0.0)).collect()
|
||||
edges
|
||||
}
|
||||
|
||||
/// Table borders from `sprmTTableBorders80`: cb (0x18) then six Brc80s in the order top,
|
||||
@@ -381,7 +444,8 @@ fn brc80(b: &[u8]) -> Option<Border> {
|
||||
}
|
||||
|
||||
/// Background colour from a 10-byte `Shd`: cvFore, cvBack (COLORREFs), ipat. Solid patterns
|
||||
/// show the foreground; other patterns are approximated by their background.
|
||||
/// show the foreground; clear (0) and the other patterns show the background (Word writes a
|
||||
/// plain cell fill as clear with cvBack); nil (0xFFFF) and automatic colours are no fill.
|
||||
fn shd_rgb(b: &[u8]) -> Option<Rgb> {
|
||||
let cv = |b: &[u8]| -> Option<Rgb> {
|
||||
match b {
|
||||
@@ -392,19 +456,21 @@ fn shd_rgb(b: &[u8]) -> Option<Rgb> {
|
||||
};
|
||||
let ipat = b.get(8..10).map(|x| u16::from_le_bytes([x[0], x[1]]))?;
|
||||
match ipat {
|
||||
0 | 0xFFFF => None,
|
||||
0xFFFF => None,
|
||||
1 => cv(b.get(0..4)?),
|
||||
_ => cv(b.get(4..8)?),
|
||||
}
|
||||
}
|
||||
|
||||
/// Background colour from a 2-byte `Shd80` (icoFore, icoBack, ipat bit-fields).
|
||||
/// Background colour from a 2-byte `Shd80` (icoFore, icoBack, ipat bit-fields). As in
|
||||
/// [`shd_rgb`], solid shows the foreground and clear (0) the background, which is how Word
|
||||
/// 97 writes a plain fill; ico 0 is automatic (no fill).
|
||||
fn shd80_rgb(b: &[u8]) -> Option<Rgb> {
|
||||
let v = u16::from_le_bytes([*b.first()?, *b.get(1)?]);
|
||||
let fore = v & 0x1F;
|
||||
let back = (v >> 5) & 0x1F;
|
||||
let ipat = v >> 10;
|
||||
if ipat == 0 || (fore == 0x1F && back == 0x1F) {
|
||||
if fore == 0x1F && back == 0x1F {
|
||||
return None;
|
||||
}
|
||||
fmt::ico(if ipat == 1 { fore as u8 } else { back as u8 })
|
||||
|
||||
+381
-2
@@ -8,6 +8,8 @@ use proptest::prelude::*;
|
||||
use super::read;
|
||||
|
||||
mod drawing;
|
||||
mod encrypted;
|
||||
mod metadata;
|
||||
|
||||
/// Offset in the WordDocument stream where test text pieces are placed (past the FIB).
|
||||
const TEXT_FC: u32 = 0x600;
|
||||
@@ -171,10 +173,10 @@ fn word_6_95_rejected() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_rejected() {
|
||||
fn encrypted_asks_for_a_password() {
|
||||
let spec = FibSpec { flags: 0x1100, ..Default::default() };
|
||||
let f = cfb_file(&[("WordDocument", &fib_bytes(&spec))]);
|
||||
assert!(matches!(read(&f), Err(super::DocbinError::Encrypted)));
|
||||
assert!(matches!(read(&f), Err(super::DocbinError::PasswordRequired)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1500,6 +1502,92 @@ fn huge_story_ranges_are_clamped_to_their_subdocument() {
|
||||
assert!(!doc.parts.values().any(|p| p.kind == wordcraft_doc::PartKind::Endnote));
|
||||
}
|
||||
|
||||
/// The text of each note a paragraph references, in order.
|
||||
fn note_texts(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph) -> Vec<String> {
|
||||
p.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
wordcraft_doc::para::InlineObject::NoteRef { id, .. } => doc.parts.get(id),
|
||||
_ => None,
|
||||
})
|
||||
.map(|part| part.blocks.iter().filter_map(|b| b.as_para()).map(|para| para.text.as_str()).collect::<Vec<_>>().join("\n"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_stories_pointing_at_the_same_text_are_read_once() {
|
||||
// 2000 footnote references whose PlcffndTxt steps back to CP 0 after every story
|
||||
// ([0, 10, 0, 10, …]): every other one was read into its own part, a copy of the whole
|
||||
// footnote subdocument each (1001 parts here; a large story times thousands of
|
||||
// references in a hostile file).
|
||||
let n = 2000u32;
|
||||
let text: &'static str = Box::leak(format!("A{}\r", "\u{2}".repeat(n as usize)).into_boxed_str());
|
||||
let ccp = text.chars().count() as u32;
|
||||
let refs: Vec<u32> = (1..=n).chain([ccp]).collect();
|
||||
let spec = StructSpec {
|
||||
text,
|
||||
note_stories: vec!["Note body\r"],
|
||||
extra_pairs: vec![(2, plc(&refs, &1u16.to_le_bytes().repeat(n as usize))), (3, plc(&[0u32, 10].repeat(n as usize / 2 + 1), &[]))],
|
||||
..structured_spec(text, ccp)
|
||||
};
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
assert_eq!(doc.parts.values().filter(|p| p.kind == wordcraft_doc::PartKind::Footnote).count(), 1);
|
||||
let p0 = doc.body.first().and_then(|b| b.as_para()).expect("para");
|
||||
assert_eq!(note_texts(&doc, p0), vec!["Note body".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_stories_stepping_back_are_dropped_and_ordered_ones_kept() {
|
||||
// Story CPs [0, 5, 10, 3, 10] for four footnotes and four endnotes: the first two
|
||||
// stories are in order and read (the control); the third runs backwards and the fourth
|
||||
// starts inside the first, so the third and fourth references get no note.
|
||||
let text = "a\u{2}b\u{2}c\u{2}d\u{2}e\u{2}f\u{2}g\u{2}h\u{2}\r";
|
||||
let ccp = text.chars().count() as u32;
|
||||
let stories = plc(&[0, 5, 10, 3, 10], &[]);
|
||||
let spec = StructSpec {
|
||||
text,
|
||||
note_stories: vec!["Aaaa\rBbbb\r"],
|
||||
endnote_stories: vec!["Cccc\rDddd\r"],
|
||||
extra_pairs: vec![
|
||||
(2, plc(&[1, 3, 5, 7, ccp], &1u16.to_le_bytes().repeat(4))),
|
||||
(3, stories.clone()),
|
||||
(46, plc(&[9, 11, 13, 15, ccp], &1u16.to_le_bytes().repeat(4))),
|
||||
(47, stories),
|
||||
],
|
||||
..structured_spec(text, ccp)
|
||||
};
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
let p0 = doc.body.first().and_then(|b| b.as_para()).expect("para");
|
||||
assert_eq!(note_texts(&doc, p0), ["Aaaa", "Bbbb", "Cccc", "Dddd"].map(String::from));
|
||||
assert_eq!(doc.parts.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_stories_pointing_at_the_same_text_are_read_once() {
|
||||
// Two sections whose odd headers both claim the header subdocument's [0, 5) (Plcfhdd
|
||||
// steps back to CP 0 inside the second section's slots): the second used to become a
|
||||
// second copy of the text. Its slot is now empty, which links it to the first section's.
|
||||
let text = "a\rb\r";
|
||||
let ccp = text.chars().count() as u32;
|
||||
// Six empty separator stories, then each section's six slots; the odd header is the
|
||||
// second slot.
|
||||
let hdd = plc(&[0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 0, 5, 5, 5, 5, 5], &[]);
|
||||
let spec = StructSpec {
|
||||
text,
|
||||
header_stories: vec!["Head\r"],
|
||||
sections: vec![(2, Vec::new()), (ccp, Vec::new())],
|
||||
papx_entries: vec![(0, 0, Vec::new()), (2, 0, Vec::new())],
|
||||
extra_pairs: vec![(11, hdd)],
|
||||
..structured_spec(text, ccp)
|
||||
};
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
assert_eq!(doc.parts.values().filter(|p| p.kind == wordcraft_doc::PartKind::Header).count(), 1);
|
||||
let first = doc.body.first().and_then(|b| b.as_para()).and_then(|p| p.section.as_ref()).expect("first section");
|
||||
let header = first.headers.default.and_then(|id| doc.parts.get(&id)).expect("first section's header");
|
||||
assert!(header.blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text == "Head")), "header: {:?}", header.blocks);
|
||||
assert_eq!(doc.last_section.headers.default, None);
|
||||
}
|
||||
|
||||
/// A document whose piece table is given raw (cps + one Pcd per piece), with `text` bytes
|
||||
/// at TEXT_FC and the FIB claiming `ccp_text` main-document characters.
|
||||
fn raw_piece_doc(cps: &[u32], fcs: &[u32], text: &[u8], ccp_text: u32) -> Vec<u8> {
|
||||
@@ -1637,6 +1725,31 @@ fn picture_bytes_are_capped_per_document() {
|
||||
const { assert!(crate::media::MAX_MEDIA_BYTES <= 256 << 20) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_inline_pictures_are_not_read_again() {
|
||||
// A picture over the cap was located and copied again for every anchor on it.
|
||||
let big = picf_with_png(1200);
|
||||
let small = picf_with_png(300);
|
||||
let data: Vec<u8> = [big.clone(), small.clone()].concat();
|
||||
let mut pics = crate::media::Pictures::default();
|
||||
pics.limit = 1000;
|
||||
assert!(pics.get(&data, 0).is_none(), "over the cap");
|
||||
// The failure is remembered: that place isn't read again, whatever it holds now.
|
||||
assert!(pics.get(&small, 0).is_none());
|
||||
// The rejected picture took nothing off the cap, and anchors sharing a picture share it.
|
||||
let at = big.len() as u32;
|
||||
let fits = pics.get(&data, at).expect("fits");
|
||||
assert_eq!(pics.get(&data, at).map(|p| p.key), Some(fits.key));
|
||||
assert_eq!(pics.media.len(), 1);
|
||||
// Filling the cap exactly works; after that, a place never tried before isn't read.
|
||||
let rest = picf_with_png(700);
|
||||
let rest_at = data.len() as u32;
|
||||
let tail: Vec<u8> = [data, rest.clone(), small].concat();
|
||||
assert!(pics.get(&tail, rest_at).is_some(), "700 more bytes fill the cap");
|
||||
assert!(pics.get(&tail, rest_at + rest.len() as u32).is_none(), "the cap is used up");
|
||||
assert_eq!(pics.media.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_height_of_i16_min_does_not_overflow() {
|
||||
// sprmTDyaRowHeight = -32768: negating the i16 overflowed (a debug-build panic).
|
||||
@@ -1906,3 +2019,269 @@ fn section_marks_end_paragraphs() {
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
assert_eq!(body_texts(&doc), ["a\u{C}b"]);
|
||||
}
|
||||
|
||||
// #1380: Word 2000+ tables. Word writes each row as its cell marks plus a separate row-end
|
||||
// (TTP) mark, cell shading as 10-byte `Shd`s in `sprmTDefTableShd`/`sprmTDefTableShdRaw` (the
|
||||
// `Shd80` palette copy in `sprmTDefTableShd80` is only a fallback), and a horizontally
|
||||
// merged row as a row with fewer, wider cells in its own `sprmTDefTable`.
|
||||
|
||||
/// A `sprmTDefTable` Prl with `edges` twip boundaries and no TC80s (cb counts the bytes
|
||||
/// after it, plus one; Word may store fewer TC80s than cells).
|
||||
fn t_def_edges(edges: &[i16]) -> Vec<u8> {
|
||||
let mut body = vec![(edges.len() as u8).saturating_sub(1)];
|
||||
for e in edges {
|
||||
body.extend_from_slice(&e.to_le_bytes());
|
||||
}
|
||||
let mut v = (0xD608u16).to_le_bytes().to_vec();
|
||||
v.extend_from_slice(&((body.len() + 1) as u16).to_le_bytes());
|
||||
v.extend_from_slice(&body);
|
||||
v
|
||||
}
|
||||
|
||||
/// A variable-length table sprm whose operand is cb then `body`.
|
||||
fn sprm_cb(op: u16, body: &[u8]) -> Vec<u8> {
|
||||
let mut v = op.to_le_bytes().to_vec();
|
||||
v.push(body.len() as u8);
|
||||
v.extend_from_slice(body);
|
||||
v
|
||||
}
|
||||
|
||||
/// `n` copies of a 10-byte `Shd`: cvFore auto, cvBack = `back`, ipat 0 (clear), the way
|
||||
/// Word writes a plain cell fill.
|
||||
fn shd_clear(back: [u8; 3], n: usize) -> Vec<u8> {
|
||||
let one = [0, 0, 0, 0xFF, back[0], back[1], back[2], 0, 0, 0];
|
||||
one.repeat(n)
|
||||
}
|
||||
|
||||
/// Word-shaped 5-column table: header row, a shaded body row, a one-cell legend row.
|
||||
fn word_table_doc(row1: Vec<u8>, row2: Vec<u8>, row3: Vec<u8>) -> wordcraft_doc::Document {
|
||||
let text = "a\u{7}b\u{7}c\u{7}d\u{7}e\u{7}\u{7}f\u{7}g\u{7}h\u{7}i\u{7}j\u{7}\u{7}legend\u{7}\u{7}tail\r";
|
||||
let in_tbl = grpprl(&[(0x2416, &[0x01]), (0x6649, &[1, 0, 0, 0])]);
|
||||
let ttp = |extra: Vec<u8>| [grpprl(&[(0x2416, &[0x01]), (0x2417, &[0x01]), (0x6649, &[1, 0, 0, 0])]), extra].concat();
|
||||
let spec = StructSpec {
|
||||
text,
|
||||
header_stories: vec![],
|
||||
sections: vec![(text.chars().count() as u32, Vec::new())],
|
||||
chpx_runs: vec![(0, Vec::new())],
|
||||
papx_entries: vec![
|
||||
(0, 0, in_tbl.clone()), // a..e cell marks
|
||||
(10, 0, ttp(row1)), // row 1 end mark
|
||||
(11, 0, in_tbl.clone()),
|
||||
(21, 0, ttp(row2)),
|
||||
(22, 0, in_tbl),
|
||||
(29, 0, ttp(row3)),
|
||||
(30, 0, Vec::new()), // tail
|
||||
],
|
||||
plf_lst: Vec::new(),
|
||||
plf_lfo: Vec::new(),
|
||||
note_stories: vec![],
|
||||
endnote_stories: vec![],
|
||||
extra_pairs: Vec::new(),
|
||||
data_stream: Vec::new(),
|
||||
};
|
||||
read(&struct_doc(&spec)).expect("opens")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_table_row_end_mark_and_cell_shading() {
|
||||
let edges5: [i16; 6] = [0, 1440, 2880, 4320, 5760, 7200];
|
||||
// Row 1: the Shd80 fallback first (icoBack 9 = navy, clear), then the exact fill, dark
|
||||
// blue 1C3A70, in sprmTDefTableShd (0xD612) and sprmTDefTableShdRaw (0xD670), as Word
|
||||
// 365 writes it. The exact colours must beat the palette colour.
|
||||
let shd80: Vec<u8> = [0x20u8, 0x01].repeat(5);
|
||||
let row1 = [
|
||||
t_def_edges(&edges5),
|
||||
sprm_cb(0xD609, &shd80),
|
||||
sprm_cb(0xD612, &shd_clear([0x1C, 0x3A, 0x70], 5)),
|
||||
sprm_cb(0xD670, &shd_clear([0x1C, 0x3A, 0x70], 5)),
|
||||
]
|
||||
.concat();
|
||||
// Row 2: a Shd80 yellow fill (icoBack 7) on every cell, then sprmTDefTableShd with light
|
||||
// blue E8F0FA for cells 0-3 and an automatic Shd for cell 4, which clears its fill.
|
||||
let shd80_yellow: Vec<u8> = [0xE0u8, 0x00].repeat(5);
|
||||
let shd2 = [shd_clear([0xE8, 0xF0, 0xFA], 4), vec![0, 0, 0, 0xFF, 0, 0, 0, 0xFF, 0, 0]].concat();
|
||||
let row2 = [t_def_edges(&edges5), sprm_cb(0xD609, &shd80_yellow), sprm_cb(0xD612, &shd2)].concat();
|
||||
// Row 3: one cell from the first edge to the last, filled FFF2CC.
|
||||
let row3 = [t_def_edges(&[0, 7200]), sprm_cb(0xD612, &shd_clear([0xFF, 0xF2, 0xCC], 1))].concat();
|
||||
let doc = word_table_doc(row1, row2, row3);
|
||||
let tbl = doc.body.iter().find_map(|b| b.as_table()).expect("table");
|
||||
assert_eq!(tbl.grid.len(), 5, "grid columns");
|
||||
assert_eq!(tbl.rows.len(), 3);
|
||||
let counts: Vec<usize> = tbl.rows.iter().map(|r| r.cells.len()).collect();
|
||||
assert_eq!(counts, [5, 5, 1], "cells per row (the row-end mark is not a cell)");
|
||||
let shd = |r: usize| tbl.rows[r].cells.iter().map(|c| c.props.shading).collect::<Vec<_>>();
|
||||
assert_eq!(shd(0), vec![Some(wordcraft_doc::Rgb(0x1C, 0x3A, 0x70)); 5], "exact fill beats the Shd80 palette colour");
|
||||
let light = Some(wordcraft_doc::Rgb(0xE8, 0xF0, 0xFA));
|
||||
assert_eq!(shd(1), vec![light, light, light, light, None], "automatic Shd clears the Shd80 fill");
|
||||
assert_eq!(shd(2), vec![Some(wordcraft_doc::Rgb(0xFF, 0xF2, 0xCC))], "legend fill");
|
||||
let legend = tbl.rows[2].cells[0].blocks.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::<String>();
|
||||
assert_eq!(legend, "legend");
|
||||
let tail = doc.body.last().and_then(|b| b.as_para()).expect("tail para");
|
||||
assert_eq!(tail.text, "tail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word97_shd80_clear_fill_shows_its_background() {
|
||||
// Word 97 writes only sprmTDefTableShd80: a plain fill is pattern clear (ipat 0) with
|
||||
// the colour in icoBack. Cells: icoBack 7 (yellow), icoBack 16 (silver), auto (none),
|
||||
// solid (ipat 1) with icoFore 2 (blue).
|
||||
let shd80: Vec<u8> = [0xE0u16, 16 << 5, 0, (1 << 10) | 2].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let papx = sprm_cb(0xD609, &shd80);
|
||||
let row = crate::table::decode(&papx);
|
||||
assert_eq!(row.shading_of(0), Some(wordcraft_doc::Rgb(255, 255, 0)));
|
||||
assert_eq!(row.shading_of(1), Some(wordcraft_doc::Rgb(192, 192, 192)));
|
||||
assert_eq!(row.shading_of(2), None);
|
||||
assert_eq!(row.shading_of(3), Some(wordcraft_doc::Rgb(0, 0, 255)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shd_arrays_keep_to_their_cell_ranges() {
|
||||
// sprmTDefTableShd and sprmTDefTableShdRaw cover cells 0-21; their 2nd and 3rd forms
|
||||
// cover 22-43 and 44-62. An over-long first array must not reach cell 22.
|
||||
let red = shd_clear([0xFF, 0, 0], 1);
|
||||
let green = shd_clear([0, 0xFF, 0], 1);
|
||||
let blue = shd_clear([0, 0, 0xFF], 1);
|
||||
let over_long = shd_clear([0x11, 0x22, 0x33], 23);
|
||||
for (first, second, third) in [(0xD612u16, 0xD616u16, 0xD60Cu16), (0xD670, 0xD671, 0xD672)] {
|
||||
let papx = [sprm_cb(second, &green), sprm_cb(third, &blue), sprm_cb(first, &over_long)].concat();
|
||||
let row = crate::table::decode(&papx);
|
||||
assert_eq!(row.shading_of(21), Some(wordcraft_doc::Rgb(0x11, 0x22, 0x33)), "{first:04X}");
|
||||
assert_eq!(row.shading_of(22), Some(wordcraft_doc::Rgb(0, 0xFF, 0)), "{second:04X} keeps cell 22");
|
||||
assert_eq!(row.shading_of(44), Some(wordcraft_doc::Rgb(0, 0, 0xFF)), "{third:04X} starts at cell 44");
|
||||
let papx = sprm_cb(first, &red);
|
||||
assert_eq!(crate::table::decode(&papx).shading_of(0), Some(wordcraft_doc::Rgb(0xFF, 0, 0)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_table_shading_and_spans_are_safe() {
|
||||
// SHD arrays longer than the row, odd lengths, empty ones; itcMac past 63; edges that
|
||||
// run backwards or past the grid; merges past the row's end.
|
||||
// (Kept small: the fixture's single PAPX page holds every row's grpprl.)
|
||||
let long = shd_clear([1, 2, 3], 6);
|
||||
let rows: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> = vec![
|
||||
([sprm_cb(0xD612, &long), sprm_cb(0xD616, &long)].concat(), sprm_cb(0xD60C, &long), sprm_cb(0xD670, &long)),
|
||||
(sprm_cb(0xD612, &[1, 2, 3, 4, 5, 6, 7]), sprm_cb(0xD670, &[]), sprm_cb(0xD672, &long[..13])),
|
||||
(
|
||||
{
|
||||
let mut v = (0xD608u16).to_le_bytes().to_vec();
|
||||
v.extend_from_slice(&[0xFF, 0x00, 200]);
|
||||
v.extend_from_slice(&[0x10; 24]);
|
||||
v
|
||||
},
|
||||
t_def_edges(&[7200, 0, -5, 30000]),
|
||||
t_def_edges(&[-32000, 32000]),
|
||||
),
|
||||
(t_def_edges(&[0]), t_def_edges(&[]), [t_def_edges(&[0, 100, i16::MAX]), sprm_cb(0xD612, &long)].concat()),
|
||||
(grpprl(&[(0x5624, &[0, 200])]), grpprl(&[(0x5624, &[200, 3])]), grpprl(&[(0x5624, &[1, 255])])),
|
||||
];
|
||||
for (r1, r2, r3) in rows {
|
||||
let doc = word_table_doc(r1, r2, r3);
|
||||
let text = doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert!(text.contains("legend") && text.contains("tail"), "{text:?}");
|
||||
if let Some(t) = doc.body.iter().find_map(|b| b.as_table()) {
|
||||
assert!(t.grid.len() <= 63);
|
||||
for r in &t.rows {
|
||||
assert!(r.cells.iter().all(|c| c.props.span <= 63));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A row that is only a row-end mark (no cell marks before it), with an out-of-range
|
||||
// merge and a SHD array, then a normal row.
|
||||
// The second variant's sprmTDefTable is truncated to a single edge (itcMac 3), which
|
||||
// must not turn the lone row-end mark into a row with no cells.
|
||||
let text = "\u{7}a\u{7}\u{7}tail\r";
|
||||
let ttp = |extra: Vec<u8>| [grpprl(&[(0x2416, &[0x01]), (0x2417, &[0x01]), (0x6649, &[1, 0, 0, 0])]), extra].concat();
|
||||
let one_edge = {
|
||||
let mut v = (0xD608u16).to_le_bytes().to_vec();
|
||||
v.extend_from_slice(&4u16.to_le_bytes()); // cb: itcMac + one edge, plus one
|
||||
v.extend_from_slice(&[3, 0, 0]);
|
||||
v
|
||||
};
|
||||
for lone in [[t_def_edges(&[0, 1440]), grpprl(&[(0x5624, &[0, 9])]), sprm_cb(0xD612, &long)].concat(), one_edge] {
|
||||
let spec = one_section(
|
||||
text,
|
||||
Vec::new(),
|
||||
vec![
|
||||
(0, 0, ttp(lone)),
|
||||
(1, 0, grpprl(&[(0x2416, &[0x01]), (0x6649, &[1, 0, 0, 0])])),
|
||||
(3, 0, ttp(t_def_edges(&[0, 1440]))),
|
||||
(4, 0, Vec::new()),
|
||||
],
|
||||
);
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
let text = doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert!(text.contains('a') && text.contains("tail"), "{text:?}");
|
||||
for t in doc.body.iter().filter_map(|b| b.as_table()) {
|
||||
assert!(t.rows.iter().all(|r| !r.cells.is_empty()), "no zero-cell rows");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nil_raw_shading_keeps_the_earlier_colour() {
|
||||
// In sprmTDefTableShdRaw (and its 2nd/3rd forms) a nil Shd (ipat 0xFFFF) means "as the
|
||||
// table style shades it", so it must not override sprmTDefTableShd; automatic clears.
|
||||
let blue = shd_clear([0, 0, 0xFF], 1);
|
||||
let red = shd_clear([0xFF, 0, 0], 1);
|
||||
let nil = vec![0, 0, 0, 0xFF, 0, 0, 0, 0xFF, 0xFF, 0xFF];
|
||||
let auto = vec![0, 0, 0, 0xFF, 0, 0, 0, 0xFF, 0, 0];
|
||||
let papx = [sprm_cb(0xD612, &[blue.clone(), blue.clone(), blue.clone()].concat()), sprm_cb(0xD670, &[nil.clone(), red, auto].concat())].concat();
|
||||
let row = crate::table::decode(&papx);
|
||||
assert_eq!(row.shading_of(0), Some(wordcraft_doc::Rgb(0, 0, 0xFF)), "nil keeps blue");
|
||||
assert_eq!(row.shading_of(1), Some(wordcraft_doc::Rgb(0xFF, 0, 0)));
|
||||
assert_eq!(row.shading_of(2), None, "automatic clears");
|
||||
for (first, raw) in [(0xD616u16, 0xD671u16), (0xD60C, 0xD672)] {
|
||||
let papx = [sprm_cb(first, &blue), sprm_cb(raw, &nil)].concat();
|
||||
let cell = if first == 0xD616 { 22 } else { 44 };
|
||||
assert_eq!(crate::table::decode(&papx).shading_of(cell), Some(wordcraft_doc::Rgb(0, 0, 0xFF)), "{raw:04X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_table_gets_its_own_grid() {
|
||||
// #1380: a 5-column table, a paragraph, then a 3-column table. The second table's grid
|
||||
// comes from its own rows, not the first table's, and its borders, alignment and indent
|
||||
// are its own too (the first table's centred, bordered and indented).
|
||||
let text = "a\u{7}b\u{7}c\u{7}d\u{7}e\u{7}\u{7}between\rx\u{7}y\u{7}z\u{7}\u{7}tail\r";
|
||||
let in_tbl = grpprl(&[(0x2416, &[0x01]), (0x6649, &[1, 0, 0, 0])]);
|
||||
let ttp = |edges: &[i16]| [grpprl(&[(0x2416, &[0x01]), (0x2417, &[0x01]), (0x6649, &[1, 0, 0, 0])]), t_def_edges(edges)].concat();
|
||||
let table1_props = {
|
||||
let mut borders = (0xD605u16).to_le_bytes().to_vec();
|
||||
borders.push(0x18);
|
||||
for _ in 0..6 {
|
||||
borders.extend_from_slice(&[4, 1, 1, 0]);
|
||||
}
|
||||
[borders, grpprl(&[(0x5400, &1u16.to_le_bytes()), (0x9601, &720i16.to_le_bytes())])].concat()
|
||||
};
|
||||
let spec = StructSpec {
|
||||
text,
|
||||
header_stories: vec![],
|
||||
sections: vec![(text.chars().count() as u32, Vec::new())],
|
||||
chpx_runs: vec![(0, Vec::new())],
|
||||
papx_entries: vec![
|
||||
(0, 0, in_tbl.clone()),
|
||||
(10, 0, [ttp(&[0, 1440, 2880, 4320, 5760, 7200]), table1_props].concat()),
|
||||
(11, 0, Vec::new()), // "between"
|
||||
(19, 0, in_tbl),
|
||||
(25, 0, ttp(&[0, 2000, 4000, 7200])),
|
||||
(26, 0, Vec::new()), // tail
|
||||
],
|
||||
plf_lst: Vec::new(),
|
||||
plf_lfo: Vec::new(),
|
||||
note_stories: vec![],
|
||||
endnote_stories: vec![],
|
||||
extra_pairs: Vec::new(),
|
||||
data_stream: Vec::new(),
|
||||
};
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
let tables: Vec<_> = doc.body.iter().filter_map(|b| b.as_table()).collect();
|
||||
assert_eq!(tables.len(), 2);
|
||||
assert_eq!(tables[0].grid.len(), 5);
|
||||
assert_eq!(tables[1].grid, vec![100.0, 100.0, 160.0], "second table's own grid");
|
||||
assert_eq!(tables[1].rows[0].cells.iter().map(|c| c.span()).collect::<Vec<_>>(), [1, 1, 1]);
|
||||
assert!(tables[0].props.borders.is_some() && tables[0].props.align.is_some() && tables[0].props.indent.is_some());
|
||||
assert_eq!(tables[1].props.borders, None, "borders reset");
|
||||
assert_eq!(tables[1].props.align, None, "alignment reset");
|
||||
assert_eq!(tables[1].props.indent, None, "indent reset");
|
||||
}
|
||||
|
||||
@@ -182,6 +182,36 @@ fn shapes_keep_kind_colours_wrap_and_text_box_text() {
|
||||
assert_eq!(part.blocks.first().and_then(|b| b.as_para()).map(|p| p.text.as_str()), Some("Inside"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_boxes_pointing_at_the_same_story_text_read_it_once() {
|
||||
// Two text boxes whose PlcftxbxTxt stories are both [0, 7) (the table steps back to CP 0
|
||||
// in between): each was read into its own part, so a hostile table could copy one story
|
||||
// thousands of times. The second story is dropped and its box stays empty.
|
||||
let tb = |spid: u32| sp(&[fsp(202, spid, 0xA00), fopt(&[(0x01BF, 1 << 20)], &[]), rec(0, 0, 0xF00D, &0x0001_0000u32.to_le_bytes())]);
|
||||
let art = art_content(&[], &[tb(1027), tb(1028)]);
|
||||
let flags = spa_flags(0, 0, 1, false);
|
||||
let spas = plc(&[1, 2, 4], &[spa(1027, [0, 0, 2880, 720], flags), spa(1028, [0, 0, 2880, 720], flags)].concat());
|
||||
// FTXBXS: cTxbx, cReusable, fReusable, reserved, lid, txidUndo.
|
||||
let ftxbxs = |lid: u32| {
|
||||
[1i32.to_le_bytes().as_slice(), &0i32.to_le_bytes(), &0i16.to_le_bytes(), &0i32.to_le_bytes(), &lid.to_le_bytes(), &0i32.to_le_bytes()]
|
||||
.concat()
|
||||
};
|
||||
let txbx = plc(&[0, 7, 0, 7], &[ftxbxs(1027), ftxbxs(1), ftxbxs(1028)].concat());
|
||||
let text = "A\u{8}\u{8}B\r";
|
||||
let ccp = text.chars().count() as u32;
|
||||
// As above: the endnote slot holds the text box subdocument, then the FIB is patched.
|
||||
let spec =
|
||||
StructSpec { text, endnote_stories: vec!["Inside\r"], extra_pairs: vec![(40, spas), (50, art), (56, txbx)], ..structured_spec(text, ccp) };
|
||||
let doc = read(&patch_word(&struct_doc(&spec), &[(0x60, 0), (0x64, 7)])).expect("opens");
|
||||
let p0 = doc.body.first().and_then(|b| b.as_para()).expect("para");
|
||||
let stories: Vec<Option<u32>> =
|
||||
p0.objects.iter().filter_map(|o| if let InlineObject::Shape { story, .. } = o { Some(*story) } else { None }).collect();
|
||||
let [Some(first), None] = stories[..] else { panic!("stories: {stories:?}") };
|
||||
let part = doc.parts.get(&first).expect("text box story part");
|
||||
assert_eq!(part.blocks.first().and_then(|b| b.as_para()).map(|p| p.text.as_str()), Some("Inside"));
|
||||
assert_eq!(doc.parts.len(), 1);
|
||||
}
|
||||
|
||||
/// Overwrite little-endian u32s in the WordDocument stream of a compound file.
|
||||
fn patch_word(file: &[u8], at: &[(usize, u32)]) -> Vec<u8> {
|
||||
use std::io::Read;
|
||||
@@ -274,3 +304,30 @@ proptest! {
|
||||
let _ = read(&struct_doc(&spec));
|
||||
}
|
||||
}
|
||||
|
||||
// A 1×1 24-bit DIB, including its padded four-byte row.
|
||||
fn one_pixel_dib() -> Vec<u8> {
|
||||
let mut dib = [40u32, 1, 1].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>();
|
||||
dib.extend_from_slice(&1u16.to_le_bytes());
|
||||
dib.extend_from_slice(&24u16.to_le_bytes());
|
||||
dib.extend_from_slice(&[0u8; 24]);
|
||||
dib.extend_from_slice(&[30, 60, 90, 0]);
|
||||
dib
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dib_conversion_caps_header_and_encoded_bytes() {
|
||||
let dib = one_pixel_dib();
|
||||
let record = rec(0, 0x7A8, officeart::rt::BLIP_DIB, &[[0u8; 16].as_slice(), &[0xFF], &dib].concat());
|
||||
let (record, _) = officeart::record(&record).unwrap();
|
||||
let bmp_size = 14 + dib.len();
|
||||
assert!(officeart::blip(&record, bmp_size - 1).is_none(), "the BMP header also needs room");
|
||||
let fallback = officeart::blip(&record, bmp_size).expect("the BMP fallback fits exactly");
|
||||
assert_eq!((fallback.ext, fallback.placeholder, fallback.bytes.len()), ("bmp", true, bmp_size));
|
||||
let img = image::load_from_memory(&fallback.bytes).unwrap().to_rgb8();
|
||||
assert_eq!((img.width(), img.height(), img.get_pixel(0, 0).0), (1, 1, [90, 60, 30]));
|
||||
let normal = officeart::blip(&record, 512).expect("normal conversion fits");
|
||||
assert_eq!((normal.ext, normal.placeholder), ("png", false));
|
||||
assert!(normal.bytes.len() > bmp_size && normal.bytes.len() <= 512);
|
||||
assert_eq!(image::load_from_memory(&normal.bytes).unwrap().width(), 1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Password-protected files. The fixtures are encrypted here with a small encryptor written from
|
||||
//! [MS-DOC] §2.2.6 and [MS-OFFCRYPTO] §2.3.5-2.3.7; no file produced by Word is used.
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use super::{Piece, body_texts, cfb_file, text_doc};
|
||||
use crate::DocbinError;
|
||||
use crate::crypt::{F_ENCRYPTED, F_OBFUSCATED, Rc4, md5, xor_array, xor_verifier};
|
||||
use crate::{is_encrypted, read, read_with_password};
|
||||
|
||||
const TEXT: &str = "Secret \u{20ac} plans";
|
||||
/// Where the piece table's pair lives in the FIB: `fcClx` of pair 33.
|
||||
const CLX_PAIR: usize = 0x9A + 33 * 8;
|
||||
|
||||
fn plain() -> (Vec<u8>, Vec<u8>) {
|
||||
let f = text_doc(&[Piece { compressed: false, text: format!("{TEXT}\r") }], &[], 0);
|
||||
let mut comp = cfb::CompoundFile::open(std::io::Cursor::new(f)).unwrap();
|
||||
let mut get = |n: &str| {
|
||||
let mut v = Vec::new();
|
||||
comp.open_stream(format!("/{n}")).unwrap().read_to_end(&mut v).unwrap();
|
||||
v
|
||||
};
|
||||
(get("WordDocument"), get("0Table"))
|
||||
}
|
||||
|
||||
fn rewrap(word: &[u8], table: &[u8]) -> Vec<u8> {
|
||||
cfb_file(&[("WordDocument", word), ("0Table", table)])
|
||||
}
|
||||
|
||||
fn put16(v: &mut [u8], at: usize, x: u16) {
|
||||
v[at..at + 2].copy_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put32(v: &mut [u8], at: usize, x: u32) {
|
||||
v[at..at + 4].copy_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
|
||||
fn utf16(s: &str) -> Vec<u8> {
|
||||
s.encode_utf16().flat_map(u16::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
fn sha1(parts: &[&[u8]]) -> Vec<u8> {
|
||||
let mut h = Sha1::new();
|
||||
for p in parts {
|
||||
h.update(p);
|
||||
}
|
||||
h.finalize().to_vec()
|
||||
}
|
||||
|
||||
/// Encrypt (= RC4 is symmetric) `data` in 512-byte blocks; the first `skip` bytes stay as they are
|
||||
/// but the keystream still runs over them.
|
||||
fn rc4_stream(data: &mut [u8], skip: usize, key: &dyn Fn(u32) -> Vec<u8>) {
|
||||
for (n, chunk) in data.chunks_mut(512).enumerate() {
|
||||
let orig = chunk.to_vec();
|
||||
Rc4::new(&key(n as u32)).apply(chunk);
|
||||
let keep = skip.saturating_sub(n * 512).min(chunk.len());
|
||||
chunk[..keep].copy_from_slice(&orig[..keep]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `header` in front of the table and set the FIB's encryption fields.
|
||||
fn assemble(mut word: Vec<u8>, table: &[u8], header: &[u8], flags: u16, lkey: u32) -> (Vec<u8>, Vec<u8>) {
|
||||
let fl = u16::from_le_bytes([word[0x0A], word[0x0B]]) | flags;
|
||||
put16(&mut word, 0x0A, fl);
|
||||
put32(&mut word, 0x0E, lkey);
|
||||
let fc = u32::from_le_bytes(word[CLX_PAIR..CLX_PAIR + 4].try_into().unwrap());
|
||||
put32(&mut word, CLX_PAIR, fc + header.len() as u32);
|
||||
([word].concat(), [header, table].concat())
|
||||
}
|
||||
|
||||
fn xor_file(pw: &[u8]) -> Vec<u8> {
|
||||
let (word, table) = plain();
|
||||
let (mut word, mut table) = assemble(word, &table, &[], F_ENCRYPTED | F_OBFUSCATED, xor_verifier(pw));
|
||||
let arr = xor_array(pw);
|
||||
for (data, skip) in [(&mut word, 68), (&mut table, 0)] {
|
||||
for (i, b) in data.iter_mut().enumerate().skip(skip) {
|
||||
if *b != 0 && *b ^ arr[i % 16] != 0 {
|
||||
*b ^= arr[i % 16];
|
||||
}
|
||||
}
|
||||
}
|
||||
rewrap(&word, &table)
|
||||
}
|
||||
|
||||
fn rc4_header(pw: &str) -> (Vec<u8>, Box<dyn Fn(u32) -> Vec<u8>>) {
|
||||
let salt = [7u8; 16];
|
||||
let h0 = md5(&utf16(pw));
|
||||
let h1 = md5(&(0..16).flat_map(|_| [&h0[..5], &salt[..]].concat()).collect::<Vec<u8>>());
|
||||
let trunc = h1[..5].to_vec();
|
||||
let key: Box<dyn Fn(u32) -> Vec<u8>> = Box::new(move |b| md5(&[trunc.as_slice(), &b.to_le_bytes()].concat()).to_vec());
|
||||
let verifier = *b"0123456789abcdef";
|
||||
let mut enc = [verifier.to_vec(), md5(&verifier).to_vec()].concat();
|
||||
Rc4::new(&key(0)).apply(&mut enc);
|
||||
([&[1, 0, 1, 0][..], &salt, &enc].concat(), key)
|
||||
}
|
||||
|
||||
fn capi_header(pw: &str, bits: u32, hflags: u32) -> (Vec<u8>, Box<dyn Fn(u32) -> Vec<u8>>) {
|
||||
let salt = [9u8; 16];
|
||||
let h0 = sha1(&[&salt, &utf16(pw)]);
|
||||
let n = (bits / 8) as usize;
|
||||
let key: Box<dyn Fn(u32) -> Vec<u8>> = Box::new(move |b| {
|
||||
let mut k = sha1(&[&h0, &b.to_le_bytes()])[..n].to_vec();
|
||||
if n == 5 {
|
||||
k.resize(16, 0);
|
||||
}
|
||||
k
|
||||
});
|
||||
let verifier = *b"fedcba9876543210";
|
||||
let mut enc = [verifier.to_vec(), sha1(&[&verifier])].concat();
|
||||
Rc4::new(&key(0)).apply(&mut enc);
|
||||
let mut body = Vec::new();
|
||||
for x in [hflags, 0, 0x6801, 0x8004, bits, 1, 0, 0] {
|
||||
body.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
body.extend_from_slice(&utf16("Test RC4 provider\0"));
|
||||
let mut h = vec![3, 0, 2, 0];
|
||||
h.extend_from_slice(&hflags.to_le_bytes());
|
||||
h.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
h.extend_from_slice(&body);
|
||||
h.extend_from_slice(&16u32.to_le_bytes());
|
||||
h.extend_from_slice(&salt);
|
||||
h.extend_from_slice(&enc[..16]);
|
||||
h.extend_from_slice(&20u32.to_le_bytes());
|
||||
h.extend_from_slice(&enc[16..]);
|
||||
(h, key)
|
||||
}
|
||||
|
||||
fn rc4_file_with(header: Vec<u8>, key: &dyn Fn(u32) -> Vec<u8>) -> Vec<u8> {
|
||||
let (word, table) = plain();
|
||||
let (mut word, mut table) = assemble(word, &table, &header, F_ENCRYPTED, header.len() as u32);
|
||||
rc4_stream(&mut word, 68, key);
|
||||
rc4_stream(&mut table, header.len(), key);
|
||||
rewrap(&word, &table)
|
||||
}
|
||||
|
||||
fn rc4_file(pw: &str) -> Vec<u8> {
|
||||
let (h, k) = rc4_header(pw);
|
||||
rc4_file_with(h, &*k)
|
||||
}
|
||||
|
||||
fn capi_file(pw: &str, bits: u32) -> Vec<u8> {
|
||||
let (h, k) = capi_header(pw, bits, 0x04);
|
||||
rc4_file_with(h, &*k)
|
||||
}
|
||||
|
||||
fn check(f: &[u8], pw: &str, wrong: &str) {
|
||||
assert!(is_encrypted(f));
|
||||
assert_eq!(read(f).unwrap_err(), DocbinError::PasswordRequired);
|
||||
assert_eq!(read_with_password(f, Some(wrong)).unwrap_err(), DocbinError::WrongPassword);
|
||||
assert_eq!(read_with_password(f, Some("")).unwrap_err(), DocbinError::WrongPassword);
|
||||
let doc = read_with_password(f, Some(pw)).unwrap();
|
||||
assert_eq!(body_texts(&doc), [TEXT]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xor_obfuscation_round_trip() {
|
||||
check(&xor_file(b"hunter2"), "hunter2", "hunter3");
|
||||
// Longer than 15 characters: only the first 15 count, as in the format.
|
||||
let long = xor_file(b"abcdefghijklmno");
|
||||
assert_eq!(body_texts(&read_with_password(&long, Some("abcdefghijklmnopqrst")).unwrap()), [TEXT]);
|
||||
// A non-ASCII (Latin-1) password.
|
||||
check(&xor_file(&[b'p', 0xE4, b's', b's']), "p\u{e4}ss", "pass");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rc4_round_trip() {
|
||||
check(&rc4_file("correct horse"), "correct horse", "Correct horse");
|
||||
check(&rc4_file("p\u{e4}ssw\u{f6}rd \u{1f511}"), "p\u{e4}ssw\u{f6}rd \u{1f511}", "password");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rc4_crypto_api_round_trip() {
|
||||
check(&capi_file("battery staple", 128), "battery staple", "battery stapl");
|
||||
// 40-bit keys are zero-padded to 128 bits.
|
||||
check(&capi_file("battery staple", 40), "battery staple", "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unencrypted_files_ignore_the_password() {
|
||||
let f = text_doc(&[Piece { compressed: false, text: "Plain\r".into() }], &[], 0);
|
||||
assert!(!is_encrypted(&f));
|
||||
assert_eq!(body_texts(&read_with_password(&f, Some("whatever")).unwrap()), ["Plain"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tampered_verifier_is_a_wrong_password_never_a_garbled_document() {
|
||||
let (h, k) = rc4_header("pw");
|
||||
let mut bad = h.clone();
|
||||
bad[40] ^= 1; // inside the encrypted verifier hash
|
||||
assert_eq!(read_with_password(&rc4_file_with(bad, &*k), Some("pw")).unwrap_err(), DocbinError::WrongPassword);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_variants_say_so() {
|
||||
// AES and external providers, an unknown header version.
|
||||
for hflags in [0x04 | 0x20, 0x10] {
|
||||
let (h, k) = capi_header("pw", 128, hflags);
|
||||
let e = read_with_password(&rc4_file_with(h, &*k), Some("pw")).unwrap_err();
|
||||
assert!(matches!(e, DocbinError::Encryption(_)), "{e:?}");
|
||||
}
|
||||
let (mut h, k) = rc4_header("pw");
|
||||
h[0] = 9;
|
||||
assert!(matches!(read_with_password(&rc4_file_with(h, &*k), Some("pw")), Err(DocbinError::Encryption(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_headers_are_errors_never_panics() {
|
||||
for f in [rc4_header("pw"), capi_header("pw", 128, 0x04)] {
|
||||
let (h, k) = f;
|
||||
let full = rc4_file_with(h.clone(), &*k);
|
||||
let (word, table) = {
|
||||
let mut comp = cfb::CompoundFile::open(std::io::Cursor::new(&full)).unwrap();
|
||||
let mut get = |n: &str| {
|
||||
let mut v = Vec::new();
|
||||
comp.open_stream(format!("/{n}")).unwrap().read_to_end(&mut v).unwrap();
|
||||
v
|
||||
};
|
||||
(get("WordDocument"), get("0Table"))
|
||||
};
|
||||
// Truncated everywhere in and around the header: an error, not a panic.
|
||||
for n in 0..h.len() + 8 {
|
||||
let r = read_with_password(&rewrap(&word, &table[..n.min(table.len())]), Some("pw"));
|
||||
assert!(r.is_err(), "length {n}");
|
||||
}
|
||||
// Every header byte garbled.
|
||||
for at in 0..h.len() {
|
||||
let mut t = table.clone();
|
||||
t[at] ^= 0xFF;
|
||||
let _ = read_with_password(&rewrap(&word, &t), Some("pw"));
|
||||
}
|
||||
}
|
||||
// A header size claiming more than the stream holds.
|
||||
let (mut h, k) = capi_header("pw", 128, 0x04);
|
||||
h[8..12].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(read_with_password(&rc4_file_with(h, &*k), Some("pw")).is_err());
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! OLE property sets constructed from MS-OLEPS, exercised through the public DOC reader.
|
||||
use super::{Piece, body_texts, text_doc};
|
||||
use std::io::{Cursor, Seek, SeekFrom, Write};
|
||||
|
||||
fn summary(cp: u16, values: &[(u32, u32, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut props = vec![(1, [2u32.to_le_bytes().as_slice(), &cp.to_le_bytes(), &[0, 0]].concat())];
|
||||
for (id, kind, bytes) in values {
|
||||
let size = if *kind == 31 { bytes.len() / 2 } else { bytes.len() } as u32;
|
||||
let mut value = [kind.to_le_bytes().as_slice(), &size.to_le_bytes(), bytes].concat();
|
||||
while !value.len().is_multiple_of(4) {
|
||||
value.push(0);
|
||||
}
|
||||
props.push((*id, value));
|
||||
}
|
||||
let mut section = vec![0; 8 + 8 * props.len()];
|
||||
section[4..8].copy_from_slice(&(props.len() as u32).to_le_bytes());
|
||||
for (i, (id, value)) in props.iter().enumerate() {
|
||||
section[8 + i * 8..12 + i * 8].copy_from_slice(&id.to_le_bytes());
|
||||
let offset = section.len() as u32;
|
||||
section[12 + i * 8..16 + i * 8].copy_from_slice(&offset.to_le_bytes());
|
||||
section.extend_from_slice(value);
|
||||
}
|
||||
let size = section.len() as u32;
|
||||
section[..4].copy_from_slice(&size.to_le_bytes());
|
||||
let mut header = vec![0; 48];
|
||||
header[..2].copy_from_slice(&[0xfe, 0xff]);
|
||||
header[24..28].copy_from_slice(&1u32.to_le_bytes());
|
||||
header[28..44].copy_from_slice(&[0xe0, 0x85, 0x9f, 0xf2, 0xf9, 0x4f, 0x68, 0x10, 0xab, 0x91, 0x08, 0, 0x2b, 0x27, 0xb3, 0xd9]);
|
||||
header[44..48].copy_from_slice(&48u32.to_le_bytes());
|
||||
header.extend(section);
|
||||
header
|
||||
}
|
||||
|
||||
fn open_with_metadata(bytes: &[u8], template: bool) -> wordcraft_doc::Document {
|
||||
let file = text_doc(&[Piece { compressed: false, text: "Body stays readable\r".into() }], &[], 0);
|
||||
let mut cfb = cfb::CompoundFile::open(Cursor::new(file)).unwrap();
|
||||
cfb.create_stream("/\u{5}SummaryInformation").unwrap().write_all(bytes).unwrap();
|
||||
if template {
|
||||
let mut stream = cfb.open_stream("/WordDocument").unwrap();
|
||||
stream.seek(SeekFrom::Start(0x0a)).unwrap();
|
||||
stream.write_all(&0x1001u16.to_le_bytes()).unwrap();
|
||||
}
|
||||
let doc = crate::read(&cfb.into_inner().into_inner()).unwrap();
|
||||
assert_eq!(body_texts(&doc), ["Body stays readable"]);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_and_dot_import_summary_text_properties() {
|
||||
let data = summary(
|
||||
1252,
|
||||
&[
|
||||
(2, 30, b"R\xe9sum\xe9\0".to_vec()),
|
||||
(3, 30, b"Subject\0".to_vec()),
|
||||
(4, 30, b"Writer\0".to_vec()),
|
||||
(5, 30, b"one;two\0".to_vec()),
|
||||
(6, 30, b"Description\0".to_vec()),
|
||||
(8, 30, b"Editor\0".to_vec()),
|
||||
(9, 30, b"12\0".to_vec()),
|
||||
],
|
||||
);
|
||||
for template in [false, true] {
|
||||
let c = open_with_metadata(&data, template).core;
|
||||
assert_eq!(c.title, "Résumé");
|
||||
assert_eq!(c.subject, "Subject");
|
||||
assert_eq!(c.creator, "Writer");
|
||||
assert_eq!(c.keywords, "one;two");
|
||||
assert_eq!(c.description, "Description");
|
||||
assert_eq!(c.last_modified_by, "Editor");
|
||||
assert_eq!(c.revision, 12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_handles_codepages_and_utf16_length_units() {
|
||||
let wide: Vec<u8> = "Unicode ä 文 😀\0".encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
for kind in [30, 31] {
|
||||
assert_eq!(open_with_metadata(&summary(1200, &[(2, kind, wide.clone())]), false).core.title, "Unicode ä 文 😀");
|
||||
}
|
||||
assert_eq!(open_with_metadata(&summary(65001, &[(2, 30, "UTF-8 ä\0".as_bytes().to_vec())]), false).core.title, "UTF-8 ä");
|
||||
assert_eq!(open_with_metadata(&summary(1251, &[(2, 30, vec![0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2, 0])]), false).core.title, "Привет");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_oversized_summary_does_not_break_doc_open() {
|
||||
let valid = summary(1252, &[(2, 30, b"Title\0".to_vec())]);
|
||||
for n in [0, 2, 24, 44, 47, 55, valid.len() - 5] {
|
||||
assert!(open_with_metadata(&valid[..n], false).core.title.is_empty());
|
||||
}
|
||||
for (at, value) in [(44, u32::MAX), (48, u32::MAX), (52, u32::MAX), (68, 4), (84, u32::MAX)] {
|
||||
let mut bad = valid.clone();
|
||||
bad[at..at + 4].copy_from_slice(&value.to_le_bytes());
|
||||
assert!(open_with_metadata(&bad, false).core.title.is_empty(), "offset {at}");
|
||||
}
|
||||
let huge = summary(1252, &[(2, 30, vec![b'x'; (64 << 10) + 1])]);
|
||||
assert!(open_with_metadata(&huge, false).core.title.is_empty());
|
||||
assert!(open_with_metadata(&vec![0; (2 << 20) + 1], false).core.title.is_empty());
|
||||
}
|
||||
+101
-18
@@ -5,7 +5,9 @@
|
||||
//!
|
||||
//! Reading unpacks the parts into an in-memory [`Package`] and hands it to the DOCX reader;
|
||||
//! writing runs the DOCX writer and lays its parts out in one file. Bounded like the zip reader:
|
||||
//! part count, part size, total size and base64 length are capped.
|
||||
//! every part counts against the part count, part size and total size limits whether it's kept
|
||||
//! or not (a repeated name), data is checked before it's copied, and nesting and elements are
|
||||
//! capped as the XML tree reader caps a part's.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -92,8 +94,24 @@ struct Part {
|
||||
data: Option<Data>,
|
||||
}
|
||||
|
||||
/// Longest base64 text of one part (the size limit, encoded; whitespace isn't kept).
|
||||
const MAX_BASE64: u64 = (MAX_PART / 3 + 1) * 4;
|
||||
/// Deepest element nesting read: a part's inline XML starts below the package, part and data
|
||||
/// elements and may nest as deep as the XML tree reader takes ([`xml::MAX_DEPTH`] open elements
|
||||
/// and an empty one inside the deepest).
|
||||
const MAX_NESTING: usize = 3 + xml::MAX_DEPTH + 1;
|
||||
|
||||
/// Most elements in one child of the package: a part, its data element and as many as the XML
|
||||
/// tree reader takes in a part ([`xml::MAX_ELEMENTS`]).
|
||||
const MAX_PART_ELEMENTS: usize = 2 + xml::MAX_ELEMENTS;
|
||||
|
||||
/// Longest base64 text of a part that decodes to at most `bytes` (whitespace isn't kept).
|
||||
fn max_base64(bytes: u64) -> u64 {
|
||||
(bytes / 3).saturating_add(1).saturating_mul(4)
|
||||
}
|
||||
|
||||
/// Bytes the next part may have: its own size limit, or what's left of the package's.
|
||||
fn room(total: u64) -> u64 {
|
||||
MAX_PART.min(MAX_TOTAL.saturating_sub(total))
|
||||
}
|
||||
|
||||
/// Unpack a Flat OPC file into its parts, with a `[Content_Types].xml` made from the parts'
|
||||
/// content types (unless the file carries one).
|
||||
@@ -103,6 +121,9 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result<Package, DocxError> {
|
||||
let mut r = NsReader::from_reader(src);
|
||||
r.config_mut().check_end_names = true;
|
||||
let mut depth = 0usize;
|
||||
// Children of the package (parts or anything else), and elements in the current one.
|
||||
let mut entries = 0usize;
|
||||
let mut elements = 0usize;
|
||||
let mut files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
|
||||
let mut types: Vec<(String, String)> = Vec::new();
|
||||
let mut total: u64 = 0;
|
||||
@@ -118,15 +139,26 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result<Package, DocxError> {
|
||||
Event::Start(ref e) | Event::Empty(ref e) => {
|
||||
let empty = matches!(ev, Event::Empty(_));
|
||||
depth += 1;
|
||||
if depth > MAX_NESTING {
|
||||
return Err(DocxError::Limit("XML nesting too deep".into()));
|
||||
}
|
||||
if depth == 2 {
|
||||
entries += 1;
|
||||
elements = 0;
|
||||
if entries > MAX_ENTRIES {
|
||||
return Err(DocxError::Limit(format!("more than {MAX_ENTRIES} parts")));
|
||||
}
|
||||
}
|
||||
elements += 1;
|
||||
if elements > MAX_PART_ELEMENTS {
|
||||
return Err(DocxError::Limit("too many XML elements".into()));
|
||||
}
|
||||
let local = e.local_name().as_ref().to_vec();
|
||||
match depth {
|
||||
1 if !(in_pkg && local == b"package") => {
|
||||
return Err(DocxError::NotWord("the root element isn't a Flat OPC pkg:package".into()));
|
||||
}
|
||||
2 if in_pkg && local == b"part" => {
|
||||
if files.len() + usize::from(part.is_some()) >= MAX_ENTRIES {
|
||||
return Err(DocxError::Limit(format!("more than {MAX_ENTRIES} parts")));
|
||||
}
|
||||
let name = attr(e, b"name").unwrap_or_default();
|
||||
let content_type = attr(e, b"contentType").unwrap_or_default();
|
||||
part = Some(Part { name, content_type, data: None });
|
||||
@@ -167,7 +199,12 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result<Package, DocxError> {
|
||||
&& let Some(Data::Xml(start)) = p.data
|
||||
{
|
||||
p.data = None;
|
||||
let xml = with_scope(src.get(start..before).unwrap_or_default(), &scope);
|
||||
let frag = src.get(start..before).unwrap_or_default();
|
||||
// Refused before it's copied when it can't fit.
|
||||
if frag.len() as u64 > room(total) {
|
||||
return Err(DocxError::Limit(format!("part {} is larger than the size limit", p.name)));
|
||||
}
|
||||
let xml = with_scope(frag, &scope);
|
||||
store(&p.name, &p.content_type, xml, &mut files, &mut types, &mut total)?;
|
||||
}
|
||||
if depth == 2
|
||||
@@ -183,15 +220,18 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result<Package, DocxError> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Event::Text(ref t) if depth == 3 => {
|
||||
if let Some(Part { data: Some(Data::Binary(b64)), .. }) = part.as_mut() {
|
||||
let s = std::str::from_utf8(t.as_ref()).map_err(|e| DocxError::Xml(e.to_string()))?;
|
||||
b64.extend(s.chars().filter(|c| !c.is_ascii_whitespace()));
|
||||
if b64.len() as u64 > MAX_BASE64 {
|
||||
return Err(DocxError::Limit("a binary part is larger than the size limit".into()));
|
||||
Event::Text(ref t) if depth == 3 => add_base64(&mut part, t, total)?,
|
||||
Event::CData(ref t) if depth == 3 => add_base64(&mut part, t, total)?,
|
||||
Event::GeneralRef(ref g) if depth == 3 => match g.resolve_char_ref() {
|
||||
// A character reference stands for its character (`A` is an `A`).
|
||||
Ok(Some(c)) => add_base64(&mut part, c.encode_utf8(&mut [0; 4]).as_bytes(), total)?,
|
||||
// An entity isn't base64: binary data holding one is broken, not shorter.
|
||||
_ => {
|
||||
if let Some(Part { name, data: Some(Data::Binary(_)), .. }) = &part {
|
||||
return Err(DocxError::Xml(format!("part {name} has invalid base64 data")));
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
@@ -225,7 +265,21 @@ fn finish_part(p: Part, files: &mut BTreeMap<String, Vec<u8>>, types: &mut Vec<(
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a part, within the size limits; a repeated or empty name is ignored.
|
||||
/// Text (or CDATA) inside a part's `pkg:binaryData`: its base64 without whitespace, checked
|
||||
/// against the size limits before it's copied.
|
||||
fn add_base64(part: &mut Option<Part>, text: &[u8], total: u64) -> Result<(), DocxError> {
|
||||
let Some(Part { data: Some(Data::Binary(b64)), .. }) = part else { return Ok(()) };
|
||||
let s = std::str::from_utf8(text).map_err(|e| DocxError::Xml(e.to_string()))?;
|
||||
let more = s.bytes().filter(|b| !b.is_ascii_whitespace()).count();
|
||||
if b64.len().saturating_add(more) as u64 > max_base64(room(total)) {
|
||||
return Err(DocxError::Limit("a binary part is larger than the size limit".into()));
|
||||
}
|
||||
b64.extend(s.chars().filter(|c| !c.is_ascii_whitespace()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a part, within the size limits; a repeated or empty name isn't stored but counts against
|
||||
/// them all the same (as a repeated zip entry does).
|
||||
fn store(
|
||||
name: &str,
|
||||
content_type: &str,
|
||||
@@ -235,9 +289,6 @@ fn store(
|
||||
total: &mut u64,
|
||||
) -> Result<(), DocxError> {
|
||||
let name = name.trim_start_matches('/');
|
||||
if name.is_empty() || files.contains_key(name) {
|
||||
return Ok(());
|
||||
}
|
||||
let len = bytes.len() as u64;
|
||||
if len > MAX_PART {
|
||||
return Err(DocxError::Limit(format!("part {name} is larger than the size limit")));
|
||||
@@ -246,6 +297,9 @@ fn store(
|
||||
if *total > MAX_TOTAL {
|
||||
return Err(DocxError::Limit("the package is larger than the size limit".into()));
|
||||
}
|
||||
if name.is_empty() || files.contains_key(name) {
|
||||
return Ok(());
|
||||
}
|
||||
if !content_type.is_empty() && !content_type.contains(['\r', '\n']) {
|
||||
types.push((name.to_string(), content_type.to_string()));
|
||||
}
|
||||
@@ -408,4 +462,33 @@ mod tests {
|
||||
assert_eq!(with_scope(own, &scope), own.to_vec());
|
||||
assert_eq!(with_scope(b"no element", &scope), b"no element".to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_is_capped_where_the_xml_tree_reader_stops() {
|
||||
let inline = |levels: usize| format!("{}<b/>{}", "<a>".repeat(levels), "</a>".repeat(levels));
|
||||
let package = |levels: usize| {
|
||||
format!(
|
||||
"<pkg:package xmlns:pkg=\"{PKG_NS}\"><pkg:part pkg:name=\"/a.xml\"><pkg:xmlData>{}</pkg:xmlData></pkg:part></pkg:package>",
|
||||
inline(levels)
|
||||
)
|
||||
};
|
||||
assert!(xml::parse(inline(xml::MAX_DEPTH).as_bytes()).is_ok());
|
||||
assert!(unpack(package(xml::MAX_DEPTH).as_bytes()).is_ok());
|
||||
assert!(matches!(xml::parse(inline(xml::MAX_DEPTH + 1).as_bytes()), Err(DocxError::Limit(_))));
|
||||
assert!(matches!(unpack(package(xml::MAX_DEPTH + 1).as_bytes()), Err(DocxError::Limit(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_and_nameless_parts_count_against_the_size_limits() {
|
||||
let (mut files, mut types, mut total) = (BTreeMap::new(), Vec::new(), 0u64);
|
||||
for name in ["/a.bin", "/a.bin", ""] {
|
||||
store(name, "", vec![0; 10], &mut files, &mut types, &mut total).unwrap();
|
||||
}
|
||||
assert_eq!((files.len(), total), (1, 30));
|
||||
// Near the package limit, what's left of it is all the next part may have.
|
||||
total = MAX_TOTAL - 5;
|
||||
assert_eq!(room(total), 5);
|
||||
assert_eq!(max_base64(5), 8);
|
||||
assert!(matches!(store("/b.bin", "", vec![0; 6], &mut files, &mut types, &mut total), Err(DocxError::Limit(_))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Fonts a file embeds through its font table (#1171).
|
||||
//!
|
||||
//! The reader keeps the font table and its font parts as opaque passthrough parts, for writing
|
||||
//! back. [`embedded_fonts`] hands their font files to whoever lays the document out, undoing the
|
||||
//! obfuscation Word applies to them (ECMA-376 Part 1, 17.8.1).
|
||||
|
||||
use wordcraft_doc::Document;
|
||||
|
||||
use crate::package::{EMBEDDED_PARTS, EmbeddedManifest, FONT_TABLE_PART};
|
||||
|
||||
/// Most font files taken from one document.
|
||||
const MAX_FONTS: usize = 64;
|
||||
|
||||
/// The font table's references to embedded font files, one per style.
|
||||
const EMBEDS: [&str; 4] = ["w:embedRegular", "w:embedBold", "w:embedItalic", "w:embedBoldItalic"];
|
||||
|
||||
/// The font files `doc`'s font table embeds, de-obfuscated, in table order. Not checked to be
|
||||
/// fonts: that is up to the font database. Empty for a document read from anything but a package
|
||||
/// with a font table.
|
||||
pub fn embedded_fonts(doc: &Document) -> Vec<Vec<u8>> {
|
||||
let Some(table) = doc.passthrough.get(FONT_TABLE_PART).and_then(|b| crate::xml::parse(b).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let manifest = doc.passthrough.get(EMBEDDED_PARTS).map(|m| EmbeddedManifest::parse(m)).unwrap_or_default();
|
||||
let Some(part) = manifest.parts.get(FONT_TABLE_PART) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for embed in table.children("w:font").flat_map(|f| f.els().filter(|e| EMBEDS.contains(&e.name.as_str()))) {
|
||||
if out.len() >= MAX_FONTS {
|
||||
log::warn!("docx: more than {MAX_FONTS} embedded fonts; the rest are not loaded");
|
||||
break;
|
||||
}
|
||||
let Some(rel) = embed.attr("r:id").and_then(|id| part.rels.iter().find(|r| r.id == id && !r.external)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(bytes) = doc.passthrough.get(&rel.target) else {
|
||||
continue;
|
||||
};
|
||||
// No key: the file is stored as is, as with the all-zero key.
|
||||
let key = match embed.attr("w:fontKey") {
|
||||
Some(k) => match font_key(k) {
|
||||
Some(key) => key,
|
||||
None => {
|
||||
log::warn!("docx: embedded font {} has an unreadable key {k:?}", rel.target);
|
||||
continue;
|
||||
}
|
||||
},
|
||||
None => [0; 16],
|
||||
};
|
||||
let mut data = bytes.to_vec();
|
||||
for (i, b) in data.iter_mut().take(32).enumerate() {
|
||||
*b ^= key.get(i % 16).copied().unwrap_or(0);
|
||||
}
|
||||
out.push(data);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The obfuscation key of a `w:fontKey` GUID (`{XXXXXXXX-XXXX-…}`): its 16 bytes, reversed.
|
||||
fn font_key(guid: &str) -> Option<[u8; 16]> {
|
||||
let digits: Vec<u8> = guid.bytes().filter(|c| !matches!(c, b'{' | b'}' | b'-')).collect();
|
||||
if digits.len() != 32 {
|
||||
return None;
|
||||
}
|
||||
let mut key = [0u8; 16];
|
||||
for (i, pair) in digits.chunks(2).enumerate() {
|
||||
let byte = u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()?;
|
||||
*key.get_mut(15 - i)? = byte;
|
||||
}
|
||||
Some(key)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ mod chart_spec;
|
||||
mod crypt;
|
||||
mod custom;
|
||||
mod flat;
|
||||
mod fonts;
|
||||
mod package;
|
||||
mod read;
|
||||
mod smart_art;
|
||||
@@ -26,6 +27,7 @@ pub use crypt::{
|
||||
is_encrypted, protection_hash,
|
||||
};
|
||||
pub use flat::{XmlKind, sniff_xml, write as write_flat};
|
||||
pub use fonts::embedded_fonts;
|
||||
pub use read::read;
|
||||
pub use smart_art::smart_art_items;
|
||||
pub use wordml2003_write::write as write_wordml2003;
|
||||
|
||||
@@ -30,6 +30,8 @@ pub mod rt {
|
||||
pub const ENDNOTES: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes";
|
||||
pub const COMMENTS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
|
||||
pub const COMMENTS_EX: &str = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended";
|
||||
pub const COMMENTS_IDS: &str = "http://schemas.microsoft.com/office/2016/09/relationships/commentsIds";
|
||||
pub const COMMENTS_EXTENSIBLE: &str = "http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible";
|
||||
pub const HEADER: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
|
||||
pub const FOOTER: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
|
||||
pub const IMAGE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
|
||||
@@ -58,9 +60,26 @@ pub const MAX_VBA_RELATED: usize = 64;
|
||||
/// types and own relationships, as [`EmbeddedManifest`] lines. Each part's bytes are kept under its
|
||||
/// part name. Not a package part: WordCraft's own bookkeeping.
|
||||
pub const EMBEDDED_PARTS: &str = "wordcraft:embedded.parts";
|
||||
/// The font table kept from a file (read by `Reader::keep_part_tree`), with the fonts it embeds.
|
||||
pub const FONT_TABLE_PART: &str = "word/fontTable.xml";
|
||||
/// Custom XML roots kept by the package (P) or main document (D): `owner\ttype\tpart`.
|
||||
/// Their opaque bytes and related parts use the same bounded manifest as embedded objects.
|
||||
pub const CUSTOM_XML_ROOTS: &str = "wordcraft:customXml.roots";
|
||||
/// The original `word/settings.xml` when it holds settings the model doesn't (merged into on
|
||||
/// save by `write::settings_merge`). Not a package part: WordCraft's own bookkeeping.
|
||||
pub const SETTINGS_ORIG: &str = "wordcraft:settings.orig";
|
||||
/// Extended properties (`docProps/app.xml`) the model doesn't hold but a save keeps
|
||||
/// ([`APP_KEPT_PROPS`]): `name\tvalue` lines. Not a package part: WordCraft's own bookkeeping.
|
||||
pub const APP_KEPT: &str = "wordcraft:app.kept";
|
||||
/// The `docProps/app.xml` properties carried over from the file. Counts (pages, lines,
|
||||
/// characters, editing time) and the producing application's version are not: they describe
|
||||
/// the file Word saved, not the one WordCraft writes.
|
||||
pub const APP_KEPT_PROPS: &[&str] =
|
||||
&["Template", "Manager", "Company", "HyperlinkBase", "ScaleCrop", "LinksUpToDate", "SharedDoc", "HyperlinksChanged"];
|
||||
/// Parts WordCraft doesn't model, carried verbatim: `owner\ttype\tpart` lines (owner `P` for
|
||||
/// the package, `D` for the main document), with their bytes and relationships in the
|
||||
/// [`EmbeddedManifest`]. Not a package part: WordCraft's own bookkeeping.
|
||||
pub const UNMODELLED_ROOTS: &str = "wordcraft:unmodelled.roots";
|
||||
/// Most parts we carry along for a file's embedded objects.
|
||||
pub const MAX_EMBEDDED_PARTS: usize = 4096;
|
||||
/// Most relationships we keep for one such part.
|
||||
|
||||
@@ -19,6 +19,48 @@ use crate::package::{
|
||||
};
|
||||
use crate::xml::{El, MAX_DEPTH, NAMESPACES, esc};
|
||||
|
||||
/// Relationship types (last path segment) the reader models or the writer produces itself, so
|
||||
/// they are never carried verbatim: carrying them would duplicate or contradict the written part.
|
||||
/// Types the main document refers to by id (headers, pictures, objects…) are listed too.
|
||||
pub const HANDLED_RELS: &[&str] = &[
|
||||
"officeDocument",
|
||||
"core-properties",
|
||||
"extended-properties",
|
||||
"custom-properties",
|
||||
"styles",
|
||||
"numbering",
|
||||
"settings",
|
||||
"theme",
|
||||
"fontTable",
|
||||
"footnotes",
|
||||
"endnotes",
|
||||
"comments",
|
||||
"commentsExtended",
|
||||
"commentsIds",
|
||||
"commentsExtensible",
|
||||
"customXml",
|
||||
"vbaProject",
|
||||
"header",
|
||||
"footer",
|
||||
"image",
|
||||
"hyperlink",
|
||||
"oleObject",
|
||||
"package",
|
||||
"chart",
|
||||
"chartEx",
|
||||
"diagramData",
|
||||
"diagramDrawing",
|
||||
"diagramLayout",
|
||||
"diagramQuickStyle",
|
||||
"diagramColors",
|
||||
"video",
|
||||
"audio",
|
||||
"media",
|
||||
"control",
|
||||
"subDocument",
|
||||
"ink",
|
||||
];
|
||||
|
||||
/// Most relationship ids one object's markup may use.
|
||||
const MAX_IDS: usize = 64;
|
||||
|
||||
@@ -45,6 +87,38 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the parts the package and the main document relate to that WordCraft neither models
|
||||
/// nor writes itself (web settings, styles-with-effects, add-in task panes, the thumbnail, a
|
||||
/// glossary…), with every part they reach, so saving carries them unchanged. Skipped: the
|
||||
/// relationship types the writer produces or the reader models ([`HANDLED_RELS`]) and any
|
||||
/// relationship the main document's markup refers to by id (its target goes with the
|
||||
/// element, or not at all).
|
||||
pub(super) fn keep_unmodelled(&mut self, package: &Rels, document: &Rels) {
|
||||
let main = self.pkg.get(&self.main).map(|b| b.to_vec()).unwrap_or_default();
|
||||
let referenced = |id: &str| {
|
||||
let needle = format!("\"{id}\"");
|
||||
main.windows(needle.len()).any(|w| w == needle.as_bytes())
|
||||
};
|
||||
let mut roots = String::new();
|
||||
for (owner, rels) in [("P", package), ("D", document)] {
|
||||
for rel in rels.list.iter().filter(|r| !r.external).take(MAX_EMBEDDED_RELS) {
|
||||
let tail = rel.kind.rsplit('/').next().unwrap_or("");
|
||||
if HANDLED_RELS.contains(&tail)
|
||||
|| (owner == "D" && referenced(&rel.id))
|
||||
|| ![&rel.kind, &rel.target].iter().all(|s| manifest_field_ok(s))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if self.keep_part_tree(&rel.target) {
|
||||
roots.push_str(&format!("{owner}\t{}\t{}\n", rel.kind, rel.target));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !roots.is_empty() {
|
||||
self.doc.passthrough.insert(crate::package::UNMODELLED_ROOTS.into(), Arc::new(roots.into_bytes()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `el` (an object's `a:graphic` or `w:object`, read with `rels`) and the parts it refers
|
||||
/// to, so the object can be written back. `extra` names relationships the object's parts use
|
||||
/// by id although its markup doesn't (a SmartArt drawing, named in the diagram's data part).
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Freeform shapes (DrawingML custom geometry, `a:custGeom`) and ink strokes drawn with them.
|
||||
//! Freeform shapes (DrawingML custom geometry, `a:custGeom`; legacy VML paths) and ink strokes
|
||||
//! drawn with them.
|
||||
|
||||
use wordcraft_doc::freeform::{FreePath, Freeform, InkTool, MAX_PATHS, MAX_POINTS};
|
||||
|
||||
@@ -7,6 +8,10 @@ use crate::xml::El;
|
||||
|
||||
/// Straight pieces a Bézier curve is flattened into.
|
||||
const CURVE_STEPS: usize = 8;
|
||||
/// Points read from one path segment. A conformant `a:lnTo`/`a:moveTo` has one, `a:quadBezTo`
|
||||
/// two and `a:cubicBezTo` three; the cap bounds the de Casteljau control polygon so a segment
|
||||
/// stuffed with points can't make curve flattening quadratic in the point count.
|
||||
const MAX_SEG_POINTS: usize = 8;
|
||||
/// Largest path coordinate kept, in EMUs.
|
||||
const MAX_EMU: f64 = 1.0e12;
|
||||
|
||||
@@ -41,7 +46,7 @@ pub fn cust_geom(sppr: &El, w: f32, h: f32) -> Option<Freeform> {
|
||||
if cur.len() >= MAX_POINTS || done.len() >= MAX_PATHS {
|
||||
break;
|
||||
}
|
||||
let pts: Vec<[f64; 2]> = seg.children("a:pt").filter_map(pt).collect();
|
||||
let pts: Vec<[f64; 2]> = seg.children("a:pt").filter_map(pt).take(MAX_SEG_POINTS).collect();
|
||||
match seg.local() {
|
||||
"moveTo" => {
|
||||
if !cur.is_empty() {
|
||||
@@ -65,7 +70,10 @@ pub fn cust_geom(sppr: &El, w: f32, h: f32) -> Option<Freeform> {
|
||||
}
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
done.push((cur, false));
|
||||
// A path drawn back to where it started is closed, though it has no `a:close` (#743:
|
||||
// Word's cover pages), so it's filled.
|
||||
let back = cur.len() > 2 && cur.first() == cur.last();
|
||||
done.push((cur, back));
|
||||
}
|
||||
for (pts, closed) in done.into_iter().take(MAX_PATHS.saturating_sub(paths.len())) {
|
||||
paths.push(FreePath { pts: pts.into_iter().take(MAX_POINTS).map(scale).collect(), closed: closed && !fill_none });
|
||||
@@ -75,6 +83,229 @@ pub fn cust_geom(sppr: &El, w: f32, h: f32) -> Option<Freeform> {
|
||||
(!f.paths.is_empty()).then_some(f)
|
||||
}
|
||||
|
||||
/// Largest VML path coordinate kept (coordinate-space units).
|
||||
const MAX_VML: f64 = 1.0e12;
|
||||
/// Characters of a VML `path` attribute read; the rest is ignored.
|
||||
const MAX_VML_PATH: usize = 1 << 20;
|
||||
/// Parameters of a VML path kept, all commands together.
|
||||
const MAX_VML_PARAMS: usize = MAX_POINTS * 8;
|
||||
|
||||
/// A legacy VML freeform (`v:shape` with a `path`, ECMA-376 Part 4 §14.1.2.19).
|
||||
pub struct VmlPath {
|
||||
pub freeform: Freeform,
|
||||
/// `nf` in the path: no fill.
|
||||
pub no_fill: bool,
|
||||
/// `ns` in the path: no outline.
|
||||
pub no_stroke: bool,
|
||||
}
|
||||
|
||||
/// The VML path commands that are two letters long.
|
||||
const VML_TWO: [&str; 11] = ["nf", "ns", "ae", "al", "at", "ar", "wa", "wr", "qx", "qy", "qb"];
|
||||
|
||||
/// The VML `path` of a shape, mapped onto its `w` × `h` frame (points) through its `coordsize`
|
||||
/// (default `1000,1000`) and `coordorigin` (default `0,0`). Commands: `m`/`t` move (absolute /
|
||||
/// relative), `l`/`r` line, `c`/`v` cubic Bézier (flattened), `x` close, `e` end, `nf`/`ns` no
|
||||
/// fill / no outline; arcs (`at`, `ar`, `wa`, `wr`) and quadrants (`qx`, `qy`) are drawn straight
|
||||
/// to their end, `qb` straight to its last point, and ellipses (`ae`, `al`) are skipped. An empty
|
||||
/// parameter is 0. `None` when the path has no points, or uses formulas (`@n`, from `v:formulas`,
|
||||
/// which aren't evaluated): such a shape isn't drawn rather than drawn wrong.
|
||||
pub fn vml_path(path: &str, coordsize: Option<&str>, coordorigin: Option<&str>, w: f32, h: f32) -> Option<VmlPath> {
|
||||
if path.contains('@') {
|
||||
return None;
|
||||
}
|
||||
let pair = |v: Option<&str>| -> Option<(f64, f64)> {
|
||||
let v = v?;
|
||||
let (a, b) = v.split_once(',').unwrap_or((v, ""));
|
||||
let n = |s: &str| int(s).map(|i| (i as f64).clamp(-MAX_VML, MAX_VML));
|
||||
Some((n(a)?, n(b).unwrap_or(0.0)))
|
||||
};
|
||||
let size = |v: f64| if v > 0.0 { v } else { 1000.0 };
|
||||
let (cw, ch) = pair(coordsize).map_or((1000.0, 1000.0), |(a, b)| (size(a), size(b)));
|
||||
let (ox, oy) = pair(coordorigin).unwrap_or((0.0, 0.0));
|
||||
let (sx, sy) = (w as f64 / cw, h as f64 / ch);
|
||||
let scale = |[x, y]: [f64; 2]| -> [f32; 2] { [((x - ox) * sx) as f32, ((y - oy) * sy) as f32] };
|
||||
|
||||
let mut d = Draw::default();
|
||||
let (mut no_fill, mut no_stroke) = (false, false);
|
||||
for (cmd, params) in vml_commands(path) {
|
||||
if d.full() {
|
||||
break;
|
||||
}
|
||||
let pts: Vec<[f64; 2]> = params.as_chunks::<2>().0.to_vec();
|
||||
match cmd.as_str() {
|
||||
"m" | "t" => {
|
||||
for (i, &p) in pts.iter().enumerate() {
|
||||
let p = if cmd == "t" { d.rel(p) } else { p };
|
||||
if i == 0 {
|
||||
d.move_to(p);
|
||||
} else {
|
||||
d.line_to(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
"l" | "r" | "qx" | "qy" => {
|
||||
for &p in &pts {
|
||||
let p = if cmd == "r" { d.rel(p) } else { p };
|
||||
d.line_to(p);
|
||||
}
|
||||
}
|
||||
"c" | "v" => {
|
||||
for c in pts.as_chunks::<3>().0 {
|
||||
let start = d.at;
|
||||
let ctrl: Vec<[f64; 2]> = std::iter::once(start).chain(c.iter().map(|&p| if cmd == "v" { d.rel(p) } else { p })).collect();
|
||||
for i in 1..=CURVE_STEPS {
|
||||
d.line_to(bezier(&ctrl, i as f64 / CURVE_STEPS as f64));
|
||||
}
|
||||
}
|
||||
}
|
||||
"qb" => {
|
||||
if let Some(&p) = pts.last() {
|
||||
d.line_to(p);
|
||||
}
|
||||
}
|
||||
// Bounding box, then start and end: `at`/`wa` draw a line to the start, `ar`/`wr` move there.
|
||||
"at" | "ar" | "wa" | "wr" => {
|
||||
for [_, _, s, e] in pts.as_chunks::<4>().0 {
|
||||
if matches!(cmd.as_str(), "ar" | "wr") {
|
||||
d.move_to(*s);
|
||||
} else {
|
||||
d.line_to(*s);
|
||||
}
|
||||
d.line_to(*e);
|
||||
}
|
||||
}
|
||||
"x" => d.end(true),
|
||||
"e" => d.end(false),
|
||||
"nf" => no_fill = true,
|
||||
"ns" => no_stroke = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
d.end(false);
|
||||
let paths = d.done.into_iter().map(|(pts, closed)| FreePath { pts: pts.into_iter().map(scale).collect(), closed }).collect();
|
||||
let freeform = Freeform { w, h, paths, alpha: 1.0, ink: None, order: None }.sanitized();
|
||||
(!freeform.paths.is_empty()).then_some(VmlPath { freeform, no_fill, no_stroke })
|
||||
}
|
||||
|
||||
/// The pen while a VML path is drawn: where it is, where the subpath began, the subpath being
|
||||
/// drawn and those done (closed or not).
|
||||
#[derive(Default)]
|
||||
struct Draw {
|
||||
at: [f64; 2],
|
||||
start: [f64; 2],
|
||||
cur: Vec<[f64; 2]>,
|
||||
done: Vec<(Vec<[f64; 2]>, bool)>,
|
||||
}
|
||||
|
||||
impl Draw {
|
||||
fn full(&self) -> bool {
|
||||
self.done.len() >= MAX_PATHS
|
||||
}
|
||||
|
||||
fn rel(&self, [x, y]: [f64; 2]) -> [f64; 2] {
|
||||
[(self.at[0] + x).clamp(-MAX_VML, MAX_VML), (self.at[1] + y).clamp(-MAX_VML, MAX_VML)]
|
||||
}
|
||||
|
||||
fn move_to(&mut self, p: [f64; 2]) {
|
||||
self.end(false);
|
||||
self.at = p;
|
||||
self.start = p;
|
||||
self.cur.push(p);
|
||||
}
|
||||
|
||||
fn line_to(&mut self, p: [f64; 2]) {
|
||||
if self.cur.is_empty() {
|
||||
self.cur.push(self.at);
|
||||
self.start = self.at;
|
||||
}
|
||||
if self.cur.len() < MAX_POINTS {
|
||||
self.cur.push(p);
|
||||
}
|
||||
self.at = p;
|
||||
}
|
||||
|
||||
/// Finish the subpath being drawn, closed back to its start or not.
|
||||
fn end(&mut self, closed: bool) {
|
||||
if !self.cur.is_empty() && !self.full() {
|
||||
self.done.push((std::mem::take(&mut self.cur), closed));
|
||||
}
|
||||
self.cur.clear();
|
||||
if closed {
|
||||
self.at = self.start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands of a VML path with their parameters: a command is a letter (or one of
|
||||
/// [`VML_TWO`]) followed by numbers separated by commas or spaces. An empty parameter (nothing
|
||||
/// before a comma) is 0, and so is a formula reference (`@n`, not expected here: see
|
||||
/// [`vml_path`]); fractions are dropped. Anything else is skipped.
|
||||
fn vml_commands(path: &str) -> Vec<(String, Vec<f64>)> {
|
||||
let mut out: Vec<(String, Vec<f64>)> = Vec::new();
|
||||
let mut chars = path.chars().take(MAX_VML_PATH).peekable();
|
||||
// Whether a number was read since the command or the last comma.
|
||||
let mut has_num = true;
|
||||
let mut kept = 0usize;
|
||||
let mut push = |out: &mut Vec<(String, Vec<f64>)>, v: f64| {
|
||||
if kept < MAX_VML_PARAMS
|
||||
&& let Some((_, p)) = out.last_mut()
|
||||
{
|
||||
p.push(v);
|
||||
kept += 1;
|
||||
}
|
||||
};
|
||||
while let Some(c) = chars.next() {
|
||||
if c.is_ascii_alphabetic() {
|
||||
if !has_num {
|
||||
push(&mut out, 0.0);
|
||||
}
|
||||
has_num = false;
|
||||
let lower = c.to_ascii_lowercase();
|
||||
let mut cmd = lower.to_string();
|
||||
if let Some(&n) = chars.peek() {
|
||||
let two: String = [lower, n.to_ascii_lowercase()].iter().collect();
|
||||
if VML_TWO.contains(&two.as_str()) {
|
||||
chars.next();
|
||||
cmd = two;
|
||||
}
|
||||
}
|
||||
out.push((cmd, Vec::new()));
|
||||
} else if c == ',' {
|
||||
if !has_num {
|
||||
push(&mut out, 0.0);
|
||||
}
|
||||
has_num = false;
|
||||
} else if matches!(c, '@' | '-' | '+' | '.') || c.is_ascii_digit() {
|
||||
let mut v = c.to_digit(10).map_or(0.0, f64::from);
|
||||
let mut frac = c == '.';
|
||||
while let Some(&n) = chars.peek() {
|
||||
if n == '.' {
|
||||
frac = true;
|
||||
} else if n.is_ascii_digit() {
|
||||
if !frac {
|
||||
v = (v * 10.0 + n.to_digit(10).map_or(0.0, f64::from)).min(MAX_VML);
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
chars.next();
|
||||
}
|
||||
let v = match c {
|
||||
'@' => 0.0,
|
||||
'-' => -v,
|
||||
_ => v,
|
||||
};
|
||||
has_num = true;
|
||||
push(&mut out, v);
|
||||
}
|
||||
// Whitespace and anything else only separate numbers.
|
||||
}
|
||||
if !has_num {
|
||||
push(&mut out, 0.0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The pen of an ink stroke written by WordCraft, from its drawing's name (`Ink Pen 3`,
|
||||
/// `Ink Highlighter 4`).
|
||||
pub fn ink_tool(name: &str) -> Option<InkTool> {
|
||||
@@ -115,3 +346,36 @@ fn bezier(c: &[[f64; 2]], t: f64) -> [f64; 2] {
|
||||
}
|
||||
p.first().copied().unwrap_or([0.0, 0.0])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sppr(seg: &str) -> crate::xml::El {
|
||||
let xml = format!(
|
||||
"<wps:spPr xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" \
|
||||
xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\">\
|
||||
<a:custGeom><a:pathLst><a:path w=\"100\" h=\"100\">\
|
||||
<a:moveTo><a:pt x=\"0\" y=\"0\"/></a:moveTo>{seg}</a:path></a:pathLst></a:custGeom></wps:spPr>"
|
||||
);
|
||||
crate::xml::parse(xml.as_bytes()).expect("parse spPr")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bezier_segment_with_many_points_is_bounded() {
|
||||
// One cubicBezTo stuffed with 50 000 points must not make de Casteljau quadratic: the
|
||||
// control polygon is capped, so flattening stays a handful of points and returns at once.
|
||||
let pts = "<a:pt x=\"1\" y=\"1\"/>".repeat(50_000);
|
||||
let sppr = sppr(&format!("<a:cubicBezTo>{pts}</a:cubicBezTo>"));
|
||||
let f = cust_geom(&sppr, 100.0, 100.0).expect("a path");
|
||||
assert!(f.paths.iter().all(|p| p.pts.len() <= 1 + CURVE_STEPS), "{:?}", f.paths.iter().map(|p| p.pts.len()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conformant_cubic_still_flattens_to_a_curve() {
|
||||
let sppr = sppr("<a:cubicBezTo><a:pt x=\"0\" y=\"100\"/><a:pt x=\"100\" y=\"100\"/><a:pt x=\"100\" y=\"0\"/></a:cubicBezTo>");
|
||||
let f = cust_geom(&sppr, 100.0, 100.0).expect("a path");
|
||||
assert_eq!(f.paths.len(), 1);
|
||||
assert!(f.paths[0].pts.len() >= 2 && f.paths[0].pts.len() <= 1 + CURVE_STEPS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,20 @@ pub fn read_omath(e: &El, jc: MathJc) -> Math {
|
||||
Math { nodes: merge_runs(arg(e, 0)), omml: e.to_xml(), jc, linear: false }
|
||||
}
|
||||
|
||||
/// A colour every math run shares, taken off the runs: it is the equation's own colour, as
|
||||
/// [`write_equation`](crate::write::math::write_equation) spreads it (#1467). The source OMML
|
||||
/// is kept: the writer replaces it only when the colour changes.
|
||||
pub fn lift_color(math: &mut Math) -> Option<Rgb> {
|
||||
let (mut shared, mut uniform) = (None, true);
|
||||
wordcraft_doc::math_edit::each_run_mut(&mut math.nodes, &mut |r| match shared {
|
||||
None => shared = Some(r.color),
|
||||
Some(c) => uniform &= c == r.color,
|
||||
});
|
||||
let c = shared.flatten().filter(|_| uniform)?;
|
||||
wordcraft_doc::math_edit::each_run_mut(&mut math.nodes, &mut |r| r.color = None);
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// `m:oMathParaPr/m:jc`.
|
||||
pub fn para_jc(para: &El) -> MathJc {
|
||||
match para.child("m:oMathParaPr").and_then(|p| p.child("m:jc")).and_then(|j| j.attr("m:val")) {
|
||||
|
||||
+186
-56
@@ -5,7 +5,7 @@ pub(crate) mod diagram;
|
||||
mod drawing_color;
|
||||
mod embed;
|
||||
mod freeform;
|
||||
mod math;
|
||||
pub(crate) mod math;
|
||||
mod props;
|
||||
mod sdt;
|
||||
mod shape_style;
|
||||
@@ -20,9 +20,12 @@ use wordcraft_doc::numbering::{AbstractNum, Level, LevelSuffix, Num};
|
||||
use wordcraft_doc::para::NoteKind;
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::props::Rgb;
|
||||
use wordcraft_doc::props::VAlign;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
use wordcraft_doc::styles::{Style, StyleKind, StyleSheet, TableStyleParts};
|
||||
use wordcraft_doc::{Block, Blocks, Comment, Document, InlineObject, Paragraph, PartKind, Revision, RevisionKind, para_block};
|
||||
use wordcraft_doc::styles::{PartFormat, Style, StyleKind, StyleSheet, TablePart, TableStyleParts};
|
||||
use wordcraft_doc::{
|
||||
Block, Blocks, Comment, Document, InlineObject, PagePicture, Paragraph, PartKind, Revision, RevisionKind, Zoom, ZoomFit, para_block,
|
||||
};
|
||||
|
||||
use crate::DocxError;
|
||||
use crate::package::{ContentTypes, EMBEDDED_PARTS, EmbeddedManifest, MAX_VBA_RELATED, Package, Rels, VBA_PROJECT_PART, VBA_RELATED, rel_is, rt};
|
||||
@@ -31,8 +34,14 @@ use crate::xml::El;
|
||||
pub(crate) use props::PropCtx;
|
||||
use story::StoryCtx;
|
||||
|
||||
/// Most fonts read from a font table, and the longest name (hostile files).
|
||||
const MAX_TABLE_FONTS: usize = 2000;
|
||||
const MAX_FONT_NAME: usize = 256;
|
||||
|
||||
/// Most parts (headers, notes, comments, text boxes) we create from one file.
|
||||
const MAX_PARTS: usize = 50_000;
|
||||
/// Deepest chain of headers/footers whose own sections reference further headers/footers.
|
||||
const MAX_HF_DEPTH: usize = 4;
|
||||
/// Most graphic work (items plus path segments, see `story::graphic_work`) built for one file's
|
||||
/// charts and diagrams; later ones are left empty.
|
||||
const MAX_GRAPHIC_WORK: usize = 2_000_000;
|
||||
@@ -62,6 +71,8 @@ pub(crate) struct Reader<'p> {
|
||||
pub moves: MoveCtx,
|
||||
media_by_path: HashMap<String, String>,
|
||||
hf_by_path: HashMap<String, u32>,
|
||||
/// Header/footer parts being read right now (see [`MAX_HF_DEPTH`]).
|
||||
hf_depth: usize,
|
||||
pub footnotes: HashMap<i64, u32>,
|
||||
pub endnotes: HashMap<i64, u32>,
|
||||
/// The note being read (kind, part id): its `w:footnoteRef` / `w:endnoteRef` mark is a
|
||||
@@ -139,6 +150,7 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
moves: MoveCtx::default(),
|
||||
media_by_path: HashMap::new(),
|
||||
hf_by_path: HashMap::new(),
|
||||
hf_depth: 0,
|
||||
footnotes: HashMap::new(),
|
||||
endnotes: HashMap::new(),
|
||||
current_note: None,
|
||||
@@ -164,6 +176,7 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
// The font table and the fonts embedded through it ride along as opaque parts.
|
||||
if let Some(p) = part(rt::FONT_TABLE) {
|
||||
r.keep_part_tree(&p);
|
||||
r.read_font_families(&p);
|
||||
}
|
||||
if let Some(p) = part(rt::THEME) {
|
||||
r.read_theme(&p);
|
||||
@@ -197,7 +210,9 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
}
|
||||
if let Some(p) = part(rt::COMMENTS) {
|
||||
let ex = part(rt::COMMENTS_EX);
|
||||
lenient("comments", r.read_comments(&p, ex.as_deref()));
|
||||
let ids = part(rt::COMMENTS_IDS);
|
||||
let cex = part(rt::COMMENTS_EXTENSIBLE);
|
||||
lenient("comments", r.read_comments(&p, ex.as_deref(), ids.as_deref(), cex.as_deref()));
|
||||
}
|
||||
// Bibliography sources live in a custom XML data store (`b:Sources`), related from the
|
||||
// package root or the main part; Word's own files sometimes leave the relationship out, so
|
||||
@@ -228,6 +243,17 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
if let Some(bg) = root.child("w:background").and_then(|b| b.attr("w:color")).and_then(Rgb::parse) {
|
||||
r.doc.settings.page_color = Some(bg);
|
||||
}
|
||||
// A picture or texture fill: `w:background/v:background/v:fill` with a relationship id.
|
||||
if let Some(fill) = root.child("w:background").and_then(|b| b.child("v:background")).and_then(|b| b.child("v:fill")) {
|
||||
let rid = fill.attr("r:id").or_else(|| fill.attr("r:embed")).or_else(|| fill.attr("o:relid"));
|
||||
if let Some(media) = rid.and_then(|id| r.media_for(&rels, id)) {
|
||||
r.doc.settings.page_picture = Some(PagePicture {
|
||||
media,
|
||||
fill_type: fill.attr("type").unwrap_or("").chars().take(32).collect(),
|
||||
title: fill.attr("o:title").unwrap_or("").chars().take(255).collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(body) = root.child("w:body") {
|
||||
let mut sc = StoryCtx::default();
|
||||
let mut blocks = Blocks::new();
|
||||
@@ -243,6 +269,9 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
|
||||
let core = root_rels.by_type(rt::CORE).map(|x| x.target.clone()).unwrap_or_else(|| "docProps/core.xml".into());
|
||||
r.read_core(&core);
|
||||
if let Some(app) = root_rels.by_type(rt::APP).map(|x| x.target.clone()) {
|
||||
r.read_app(&app);
|
||||
}
|
||||
if let Some(c) = root_rels.by_type(rt::CUSTOM)
|
||||
&& let Ok(Some(x)) = r.xml(&c.target)
|
||||
{
|
||||
@@ -258,6 +287,7 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
r.read_vba_related(&v);
|
||||
}
|
||||
r.keep_custom_xml(&root_rels, &rels);
|
||||
r.keep_unmodelled(&root_rels, &rels);
|
||||
if !r.embedded.parts.is_empty() {
|
||||
let manifest = r.embedded.to_bytes();
|
||||
r.doc.passthrough.insert(EMBEDDED_PARTS.into(), Arc::new(manifest));
|
||||
@@ -418,9 +448,17 @@ fn toc_field_to_heading(body: &mut Blocks) {
|
||||
}
|
||||
let Some((field, props, end)) = body[i].as_para().and_then(|p| {
|
||||
let (field, end) = match p.object_at(0) {
|
||||
Some(InlineObject::FieldStart { instr, locked }) if is_toc(instr) => {
|
||||
(InlineObject::Field { instr: instr.clone(), result: String::new(), locked: *locked, code: false }, Some(toc_range_end(body, i)?))
|
||||
}
|
||||
Some(InlineObject::FieldStart { instr, locked, dirty }) if is_toc(instr) => (
|
||||
InlineObject::Field {
|
||||
instr: instr.clone(),
|
||||
result: String::new(),
|
||||
locked: *locked,
|
||||
dirty: *dirty,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
Some(toc_range_end(body, i)?),
|
||||
),
|
||||
Some(f @ InlineObject::Field { result, .. }) if result.is_empty() && has_toc(f) => (f.clone(), None),
|
||||
_ => return None,
|
||||
};
|
||||
@@ -556,6 +594,19 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts the font table classes as roman (`w:font/w:family w:val="roman"`).
|
||||
fn read_font_families(&mut self, path: &str) {
|
||||
let Ok(Some(table)) = self.xml(path) else { return };
|
||||
self.doc.settings.roman_fonts = table
|
||||
.children("w:font")
|
||||
.filter(|f| f.child("w:family").and_then(|v| v.attr("w:val")) == Some("roman"))
|
||||
.filter_map(|f| f.attr("w:name"))
|
||||
.filter(|n| !n.is_empty() && n.len() <= MAX_FONT_NAME)
|
||||
.take(MAX_TABLE_FONTS)
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
}
|
||||
|
||||
fn xml(&self, path: &str) -> Result<Option<El>, DocxError> {
|
||||
self.pkg.xml(path)
|
||||
}
|
||||
@@ -623,7 +674,7 @@ impl Reader<'_> {
|
||||
if let Some(id) = self.hf_by_path.get(path) {
|
||||
return Some(*id);
|
||||
}
|
||||
if self.doc.parts.len() >= MAX_PARTS {
|
||||
if self.doc.parts.len() >= MAX_PARTS || self.hf_depth >= MAX_HF_DEPTH {
|
||||
return None;
|
||||
}
|
||||
// Reserve the id first so a (malformed) self-reference can't recurse.
|
||||
@@ -636,8 +687,11 @@ impl Reader<'_> {
|
||||
};
|
||||
let rels = self.pkg.rels(path);
|
||||
let mut sc = StoryCtx::default();
|
||||
sc.in_hf = true;
|
||||
let mut blocks = Blocks::new();
|
||||
self.hf_depth += 1;
|
||||
self.read_blocks(&mut sc, &root, &rels, &mut blocks, 0);
|
||||
self.hf_depth = self.hf_depth.saturating_sub(1);
|
||||
self.flush_pending(&mut sc, &mut blocks);
|
||||
if let Some(p) = self.doc.parts.get_mut(&id)
|
||||
&& !blocks.is_empty()
|
||||
@@ -680,6 +734,9 @@ impl Reader<'_> {
|
||||
if let Some(f) = face("a:minorFont") {
|
||||
self.doc.settings.minor_font = f;
|
||||
}
|
||||
let cs = |n: &str| fs.child(n).and_then(|f| f.child("a:cs")).and_then(|c| c.attr("typeface")).unwrap_or_default().to_string();
|
||||
self.pc.major_cs = cs("a:majorFont");
|
||||
self.pc.minor_cs = cs("a:minorFont");
|
||||
}
|
||||
self.pc.major_font = self.doc.settings.major_font.clone();
|
||||
self.pc.minor_font = self.doc.settings.minor_font.clone();
|
||||
@@ -728,6 +785,8 @@ impl Reader<'_> {
|
||||
}
|
||||
|
||||
fn read_styles(&mut self, path: &str) -> Result<(), DocxError> {
|
||||
/// Largest `w:latentStyles` kept (Word's has ~380 exceptions, ~40 KB).
|
||||
const MAX_LATENT_STYLES_XML: usize = 1 << 20;
|
||||
let Some(root) = self.xml(path)? else { return Ok(()) };
|
||||
// The default paragraph style must be called `Normal` in our model.
|
||||
let has_normal = root.children("w:style").any(|s| s.attr("w:styleId") == Some("Normal"));
|
||||
@@ -752,6 +811,8 @@ impl Reader<'_> {
|
||||
if sheet.default_chr.size.is_none() {
|
||||
sheet.default_chr.size = Some(10.0);
|
||||
}
|
||||
// Built-in styles' behaviour (gallery, priority, visibility), written back as is.
|
||||
sheet.latent_styles = root.child("w:latentStyles").map(|l| l.to_xml()).filter(|x| x.len() <= MAX_LATENT_STYLES_XML);
|
||||
for s in root.children("w:style").take(10_000) {
|
||||
let Some(raw_id) = s.attr("w:styleId").filter(|i| !i.is_empty()) else { continue };
|
||||
let id = self.pc.style_id(raw_id);
|
||||
@@ -778,6 +839,15 @@ impl Reader<'_> {
|
||||
hidden: flag(s, "w:semiHidden").unwrap_or(false) || flag(s, "w:hidden").unwrap_or(false),
|
||||
builtin: !s.attr("w:customStyle").is_some_and(|v| v == "1" || v == "true"),
|
||||
locked: flag(s, "w:locked").unwrap_or(false),
|
||||
// Only where the writer couldn't tell from the id (it flags the English ids).
|
||||
default: s.attr("w:default").is_some_and(|v| v == "1" || v == "true")
|
||||
&& !matches!(
|
||||
(kind, id.as_str()),
|
||||
(StyleKind::Paragraph, "Normal")
|
||||
| (StyleKind::Character, "DefaultParagraphFont")
|
||||
| (StyleKind::Table, "TableNormal")
|
||||
| (StyleKind::Numbering, "NoList")
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(p) = s.child("w:pPr") {
|
||||
@@ -811,6 +881,10 @@ impl Reader<'_> {
|
||||
if sheet.default_para.numbering.is_some_and(|n| n.num == props::LEVEL_ONLY) {
|
||||
sheet.default_para.numbering = None;
|
||||
}
|
||||
// A producer that never writes `w:qFormat` (LibreOffice) still gets Word's usual gallery.
|
||||
if !sheet.styles.iter().any(|s| s.quick) {
|
||||
sheet.add_default_gallery();
|
||||
}
|
||||
self.doc.styles = sheet;
|
||||
Ok(())
|
||||
}
|
||||
@@ -828,56 +902,38 @@ impl Reader<'_> {
|
||||
t.band_size = tp.child_val("w:tblStyleRowBandSize").and_then(u32_of).filter(|n| *n > 0).map(|n| n.min(1000));
|
||||
}
|
||||
for c in s.children("w:tblStylePr").take(64) {
|
||||
let fill = c.child("w:tcPr").and_then(|p| p.child("w:shd")).and_then(|e| self.pc.shd_fill(e));
|
||||
let cell_borders = c.child("w:tcPr").and_then(|p| p.child("w:tcBorders")).map(props::borders);
|
||||
let chr = c.child("w:rPr").map(|r| self.pc.rpr(r)).unwrap_or_default();
|
||||
match c.attr("w:type") {
|
||||
Some("wholeTable") => {
|
||||
if let Some(p) = c.child("w:pPr") {
|
||||
st.para.overlay(&self.pc.ppr(p).0);
|
||||
}
|
||||
st.chr.overlay(&chr);
|
||||
if fill.is_some() {
|
||||
t.fill = fill;
|
||||
}
|
||||
if let Some(b) = c.child("w:tblPr").and_then(|p| p.child("w:tblBorders")) {
|
||||
t.borders = Some(props::borders(b));
|
||||
}
|
||||
let Some(part) = c.attr("w:type").and_then(TablePart::from_ooxml) else { continue };
|
||||
let tc = c.child("w:tcPr");
|
||||
let ppr = c.child("w:pPr").map(|p| self.pc.ppr(p).0);
|
||||
let f = PartFormat {
|
||||
chr: c.child("w:rPr").map(|r| self.pc.rpr(r)).unwrap_or_default(),
|
||||
fill: tc.and_then(|p| p.child("w:shd")).and_then(|e| self.pc.shd_fill(e)),
|
||||
borders: tc.and_then(|p| p.child("w:tcBorders")).map(props::borders),
|
||||
align: ppr.as_ref().and_then(|p| p.align),
|
||||
v_align: tc.and_then(|p| p.child_val("w:vAlign")).map(|v| match v {
|
||||
"center" => VAlign::Center,
|
||||
"bottom" => VAlign::Bottom,
|
||||
_ => VAlign::Top,
|
||||
}),
|
||||
};
|
||||
if part == TablePart::WholeTable {
|
||||
// The whole table's paragraph and run properties are the style's own; its
|
||||
// borders the table borders.
|
||||
if let Some(p) = ppr {
|
||||
st.para.overlay(&p);
|
||||
}
|
||||
Some("firstRow") => {
|
||||
t.header_fill = fill;
|
||||
t.header_chr = chr;
|
||||
t.header_borders = cell_borders;
|
||||
st.chr.overlay(&f.chr);
|
||||
if f.fill.is_some() {
|
||||
t.fill = f.fill;
|
||||
}
|
||||
Some("band1Horz") => {
|
||||
t.band_fill = fill;
|
||||
t.band_chr = chr;
|
||||
t.band_borders = cell_borders;
|
||||
if let Some(b) = c.child("w:tblPr").and_then(|p| p.child("w:tblBorders")) {
|
||||
t.borders = Some(props::borders(b));
|
||||
}
|
||||
Some("firstCol") => {
|
||||
t.first_col_chr = chr;
|
||||
t.first_col_fill = fill;
|
||||
t.first_col_borders = cell_borders;
|
||||
if f.v_align.is_some() {
|
||||
t.regions.insert(part, PartFormat { v_align: f.v_align, ..PartFormat::default() });
|
||||
}
|
||||
Some("lastCol") => {
|
||||
t.last_col_chr = chr;
|
||||
t.last_col_fill = fill;
|
||||
t.last_col_borders = cell_borders;
|
||||
}
|
||||
Some("lastRow") => {
|
||||
t.total_chr = chr;
|
||||
t.total_fill = fill;
|
||||
// The top rule is kept on its own (as built-in styles have it); the other edges
|
||||
// are the region's borders.
|
||||
t.total_border_top = cell_borders.and_then(|b| b.top);
|
||||
t.total_borders = cell_borders.map(|b| wordcraft_doc::props::Borders { top: None, ..b }).filter(|b| *b != Default::default());
|
||||
}
|
||||
Some("band1Vert") => {
|
||||
t.col_band_fill = fill;
|
||||
t.col_band_chr = chr;
|
||||
t.col_band_borders = cell_borders;
|
||||
}
|
||||
_ => {}
|
||||
} else {
|
||||
t.set_part(part, f);
|
||||
}
|
||||
}
|
||||
t
|
||||
@@ -899,7 +955,19 @@ impl Reader<'_> {
|
||||
if let Some(link) = a.child_val("w:numStyleLink") {
|
||||
links.push((id, link.to_string()));
|
||||
}
|
||||
abstracts.push(AbstractNum { id, name: a.child_val("w:name").map(str::to_string), levels });
|
||||
let hex = |v: &str| v.len() == 8 && v.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
abstracts.push(AbstractNum {
|
||||
id,
|
||||
name: a.child_val("w:name").map(str::to_string),
|
||||
levels,
|
||||
nsid: a.child_val("w:nsid").filter(|v| hex(v)).map(str::to_ascii_uppercase),
|
||||
tmpl: a.child_val("w:tmpl").filter(|v| hex(v)).map(str::to_ascii_uppercase),
|
||||
multi_level_type: a
|
||||
.child_val("w:multiLevelType")
|
||||
// `multilevel` is what the writer derives for the nine levels read here.
|
||||
.filter(|v| matches!(*v, "singleLevel" | "hybridMultilevel"))
|
||||
.map(str::to_string),
|
||||
});
|
||||
}
|
||||
let mut nums = Vec::new();
|
||||
for n in root.children("w:num").take(10_000) {
|
||||
@@ -981,6 +1049,9 @@ impl Reader<'_> {
|
||||
|
||||
fn read_settings(&mut self, path: &str) -> Result<(), DocxError> {
|
||||
let Some(root) = self.xml(path)? else { return Ok(()) };
|
||||
if let Some(b) = self.pkg.get(path).filter(|b| crate::write::settings_has_unowned(b)) {
|
||||
self.doc.passthrough.insert(crate::package::SETTINGS_ORIG.into(), Arc::new(b.to_vec()));
|
||||
}
|
||||
let rels = self.pkg.rels(path);
|
||||
let s = &mut self.doc.settings;
|
||||
for k in root.els() {
|
||||
@@ -997,6 +1068,7 @@ impl Reader<'_> {
|
||||
"w:removePersonalInformation" => s.remove_personal_info = on_off(k),
|
||||
"w:removeDateAndTime" => s.remove_date_time = on_off(k),
|
||||
"w:compat" => {
|
||||
s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off);
|
||||
// Only Word's own setting: another `w:uri` names a different application's.
|
||||
let mode = k
|
||||
.children("w:compatSetting")
|
||||
@@ -1008,6 +1080,7 @@ impl Reader<'_> {
|
||||
if let Some(m) = mode.and_then(u32_of) {
|
||||
s.compat_mode = m.clamp(11, 99);
|
||||
}
|
||||
s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off);
|
||||
}
|
||||
"w:trackRevisions" => s.track_changes = on_off(k),
|
||||
"w:defaultTabStop" => {
|
||||
@@ -1049,6 +1122,16 @@ impl Reader<'_> {
|
||||
s.endnote_pr = props::note_pr(k, false);
|
||||
}
|
||||
"w:documentProtection" => read_protection(k, s),
|
||||
"w:zoom" => {
|
||||
let percent = k.attr("w:percent").and_then(|v| u32_of(v.trim_end_matches('%'))).unwrap_or(100).clamp(10, 500);
|
||||
let fit = match k.attr("w:val") {
|
||||
Some("fullPage") => Some(ZoomFit::OnePage),
|
||||
Some("bestFit") => Some(ZoomFit::PageWidth),
|
||||
Some("textFit") => Some(ZoomFit::TextWidth),
|
||||
_ => None,
|
||||
};
|
||||
s.zoom = Some(Zoom { percent, fit }).filter(|z| z.percent != 100 || z.fit.is_some());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -1125,7 +1208,23 @@ impl Reader<'_> {
|
||||
*slot = Some(blocks);
|
||||
}
|
||||
|
||||
fn read_comments(&mut self, path: &str, ext: Option<&str>) -> Result<(), DocxError> {
|
||||
/// The extended properties a save carries over ([`crate::package::APP_KEPT_PROPS`]).
|
||||
fn read_app(&mut self, path: &str) {
|
||||
let Ok(Some(root)) = self.xml(path) else { return };
|
||||
let mut kept = String::new();
|
||||
for e in root.els() {
|
||||
let name = e.local();
|
||||
let value = e.text();
|
||||
if crate::package::APP_KEPT_PROPS.contains(&name) && value.len() <= 2048 && !value.contains(['\t', '\n']) {
|
||||
kept.push_str(&format!("{name}\t{value}\n"));
|
||||
}
|
||||
}
|
||||
if !kept.is_empty() {
|
||||
self.doc.passthrough.insert(crate::package::APP_KEPT.into(), Arc::new(kept.into_bytes()));
|
||||
}
|
||||
}
|
||||
|
||||
fn read_comments(&mut self, path: &str, ext: Option<&str>, ids: Option<&str>, cex: Option<&str>) -> Result<(), DocxError> {
|
||||
let Some(root) = self.xml(path)? else { return Ok(()) };
|
||||
let rels = self.pkg.rels(path);
|
||||
let mut by_para: HashMap<String, u32> = HashMap::new();
|
||||
@@ -1165,6 +1264,7 @@ impl Reader<'_> {
|
||||
parent: None,
|
||||
resolved: false,
|
||||
part,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
self.comment_map.insert(file_id, id);
|
||||
@@ -1182,6 +1282,36 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Durable ids (by paragraph id) and UTC dates (by durable id), which the writer
|
||||
// carries over (`write_comment_ids`). Their namespaces (w16cid, w16cex) have no canonical
|
||||
// prefix here, so attributes are found by local name.
|
||||
let local = |e: &crate::xml::El, name: &str| -> Option<String> {
|
||||
e.attrs.iter().find(|(k, _)| k.rsplit(':').next() == Some(name)).map(|(_, v)| v.clone())
|
||||
};
|
||||
let mut by_durable: HashMap<String, u32> = HashMap::new();
|
||||
if let Some(ids) = ids
|
||||
&& let Ok(Some(x)) = self.xml(ids)
|
||||
{
|
||||
for e in x.els().filter(|e| e.local() == "commentId") {
|
||||
let Some(cid) = local(e, "paraId").and_then(|p| by_para.get(&p).copied()) else { continue };
|
||||
let Some(durable) = local(e, "durableId").filter(|d| crate::write::durable_id_ok(d)) else { continue };
|
||||
if let Some(c) = entries.get_mut(&cid) {
|
||||
c.durable_id = Some(durable.to_ascii_uppercase());
|
||||
by_durable.insert(durable.to_ascii_uppercase(), cid);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(cex) = cex
|
||||
&& let Ok(Some(x)) = self.xml(cex)
|
||||
{
|
||||
for e in x.els().filter(|e| e.local() == "commentExtensible") {
|
||||
let Some(cid) = local(e, "durableId").and_then(|d| by_durable.get(&d.to_ascii_uppercase()).copied()) else { continue };
|
||||
let date = local(e, "dateUtc").filter(|d| d.len() <= 40 && d.chars().all(|c| c.is_ascii_alphanumeric() || ":-.+".contains(c)));
|
||||
if let (Some(c), Some(date)) = (entries.get_mut(&cid), date) {
|
||||
c.date_utc = Some(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.doc.comments = entries;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use wordcraft_doc::props::{
|
||||
};
|
||||
use wordcraft_doc::section::{
|
||||
Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, MAX_CHAR_SPACE, MAX_GRID_PITCH, NotePos, NoteProps, NoteRestart, NumFormat,
|
||||
SectionProps, SectionStart,
|
||||
PageVAlign, SectionProps, SectionStart,
|
||||
};
|
||||
|
||||
use super::drawing_color::adjust_lum;
|
||||
@@ -43,6 +43,9 @@ use crate::xml::El;
|
||||
pub struct PropCtx {
|
||||
pub major_font: String,
|
||||
pub minor_font: String,
|
||||
/// The theme's complex-script fonts (`a:cs`), which the `…Bidi` theme slots name.
|
||||
pub major_cs: String,
|
||||
pub minor_cs: String,
|
||||
/// The theme's colour scheme (dk1, lt1, dk2, lt2, accent1..6, hlink, folHlink); empty when the
|
||||
/// package has none, and then `w:themeColor` falls back to the fixed colour.
|
||||
pub theme_colors: Vec<Rgb>,
|
||||
@@ -82,7 +85,10 @@ impl PropCtx {
|
||||
}
|
||||
|
||||
fn theme_font(&self, t: &str) -> Option<String> {
|
||||
let f = if t.starts_with("major") { &self.major_font } else { &self.minor_font };
|
||||
let (latin, cs) = if t.starts_with("major") { (&self.major_font, &self.major_cs) } else { (&self.minor_font, &self.minor_cs) };
|
||||
// Measured in Word: `minorBidi`/`majorBidi` name the complex-script font, and an empty one
|
||||
// names nothing, so the font beside it or the inherited one applies.
|
||||
let f = if t.ends_with("Bidi") { cs } else { latin };
|
||||
(!f.is_empty()).then(|| f.clone())
|
||||
}
|
||||
|
||||
@@ -510,12 +516,24 @@ pub fn trpr(e: &El) -> RowProps {
|
||||
}
|
||||
"w:tblHeader" => r.header = on_off(k),
|
||||
"w:cantSplit" => r.cant_split = on_off(k),
|
||||
"w:gridBefore" => r.grid_before = k.attr("w:val").and_then(u32_of).unwrap_or(0).min(63),
|
||||
"w:gridAfter" => r.grid_after = k.attr("w:val").and_then(u32_of).unwrap_or(0).min(63),
|
||||
"w:wBefore" => r.w_before = gap_width(k),
|
||||
"w:wAfter" => r.w_after = gap_width(k),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// `w:wBefore`/`w:wAfter` in points: only a width in twips (`dxa`) is kept.
|
||||
fn gap_width(k: &El) -> Option<f32> {
|
||||
match k.attr("w:type") {
|
||||
None | Some("dxa") => tw(k, "w:w").filter(|v| *v >= 0.0).map(|v| v.min(crate::units::MAX_LEN_PT)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `w:tcPr`; returns the props and whether the cell is a legacy `hMerge` continuation.
|
||||
pub fn tcpr(pc: &PropCtx, e: &El) -> (CellProps, bool) {
|
||||
let mut c = CellProps { span: 1, ..Default::default() };
|
||||
@@ -540,13 +558,16 @@ pub fn tcpr(pc: &PropCtx, e: &El) -> (CellProps, bool) {
|
||||
"w:noWrap" => c.no_wrap = on_off(k),
|
||||
"w:hideMark" => c.hide_mark = on_off(k),
|
||||
"w:tcMar" => c.margins = Some(margins(k)),
|
||||
"w:textDirection" => c.text_direction = TextDirection::from_ooxml(k.attr("w:val").unwrap_or("")),
|
||||
"w:textDirection" => {
|
||||
c.text_direction = TextDirection::from_ooxml(k.attr("w:val").unwrap_or(""));
|
||||
c.text_direction_set = k.attr("w:val") == Some("lrTb");
|
||||
}
|
||||
"w:vAlign" => {
|
||||
c.valign = match k.attr("w:val") {
|
||||
c.valign = Some(match k.attr("w:val") {
|
||||
Some("center") => VAlign::Center,
|
||||
Some("bottom") => VAlign::Bottom,
|
||||
_ => VAlign::Top,
|
||||
}
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -629,14 +650,19 @@ pub fn sectpr(e: &El) -> (SectionProps, Vec<HfRef>) {
|
||||
}
|
||||
"w:footnotePr" => s.footnote_pr = note_pr(k, true),
|
||||
"w:endnotePr" => s.endnote_pr = note_pr(k, true),
|
||||
"w:formProt" => s.form_prot = Some(on_off(k)),
|
||||
"w:titlePg" => s.title_page = on_off(k),
|
||||
"w:bidi" => s.rtl = on_off(k),
|
||||
"w:textDirection" => s.text_direction = wordcraft_doc::props::TextDirection::from_ooxml(k.attr("w:val").unwrap_or("")),
|
||||
"w:textDirection" => {
|
||||
s.text_direction = wordcraft_doc::props::TextDirection::from_ooxml(k.attr("w:val").unwrap_or(""));
|
||||
s.text_direction_set = k.attr("w:val") == Some("lrTb");
|
||||
}
|
||||
"w:pgNumType" => {
|
||||
s.page_num_start = k.attr("w:start").and_then(u32_of);
|
||||
if let Some(f) = k.attr("w:fmt") {
|
||||
s.page_num_format = NumFormat::from_ooxml(f);
|
||||
}
|
||||
s.page_num_set = s.page_num_start.is_none() && s.page_num_format == NumFormat::Decimal;
|
||||
}
|
||||
"w:lnNumType" => {
|
||||
let mut l = LineNumbering::default();
|
||||
@@ -656,9 +682,10 @@ pub fn sectpr(e: &El) -> (SectionProps, Vec<HfRef>) {
|
||||
}
|
||||
"w:vAlign" => {
|
||||
s.valign = match k.attr("w:val") {
|
||||
Some("center") | Some("both") => VAlign::Center,
|
||||
Some("bottom") => VAlign::Bottom,
|
||||
_ => VAlign::Top,
|
||||
Some("center") => PageVAlign::Center,
|
||||
Some("both") => PageVAlign::Justify,
|
||||
Some("bottom") => PageVAlign::Bottom,
|
||||
_ => PageVAlign::Top,
|
||||
}
|
||||
}
|
||||
"w:pgBorders" => s.page_borders = Some(borders(k)),
|
||||
|
||||
@@ -29,7 +29,9 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind {
|
||||
"ellipse" | "wedgeEllipseCallout" | "cloudCallout" | "cloud" | "flowChartConnector" | "donut" | "flowChartOnlineStorage" => {
|
||||
ShapeKind::Ellipse
|
||||
}
|
||||
"triangle" | "rtTriangle" | "flowChartExtract" | "flowChartMerge" => ShapeKind::Triangle,
|
||||
"flowChartOr" => ShapeKind::FlowchartOr,
|
||||
"triangle" | "flowChartExtract" | "flowChartMerge" => ShapeKind::Triangle,
|
||||
"rtTriangle" => ShapeKind::RightTriangle,
|
||||
"diamond" | "flowChartDecision" => ShapeKind::Diamond,
|
||||
"line" | "lineInv" => ShapeKind::Line,
|
||||
"straightConnector1" => ShapeKind::StraightConnector,
|
||||
@@ -44,6 +46,65 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape kind drawn for a legacy VML preset shape type `spt` (`o:spt`, the MSOSPT numbers of
|
||||
/// [MS-ODRAW] §2.4.24): that of the DrawingML preset of the same shape, through [`preset_kind`],
|
||||
/// so a preset WordCraft has no shape for is drawn as the nearest one; None for shapes with no
|
||||
/// preset geometry (freeforms, WordArt text, picture frames) and numbers MSOSPT doesn't define.
|
||||
pub(crate) fn vml_preset_kind(spt: u32) -> Option<ShapeKind> {
|
||||
let prst = match spt {
|
||||
// A text box's shapetype: a text box even without text, as DrawingML's `txBox`.
|
||||
202 => return Some(ShapeKind::TextBox),
|
||||
// Not primitive (freeform), WordArt text shapes, picture frame, host control.
|
||||
0 | 24..=31 | 75 | 136..=175 | 201 => return None,
|
||||
// Line and straight connector: corner to corner of the shape's box.
|
||||
20 | 32 => "line",
|
||||
2 => "roundRect",
|
||||
3 => "ellipse",
|
||||
4 => "diamond",
|
||||
5 => "triangle",
|
||||
6 => "rtTriangle",
|
||||
12 => "star5",
|
||||
13 => "rightArrow",
|
||||
21 => "plaque",
|
||||
23 => "donut",
|
||||
33 => "bentConnector2",
|
||||
34 => "bentConnector3",
|
||||
35 => "bentConnector4",
|
||||
36 => "bentConnector5",
|
||||
37 => "curvedConnector2",
|
||||
38 => "curvedConnector3",
|
||||
39 => "curvedConnector4",
|
||||
40 => "curvedConnector5",
|
||||
58 => "star8",
|
||||
59 => "star16",
|
||||
60 => "star32",
|
||||
62 => "wedgeRoundRectCallout",
|
||||
63 => "wedgeEllipseCallout",
|
||||
66 => "leftArrow",
|
||||
67 => "downArrow",
|
||||
68 => "upArrow",
|
||||
69 => "leftRightArrow",
|
||||
70 => "upDownArrow",
|
||||
74 => "heart",
|
||||
92 => "star24",
|
||||
93 => "stripedRightArrow",
|
||||
94 => "notchedRightArrow",
|
||||
106 => "cloudCallout",
|
||||
110 => "flowChartDecision",
|
||||
116 => "flowChartTerminator",
|
||||
120 => "flowChartConnector",
|
||||
127 => "flowChartExtract",
|
||||
128 => "flowChartMerge",
|
||||
130 => "flowChartOnlineStorage",
|
||||
176 => "flowChartAlternateProcess",
|
||||
187 => "star4",
|
||||
// Every other preset is drawn as its box, as `preset_kind` does.
|
||||
1..=201 => "rect",
|
||||
_ => return None,
|
||||
};
|
||||
Some(preset_kind(prst))
|
||||
}
|
||||
|
||||
/// A shape's fill and outline.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(crate) struct ShapePaint {
|
||||
@@ -122,6 +183,11 @@ mod tests {
|
||||
assert_eq!(p.fill, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flowchart_or_keeps_its_spokes() {
|
||||
assert_eq!(preset_kind("flowChartOr"), ShapeKind::FlowchartOr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_paint_wins_over_the_style() {
|
||||
let sp = el(r#"<wps:spPr xmlns:wps="w" xmlns:a="a"><a:noFill/><a:ln><a:solidFill><a:srgbClr val="EE0000"/></a:solidFill></a:ln></wps:spPr>"#);
|
||||
@@ -166,6 +232,26 @@ mod tests {
|
||||
assert_eq!(preset_kind("flowChartDecision"), ShapeKind::Diamond);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vml_presets_map_like_drawingml_presets() {
|
||||
assert_eq!(vml_preset_kind(13), Some(ShapeKind::Arrow));
|
||||
assert_eq!(vml_preset_kind(12), Some(ShapeKind::Star));
|
||||
assert_eq!(vml_preset_kind(32), Some(ShapeKind::Line));
|
||||
assert_eq!(vml_preset_kind(202), Some(ShapeKind::TextBox));
|
||||
// The nearest shape, as `preset_kind` gives it: left arrow, right triangle, four-point
|
||||
// star, rounded callout, elbow connector, a bevel (its box).
|
||||
assert_eq!(vml_preset_kind(66), Some(ShapeKind::Arrow));
|
||||
assert_eq!(vml_preset_kind(6), Some(ShapeKind::RightTriangle));
|
||||
assert_eq!(vml_preset_kind(187), Some(ShapeKind::Star));
|
||||
assert_eq!(vml_preset_kind(62), Some(ShapeKind::RoundedRectangle));
|
||||
assert_eq!(vml_preset_kind(34), Some(ShapeKind::ElbowConnector));
|
||||
assert_eq!(vml_preset_kind(84), Some(ShapeKind::Rectangle));
|
||||
// No preset geometry: freeform, WordArt text, picture frame, host control, out of range.
|
||||
for spt in [0, 24, 31, 136, 175, 75, 201, 203, u32::MAX] {
|
||||
assert_eq!(vml_preset_kind(spt), None, "{spt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vml_colours() {
|
||||
assert_eq!(vml_color("#ffc000 [3207]"), Some(Rgb(0xFF, 0xC0, 0)));
|
||||
|
||||
+249
-41
@@ -7,13 +7,13 @@ use wordcraft_doc::control::{ContentControl, ControlKind, ControlWrap};
|
||||
use wordcraft_doc::effects::{Glow, Shadow, ShapeEffects};
|
||||
use wordcraft_doc::graphic::{Embedded, Graphic, GraphicItem, GraphicKind};
|
||||
use wordcraft_doc::para::{AltText, Anchor, Float, FloatAlign, NoteKind, ShapeKind, Wrap, WrapText, cap_alt};
|
||||
use wordcraft_doc::props::{CharProps, NumChange, PropChange, Rgb};
|
||||
use wordcraft_doc::props::{CharProps, NumChange, PropChange, Rgb, TextColor};
|
||||
use wordcraft_doc::table::{Cell, MAX_COLS, MAX_ROWS, Row, Table};
|
||||
use wordcraft_doc::{Block, Blocks, InlineObject, Paragraph, PartKind, RevisionKind, Run, para_block};
|
||||
|
||||
use super::Reader;
|
||||
use super::props::{sectpr, tcpr, trpr};
|
||||
use super::shape_style::{preset_kind, shape_paint, vml_color};
|
||||
use super::shape_style::{preset_kind, shape_paint, vml_color, vml_preset_kind};
|
||||
use crate::package::{ContentTypes, Rels, rt};
|
||||
use crate::units::{int, measure, u32_of};
|
||||
use crate::xml::{El, Node};
|
||||
@@ -21,6 +21,8 @@ use wordcraft_doc::wordart::TextWarp;
|
||||
|
||||
const INK_URI: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingInk";
|
||||
const INK_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
|
||||
/// The `a:graphicData` URI of an Office 2016 chart (`cx:chart`).
|
||||
const CHARTEX_URI: &str = "http://schemas.microsoft.com/office/drawing/2014/chartex";
|
||||
|
||||
/// Deepest table nesting we build (deeper tables become plain paragraphs).
|
||||
const MAX_TABLE_DEPTH: usize = 24;
|
||||
@@ -30,6 +32,8 @@ const MAX_FIELD_DEPTH: usize = 32;
|
||||
const MAX_STORY_DEPTH: usize = 4;
|
||||
/// Longest field code we keep (Zotero's citation codes embed item data as JSON).
|
||||
const MAX_INSTR: usize = 2 * 1024 * 1024;
|
||||
/// Longest legacy form field definition (`w:ffData`) we keep.
|
||||
const MAX_FORM: usize = 64 * 1024;
|
||||
|
||||
/// Inherited run context (from `w:hyperlink`, `w:ins`, `w:del` wrappers).
|
||||
#[derive(Clone, Default)]
|
||||
@@ -59,12 +63,16 @@ struct FieldState {
|
||||
buf: Vec<(Item, CharProps)>,
|
||||
props: CharProps,
|
||||
locked: bool,
|
||||
/// `w:dirty` from the begin marker: the result is stale, Word refreshes it on open.
|
||||
dirty: bool,
|
||||
/// Kept as a range field: its result flows into the document as ordinary content between
|
||||
/// `FieldStart` and `FieldEnd` markers instead of being buffered.
|
||||
range: bool,
|
||||
/// The font size of each piece of the code (where it starts in `instr`): an enclosure's
|
||||
/// style is the size of its symbol and text (see [`wordcraft_doc::eq`]).
|
||||
sizes: Vec<(usize, Option<f32>)>,
|
||||
/// A legacy form field's `w:ffData`, as raw XML.
|
||||
form: String,
|
||||
}
|
||||
|
||||
/// Enclosed characters (`eq \o\ac(○,字)`), with their style from the code's font sizes: Word
|
||||
@@ -119,6 +127,8 @@ pub struct StoryCtx {
|
||||
pending: Vec<InlineObject>,
|
||||
/// Text-box nesting depth.
|
||||
pub story_depth: usize,
|
||||
/// Reading a header or footer (not a text box inside one): where Word keeps its watermark.
|
||||
pub in_hf: bool,
|
||||
}
|
||||
|
||||
/// Paragraph content under construction.
|
||||
@@ -389,6 +399,11 @@ impl Reader<'_> {
|
||||
para.text = pb.text;
|
||||
para.runs = pb.runs;
|
||||
para.objects = pb.objects;
|
||||
// Paragraph boundaries inside an instruction are hidden with the field code.
|
||||
// The result paragraph still takes a line, even when its cached text is empty.
|
||||
if sc.fields.iter().any(|f| f.phase == Phase::Instr) && para.plain_text().is_empty() {
|
||||
para.mark.hidden = Some(true);
|
||||
}
|
||||
para.normalize();
|
||||
para
|
||||
}
|
||||
@@ -439,7 +454,7 @@ impl Reader<'_> {
|
||||
"w:r" => self.read_run(sc, pb, k, rels, ctx, depth),
|
||||
"w:hyperlink" => {
|
||||
let mut c = ctx.clone();
|
||||
let url = k.attr("r:id").and_then(|id| rels.by_id(id)).map(|r| r.target.clone());
|
||||
let url = k.attr("r:id").and_then(|id| rels.by_id(id)).map(|r| r.target.trim().to_string()).filter(|u| !u.is_empty());
|
||||
let anchor = k.attr("w:anchor").filter(|a| !a.is_empty());
|
||||
c.link = match (url, anchor) {
|
||||
(Some(u), Some(a)) => Some(format!("{u}#{a}")),
|
||||
@@ -463,7 +478,7 @@ impl Reader<'_> {
|
||||
"w:fldSimple" => {
|
||||
let instr = k.attr("w:instr").unwrap_or("").to_string();
|
||||
let props = k.child("w:r").and_then(|r| r.child("w:rPr")).map(|p| self.run_props(p, ctx)).unwrap_or_else(|| self.run_props_none(ctx));
|
||||
self.begin_field(sc, props, instr, on_off_attr(k, "w:fldLock"));
|
||||
self.begin_field(sc, props, instr, on_off_attr(k, "w:fldLock"), on_off_attr(k, "w:dirty"), String::new());
|
||||
self.separate_field(sc, pb);
|
||||
self.read_inline_children(sc, pb, k, rels, ctx, depth + 1);
|
||||
self.end_field(sc, pb);
|
||||
@@ -496,8 +511,11 @@ impl Reader<'_> {
|
||||
}
|
||||
"w:smartTag" | "w:customXml" | "w:dir" | "w:bdo" => self.read_inline_children(sc, pb, k, rels, ctx, depth + 1),
|
||||
"m:oMath" => {
|
||||
let props = self.run_props_none(ctx);
|
||||
let math = super::math::read_omath(k, Default::default());
|
||||
let mut props = self.run_props_none(ctx);
|
||||
let mut math = super::math::read_omath(k, Default::default());
|
||||
if let Some(c) = super::math::lift_color(&mut math) {
|
||||
props.color = Some(TextColor::Rgb(c));
|
||||
}
|
||||
let linear = wordcraft_doc::math::to_linear(&math.nodes);
|
||||
self.emit_obj(sc, pb, InlineObject::Equation { linear, display: false, math }, &props);
|
||||
}
|
||||
@@ -505,13 +523,17 @@ impl Reader<'_> {
|
||||
let props = self.run_props_none(ctx);
|
||||
let jc = super::math::para_jc(k);
|
||||
for m in k.children("m:oMath") {
|
||||
let math = super::math::read_omath(m, jc);
|
||||
let mut math = super::math::read_omath(m, jc);
|
||||
let mut props = props.clone();
|
||||
if let Some(c) = super::math::lift_color(&mut math) {
|
||||
props.color = Some(TextColor::Rgb(c));
|
||||
}
|
||||
let linear = wordcraft_doc::math::to_linear(&math.nodes);
|
||||
self.emit_obj(sc, pb, InlineObject::Equation { linear, display: true, math }, &props);
|
||||
}
|
||||
}
|
||||
"mc:AlternateContent" => {
|
||||
if let Some(o) = self.read_ink_alternate(sc, k, rels) {
|
||||
if let Some(o) = self.read_ink_alternate(sc, k, rels).or_else(|| self.read_chartex_alternate(sc, k, rels)) {
|
||||
let props = self.run_props_none(ctx);
|
||||
self.emit_obj(sc, pb, o, &props);
|
||||
} else if let Some(c) = children_of_choice(k) {
|
||||
@@ -598,6 +620,9 @@ impl Reader<'_> {
|
||||
}
|
||||
"w:tab" | "w:ptab" => self.emit_text(sc, pb, "\t", props),
|
||||
"w:br" => {
|
||||
if sc.fields.iter().any(|f| f.phase == Phase::Instr) {
|
||||
return;
|
||||
}
|
||||
let c = match k.attr("w:type") {
|
||||
Some("page") => "\u{000C}",
|
||||
Some("column") => "\u{000E}",
|
||||
@@ -605,7 +630,11 @@ impl Reader<'_> {
|
||||
};
|
||||
self.emit_text(sc, pb, c, props);
|
||||
}
|
||||
"w:cr" => self.emit_text(sc, pb, "\n", props),
|
||||
"w:cr" => {
|
||||
if !sc.fields.iter().any(|f| f.phase == Phase::Instr) {
|
||||
self.emit_text(sc, pb, "\n", props);
|
||||
}
|
||||
}
|
||||
"w:noBreakHyphen" => self.emit_text(sc, pb, "\u{2011}", props),
|
||||
"w:softHyphen" => self.emit_text(sc, pb, "\u{00AD}", props),
|
||||
"w:sym" => {
|
||||
@@ -619,7 +648,10 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
"w:fldChar" => match k.attr("w:fldCharType") {
|
||||
Some("begin") => self.begin_field(sc, props.clone(), String::new(), on_off_attr(k, "w:fldLock")),
|
||||
Some("begin") => {
|
||||
let form = k.child("w:ffData").map(|f| f.to_xml()).filter(|x| x.len() <= MAX_FORM).unwrap_or_default();
|
||||
self.begin_field(sc, props.clone(), String::new(), on_off_attr(k, "w:fldLock"), on_off_attr(k, "w:dirty"), form)
|
||||
}
|
||||
Some("separate") => self.separate_field(sc, pb),
|
||||
Some("end") => self.end_field(sc, pb),
|
||||
_ => {}
|
||||
@@ -675,12 +707,15 @@ impl Reader<'_> {
|
||||
pb.push_obj(InlineObject::CommentEnd { id: cid }, props);
|
||||
}
|
||||
}
|
||||
"w:pgNum" => {
|
||||
self.emit_obj(sc, pb, InlineObject::Field { instr: "PAGE".into(), result: String::new(), locked: false, code: false }, props)
|
||||
}
|
||||
"w:pgNum" => self.emit_obj(
|
||||
sc,
|
||||
pb,
|
||||
InlineObject::Field { instr: "PAGE".into(), result: String::new(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
props,
|
||||
),
|
||||
"w:ruby" => self.read_ruby(sc, pb, k, props),
|
||||
"mc:AlternateContent" => {
|
||||
if let Some(o) = self.read_ink_alternate(sc, k, rels) {
|
||||
if let Some(o) = self.read_ink_alternate(sc, k, rels).or_else(|| self.read_chartex_alternate(sc, k, rels)) {
|
||||
self.emit_obj(sc, pb, o, props);
|
||||
} else if let Some(c) = children_of_choice(k) {
|
||||
for x in c.els() {
|
||||
@@ -749,13 +784,24 @@ impl Reader<'_> {
|
||||
|
||||
// ---- fields ----
|
||||
|
||||
fn begin_field(&mut self, sc: &mut StoryCtx, props: CharProps, instr: String, locked: bool) {
|
||||
fn begin_field(&mut self, sc: &mut StoryCtx, props: CharProps, instr: String, locked: bool, dirty: bool, form: String) {
|
||||
if sc.fields.len() >= MAX_FIELD_DEPTH || sc.ignored_begins > 0 {
|
||||
sc.ignored_begins += 1;
|
||||
return;
|
||||
}
|
||||
// Fields nested deeper than the cap are ignored (their content flows to the enclosing field).
|
||||
sc.fields.push(FieldState { instr, phase: Phase::Instr, spilled: false, buf: Vec::new(), props, locked, range: false, sizes: Vec::new() });
|
||||
sc.fields.push(FieldState {
|
||||
instr,
|
||||
phase: Phase::Instr,
|
||||
spilled: false,
|
||||
buf: Vec::new(),
|
||||
props,
|
||||
locked,
|
||||
dirty,
|
||||
range: false,
|
||||
sizes: Vec::new(),
|
||||
form,
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the field below the innermost one is still collecting its code (a field nested
|
||||
@@ -778,7 +824,7 @@ impl Reader<'_> {
|
||||
f.phase = Phase::Result;
|
||||
if !f.spilled && !nested_in_instr && is_range_instr(&f.instr) {
|
||||
f.range = true;
|
||||
let (obj, props) = (InlineObject::FieldStart { instr: f.instr.trim().to_string(), locked: f.locked }, f.props.clone());
|
||||
let (obj, props) = (InlineObject::FieldStart { instr: f.instr.trim().to_string(), locked: f.locked, dirty: f.dirty }, f.props.clone());
|
||||
self.emit_obj(sc, pb, obj, &props);
|
||||
}
|
||||
}
|
||||
@@ -799,15 +845,19 @@ impl Reader<'_> {
|
||||
}
|
||||
if f.phase == Phase::Instr && !nested_in_instr && is_range_instr(&f.instr) {
|
||||
// A range field with no result yet.
|
||||
self.emit_obj(sc, pb, InlineObject::FieldStart { instr: f.instr.trim().to_string(), locked: f.locked }, &f.props);
|
||||
self.emit_obj(sc, pb, InlineObject::FieldStart { instr: f.instr.trim().to_string(), locked: f.locked, dirty: f.dirty }, &f.props);
|
||||
self.emit_obj(sc, pb, InlineObject::FieldEnd, &f.props);
|
||||
return;
|
||||
}
|
||||
// A cached result holding a picture, chart or shape (`INCLUDEPICTURE`'s embedded
|
||||
// picture) can't be a text result: keep the field as a range around it so the picture
|
||||
// stays in the document and is saved again. The linked source is never read.
|
||||
if !nested_in_instr && f.buf.iter().any(|(it, _)| matches!(it, Item::Obj(o) if o.frame().is_some())) {
|
||||
self.emit_obj(sc, pb, InlineObject::FieldStart { instr: f.instr.trim().to_string(), locked: f.locked }, &f.props);
|
||||
// A tracked insertion or deletion inside the result (one the field itself isn't wrapped
|
||||
// in) keeps the field a range too: a cached text result has one revision at most, so
|
||||
// each piece stays an ordinary run with its own `w:ins` / `w:del` (#1037).
|
||||
let tracked_inside = f.buf.iter().any(|(_, p)| (p.ins, p.del) != (f.props.ins, f.props.del));
|
||||
if !nested_in_instr && (tracked_inside || f.buf.iter().any(|(it, _)| matches!(it, Item::Obj(o) if o.frame().is_some()))) {
|
||||
self.emit_obj(sc, pb, InlineObject::FieldStart { instr: f.instr.trim().to_string(), locked: f.locked, dirty: f.dirty }, &f.props);
|
||||
for (it, p) in f.buf {
|
||||
match it {
|
||||
Item::Text(t) => self.emit_text(sc, pb, &t, &p),
|
||||
@@ -829,7 +879,7 @@ impl Reader<'_> {
|
||||
Some(e) => (e.instr(), if result.is_empty() { e.text } else { result }),
|
||||
None => (f.instr.trim().to_string(), result),
|
||||
};
|
||||
let obj = InlineObject::Field { instr, result, locked: f.locked, code: false };
|
||||
let obj = InlineObject::Field { instr, result, locked: f.locked, dirty: f.dirty, code: false, form: f.form };
|
||||
if let Some(parent) = sc.fields.last_mut()
|
||||
&& !parent.spilled
|
||||
&& parent.phase == Phase::Instr
|
||||
@@ -848,7 +898,11 @@ impl Reader<'_> {
|
||||
continue;
|
||||
}
|
||||
f.spilled = true;
|
||||
pb.push_obj(InlineObject::Field { instr: f.instr.trim().to_string(), result: String::new(), locked: f.locked, code: false }, &f.props);
|
||||
let form = std::mem::take(&mut f.form);
|
||||
pb.push_obj(
|
||||
InlineObject::Field { instr: f.instr.trim().to_string(), result: String::new(), locked: f.locked, dirty: f.dirty, code: false, form },
|
||||
&f.props,
|
||||
);
|
||||
for (it, p) in f.buf.drain(..) {
|
||||
match it {
|
||||
Item::Text(t) => pb.push_text(&t, &p),
|
||||
@@ -1004,6 +1058,29 @@ impl Reader<'_> {
|
||||
Some(object)
|
||||
}
|
||||
|
||||
/// An Office 2016 chart (`cx:chart`: waterfall, sunburst, box & whisker…) drawn from its
|
||||
/// fallback picture, keeping both branches so saving writes the chart back rather than only
|
||||
/// the picture. `None` (read the fallback alone) when it can't be kept whole.
|
||||
fn read_chartex_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let choice = ac
|
||||
.children("mc:Choice")
|
||||
.find(|c| c.child("w:drawing").and_then(|d| d.find("a:graphicData")).and_then(|g| g.attr("uri")) == Some(CHARTEX_URI))?;
|
||||
// A requirement in a namespace we can't name couldn't be written back.
|
||||
let requires = choice.attr("Requires").unwrap_or("");
|
||||
if requires.split_whitespace().next().is_none() || requires.split_whitespace().any(|p| p == "?") {
|
||||
return None;
|
||||
}
|
||||
let fallback = ac.child("mc:Fallback")?;
|
||||
let kept = El { name: "mc:AlternateContent".into(), attrs: Vec::new(), kids: vec![Node::El(choice.clone()), Node::El(fallback.clone())] };
|
||||
let source = self.keep_embedded(&kept, rels, &[])?;
|
||||
let Some(InlineObject::Image { media, w, h, alt, float, .. }) = self.read_drawing(sc, fallback.child("w:drawing")?, rels) else {
|
||||
return None;
|
||||
};
|
||||
let items = vec![GraphicItem::Image { rect: [0.0, 0.0, w, h], media }];
|
||||
let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() });
|
||||
Some(InlineObject::Graphic { w, h, alt, float, graphic })
|
||||
}
|
||||
|
||||
fn read_ink_content_part(&mut self, content: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let part = super::part_of(rels, content.attr("r:id")?, INK_REL)?;
|
||||
let pkg = self.pkg;
|
||||
@@ -1251,6 +1328,14 @@ impl Reader<'_> {
|
||||
part.body.auto_fit = bp.child("a:spAutoFit").is_some();
|
||||
}
|
||||
let mut extra = ShapeExtra::default();
|
||||
// A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56); other presets drawn as
|
||||
// rounded rectangles keep the default.
|
||||
if prst == "roundRect" {
|
||||
extra.corner = sppr
|
||||
.and_then(|s| s.child("a:prstGeom"))
|
||||
.and_then(|g| preset_adj(g, "adj"))
|
||||
.and_then(|v| u32::try_from(v.clamp(0, i64::from(wordcraft_doc::connector::MAX_CORNER))).ok());
|
||||
}
|
||||
// Arrowheads: any end type but `none` (ECMA-376 §20.1.10.33) is drawn as a triangle.
|
||||
let arrow = |tag: &str| ln.and_then(|l| l.child(tag)).and_then(|e| e.attr("type")).is_some_and(|t| t != "none");
|
||||
extra.arrow_start = arrow("a:headEnd");
|
||||
@@ -1295,9 +1380,16 @@ impl Reader<'_> {
|
||||
self.doc.add_part(PartKind::TextBox, blocks)
|
||||
}
|
||||
|
||||
/// Legacy VML pictures, text boxes, lines, rectangles and ovals (best effort).
|
||||
/// Legacy VML pictures, text boxes, lines, rectangles, ovals and preset shapes (best effort).
|
||||
fn read_vml(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let shape = pict.els().find(|e| e.name.starts_with("v:") && e.local() != "shapetype")?;
|
||||
if sc.in_hf
|
||||
&& let Some(wm) = vml_watermark(shape)
|
||||
{
|
||||
// The document's watermark (the first one found); drawn on every page, not as a shape.
|
||||
self.doc.settings.watermark.get_or_insert(wm);
|
||||
return None;
|
||||
}
|
||||
let style = shape.attr("style").unwrap_or("");
|
||||
let len = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
|
||||
let (mut w, mut h) = (len("width"), len("height"));
|
||||
@@ -1308,10 +1400,26 @@ impl Reader<'_> {
|
||||
let alt = shape.attr("alt").or_else(|| img.attr("o:title")).unwrap_or("").to_string();
|
||||
return Some(InlineObject::Image { media, w, h, alt, float, crop: [0.0; 4], ole: None });
|
||||
}
|
||||
let on = |name: &str| shape.attr(name).is_none_or(|v| !matches!(v, "f" | "false" | "0"));
|
||||
let stroke = on("stroked").then(|| shape.attr("strokecolor").map_or(Some(Rgb::BLACK), vml_color)).flatten();
|
||||
let stroke_width = shape.attr("strokeweight").and_then(|v| measure(v, 1.0)).unwrap_or(0.75).clamp(0.0, 100.0);
|
||||
let fill = on("filled").then(|| shape.attr("fillcolor").map_or(Some(Rgb::WHITE), vml_color)).flatten();
|
||||
// The shapetype the shape is drawn from (its `type`, ECMA-376 Part 4 VML), when written in
|
||||
// the same picture: what the shape leaves out, it takes from there.
|
||||
let type_id = shape.attr("type").map(|t| t.trim().trim_start_matches('#'));
|
||||
let shapetype = type_id.and_then(|id| pict.els().find(|e| e.name == "v:shapetype" && e.attr("id") == Some(id)));
|
||||
let attr = |name: &str| shape.attr(name).or_else(|| shapetype.and_then(|t| t.attr(name)));
|
||||
let on = |name: &str| attr(name).is_none_or(|v| !matches!(v, "f" | "false" | "0"));
|
||||
let stroke = on("stroked").then(|| attr("strokecolor").map_or(Some(Rgb::BLACK), vml_color)).flatten();
|
||||
let stroke_width = attr("strokeweight").and_then(|v| measure(v, 1.0)).unwrap_or(0.75).clamp(0.0, 100.0);
|
||||
let fill = on("filled").then(|| attr("fillcolor").map_or(Some(Rgb::WHITE), vml_color)).flatten();
|
||||
let kind = match shape.local() {
|
||||
"line" => Some(ShapeKind::Line),
|
||||
"rect" => Some(ShapeKind::Rectangle),
|
||||
"roundrect" => Some(ShapeKind::RoundedRectangle),
|
||||
"oval" => Some(ShapeKind::Ellipse),
|
||||
// A preset, unless the shape's own path replaces its shapetype's geometry.
|
||||
"shape" if shape.attr("path").is_none() && shape.child("v:path").and_then(|p| p.attr("v")).is_none() => {
|
||||
vml_spt(shape, shapetype, type_id).and_then(vml_preset_kind)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((tb, t)) = vml_textbox(shape, 0)
|
||||
&& sc.story_depth < MAX_STORY_DEPTH
|
||||
{
|
||||
@@ -1341,8 +1449,10 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
let story = Some(id);
|
||||
// Text in a preset shape keeps the shape around it; otherwise it is a text box.
|
||||
let kind = kind.filter(|k| *k != ShapeKind::Rectangle && !k.is_open()).unwrap_or(ShapeKind::TextBox);
|
||||
return Some(InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
kind,
|
||||
w,
|
||||
h,
|
||||
fill,
|
||||
@@ -1355,16 +1465,46 @@ impl Reader<'_> {
|
||||
extra: Default::default(),
|
||||
});
|
||||
}
|
||||
let kind = match shape.local() {
|
||||
"line" => ShapeKind::Line,
|
||||
"rect" => ShapeKind::Rectangle,
|
||||
"roundrect" => ShapeKind::RoundedRectangle,
|
||||
"oval" => ShapeKind::Ellipse,
|
||||
_ => return None,
|
||||
};
|
||||
// A freeform: its `path`, in its `coordsize` space; a `v:fill` with no opacity
|
||||
// or `nf` in the path leaves it unfilled. Not WordArt (`v:textpath`).
|
||||
if shape.local() == "shape"
|
||||
&& shape.child("v:textpath").is_none()
|
||||
&& let Some(path) = shape.attr("path")
|
||||
&& let Some(vp) = super::freeform::vml_path(path, shape.attr("coordsize"), shape.attr("coordorigin"), w, h)
|
||||
{
|
||||
let opacity = |el: &str| shape.child(el).and_then(|e| e.attr("opacity")).and_then(vml_fraction).unwrap_or(1.0);
|
||||
let fill = fill.filter(|_| !vp.no_fill && opacity("v:fill") > 0.0);
|
||||
let stroke = stroke.filter(|_| !vp.no_stroke);
|
||||
if stroke.is_none() && fill.is_none() {
|
||||
return None;
|
||||
}
|
||||
let mut f = vp.freeform;
|
||||
f.alpha = opacity("v:stroke");
|
||||
return Some(InlineObject::Shape {
|
||||
kind: ShapeKind::Freeform,
|
||||
w,
|
||||
h,
|
||||
fill,
|
||||
stroke,
|
||||
stroke_width,
|
||||
float,
|
||||
story: None,
|
||||
freeform: Some(Arc::new(f)),
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
});
|
||||
}
|
||||
let kind = kind?;
|
||||
let mut extra = ShapeExtra::default();
|
||||
if kind == ShapeKind::Line {
|
||||
// A line runs `from` → `to` (points, offsets from where its style places it).
|
||||
// Arrowheads (`v:stroke` startarrow / endarrow): any but `none` is drawn.
|
||||
let arrow = |name: &str| shape.child("v:stroke").and_then(|s| s.attr(name)).is_some_and(|v| v != "none");
|
||||
extra.arrow_start = arrow("startarrow");
|
||||
extra.arrow_end = arrow("endarrow");
|
||||
}
|
||||
if shape.local() == "line" {
|
||||
// A line runs `from` → `to` (points, offsets from where its style places it). A preset
|
||||
// line (`v:shape`) runs corner to corner of the box its style gives it.
|
||||
let pt = |name: &str| -> (f32, f32) {
|
||||
let v = shape.attr(name).unwrap_or("0,0");
|
||||
let (x, y) = v.split_once(',').unwrap_or((v, "0"));
|
||||
@@ -1379,10 +1519,6 @@ impl Reader<'_> {
|
||||
// Drawn top-left to bottom-right; flipped for the other directions.
|
||||
float.flip_h ^= x1 < x0;
|
||||
float.flip_v ^= y1 < y0;
|
||||
// Arrowheads (`v:stroke` startarrow / endarrow): any but `none` is drawn.
|
||||
let arrow = |name: &str| shape.child("v:stroke").and_then(|s| s.attr(name)).is_some_and(|v| v != "none");
|
||||
extra.arrow_start = arrow("startarrow");
|
||||
extra.arrow_end = arrow("endarrow");
|
||||
}
|
||||
if stroke.is_none() && (fill.is_none() || kind == ShapeKind::Line) {
|
||||
return None;
|
||||
@@ -1440,6 +1576,7 @@ impl Reader<'_> {
|
||||
collect(t, "w:tr", &mut rows, &mut Vec::new(), 0);
|
||||
for (tr, row_controls) in rows.into_iter().take(MAX_ROWS) {
|
||||
let mut row = Row { props: tr.child("w:trPr").map(trpr).unwrap_or_default(), cells: Vec::new(), controls: row_controls };
|
||||
row.props.exceptions = tr.child("w:tblPrEx").map(|e| Box::new(self.pc.tblpr(e)));
|
||||
if let Some(ch) = tr.child("w:trPr").and_then(|p| p.child("w:trPrChange")) {
|
||||
let old = ch.child("w:trPr").map(trpr).unwrap_or_default();
|
||||
row.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old);
|
||||
@@ -1540,7 +1677,13 @@ fn nv_alt(p: Option<&El>) -> (String, AltText) {
|
||||
fn anchor_float(c: &El) -> Float {
|
||||
let mut f = Float { wrap: Wrap::Square, ..Float::default() };
|
||||
let behind = on_off_attr(c, "behindDoc");
|
||||
for k in c.els() {
|
||||
// Word wraps a position relative to the page's size (`wp14:pctPosVOffset`) in
|
||||
// `mc:AlternateContent`; its Fallback gives the same position as an offset (#743).
|
||||
let kids = c.els().flat_map(|k| match k.name.as_str() {
|
||||
"mc:AlternateContent" => k.child("mc:Fallback").map(|f| f.els().collect()).unwrap_or_default(),
|
||||
_ => vec![k],
|
||||
});
|
||||
for k in kids {
|
||||
match k.name.as_str() {
|
||||
"wp:wrapSquare" => {
|
||||
f.wrap = Wrap::Square;
|
||||
@@ -1616,6 +1759,17 @@ fn wrap_polygon(e: &El) -> Option<wordcraft_doc::wrap::WrapPolygon> {
|
||||
wordcraft_doc::wrap::WrapPolygon::new(edited, pts)
|
||||
}
|
||||
|
||||
/// A VML shape's preset type (`o:spt`): its own, its shapetype's, or the number in Word's
|
||||
/// shapetype id `_x0000_tNN` (`type_id`), Word writing each shapetype only at its first use.
|
||||
fn vml_spt(shape: &El, shapetype: Option<&El>, type_id: Option<&str>) -> Option<u32> {
|
||||
let num = |v: &str| v.trim().parse::<u32>().ok();
|
||||
shape
|
||||
.attr("o:spt")
|
||||
.and_then(num)
|
||||
.or_else(|| shapetype.and_then(|t| t.attr("o:spt")).and_then(num))
|
||||
.or_else(|| type_id?.strip_prefix("_x0000_t").and_then(num))
|
||||
}
|
||||
|
||||
/// The value of property `key` in a VML `style` attribute (CSS declarations; the last one wins).
|
||||
/// The first `v:textbox` under `e` holding text, with its `w:txbxContent` (depth-first, bounded
|
||||
/// like `El::find`): in a group, a member's margins go with that member's text.
|
||||
@@ -1698,6 +1852,54 @@ fn vml_float(shape: &El, style: &str) -> Float {
|
||||
f
|
||||
}
|
||||
|
||||
/// Word's text watermark (Design › Watermark): a VML shape in a header whose `v:textpath` draws
|
||||
/// its `string` as text (ECMA-376 Part 4, VML `textpath`), in the textpath's `font-family`, filled
|
||||
/// with the shape's `fillcolor`, semitransparent when its `v:fill` has an `opacity` below 1, and
|
||||
/// diagonal when the shape is turned. Only Word's watermark shape counts (its `id`), or text
|
||||
/// placed absolutely and centred both ways; other header WordArt (a logo or a title) is None.
|
||||
fn vml_watermark(shape: &El) -> Option<wordcraft_doc::Watermark> {
|
||||
let tp = shape.child("v:textpath")?;
|
||||
if tp.attr("on").is_some_and(|v| matches!(v, "f" | "false" | "0")) {
|
||||
return None;
|
||||
}
|
||||
let style = shape.attr("style").unwrap_or("");
|
||||
let centred = |k: &str| vml_style(style, k).is_some_and(|v| v.eq_ignore_ascii_case("center"));
|
||||
let word = shape.attr("id").is_some_and(|id| id.starts_with("PowerPlusWaterMarkObject"));
|
||||
let placed = vml_style(style, "position").is_some_and(|p| p.eq_ignore_ascii_case("absolute"))
|
||||
&& centred("mso-position-horizontal")
|
||||
&& centred("mso-position-vertical");
|
||||
if !word && !placed {
|
||||
return None;
|
||||
}
|
||||
let text: String = tp.attr("string")?.chars().take(200).collect();
|
||||
if text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let default = wordcraft_doc::Watermark::default();
|
||||
let font = tp
|
||||
.attr("style")
|
||||
.and_then(|s| vml_style(s, "font-family"))
|
||||
.map(|f| f.trim_matches(|c: char| c == '"' || c == '\'' || c.is_whitespace()).chars().take(100).collect::<String>())
|
||||
.filter(|f| !f.is_empty())
|
||||
.unwrap_or(default.font);
|
||||
let color = shape.attr("fillcolor").and_then(vml_color).unwrap_or(default.color);
|
||||
let opacity = shape.child("v:fill").and_then(|f| f.attr("opacity")).and_then(vml_fraction).unwrap_or(1.0);
|
||||
Some(wordcraft_doc::Watermark { text, font, color, diagonal: vml_spin(style).deg != 0.0, semitransparent: opacity < 1.0 })
|
||||
}
|
||||
|
||||
/// A VML fraction (`opacity`): a number, a percentage, or 65536ths with an `f` suffix; 0..=1.
|
||||
fn vml_fraction(v: &str) -> Option<f32> {
|
||||
let v = v.trim();
|
||||
let f = if let Some(n) = v.strip_suffix('f') {
|
||||
n.trim().parse::<f32>().ok()? / 65_536.0
|
||||
} else if let Some(n) = v.strip_suffix('%') {
|
||||
n.trim().parse::<f32>().ok()? / 100.0
|
||||
} else {
|
||||
v.parse::<f32>().ok()?
|
||||
};
|
||||
f.is_finite().then(|| f.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// A VML shape's turn: `rotation` in degrees, or 65536ths of one with an `fd` suffix; `flip`: `x`
|
||||
/// and/or `y`.
|
||||
fn vml_spin(style: &str) -> wordcraft_geom::Spin {
|
||||
@@ -1730,6 +1932,12 @@ fn text_warp(e: &El) -> Option<TextWarp> {
|
||||
Some(w)
|
||||
}
|
||||
|
||||
/// A preset geometry's adjust value `name` (`a:avLst/a:gd` with `fmla="val N"`).
|
||||
fn preset_adj(geom: &El, name: &str) -> Option<i64> {
|
||||
let gd = geom.child("a:avLst")?.children("a:gd").find(|g| g.attr("name") == Some(name))?;
|
||||
gd.attr("fmla")?.trim().strip_prefix("val")?.trim().parse::<i64>().ok()
|
||||
}
|
||||
|
||||
fn effect_list(l: &El) -> ShapeEffects {
|
||||
let pt = |e: &El, n: &str| e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0);
|
||||
let shadow = l.child("a:outerShdw").map(|e| {
|
||||
|
||||
@@ -14,7 +14,8 @@ use wordcraft_doc::para::Float;
|
||||
|
||||
use super::PartRels;
|
||||
use crate::package::{
|
||||
CUSTOM_XML_ROOTS, EMBEDDED_PARTS, EmbeddedManifest, MAX_EMBEDDED_PARTS, MAX_EMBEDDED_RELS, VBA_PROJECT_PART, VBA_RELATED, rel_is, relative, rt,
|
||||
CUSTOM_XML_ROOTS, EMBEDDED_PARTS, EmbeddedManifest, FONT_TABLE_PART, MAX_EMBEDDED_PARTS, MAX_EMBEDDED_RELS, VBA_PROJECT_PART, VBA_RELATED,
|
||||
rel_is, relative, rt,
|
||||
};
|
||||
use crate::units::{MAX_LEN_PT, emu, int};
|
||||
use crate::xml::{self, El, MAX_DEPTH};
|
||||
@@ -29,9 +30,6 @@ const PART_COST: u64 = 4096;
|
||||
/// Where the stories' parts live: every story this writer makes is a part in `word/`.
|
||||
const STORY_PART: &str = "word/document.xml";
|
||||
|
||||
/// The font table kept from a file (read by `Reader::keep_part_tree`).
|
||||
const FONT_TABLE_PART: &str = "word/fontTable.xml";
|
||||
|
||||
/// The embedded-object parts of a package being written.
|
||||
pub(crate) struct EmbedWriter<'d> {
|
||||
manifest: EmbeddedManifest,
|
||||
@@ -63,6 +61,8 @@ impl<'d> EmbedWriter<'d> {
|
||||
"word/endnotes.xml",
|
||||
"word/comments.xml",
|
||||
"word/commentsextended.xml",
|
||||
"word/commentsids.xml",
|
||||
"word/commentsextensible.xml",
|
||||
"[content_types].xml",
|
||||
]
|
||||
.iter()
|
||||
@@ -111,7 +111,7 @@ impl<'d> EmbedWriter<'d> {
|
||||
/// Names this writer may give its own parts later (headers, footers, package parts).
|
||||
fn reserved(lower: &str) -> bool {
|
||||
lower.ends_with(".rels")
|
||||
|| lower.starts_with("docprops/")
|
||||
|| (lower.starts_with("docprops/") && !lower.starts_with("docprops/thumbnail."))
|
||||
|| lower.starts_with("_rels/")
|
||||
|| ((lower.starts_with("word/header") || lower.starts_with("word/footer")) && lower.ends_with(".xml"))
|
||||
}
|
||||
@@ -196,6 +196,26 @@ impl<'d> EmbedWriter<'d> {
|
||||
self.first = memo;
|
||||
}
|
||||
|
||||
/// Reattach the parts kept by `keep_unmodelled` (`UNMODELLED_ROOTS`) to their owner: the
|
||||
/// package (`P`) or the main document (`D`).
|
||||
pub fn unmodelled_rels(&mut self, owner: &str, rels: &mut PartRels) {
|
||||
let Some(roots) = self.passthrough.get(crate::package::UNMODELLED_ROOTS).cloned() else { return };
|
||||
let mut memo = std::mem::take(&mut self.first);
|
||||
let mut written = Vec::new();
|
||||
for line in String::from_utf8_lossy(&roots).lines().take(MAX_EMBEDDED_RELS * 2) {
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let [source, kind, target] = fields.as_slice() else { continue };
|
||||
if *source != owner {
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = self.copy_tree(target, &mut memo, &mut written) {
|
||||
let source_part = if owner == "P" { "" } else { STORY_PART };
|
||||
rels.add(kind, &relative(source_part, &name), false);
|
||||
}
|
||||
}
|
||||
self.first = memo;
|
||||
}
|
||||
|
||||
/// What copying the parts reached from `roots` costs against the copy budget.
|
||||
fn tree_cost(&self, roots: &[&str]) -> u64 {
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
|
||||
@@ -3,12 +3,32 @@
|
||||
use wordcraft_doc::math::{
|
||||
Arg, BrkBin, BrkBinSub, ColJc, FracKind, LimLoc, MAX_DEPTH, MNode, MRun, MScr, MSty, Math, MathJc, MathProps, ScriptKind, parse_linear,
|
||||
};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
|
||||
use crate::xml::W;
|
||||
|
||||
/// Write an equation: `m:oMath`, inside `m:oMathPara` for a display equation. The source OMML
|
||||
/// is written back unchanged when the equation came from a file.
|
||||
pub fn write_equation(w: &mut W, linear: &str, display: bool, math: &Math) {
|
||||
/// is written back unchanged when the equation came from a file. `color` (the equation's run
|
||||
/// colour) goes on every math run without its own: OMML has no equation-level colour (#1467).
|
||||
pub fn write_equation(w: &mut W, linear: &str, display: bool, math: &Math, color: Option<Rgb>) {
|
||||
let tinted;
|
||||
let math = if color == omml_color(&math.omml) {
|
||||
math
|
||||
} else {
|
||||
// The kept source XML has the old colour baked in: write from the nodes instead.
|
||||
let mut m = math.clone();
|
||||
if m.nodes.is_empty() {
|
||||
m.nodes = parse_linear(linear);
|
||||
}
|
||||
if let Some(c) = color {
|
||||
wordcraft_doc::math_edit::each_run_mut(&mut m.nodes, &mut |r| {
|
||||
r.color.get_or_insert(c);
|
||||
});
|
||||
}
|
||||
m.omml.clear();
|
||||
tinted = m;
|
||||
&tinted
|
||||
};
|
||||
if display {
|
||||
w.open("m:oMathPara", &[]);
|
||||
let jc = match math.jc {
|
||||
@@ -82,6 +102,16 @@ pub fn resolve_numbers(math: &Math, display: bool, counter: &mut u32) -> Option<
|
||||
changed.then(|| Math { nodes: vec![MNode::EqArr { rows: out }], omml: String::new(), ..math.clone() })
|
||||
}
|
||||
|
||||
/// The equation colour the kept source OMML carries, as the reader lifts it.
|
||||
fn omml_color(omml: &str) -> Option<Rgb> {
|
||||
if omml.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let root = crate::xml::parse(wrap_ns(omml).as_bytes()).ok()?;
|
||||
let e = root.child("m:oMath")?;
|
||||
crate::read::math::lift_color(&mut crate::read::math::read_omath(e, MathJc::default()))
|
||||
}
|
||||
|
||||
/// The kept XML with namespace declarations, for validating it on its own.
|
||||
fn wrap_ns(xml: &str) -> String {
|
||||
let decl: String = crate::xml::body_ns().iter().filter(|(k, _)| k.starts_with("xmlns:")).map(|(k, v)| format!(" {k}=\"{v}\"")).collect();
|
||||
|
||||
+217
-45
@@ -1,16 +1,21 @@
|
||||
//! [`Document`] → DOCX.
|
||||
|
||||
mod embed;
|
||||
mod settings_merge;
|
||||
pub(crate) use settings_merge::has_unowned as settings_has_unowned;
|
||||
mod math;
|
||||
mod props;
|
||||
mod sdt;
|
||||
mod story;
|
||||
mod watermark;
|
||||
mod wordart;
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use wordcraft_doc::ParaProps;
|
||||
use wordcraft_doc::numbering::{Level, LevelSuffix};
|
||||
use wordcraft_doc::styles::{Style, StyleKind};
|
||||
use wordcraft_doc::props::VAlign;
|
||||
use wordcraft_doc::styles::{Style, StyleKind, TablePart};
|
||||
use wordcraft_doc::{Blocks, Document, PartKind};
|
||||
|
||||
use crate::package::{MAX_VBA_RELATED, VBA_PROJECT_PART, VBA_RELATED, rt, zip_entries};
|
||||
@@ -81,6 +86,13 @@ pub(crate) struct Writer<'d> {
|
||||
endnotes: Vec<u32>,
|
||||
/// Header/footer part id → (file name, is footer).
|
||||
hf: Vec<(u32, String, bool)>,
|
||||
/// The headers each slot has so far in body order, with sections' empty slots linked to the
|
||||
/// ones before (as layout shows them): where a watermark needs a header of its own.
|
||||
linked_headers: wordcraft_doc::section::HeaderSet,
|
||||
/// The part id standing for a header written only to hold the watermark (no such part).
|
||||
wm_header: u32,
|
||||
/// The watermark shape to put at the start of the next top-level paragraph (a header's first).
|
||||
pending_watermark: Option<String>,
|
||||
/// Paragraphs that need a `w14:paraId` (last paragraph of each comment), by address.
|
||||
para_ids: HashMap<usize, String>,
|
||||
/// A note reference mark to put at the start of the next paragraph.
|
||||
@@ -90,7 +102,7 @@ pub(crate) struct Writer<'d> {
|
||||
/// Writing a TOC heading: its TOC field is held back so the entries become the field's result.
|
||||
toc_hold_end: bool,
|
||||
/// The held TOC field (instruction, locked, props), opened in the first entry as Word does.
|
||||
toc_field: Option<(String, bool, wordcraft_doc::props::CharProps)>,
|
||||
toc_field: Option<(String, bool, bool, wordcraft_doc::props::CharProps)>,
|
||||
/// Open the held TOC field at the start of the paragraph being written.
|
||||
toc_begin_here: bool,
|
||||
/// Close the open TOC field at the end of the paragraph being written.
|
||||
@@ -147,6 +159,9 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
footnotes: Vec::new(),
|
||||
endnotes: Vec::new(),
|
||||
hf: Vec::new(),
|
||||
linked_headers: Default::default(),
|
||||
wm_header: (0..=u32::MAX).rev().find(|id| !doc.parts.contains_key(id)).unwrap_or(u32::MAX),
|
||||
pending_watermark: None,
|
||||
para_ids: HashMap::new(),
|
||||
pending_mark: None,
|
||||
current_note: None,
|
||||
@@ -189,8 +204,28 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
let ns = xml::body_ns();
|
||||
let ns_refs: Vec<(&str, &str)> = ns.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
w.open("w:document", &ns_refs);
|
||||
if let Some(c) = doc.settings.page_color {
|
||||
w.empty("w:background", &[("w:color", &c.hex())]);
|
||||
let pic = doc.settings.page_picture.as_ref().filter(|p| wr.media_files.contains_key(&p.media) && doc.media.contains_key(&p.media));
|
||||
if pic.is_some() || doc.settings.page_color.is_some() {
|
||||
let color = doc.settings.page_color.map(|c| c.hex());
|
||||
let attrs: Vec<(&str, &str)> = color.iter().map(|c| ("w:color", c.as_str())).collect();
|
||||
w.open("w:background", &attrs);
|
||||
if let Some(p) = pic
|
||||
&& let Some(file) = wr.media_files.get(&p.media)
|
||||
{
|
||||
let rid = rels.add(rt::IMAGE, &format!("media/{file}"), false);
|
||||
wr.used_media.insert(p.media.clone());
|
||||
w.open("v:background", &[("id", "_x0000_s1025"), ("o:bwmode", "white")]);
|
||||
let mut fa: Vec<(&str, &str)> = vec![("r:id", &rid)];
|
||||
if !p.fill_type.is_empty() {
|
||||
fa.push(("type", &p.fill_type));
|
||||
}
|
||||
if !p.title.is_empty() {
|
||||
fa.push(("o:title", &p.title));
|
||||
}
|
||||
w.empty("v:fill", &fa);
|
||||
w.close("v:background");
|
||||
}
|
||||
w.close("w:background");
|
||||
}
|
||||
w.open("w:body", &[]);
|
||||
wr.blocks(&mut w, &doc.body, &mut rels, true, 0);
|
||||
@@ -209,7 +244,14 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
let tag = if footer { "w:ftr" } else { "w:hdr" };
|
||||
w.open(tag, &ns_refs);
|
||||
let blocks: Blocks = doc.parts.get(&id).map(|p| p.blocks.clone()).unwrap_or_default();
|
||||
// The watermark goes in every header, at the start of its first paragraph.
|
||||
wr.pending_watermark = match &doc.settings.watermark {
|
||||
Some(wm) if !footer => watermark::run(wm, done, &doc.last_section),
|
||||
_ => None,
|
||||
};
|
||||
wr.blocks(&mut w, &blocks, &mut prels, false, 0);
|
||||
// Always taken: the story ends with a top-level paragraph.
|
||||
wr.pending_watermark = None;
|
||||
w.close(tag);
|
||||
push_part(
|
||||
&mut entries,
|
||||
@@ -339,6 +381,7 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
&format!("{CT_WML}commentsExtended+xml"),
|
||||
PartRels::default(),
|
||||
);
|
||||
write_comment_ids(doc, &comment_paras, &mut entries, &mut overrides, &mut rels);
|
||||
}
|
||||
|
||||
rels.add(rt::STYLES, "styles.xml", false);
|
||||
@@ -356,7 +399,13 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
&mut entries,
|
||||
&mut overrides,
|
||||
"word/settings.xml",
|
||||
settings_xml(doc, notes_part(doc, &wr, true), notes_part(doc, &wr, false), template_rel.as_deref()),
|
||||
{
|
||||
let generated = settings_xml(doc, notes_part(doc, &wr, true), notes_part(doc, &wr, false), template_rel.as_deref());
|
||||
match doc.passthrough.get(crate::package::SETTINGS_ORIG) {
|
||||
Some(orig) => settings_merge::merge(orig, &generated).unwrap_or(generated),
|
||||
None => generated,
|
||||
}
|
||||
},
|
||||
&format!("{CT_WML}settings+xml"),
|
||||
settings_rels,
|
||||
);
|
||||
@@ -387,6 +436,8 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
|
||||
wr.embeds.custom_xml_rels("D", &mut rels);
|
||||
wr.embeds.custom_xml_rels("P", &mut root);
|
||||
wr.embeds.unmodelled_rels("D", &mut rels);
|
||||
wr.embeds.unmodelled_rels("P", &mut root);
|
||||
// Parts of embedded objects and custom XML stores kept from the file.
|
||||
for (name, bytes, ct, prels) in std::mem::take(&mut wr.embeds.parts) {
|
||||
push_part(&mut entries, &mut overrides, &name, bytes, &ct, prels);
|
||||
@@ -591,7 +642,7 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
fn hf_rel(&mut self, part: u32, footer: bool, rels: &mut PartRels) -> Option<String> {
|
||||
let kind = self.doc.parts.get(&part)?.kind;
|
||||
let kind = if part == self.wm_header && !footer { PartKind::Header } else { self.doc.parts.get(&part)?.kind };
|
||||
if !matches!(kind, PartKind::Header | PartKind::Footer) {
|
||||
return None;
|
||||
}
|
||||
@@ -666,27 +717,33 @@ fn styles_xml(doc: &Document) -> Vec<u8> {
|
||||
w.close("w:pPrDefault");
|
||||
}
|
||||
w.close("w:docDefaults");
|
||||
if let Some(latent) = s.latent_styles.as_deref() {
|
||||
w.raw(latent);
|
||||
}
|
||||
// Kinds whose default style the file named (`w:default`); the English ids stand in otherwise.
|
||||
let flagged: Vec<StyleKind> = s.styles.iter().filter(|st| st.default).map(|st| st.kind).collect();
|
||||
for st in &s.styles {
|
||||
style_xml(&mut w, st);
|
||||
style_xml(&mut w, st, &flagged);
|
||||
}
|
||||
w.close("w:styles");
|
||||
w.into_bytes()
|
||||
}
|
||||
|
||||
fn style_xml(w: &mut W, st: &Style) {
|
||||
fn style_xml(w: &mut W, st: &Style, flagged: &[StyleKind]) {
|
||||
let ty = match st.kind {
|
||||
StyleKind::Paragraph => "paragraph",
|
||||
StyleKind::Character => "character",
|
||||
StyleKind::Table => "table",
|
||||
StyleKind::Numbering => "numbering",
|
||||
};
|
||||
let is_default = matches!(
|
||||
let english_default = matches!(
|
||||
(st.kind, st.id.as_str()),
|
||||
(StyleKind::Paragraph, "Normal")
|
||||
| (StyleKind::Character, "DefaultParagraphFont")
|
||||
| (StyleKind::Table, "TableNormal")
|
||||
| (StyleKind::Numbering, "NoList")
|
||||
);
|
||||
let is_default = st.default || (english_default && !flagged.contains(&st.kind));
|
||||
let mut a = vec![("w:type", ty), ("w:styleId", st.id.as_str())];
|
||||
if is_default {
|
||||
a.push(("w:default", "1"));
|
||||
@@ -742,49 +799,52 @@ fn style_xml(w: &mut W, st: &Style) {
|
||||
}
|
||||
w.close("w:tblPr");
|
||||
}
|
||||
// One conditional formatting region (ECMA-376 §17.7.6): run properties, then cell borders
|
||||
// and shading.
|
||||
let cond = |w: &mut W,
|
||||
ty: &str,
|
||||
chr: &wordcraft_doc::CharProps,
|
||||
fill: Option<wordcraft_doc::Rgb>,
|
||||
borders: Option<wordcraft_doc::props::Borders>| {
|
||||
if !props::has_rpr(chr) && fill.is_none() && borders.is_none() {
|
||||
return;
|
||||
// The conditional formatting parts (ECMA-376 §17.7.6): paragraph and run properties,
|
||||
// then cell borders, shading and vertical alignment. The whole table's text formatting
|
||||
// is the style's own (above).
|
||||
for part in TablePart::ALL {
|
||||
let f = t.part(part);
|
||||
let ppr = ParaProps { align: f.align, ..ParaProps::default() };
|
||||
let has_rpr = props::has_rpr(&f.chr);
|
||||
// The whole table's borders are its table borders (`w:tblPr` above).
|
||||
let borders = f.borders.filter(|_| part != TablePart::WholeTable);
|
||||
let has_tc = f.fill.is_some() || borders.is_some() || f.v_align.is_some();
|
||||
if !has_rpr && !has_tc && f.align.is_none() {
|
||||
continue;
|
||||
}
|
||||
w.open("w:tblStylePr", &[("w:type", ty)]);
|
||||
if props::has_rpr(chr) {
|
||||
w.open("w:tblStylePr", &[("w:type", part.ooxml())]);
|
||||
if f.align.is_some() {
|
||||
w.open("w:pPr", &[]);
|
||||
props::ppr_inner(w, &ppr, false, None);
|
||||
w.close("w:pPr");
|
||||
}
|
||||
if has_rpr {
|
||||
w.open("w:rPr", &[]);
|
||||
props::rpr_inner(w, chr);
|
||||
props::rpr_inner(w, &f.chr);
|
||||
w.close("w:rPr");
|
||||
}
|
||||
if fill.is_some() || borders.is_some() {
|
||||
if has_tc {
|
||||
w.open("w:tcPr", &[]);
|
||||
if let Some(bs) = &borders {
|
||||
props::borders(w, "w:tcBorders", bs, Some("w:insideH"), &[]);
|
||||
if let Some(bs) = borders {
|
||||
props::borders(w, "w:tcBorders", &bs, Some("w:insideH"), &[]);
|
||||
}
|
||||
if let Some(f) = fill {
|
||||
w.empty("w:shd", &[("w:val", "clear"), ("w:color", "auto"), ("w:fill", &f.hex())]);
|
||||
if let Some(c) = f.fill {
|
||||
w.empty("w:shd", &[("w:val", "clear"), ("w:color", "auto"), ("w:fill", &c.hex())]);
|
||||
}
|
||||
if let Some(v) = f.v_align {
|
||||
w.val(
|
||||
"w:vAlign",
|
||||
match v {
|
||||
VAlign::Top => "top",
|
||||
VAlign::Center => "center",
|
||||
VAlign::Bottom => "bottom",
|
||||
},
|
||||
);
|
||||
}
|
||||
w.close("w:tcPr");
|
||||
}
|
||||
w.close("w:tblStylePr");
|
||||
};
|
||||
cond(w, "wholeTable", &wordcraft_doc::CharProps::default(), t.fill, None);
|
||||
cond(w, "firstRow", &t.header_chr, t.header_fill, t.header_borders);
|
||||
// The total row's borders, its top edge falling back to the built-in top rule.
|
||||
let total_borders = match (t.total_borders, t.total_border_top) {
|
||||
(Some(mut b), top) => {
|
||||
b.top = b.top.or(top);
|
||||
Some(b)
|
||||
}
|
||||
(None, top) => top.map(|b| wordcraft_doc::props::Borders { top: Some(b), ..Default::default() }),
|
||||
};
|
||||
cond(w, "lastRow", &t.total_chr, t.total_fill, total_borders);
|
||||
cond(w, "firstCol", &t.first_col_chr, t.first_col_fill, t.first_col_borders);
|
||||
cond(w, "lastCol", &t.last_col_chr, t.last_col_fill, t.last_col_borders);
|
||||
cond(w, "band1Vert", &t.col_band_chr, t.col_band_fill, t.col_band_borders);
|
||||
cond(w, "band1Horz", &t.band_chr, t.band_fill, t.band_borders);
|
||||
}
|
||||
}
|
||||
w.close("w:style");
|
||||
}
|
||||
@@ -794,9 +854,19 @@ fn numbering_xml(doc: &Document) -> Vec<u8> {
|
||||
let ns = xml::body_ns();
|
||||
let ns_refs: Vec<(&str, &str)> = ns.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
w.open("w:numbering", &ns_refs);
|
||||
let mut nsids: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
for a in &doc.numbering.abstracts {
|
||||
w.open("w:abstractNum", &[("w:abstractNumId", &a.id.to_string())]);
|
||||
w.val("w:multiLevelType", if a.levels.len() > 1 { "multilevel" } else { "singleLevel" });
|
||||
// CT_AbstractNum order: nsid, multiLevelType, tmpl, name… A copied definition repeats
|
||||
// its source's nsid; only the first keeps it, so Word doesn't take them for one list.
|
||||
if let Some(n) = a.nsid.as_deref().filter(|n| nsids.insert(n)) {
|
||||
w.val("w:nsid", n);
|
||||
}
|
||||
let derived = if a.levels.len() > 1 { "multilevel" } else { "singleLevel" };
|
||||
w.val("w:multiLevelType", a.multi_level_type.as_deref().unwrap_or(derived));
|
||||
if let Some(t) = &a.tmpl {
|
||||
w.val("w:tmpl", t);
|
||||
}
|
||||
if let Some(n) = &a.name {
|
||||
w.val("w:name", n);
|
||||
}
|
||||
@@ -892,7 +962,19 @@ fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, template_rel: O
|
||||
let ns = xml::body_ns();
|
||||
let ns_refs: Vec<(&str, &str)> = ns.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
w.open("w:settings", &ns_refs);
|
||||
w.empty("w:zoom", &[("w:percent", "100")]);
|
||||
let zoom = s.zoom.unwrap_or(wordcraft_doc::Zoom { percent: 100, fit: None });
|
||||
let percent = zoom.percent.clamp(10, 500).to_string();
|
||||
match zoom.fit {
|
||||
Some(fit) => {
|
||||
let val = match fit {
|
||||
wordcraft_doc::ZoomFit::OnePage => "fullPage",
|
||||
wordcraft_doc::ZoomFit::PageWidth => "bestFit",
|
||||
wordcraft_doc::ZoomFit::TextWidth => "textFit",
|
||||
};
|
||||
w.empty("w:zoom", &[("w:val", val), ("w:percent", &percent)]);
|
||||
}
|
||||
None => w.empty("w:zoom", &[("w:percent", &percent)]),
|
||||
}
|
||||
// §17.15.1.70 / §17.15.1.69, right after `w:zoom` in CT_Settings.
|
||||
if s.remove_personal_info {
|
||||
w.empty("w:removePersonalInformation", &[]);
|
||||
@@ -900,7 +982,7 @@ fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, template_rel: O
|
||||
if s.remove_date_time {
|
||||
w.empty("w:removeDateAndTime", &[]);
|
||||
}
|
||||
if s.page_color.is_some() {
|
||||
if s.page_color.is_some() || s.page_picture.is_some() {
|
||||
w.empty("w:displayBackgroundShape", &[]);
|
||||
}
|
||||
if s.mirror_margins {
|
||||
@@ -972,6 +1054,13 @@ fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, template_rel: O
|
||||
w.close(tag);
|
||||
}
|
||||
w.open("w:compat", &[]);
|
||||
// CT_Compat: the older switches come before the `w:compatSetting`s.
|
||||
if doc.settings.sum_paragraph_spacing {
|
||||
w.empty("w:doNotUseHTMLParagraphAutoSpacing", &[]);
|
||||
}
|
||||
if s.allow_space_of_same_style_in_table {
|
||||
w.empty("w:allowSpaceOfSameStyleInTable", &[]);
|
||||
}
|
||||
let mode = doc.settings.compat_mode.clamp(11, 15).to_string();
|
||||
w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]);
|
||||
w.close("w:compat");
|
||||
@@ -982,6 +1071,76 @@ fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, template_rel: O
|
||||
w.into_bytes()
|
||||
}
|
||||
|
||||
/// Is `d` a usable `w16cid:durableId`: 1–8 hex digits, below 0x7FFFFFFF, not 0?
|
||||
pub(crate) fn durable_id_ok(d: &str) -> bool {
|
||||
d.len() <= 8 && u32::from_str_radix(d, 16).is_ok_and(|v| v != 0 && v < 0x7FFF_FFFF)
|
||||
}
|
||||
|
||||
/// `commentsIds.xml` (paragraph id → durable id) and `commentsExtensible.xml` (durable id → UTC
|
||||
/// date) for the comments that got paragraph ids. Durable ids read from the file are kept (unique
|
||||
/// ones); comments without one get the next free id. Word uses them to keep tracking a comment
|
||||
/// across saves and for its UTC time.
|
||||
fn write_comment_ids(
|
||||
doc: &Document,
|
||||
comment_paras: &[(u32, String)],
|
||||
entries: &mut Vec<(String, Vec<u8>)>,
|
||||
overrides: &mut Vec<(String, String)>,
|
||||
rels: &mut PartRels,
|
||||
) {
|
||||
if comment_paras.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
let mut next = 0x1000_0000u32;
|
||||
let mut rows: Vec<(String, String, Option<String>)> = Vec::new();
|
||||
for (cid, pid) in comment_paras {
|
||||
let Some(c) = doc.comments.get(cid) else { continue };
|
||||
let kept = c.durable_id.as_deref().filter(|d| durable_id_ok(d)).map(|d| format!("{:08X}", u32::from_str_radix(d, 16).unwrap_or(0)));
|
||||
let durable = match kept.filter(|d| !used.contains(d)) {
|
||||
Some(d) => d,
|
||||
None => loop {
|
||||
next = next.saturating_add(1);
|
||||
let d = format!("{next:08X}");
|
||||
if !used.contains(&d) && !doc.comments.values().any(|o| o.durable_id.as_deref() == Some(d.as_str())) {
|
||||
break d;
|
||||
}
|
||||
},
|
||||
};
|
||||
used.insert(durable.clone());
|
||||
// A local `w:date` with a zone designator is UTC already; otherwise only the file's own.
|
||||
// Remove date and time on save (#1062): no comment date here either.
|
||||
let utc = if doc.settings.remove_date_time { None } else { c.date_utc.clone().or_else(|| c.date.ends_with('Z').then(|| c.date.clone())) };
|
||||
rows.push((pid.clone(), durable, utc));
|
||||
}
|
||||
let mc = "http://schemas.openxmlformats.org/markup-compatibility/2006";
|
||||
let mut w = W::new();
|
||||
w.open(
|
||||
"w16cid:commentsIds",
|
||||
&[("xmlns:mc", mc), ("xmlns:w16cid", "http://schemas.microsoft.com/office/word/2016/wordml/cid"), ("mc:Ignorable", "w16cid")],
|
||||
);
|
||||
for (pid, durable, _) in &rows {
|
||||
w.empty("w16cid:commentId", &[("w16cid:paraId", pid), ("w16cid:durableId", durable)]);
|
||||
}
|
||||
w.close("w16cid:commentsIds");
|
||||
rels.add(rt::COMMENTS_IDS, "commentsIds.xml", false);
|
||||
push_part(entries, overrides, "word/commentsIds.xml", w.into_bytes(), &format!("{CT_WML}commentsIds+xml"), PartRels::default());
|
||||
|
||||
let mut w = W::new();
|
||||
w.open(
|
||||
"w16cex:commentsExtensible",
|
||||
&[("xmlns:mc", mc), ("xmlns:w16cex", "http://schemas.microsoft.com/office/word/2018/wordml/cex"), ("mc:Ignorable", "w16cex")],
|
||||
);
|
||||
for (_, durable, utc) in &rows {
|
||||
match utc {
|
||||
Some(d) => w.empty("w16cex:commentExtensible", &[("w16cex:durableId", durable), ("w16cex:dateUtc", d)]),
|
||||
None => w.empty("w16cex:commentExtensible", &[("w16cex:durableId", durable)]),
|
||||
}
|
||||
}
|
||||
w.close("w16cex:commentsExtensible");
|
||||
rels.add(rt::COMMENTS_EXTENSIBLE, "commentsExtensible.xml", false);
|
||||
push_part(entries, overrides, "word/commentsExtensible.xml", w.into_bytes(), &format!("{CT_WML}commentsExtensible+xml"), PartRels::default());
|
||||
}
|
||||
|
||||
fn theme_xml(doc: &Document) -> Vec<u8> {
|
||||
let s = &doc.settings;
|
||||
let names = ["dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink"];
|
||||
@@ -1109,6 +1268,19 @@ fn app_xml(doc: &Document) -> Vec<u8> {
|
||||
w.leaf("Words", &[], &doc.word_count().to_string());
|
||||
w.leaf("Paragraphs", &[], &doc.paragraph_count().to_string());
|
||||
w.leaf("DocSecurity", &[], "0");
|
||||
// Kept properties, except the personal ones when the file asks Word to remove personal
|
||||
// information on save.
|
||||
let private = doc.settings.remove_personal_info;
|
||||
if let Some(kept) = doc.passthrough.get(crate::package::APP_KEPT) {
|
||||
for line in String::from_utf8_lossy(kept).lines().take(crate::package::APP_KEPT_PROPS.len()) {
|
||||
let Some((name, value)) = line.split_once('\t') else { continue };
|
||||
let Some(name) = crate::package::APP_KEPT_PROPS.iter().find(|n| **n == name) else { continue };
|
||||
if private && matches!(*name, "Company" | "Manager") {
|
||||
continue;
|
||||
}
|
||||
w.leaf(name, &[], value);
|
||||
}
|
||||
}
|
||||
w.close("Properties");
|
||||
w.into_bytes()
|
||||
}
|
||||
|
||||
@@ -464,8 +464,12 @@ fn tblpr_inner(w: &mut W, t: &TableProps) {
|
||||
|
||||
/// `w:trPr` (when the row has any), with a tracked change last as for [`tblpr`].
|
||||
pub fn trpr(w: &mut W, r: &RowProps, change: Option<&ChangeAttrs>) {
|
||||
if let Some(x) = &r.exceptions {
|
||||
tblprex(w, x);
|
||||
}
|
||||
let change = change.zip(r.fmt_change.as_ref());
|
||||
if r.height.is_none() && !r.header && !r.cant_split && change.is_none() {
|
||||
let gaps = r.grid_before > 0 || r.grid_after > 0 || r.w_before.is_some() || r.w_after.is_some();
|
||||
if r.height.is_none() && !r.header && !r.cant_split && !gaps && change.is_none() {
|
||||
return;
|
||||
}
|
||||
w.open("w:trPr", &[]);
|
||||
@@ -476,7 +480,48 @@ pub fn trpr(w: &mut W, r: &RowProps, change: Option<&ChangeAttrs>) {
|
||||
w.close("w:trPr");
|
||||
}
|
||||
|
||||
/// `w:tblPrEx`: only the properties the row overrides (it takes no style, float or look).
|
||||
fn tblprex(w: &mut W, t: &TableProps) {
|
||||
w.open("w:tblPrEx", &[]);
|
||||
if let Some(p) = t.width_pct {
|
||||
w.empty("w:tblW", &[("w:w", &n(round(p.clamp(0.0, 1000.0) * 50.0))), ("w:type", "pct")]);
|
||||
} else if let Some(v) = t.width {
|
||||
w.empty("w:tblW", &[("w:w", &twips(v.max(0.0))), ("w:type", "dxa")]);
|
||||
}
|
||||
if let Some(a) = t.align {
|
||||
w.val("w:jc", align_val(if a == Align::Justify || a == Align::Distribute { Align::Left } else { a }));
|
||||
}
|
||||
if let Some(i) = t.indent {
|
||||
w.empty("w:tblInd", &[("w:w", &twips(i)), ("w:type", "dxa")]);
|
||||
}
|
||||
if let Some(b) = &t.borders {
|
||||
borders(w, "w:tblBorders", b, Some("w:insideH"), &[]);
|
||||
}
|
||||
if let Some(s) = t.shading {
|
||||
w.empty("w:shd", &[("w:val", "clear"), ("w:color", "auto"), ("w:fill", &s.hex())]);
|
||||
}
|
||||
if t.fixed {
|
||||
w.empty("w:tblLayout", &[("w:type", "fixed")]);
|
||||
}
|
||||
if let Some(m) = &t.cell_margins {
|
||||
margins(w, "w:tblCellMar", m);
|
||||
}
|
||||
w.close("w:tblPrEx");
|
||||
}
|
||||
|
||||
fn trpr_inner(w: &mut W, r: &RowProps) {
|
||||
// The grid gaps go first, in the schema's order (as Word writes them).
|
||||
if r.grid_before > 0 {
|
||||
w.val("w:gridBefore", &n(r.grid_before.into()));
|
||||
}
|
||||
if r.grid_after > 0 {
|
||||
w.val("w:gridAfter", &n(r.grid_after.into()));
|
||||
}
|
||||
for (name, width) in [("w:wBefore", r.w_before), ("w:wAfter", r.w_after)] {
|
||||
if let Some(v) = width {
|
||||
w.empty(name, &[("w:w", &twips(v)), ("w:type", "dxa")]);
|
||||
}
|
||||
}
|
||||
if r.cant_split {
|
||||
w.empty("w:cantSplit", &[]);
|
||||
}
|
||||
@@ -529,13 +574,14 @@ fn tcpr_inner(w: &mut W, c: &CellProps) {
|
||||
if let Some(m) = &c.margins {
|
||||
margins(w, "w:tcMar", m);
|
||||
}
|
||||
if c.text_direction.is_turned() {
|
||||
if c.text_direction.is_turned() || c.text_direction_set {
|
||||
w.val("w:textDirection", c.text_direction.ooxml());
|
||||
}
|
||||
match c.valign {
|
||||
VAlign::Top => {}
|
||||
VAlign::Center => w.val("w:vAlign", "center"),
|
||||
VAlign::Bottom => w.val("w:vAlign", "bottom"),
|
||||
None => {}
|
||||
Some(VAlign::Top) => w.val("w:vAlign", "top"),
|
||||
Some(VAlign::Center) => w.val("w:vAlign", "center"),
|
||||
Some(VAlign::Bottom) => w.val("w:vAlign", "bottom"),
|
||||
}
|
||||
if c.hide_mark {
|
||||
w.empty("w:hideMark", &[]);
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
//! `word/settings.xml` merged into the file's original settings part.
|
||||
//!
|
||||
//! The model owns only some settings (`super::settings_xml`). Regenerating the part from the
|
||||
//! model alone drops everything else Word stores there: compatibility options, rsids, document
|
||||
//! variables, proofing state, the colour scheme mapping, "remove personal information on save"…
|
||||
//! So when a file brought settings the model doesn't hold ([`has_unowned`]; the reader keeps its
|
||||
//! bytes under `SETTINGS_ORIG`), the writer merges instead ([`merge`]): the original root start
|
||||
//! tag (namespace declarations, `mc:Ignorable`) and every child the model doesn't own are kept
|
||||
//! byte for byte; owned children come from the generated part (or go, when the model turned
|
||||
//! them off); owned children the original lacks are inserted at their CT_Settings position; in
|
||||
//! `w:compat` only the `compatibilityMode` setting is replaced. Kept children that refer to a
|
||||
//! relationship (`r:id`, e.g. a mail merge data source) are dropped: their relationships aren't
|
||||
//! carried. Anything unexpected returns `None`, and the generated part is written as before.
|
||||
|
||||
/// Children of `w:settings` the model writes (`super::settings_xml`).
|
||||
const OWNED: &[&str] = &[
|
||||
"w:removePersonalInformation",
|
||||
"w:removeDateAndTime",
|
||||
"w:displayBackgroundShape",
|
||||
"w:mirrorMargins",
|
||||
"w:attachedTemplate",
|
||||
"w:linkStyles",
|
||||
"w:trackRevisions",
|
||||
"w:documentProtection",
|
||||
"w:defaultTabStop",
|
||||
"w:autoHyphenation",
|
||||
"w:consecutiveHyphenLimit",
|
||||
"w:hyphenationZone",
|
||||
"w:doNotHyphenateCaps",
|
||||
"w:evenAndOddHeaders",
|
||||
"w:drawingGridHorizontalSpacing",
|
||||
"w:drawingGridVerticalSpacing",
|
||||
"w:characterSpacingControl",
|
||||
"w:footnotePr",
|
||||
"w:endnotePr",
|
||||
"m:mathPr",
|
||||
];
|
||||
|
||||
/// Owned children whose original, when there is one, is kept as is.
|
||||
const KEEP_ORIGINAL: &[&str] = &["m:mathPr", "w:displayBackgroundShape"];
|
||||
|
||||
/// CT_Settings' sequence (ECMA-376 §17.15.1.78), for placing inserted children.
|
||||
const ORDER: &[&str] = &[
|
||||
"w:writeProtection",
|
||||
"w:view",
|
||||
"w:zoom",
|
||||
"w:removePersonalInformation",
|
||||
"w:removeDateAndTime",
|
||||
"w:doNotDisplayPageBoundaries",
|
||||
"w:displayBackgroundShape",
|
||||
"w:printPostScriptOverText",
|
||||
"w:printFractionalCharacterWidth",
|
||||
"w:printFormsData",
|
||||
"w:embedTrueTypeFonts",
|
||||
"w:embedSystemFonts",
|
||||
"w:saveSubsetFonts",
|
||||
"w:saveFormsData",
|
||||
"w:mirrorMargins",
|
||||
"w:alignBordersAndEdges",
|
||||
"w:bordersDoNotSurroundHeader",
|
||||
"w:bordersDoNotSurroundFooter",
|
||||
"w:gutterAtTop",
|
||||
"w:hideSpellingErrors",
|
||||
"w:hideGrammaticalErrors",
|
||||
"w:activeWritingStyle",
|
||||
"w:proofState",
|
||||
"w:formsDesign",
|
||||
"w:attachedTemplate",
|
||||
"w:linkStyles",
|
||||
"w:stylePaneFormatFilter",
|
||||
"w:stylePaneSortMethod",
|
||||
"w:documentType",
|
||||
"w:mailMerge",
|
||||
"w:revisionView",
|
||||
"w:trackRevisions",
|
||||
"w:doNotTrackMoves",
|
||||
"w:doNotTrackFormatting",
|
||||
"w:documentProtection",
|
||||
"w:autoFormatOverride",
|
||||
"w:styleLockTheme",
|
||||
"w:styleLockQFSet",
|
||||
"w:defaultTabStop",
|
||||
"w:autoHyphenation",
|
||||
"w:consecutiveHyphenLimit",
|
||||
"w:hyphenationZone",
|
||||
"w:doNotHyphenateCaps",
|
||||
"w:showEnvelope",
|
||||
"w:summaryLength",
|
||||
"w:clickAndTypeStyle",
|
||||
"w:defaultTableStyle",
|
||||
"w:evenAndOddHeaders",
|
||||
"w:bookFoldRevPrinting",
|
||||
"w:bookFoldPrinting",
|
||||
"w:bookFoldPrintingSheets",
|
||||
"w:drawingGridHorizontalSpacing",
|
||||
"w:drawingGridVerticalSpacing",
|
||||
"w:displayHorizontalDrawingGridEvery",
|
||||
"w:displayVerticalDrawingGridEvery",
|
||||
"w:doNotUseMarginsForDrawingGridOrigin",
|
||||
"w:drawingGridHorizontalOrigin",
|
||||
"w:drawingGridVerticalOrigin",
|
||||
"w:doNotShadeFormData",
|
||||
"w:noPunctuationKerning",
|
||||
"w:characterSpacingControl",
|
||||
"w:printTwoOnOne",
|
||||
"w:strictFirstAndLastChars",
|
||||
"w:noLineBreaksAfter",
|
||||
"w:noLineBreaksBefore",
|
||||
"w:savePreviewPicture",
|
||||
"w:doNotValidateAgainstSchema",
|
||||
"w:saveInvalidXml",
|
||||
"w:ignoreMixedContent",
|
||||
"w:alwaysShowPlaceholderText",
|
||||
"w:doNotDemarcateInvalidXml",
|
||||
"w:saveXmlDataOnly",
|
||||
"w:useXSLTWhenSaving",
|
||||
"w:saveThroughXslt",
|
||||
"w:showXMLTags",
|
||||
"w:alwaysMergeEmptyNamespace",
|
||||
"w:updateFields",
|
||||
"w:hdrShapeDefaults",
|
||||
"w:footnotePr",
|
||||
"w:endnotePr",
|
||||
"w:compat",
|
||||
"w:docVars",
|
||||
"w:rsids",
|
||||
"m:mathPr",
|
||||
"w:attachedSchema",
|
||||
"w:themeFontLang",
|
||||
"w:clrSchemeMapping",
|
||||
"w:doNotIncludeSubdocsInStats",
|
||||
"w:doNotAutoCompressPictures",
|
||||
"w:forceUpgrade",
|
||||
"w:captions",
|
||||
"w:readModeInkLockDown",
|
||||
"w:smartTagType",
|
||||
"sl:schemaLibrary",
|
||||
"w:shapeDefaults",
|
||||
"w:doNotEmbedSmartTags",
|
||||
"w:decimalSymbol",
|
||||
"w:listSeparator",
|
||||
];
|
||||
|
||||
fn rank(name: &str) -> usize {
|
||||
ORDER.iter().position(|n| *n == name).unwrap_or(ORDER.len())
|
||||
}
|
||||
|
||||
/// A child element of the root: its qualified name and byte span.
|
||||
struct Child {
|
||||
name: String,
|
||||
start: usize,
|
||||
end: usize,
|
||||
}
|
||||
|
||||
/// The root start tag's span end and the root's direct children, or `None` for anything the
|
||||
/// scanner doesn't expect (CDATA, DOCTYPE, a different root).
|
||||
fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec<Child>)> {
|
||||
let open = xml.find(&format!("<{root}"))?;
|
||||
let open_end = open + xml.get(open..)?.find('>')? + 1;
|
||||
if xml.get(open_end - 2..open_end)? == "/>" {
|
||||
return None;
|
||||
}
|
||||
let close = xml.rfind(&format!("</{root}>"))?;
|
||||
let mut out = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
let mut i = open_end;
|
||||
let mut cur: Option<(String, usize)> = None;
|
||||
while i < close {
|
||||
let rest = xml.get(i..close)?;
|
||||
let Some(lt) = rest.find('<') else { break };
|
||||
let at = i + lt;
|
||||
let tail = xml.get(at..close)?;
|
||||
if tail.starts_with("<!--") {
|
||||
i = at + tail.find("-->")? + 3;
|
||||
continue;
|
||||
}
|
||||
if tail.starts_with("<![CDATA[") || tail.starts_with("<!") {
|
||||
return None;
|
||||
}
|
||||
if tail.starts_with("<?") {
|
||||
i = at + tail.find("?>")? + 2;
|
||||
continue;
|
||||
}
|
||||
let gt = at + tail.find('>')? + 1;
|
||||
let tag = xml.get(at..gt)?;
|
||||
if tag.starts_with("</") {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
let (name, s) = cur.take()?;
|
||||
out.push(Child { name, start: s, end: gt });
|
||||
}
|
||||
} else {
|
||||
let name: String = tag.get(1..)?.chars().take_while(|c| !c.is_whitespace() && *c != '>' && *c != '/').collect();
|
||||
let selfclose = tag.ends_with("/>");
|
||||
if depth == 0 {
|
||||
if selfclose {
|
||||
out.push(Child { name, start: at, end: gt });
|
||||
} else {
|
||||
cur = Some((name, at));
|
||||
depth = 1;
|
||||
}
|
||||
} else if !selfclose {
|
||||
depth += 1;
|
||||
}
|
||||
}
|
||||
i = gt;
|
||||
}
|
||||
if depth != 0 {
|
||||
return None;
|
||||
}
|
||||
Some((open_end, close, out))
|
||||
}
|
||||
|
||||
/// The original `w:compat` with its `compatibilityMode` taken from the generated one.
|
||||
fn merge_compat(orig: &str, generated: &str) -> Option<String> {
|
||||
let mode = |s: &str| -> Option<(usize, usize)> {
|
||||
let at = s.find("w:name=\"compatibilityMode\"")?;
|
||||
let tag_start = s.get(..at)?.rfind('<')?;
|
||||
let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1;
|
||||
Some((tag_start, tag_end))
|
||||
};
|
||||
match (mode(orig), mode(generated)) {
|
||||
(Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)),
|
||||
(None, Some((c, d))) => {
|
||||
// No mode in the original: add the generated one before `</w:compat>`.
|
||||
let close = orig.rfind("</w:compat>")?;
|
||||
Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?))
|
||||
}
|
||||
_ => Some(orig.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps
|
||||
/// it for [`merge`]. False for parts WordCraft wrote itself, and for anything it can't scan.
|
||||
pub fn has_unowned(original: &[u8]) -> bool {
|
||||
let Some(xml) = std::str::from_utf8(original).ok() else { return false };
|
||||
let Some((_, _, kids)) = children(xml, "w:settings") else { return false };
|
||||
kids.iter().any(|k| match k.name.as_str() {
|
||||
"w:zoom" => false,
|
||||
// Anything in `w:compat` beyond its own tag and the compatibility mode.
|
||||
"w:compat" => xml.get(k.start..k.end).is_some_and(|c| {
|
||||
let mode = usize::from(c.contains("w:name=\"compatibilityMode\""));
|
||||
c.matches("<w:").count().saturating_sub(1 + mode) > 0
|
||||
}),
|
||||
n => !OWNED.contains(&n),
|
||||
})
|
||||
}
|
||||
|
||||
/// The merged settings part, or `None` to fall back to `generated`.
|
||||
pub fn merge(original: &[u8], generated: &[u8]) -> Option<Vec<u8>> {
|
||||
let orig = std::str::from_utf8(original).ok()?;
|
||||
let gen_s = std::str::from_utf8(generated).ok()?;
|
||||
let (o_open, o_close, o_kids) = children(orig, "w:settings")?;
|
||||
let (_, _, g_kids) = children(gen_s, "w:settings")?;
|
||||
// Prefixes the generated children use must be declared by the original root.
|
||||
let root_tag = orig.get(..o_open)?;
|
||||
for p in ["w", "m", "r"] {
|
||||
if g_kids.iter().any(|k| k.name.starts_with(&format!("{p}:"))) && !root_tag.contains(&format!("xmlns:{p}=")) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let g_text = |k: &Child| gen_s.get(k.start..k.end).map(str::to_string);
|
||||
let mut used = vec![false; g_kids.len()];
|
||||
let mark = |name: &str, used: &mut Vec<bool>| -> Option<usize> {
|
||||
let gi = g_kids.iter().enumerate().position(|(i, g)| g.name == name && !used.get(i).copied().unwrap_or(true))?;
|
||||
if let Some(u) = used.get_mut(gi) {
|
||||
*u = true;
|
||||
}
|
||||
Some(gi)
|
||||
};
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for k in &o_kids {
|
||||
let text = orig.get(k.start..k.end)?;
|
||||
if KEEP_ORIGINAL.contains(&k.name.as_str()) {
|
||||
// The model reads these only partly (math settings) or writes them only in one case
|
||||
// (the background shape flag, with a page colour): the original wins.
|
||||
mark(&k.name, &mut used);
|
||||
out.push((k.name.clone(), text.to_string()));
|
||||
} else if OWNED.contains(&k.name.as_str()) {
|
||||
if let Some(gi) = mark(&k.name, &mut used) {
|
||||
out.push((k.name.clone(), g_text(g_kids.get(gi)?)?));
|
||||
}
|
||||
} else if k.name == "w:compat" {
|
||||
let merged = match mark("w:compat", &mut used) {
|
||||
Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?,
|
||||
None => text.to_string(),
|
||||
};
|
||||
out.push((k.name.clone(), merged));
|
||||
} else if !text.contains("r:id=") {
|
||||
out.push((k.name.clone(), text.to_string()));
|
||||
}
|
||||
}
|
||||
for (gi, g) in g_kids.iter().enumerate() {
|
||||
let owned = OWNED.contains(&g.name.as_str()) || g.name == "w:compat";
|
||||
if used.get(gi).copied().unwrap_or(true) || !owned {
|
||||
continue;
|
||||
}
|
||||
let r = rank(&g.name);
|
||||
let at = out.iter().position(|(n, _)| rank(n) > r).unwrap_or(out.len());
|
||||
out.insert(at, (g.name.clone(), g_text(g)?));
|
||||
}
|
||||
let mut s = String::with_capacity(orig.len() + 256);
|
||||
s.push_str(root_tag);
|
||||
for (_, t) in &out {
|
||||
s.push_str(t);
|
||||
}
|
||||
s.push_str(orig.get(o_close..)?);
|
||||
Some(s.into_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const GEN: &str = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:zoom w:percent="100"/><w:defaultTabStop w:val="720"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="u" w:val="15"/></w:compat></w:settings>"#;
|
||||
|
||||
#[test]
|
||||
fn odd_or_hostile_originals_fall_back_or_merge_without_panicking() {
|
||||
let odd = [
|
||||
"",
|
||||
"<w:settings",
|
||||
"<w:settings/>",
|
||||
"<x:other/>",
|
||||
r#"<w:settings xmlns:w="w"><w:a><w:b></w:a></w:settings>"#,
|
||||
r#"<w:settings xmlns:w="w"><![CDATA[x]]></w:settings>"#,
|
||||
r#"<w:settings xmlns:w="w"></w:x></w:settings>"#,
|
||||
"<w:settings xmlns:w=\"w\">\u{1F600}<w:rsids/></w:settings>",
|
||||
r#"<w:settings xmlns:w="w"><!-- c --><?pi x?><w:rsids/></w:settings>"#,
|
||||
];
|
||||
for o in odd {
|
||||
let _ = merge(o.as_bytes(), GEN.as_bytes());
|
||||
let _ = has_unowned(o.as_bytes());
|
||||
}
|
||||
assert!(merge(&[0xff, 0xfe], GEN.as_bytes()).is_none());
|
||||
// Missing declarations for a prefix the generated part uses: fall back.
|
||||
assert!(merge(br#"<w:settings xmlns:x="x"><w:rsids/></w:settings>"#, GEN.as_bytes()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compat_block_without_a_mode_gets_the_generated_one() {
|
||||
let orig = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:useFELayout/></w:compat></w:settings>"#;
|
||||
let out = String::from_utf8(merge(orig.as_bytes(), GEN.as_bytes()).unwrap()).unwrap();
|
||||
assert!(out.contains("<w:useFELayout/>") && out.contains("compatibilityMode"), "{out}");
|
||||
assert!(has_unowned(orig.as_bytes()));
|
||||
assert!(!has_unowned(GEN.as_bytes()));
|
||||
}
|
||||
}
|
||||
+135
-34
@@ -2,7 +2,7 @@
|
||||
|
||||
use wordcraft_doc::effects::ShapeEffects;
|
||||
use wordcraft_doc::para::{AltText, Anchor, Float, NoteKind, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::{CharProps, PropChange, Rgb};
|
||||
use wordcraft_doc::props::{CharProps, PropChange, Rgb, TextColor};
|
||||
use wordcraft_doc::section::{LineNumberRestart, NoteProps, SectionProps, SectionStart};
|
||||
use wordcraft_doc::table::Table;
|
||||
use wordcraft_doc::{Block, Blocks, InlineObject, Paragraph, RevisionKind};
|
||||
@@ -74,7 +74,16 @@ impl Writer<'_> {
|
||||
self.move_ranges(w, &[]);
|
||||
}
|
||||
if bl.last().is_none_or(|b| matches!(**b, Block::Table(_))) {
|
||||
w.raw("<w:p/>");
|
||||
// A header with no paragraph of its own before: the watermark goes in this one.
|
||||
if depth == 0
|
||||
&& let Some(run) = self.pending_watermark.take()
|
||||
{
|
||||
w.raw("<w:p>");
|
||||
w.raw(&run);
|
||||
w.raw("</w:p>");
|
||||
} else {
|
||||
w.raw("<w:p/>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,12 +216,18 @@ impl Writer<'_> {
|
||||
w.empty(mark, &[]);
|
||||
w.raw("</w:r>");
|
||||
}
|
||||
// A header's watermark, in its first top-level paragraph (not a table cell or text box).
|
||||
if depth == 0
|
||||
&& let Some(run) = self.pending_watermark.take()
|
||||
{
|
||||
w.raw(&run);
|
||||
}
|
||||
// Taken before the content so a nested story (a text box in an entry) can't claim them.
|
||||
if std::mem::take(&mut self.toc_begin_here)
|
||||
&& let Some((instr, locked, props)) = self.toc_field.take()
|
||||
&& let Some((instr, locked, dirty, props)) = self.toc_field.take()
|
||||
{
|
||||
self.rev_open(w, &props);
|
||||
self.field_start(w, &instr, locked, &props);
|
||||
self.field_start(w, &instr, locked, dirty, "", &props);
|
||||
self.rev_close(w, &props);
|
||||
}
|
||||
let toc_end = std::mem::take(&mut self.toc_end_here);
|
||||
@@ -464,7 +479,7 @@ impl Writer<'_> {
|
||||
w.empty("w:commentRangeEnd", &[("w:id", &s)]);
|
||||
w.open("w:r", &[]);
|
||||
w.open("w:rPr", &[]);
|
||||
w.val("w:rStyle", "CommentReference");
|
||||
w.val("w:rStyle", comment_reference_style(self.doc));
|
||||
w.close("w:rPr");
|
||||
w.empty("w:commentReference", &[("w:id", &s)]);
|
||||
w.close("w:r");
|
||||
@@ -472,15 +487,19 @@ impl Writer<'_> {
|
||||
}
|
||||
InlineObject::Equation { linear, display, math } => {
|
||||
// Automatic equation numbers become text: Word numbers nothing by itself.
|
||||
let color = match props.color {
|
||||
Some(TextColor::Rgb(c)) => Some(c),
|
||||
_ => None,
|
||||
};
|
||||
match super::math::resolve_numbers(math, *display, &mut self.eq_number) {
|
||||
Some(m) => super::math::write_equation(w, linear, *display, &m),
|
||||
None => super::math::write_equation(w, linear, *display, math),
|
||||
Some(m) => super::math::write_equation(w, linear, *display, &m, color),
|
||||
None => super::math::write_equation(w, linear, *display, math, color),
|
||||
}
|
||||
}
|
||||
InlineObject::Field { instr, result, locked, .. } => self.field(w, instr, result, *locked, props),
|
||||
InlineObject::FieldStart { instr, locked } => {
|
||||
InlineObject::Field { instr, result, locked, dirty, form, .. } => self.field(w, instr, result, *locked, *dirty, form, props),
|
||||
InlineObject::FieldStart { instr, locked, dirty } => {
|
||||
self.rev_open(w, props);
|
||||
self.field_start(w, instr, *locked, props);
|
||||
self.field_start(w, instr, *locked, *dirty, "", props);
|
||||
self.rev_close(w, props);
|
||||
}
|
||||
InlineObject::FieldEnd => {
|
||||
@@ -540,12 +559,16 @@ impl Writer<'_> {
|
||||
if ink && !direct_ink {
|
||||
Self::ink_transform(&mut root, (graphic.w, graphic.h), (*gw, *gh), float, 0);
|
||||
}
|
||||
let alternate = (ink && root.name == "mc:AlternateContent").then_some(&root);
|
||||
// Native ink, or an Office 2016 chart (`cx:chart`) with its fallback picture.
|
||||
let alternate = (root.name == "mc:AlternateContent").then_some(&root);
|
||||
let fallback = alternate.and_then(|e| e.child("mc:Fallback"));
|
||||
let native = alternate.and_then(|e| e.child("mc:Choice")).and_then(|e| e.find("a:graphic"));
|
||||
let choice = alternate.and_then(|e| e.child("mc:Choice"));
|
||||
let native = choice.and_then(|e| e.find("a:graphic"));
|
||||
if alternate.is_some() && native.is_none() {
|
||||
return;
|
||||
}
|
||||
// A chart's picture gets the chart's current frame too; ink's VML preview is resized in place.
|
||||
let picture = if ink { None } else { fallback.and_then(|e| e.find("a:graphic")) };
|
||||
self.rev_open(w, props);
|
||||
w.open("w:r", &[]);
|
||||
self.rpr(w, props);
|
||||
@@ -553,24 +576,30 @@ impl Writer<'_> {
|
||||
w.raw(&root.to_xml());
|
||||
} else {
|
||||
if fallback.is_some() {
|
||||
let requires = if ink { "wpi" } else { choice.and_then(|c| c.attr("Requires")).unwrap_or_default() };
|
||||
w.open("mc:AlternateContent", &[]);
|
||||
w.open("mc:Choice", &[("Requires", "wpi")]);
|
||||
w.open("mc:Choice", &[("Requires", requires)]);
|
||||
}
|
||||
w.open("w:drawing", &[]);
|
||||
let docpr = self.next_docpr();
|
||||
let name = match graphic.kind {
|
||||
wordcraft_doc::graphic::GraphicKind::Chart => format!("Chart {docpr}"),
|
||||
wordcraft_doc::graphic::GraphicKind::Diagram => format!("Diagram {docpr}"),
|
||||
wordcraft_doc::graphic::GraphicKind::Ink => format!("Ink {docpr}"),
|
||||
};
|
||||
self.drawing_open(w, float, *gw, *gh, &docpr, &name, alt);
|
||||
w.empty("wp:cNvGraphicFramePr", &[]);
|
||||
w.raw(&native.unwrap_or(&root).to_xml());
|
||||
w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" });
|
||||
w.close("w:drawing");
|
||||
let z = self.z;
|
||||
self.graphic_frame(w, float, (*gw, *gh), &docpr, &name, alt, native.unwrap_or(&root));
|
||||
if let Some(fallback) = fallback {
|
||||
w.close("mc:Choice");
|
||||
w.raw(&fallback.to_xml());
|
||||
match picture {
|
||||
Some(picture) => {
|
||||
// Both branches are one object: same id and stacking order.
|
||||
self.z = z;
|
||||
w.open("mc:Fallback", &[]);
|
||||
self.graphic_frame(w, float, (*gw, *gh), &docpr, &name, alt, picture);
|
||||
w.close("mc:Fallback");
|
||||
}
|
||||
None => w.raw(&fallback.to_xml()),
|
||||
}
|
||||
w.close("mc:AlternateContent");
|
||||
}
|
||||
}
|
||||
@@ -624,7 +653,7 @@ impl Writer<'_> {
|
||||
}
|
||||
// Tight and Through wrapping need a polygon: the shape's outline unless it has one.
|
||||
if matches!(float.wrap, Wrap::Tight | Wrap::Through) && float.wrap_polygon.is_none() {
|
||||
float.wrap_polygon = wordcraft_doc::wrap::shape_outline(*kind, *sw, *sh)
|
||||
float.wrap_polygon = wordcraft_doc::wrap::shape_outline(*kind, *sw, *sh, extra.corner)
|
||||
.and_then(|pts| wordcraft_doc::wrap::WrapPolygon::from_unit(false, &pts))
|
||||
.map(std::sync::Arc::new);
|
||||
}
|
||||
@@ -766,11 +795,11 @@ impl Writer<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn field(&mut self, w: &mut W, instr: &str, result: &str, locked: bool, props: &CharProps) {
|
||||
fn field(&mut self, w: &mut W, instr: &str, result: &str, locked: bool, dirty: bool, form: &str, props: &CharProps) {
|
||||
if self.toc_hold_end && is_toc(instr) {
|
||||
// A TOC heading's field opens in the first entry and closes after the last (see `toc_span`).
|
||||
self.toc_hold_end = false;
|
||||
self.toc_field = Some((instr.to_string(), locked, props.clone()));
|
||||
self.toc_field = Some((instr.to_string(), locked, dirty, props.clone()));
|
||||
return;
|
||||
}
|
||||
if let Some(e) = wordcraft_doc::eq::Enclosure::parse(instr) {
|
||||
@@ -787,7 +816,7 @@ impl Writer<'_> {
|
||||
w.close("w:r");
|
||||
};
|
||||
self.rev_open(w, props);
|
||||
self.field_start(w, instr, locked, props);
|
||||
self.field_start(w, instr, locked, dirty, form, props);
|
||||
if !result.is_empty() {
|
||||
run(w, &|w| {
|
||||
let mut buf = String::new();
|
||||
@@ -865,7 +894,9 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
/// A field's begin, instruction and separate runs.
|
||||
fn field_start(&self, w: &mut W, instr: &str, locked: bool, props: &CharProps) {
|
||||
/// A field's begin, code and separator; `form` is a legacy form field's `w:ffData`, which
|
||||
/// belongs inside the begin.
|
||||
fn field_start(&self, w: &mut W, instr: &str, locked: bool, dirty: bool, form: &str, props: &CharProps) {
|
||||
let del = self.is_del(props);
|
||||
let run = |w: &mut W, f: &dyn Fn(&mut W)| {
|
||||
w.open("w:r", &[]);
|
||||
@@ -874,10 +905,19 @@ impl Writer<'_> {
|
||||
w.close("w:r");
|
||||
};
|
||||
run(w, &|w| {
|
||||
let mut attrs: Vec<(&str, &str)> = vec![("w:fldCharType", "begin")];
|
||||
if locked {
|
||||
w.empty("w:fldChar", &[("w:fldCharType", "begin"), ("w:fldLock", "1")])
|
||||
attrs.push(("w:fldLock", "1"));
|
||||
}
|
||||
if dirty {
|
||||
attrs.push(("w:dirty", "true"));
|
||||
}
|
||||
if form.is_empty() {
|
||||
w.empty("w:fldChar", &attrs);
|
||||
} else {
|
||||
w.empty("w:fldChar", &[("w:fldCharType", "begin")])
|
||||
w.open("w:fldChar", &attrs);
|
||||
w.raw(form);
|
||||
w.close("w:fldChar");
|
||||
}
|
||||
});
|
||||
let instr_text = format!(" {} ", instr.trim());
|
||||
@@ -951,7 +991,9 @@ impl Writer<'_> {
|
||||
ShapeKind::Rectangle | ShapeKind::TextBox | ShapeKind::Freeform => "rect",
|
||||
ShapeKind::RoundedRectangle => "roundRect",
|
||||
ShapeKind::Ellipse => "ellipse",
|
||||
ShapeKind::FlowchartOr => "flowChartOr",
|
||||
ShapeKind::Triangle => "triangle",
|
||||
ShapeKind::RightTriangle => "rtTriangle",
|
||||
ShapeKind::Diamond => "diamond",
|
||||
ShapeKind::Line => "line",
|
||||
ShapeKind::StraightConnector => "straightConnector1",
|
||||
@@ -965,7 +1007,15 @@ impl Writer<'_> {
|
||||
Some(f) => cust_geom(w, f, *sw, *sh),
|
||||
None => {
|
||||
w.open("a:prstGeom", &[("prst", prst)]);
|
||||
w.empty("a:avLst", &[]);
|
||||
match extra.corner.filter(|_| *kind == ShapeKind::RoundedRectangle) {
|
||||
Some(c) => {
|
||||
w.open("a:avLst", &[]);
|
||||
let fmla = format!("val {}", c.min(wordcraft_doc::connector::MAX_CORNER));
|
||||
w.empty("a:gd", &[("name", "adj"), ("fmla", &fmla)]);
|
||||
w.close("a:avLst");
|
||||
}
|
||||
None => w.empty("a:avLst", &[]),
|
||||
}
|
||||
w.close("a:prstGeom");
|
||||
}
|
||||
}
|
||||
@@ -1061,6 +1111,17 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// A `w:drawing` holding `graphic` (an `a:graphic`) in a frame of the object's size and place.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn graphic_frame(&mut self, w: &mut W, float: &Float, (gw, gh): (f32, f32), docpr: &str, name: &str, alt: &str, graphic: &crate::xml::El) {
|
||||
w.open("w:drawing", &[]);
|
||||
self.drawing_open(w, float, gw, gh, docpr, name, alt);
|
||||
w.empty("wp:cNvGraphicFramePr", &[]);
|
||||
w.raw(&graphic.to_xml());
|
||||
w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" });
|
||||
w.close("w:drawing");
|
||||
}
|
||||
|
||||
fn drawing_open(&mut self, w: &mut W, float: &Float, iw: f32, ih: f32, docpr: &str, name: &str, alt: &str) {
|
||||
let (cx, cy) = (emu(iw.max(0.0)), emu(ih.max(0.0)));
|
||||
if float.wrap == Wrap::Inline {
|
||||
@@ -1202,9 +1263,34 @@ impl Writer<'_> {
|
||||
w.close("w:tbl");
|
||||
}
|
||||
|
||||
/// The section's headers, plus the header holding only the watermark in each slot the
|
||||
/// pages show (first page with a title page, even pages with even/odd headers) that has no
|
||||
/// header of its own or linked from an earlier section. Sections are written in body order.
|
||||
fn watermark_headers(&mut self, s: &SectionProps) -> wordcraft_doc::section::HeaderSet {
|
||||
let mut set = s.headers;
|
||||
let linked = &mut self.linked_headers;
|
||||
if self.doc.settings.watermark.as_ref().and_then(super::watermark::text).is_some() {
|
||||
let id = self.wm_header;
|
||||
if set.default.or(linked.default).is_none() {
|
||||
set.default = Some(id);
|
||||
}
|
||||
if s.title_page && set.first.or(linked.first).is_none() {
|
||||
set.first = Some(id);
|
||||
}
|
||||
if self.doc.settings.even_odd_headers && set.even.or(linked.even).is_none() {
|
||||
set.even = Some(id);
|
||||
}
|
||||
}
|
||||
linked.default = set.default.or(linked.default);
|
||||
linked.first = set.first.or(linked.first);
|
||||
linked.even = set.even.or(linked.even);
|
||||
set
|
||||
}
|
||||
|
||||
pub fn sectpr(&mut self, w: &mut W, s: &SectionProps, rels: &mut PartRels) {
|
||||
w.open("w:sectPr", &[]);
|
||||
for (set, footer) in [(&s.headers, false), (&s.footers, true)] {
|
||||
let headers = self.watermark_headers(s);
|
||||
for (set, footer) in [(&headers, false), (&s.footers, true)] {
|
||||
for (kind, id) in [("default", set.default), ("first", set.first), ("even", set.even)] {
|
||||
let Some(id) = id else { continue };
|
||||
if let Some(rid) = self.hf_rel(id, footer, rels) {
|
||||
@@ -1283,7 +1369,7 @@ fn sectpr_body(w: &mut W, s: &SectionProps) {
|
||||
let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
w.empty("w:lnNumType", &refs);
|
||||
}
|
||||
if s.page_num_start.is_some() || s.page_num_format != wordcraft_doc::section::NumFormat::Decimal {
|
||||
if s.page_num_set || s.page_num_start.is_some() || s.page_num_format != wordcraft_doc::section::NumFormat::Decimal {
|
||||
let mut a = vec![("w:fmt", s.page_num_format.ooxml().to_string())];
|
||||
if let Some(st) = s.page_num_start {
|
||||
a.push(("w:start", st.to_string()));
|
||||
@@ -1310,15 +1396,19 @@ fn sectpr_body(w: &mut W, s: &SectionProps) {
|
||||
let refs: Vec<(&str, &str)> = ca.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
w.empty("w:cols", &refs);
|
||||
}
|
||||
if let Some(on) = s.form_prot {
|
||||
w.empty("w:formProt", if on { &[] } else { &[("w:val", "0")] });
|
||||
}
|
||||
match s.valign {
|
||||
wordcraft_doc::props::VAlign::Top => {}
|
||||
wordcraft_doc::props::VAlign::Center => w.val("w:vAlign", "center"),
|
||||
wordcraft_doc::props::VAlign::Bottom => w.val("w:vAlign", "bottom"),
|
||||
wordcraft_doc::section::PageVAlign::Top => {}
|
||||
wordcraft_doc::section::PageVAlign::Center => w.val("w:vAlign", "center"),
|
||||
wordcraft_doc::section::PageVAlign::Justify => w.val("w:vAlign", "both"),
|
||||
wordcraft_doc::section::PageVAlign::Bottom => w.val("w:vAlign", "bottom"),
|
||||
}
|
||||
if s.title_page {
|
||||
w.empty("w:titlePg", &[]);
|
||||
}
|
||||
if s.text_direction.is_turned() {
|
||||
if s.text_direction.is_turned() || s.text_direction_set {
|
||||
w.val("w:textDirection", s.text_direction.ooxml());
|
||||
}
|
||||
if s.rtl {
|
||||
@@ -1595,3 +1685,14 @@ pub(super) fn note_pr_inner(w: &mut W, pr: &NoteProps) {
|
||||
w.val("w:numRestart", r.ooxml());
|
||||
}
|
||||
}
|
||||
|
||||
/// The character style for comment reference marks: the document's "annotation reference" style
|
||||
/// (Word's built-in name; localized documents give it another id, e.g. Polish
|
||||
/// `Odwoaniedokomentarza`), else `CommentReference`.
|
||||
fn comment_reference_style(doc: &wordcraft_doc::Document) -> &str {
|
||||
doc.styles
|
||||
.styles
|
||||
.iter()
|
||||
.find(|s| s.kind == wordcraft_doc::styles::StyleKind::Character && s.name.eq_ignore_ascii_case("annotation reference"))
|
||||
.map_or("CommentReference", |s| s.id.as_str())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The document's text watermark as a VML text shape in the headers (ECMA-376 Part 4, VML:
|
||||
//! `shape`, `shapetype`, `path`, `textpath`, `fill`), which is how a WordprocessingML consumer
|
||||
//! draws text behind every page. The reader (`read::story::vml_watermark`) maps it back.
|
||||
|
||||
use wordcraft_doc::{SectionProps, Watermark};
|
||||
|
||||
use crate::xml::esc;
|
||||
|
||||
/// The shape type the watermark shape uses: two straight subpaths, the box's top and bottom
|
||||
/// edges, between which the `v:textpath` text is stretched to fit the shape (`fitshape`). A single
|
||||
/// path gives the text no height, and Word draws nothing.
|
||||
const SHAPETYPE_ID: &str = "_x0000_t136";
|
||||
const SHAPETYPE_PATH: &str = "m0,0l21600,0m0,21600l21600,21600e";
|
||||
|
||||
/// The watermark text as written: what the reader accepts (non-blank, at most 200 characters).
|
||||
pub(super) fn text(wm: &Watermark) -> Option<String> {
|
||||
let t: String = wm.text.chars().take(200).collect();
|
||||
(!t.trim().is_empty()).then_some(t)
|
||||
}
|
||||
|
||||
/// A `w:r` holding the watermark shape (and its shape type), for the first paragraph of header
|
||||
/// part number `n`. Sized like the renderers draw it: half the page width across, or half the
|
||||
/// page diagonal when diagonal; the height follows the text's length.
|
||||
pub(super) fn run(wm: &Watermark, n: usize, page: &SectionProps) -> Option<String> {
|
||||
let text = text(wm)?;
|
||||
let (pw, ph) = (page.page_w.clamp(72.0, 4000.0), page.page_h.clamp(72.0, 4000.0));
|
||||
let across = if wm.diagonal { (pw * pw + ph * ph).sqrt() } else { pw };
|
||||
let width = (across * 0.5).clamp(36.0, 2000.0);
|
||||
let chars = text.chars().count().clamp(1, 200) as f32;
|
||||
let height = (width / (0.55 * chars)).clamp(12.0, 400.0);
|
||||
// A font name can't break out of the textpath's CSS-like style.
|
||||
let font: String = wm.font.chars().filter(|c| !matches!(c, '"' | '\'' | ';' | ':')).take(100).collect();
|
||||
let font = if font.trim().is_empty() { Watermark::default().font } else { font };
|
||||
let rotation = if wm.diagonal { "rotation:315;" } else { "" };
|
||||
let style = format!(
|
||||
"position:absolute;margin-left:0;margin-top:0;width:{width:.1}pt;height:{height:.1}pt;{rotation}z-index:-251654144;\
|
||||
mso-position-horizontal:center;mso-position-horizontal-relative:margin;\
|
||||
mso-position-vertical:center;mso-position-vertical-relative:margin"
|
||||
);
|
||||
let fill = if wm.semitransparent { r#"<v:fill opacity=".5"/>"# } else { "" };
|
||||
Some(format!(
|
||||
concat!(
|
||||
r#"<w:r><w:rPr><w:noProof/></w:rPr><w:pict>"#,
|
||||
r#"<v:shapetype id="{st}" coordsize="21600,21600" o:spt="136" path="{path}">"#,
|
||||
r#"<v:path textpathok="t"/><v:textpath on="t" fitshape="t"/></v:shapetype>"#,
|
||||
r##"<v:shape id="PowerPlusWaterMarkObject{n}" type="#{st}" style="{style}" o:allowincell="f" fillcolor="#{color}" stroked="f">"##,
|
||||
r#"{fill}<v:textpath style="{tstyle}" string="{text}"/></v:shape></w:pict></w:r>"#
|
||||
),
|
||||
st = SHAPETYPE_ID,
|
||||
path = SHAPETYPE_PATH,
|
||||
n = n,
|
||||
style = esc(&style),
|
||||
color = wm.color.hex(),
|
||||
fill = fill,
|
||||
tstyle = esc(&format!("font-family:\"{font}\";font-size:1pt")),
|
||||
text = esc(&text),
|
||||
))
|
||||
}
|
||||
@@ -38,6 +38,16 @@ pub const NAMESPACES: &[(&str, &str)] = &[
|
||||
("v", "urn:schemas-microsoft-com:vml"),
|
||||
("o", "urn:schemas-microsoft-com:office:office"),
|
||||
("w10", "urn:schemas-microsoft-com:office:word"),
|
||||
// Office 2016 charts (`cx:chart`), and the namespaces their `mc:Choice` requires.
|
||||
("cx", "http://schemas.microsoft.com/office/drawing/2014/chartex"),
|
||||
("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex"),
|
||||
("cx2", "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex"),
|
||||
("cx3", "http://schemas.microsoft.com/office/drawing/2016/5/9/chartex"),
|
||||
("cx4", "http://schemas.microsoft.com/office/drawing/2016/5/10/chartex"),
|
||||
("cx5", "http://schemas.microsoft.com/office/drawing/2016/5/11/chartex"),
|
||||
("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex"),
|
||||
("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex"),
|
||||
("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex"),
|
||||
];
|
||||
|
||||
/// The `a:ext` URI under which a drawing is marked decorative ([MS-ODRAWXML]), and the
|
||||
|
||||
@@ -190,7 +190,7 @@ fn orphan_markers_from_editing_are_dropped_on_save() {
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().insert_object(0, InlineObject::FieldEnd, &c).unwrap();
|
||||
d.para_mut(StoryRef::Body, &Path::top(1))
|
||||
.unwrap()
|
||||
.insert_object(1, InlineObject::FieldStart { instr: "ADDIN X".into(), locked: true }, &c)
|
||||
.insert_object(1, InlineObject::FieldStart { instr: "ADDIN X".into(), locked: true, dirty: false }, &c)
|
||||
.unwrap();
|
||||
let xml = document_xml(&write(&d).unwrap());
|
||||
assert_eq!(count(&xml, "begin"), 0);
|
||||
@@ -204,7 +204,7 @@ fn programmatic_range_field_writes_as_word_field() {
|
||||
let mut d = Document::from_text("ab");
|
||||
let c = CharProps::default();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(1, InlineObject::FieldStart { instr: "ADDIN ZOTERO_ITEM {}".into(), locked: false }, &c).unwrap();
|
||||
p.insert_object(1, InlineObject::FieldStart { instr: "ADDIN ZOTERO_ITEM {}".into(), locked: false, dirty: false }, &c).unwrap();
|
||||
let end = 1 + OBJ.len_utf8() + 1;
|
||||
p.insert_object(end, InlineObject::FieldEnd, &c).unwrap();
|
||||
d.set_custom_prop("ZOTERO_PREF_1", "<data/>");
|
||||
|
||||
@@ -113,11 +113,31 @@ fn single_entry_toc_keeps_formatted_result_and_nested_page_field() {
|
||||
);
|
||||
let p = paras(&d);
|
||||
assert_eq!(p[0].plain_text(), "Contents");
|
||||
assert_eq!(p[0].objects, vec![InlineObject::Field { instr: r#"TOC \o "1-1" \h"#.into(), result: String::new(), locked: true, code: false }]);
|
||||
assert_eq!(
|
||||
p[0].objects,
|
||||
vec![InlineObject::Field {
|
||||
instr: r#"TOC \o "1-1" \h"#.into(),
|
||||
result: String::new(),
|
||||
locked: true,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new()
|
||||
}]
|
||||
);
|
||||
assert_eq!(p[1].plain_text(), "Intro\t1");
|
||||
assert_eq!(p[1].props_of_char(0).bold, Some(true));
|
||||
assert_eq!(p[1].props_of_char(0).link.as_deref(), Some("#_Toc1"));
|
||||
assert_eq!(p[1].objects, vec![InlineObject::Field { instr: r#"PAGEREF _Toc1 \h"#.into(), result: "1".into(), locked: false, code: false }]);
|
||||
assert_eq!(
|
||||
p[1].objects,
|
||||
vec![InlineObject::Field {
|
||||
instr: r#"PAGEREF _Toc1 \h"#.into(),
|
||||
result: "1".into(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -135,8 +155,18 @@ fn toc_complex_field_spanning_paragraphs() {
|
||||
let p = paras(&d);
|
||||
assert_eq!(p.len(), 5);
|
||||
assert_eq!(p[0].text, "\u{FFFC}Intro\t\u{FFFC}");
|
||||
assert_eq!(p[0].objects[0], InlineObject::FieldStart { instr: r#"TOC \o "1-3" \h \z \u"#.into(), locked: false });
|
||||
assert_eq!(p[0].objects[1], InlineObject::Field { instr: r#"PAGEREF _Toc1 \h"#.into(), result: "1".into(), locked: false, code: false });
|
||||
assert_eq!(p[0].objects[0], InlineObject::FieldStart { instr: r#"TOC \o "1-3" \h \z \u"#.into(), locked: false, dirty: false });
|
||||
assert_eq!(
|
||||
p[0].objects[1],
|
||||
InlineObject::Field {
|
||||
instr: r#"PAGEREF _Toc1 \h"#.into(),
|
||||
result: "1".into(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new()
|
||||
}
|
||||
);
|
||||
assert_eq!(p[0].props_of_char(3).link.as_deref(), Some("#_Toc1"));
|
||||
assert_eq!(p[0].props.style.as_deref(), Some("TOC1"));
|
||||
assert_eq!(p[1].text, "Body\t2");
|
||||
@@ -144,7 +174,10 @@ fn toc_complex_field_spanning_paragraphs() {
|
||||
assert_eq!(p[2].objects, vec![InlineObject::FieldEnd]);
|
||||
assert_eq!(p[3].objects, vec![InlineObject::BookmarkStart { name: "_Toc1".into() }, InlineObject::BookmarkEnd { name: "_Toc1".into() }]);
|
||||
assert_eq!(p[4].plain_text(), "Page 7");
|
||||
assert_eq!(p[4].objects[0], InlineObject::Field { instr: "PAGE".into(), result: "7".into(), locked: false, code: false });
|
||||
assert_eq!(
|
||||
p[4].objects[0],
|
||||
InlineObject::Field { instr: "PAGE".into(), result: "7".into(), locked: false, dirty: false, code: false, form: String::new() }
|
||||
);
|
||||
// And it writes back out and reads the same.
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(again.body, d.body);
|
||||
@@ -404,6 +437,56 @@ fn table_style_whole_table_shading_and_margins() {
|
||||
assert_eq!(merged.parts.cell_margins, Some([1.0, 14.4, 0.0, 14.4]), "from Base");
|
||||
}
|
||||
|
||||
fn gallery_ids(styles: &str) -> Vec<String> {
|
||||
let bytes = docx("<w:p/>", &[("rId1", "styles", "styles.xml")], &[("word/styles.xml", styles)]);
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
d.styles.gallery().iter().map(|s| s.id.clone()).collect()
|
||||
}
|
||||
|
||||
/// LibreOffice writes no `w:qFormat`: the Styles gallery still shows Word's usual quick styles.
|
||||
#[test]
|
||||
fn styles_without_qformat_get_the_default_gallery() {
|
||||
let styles = format!(
|
||||
r#"<w:styles {W_NS}>
|
||||
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/></w:style>
|
||||
<w:style w:type="character" w:styleId="Emphasis"><w:name w:val="Emphasis"/></w:style>
|
||||
</w:styles>"#
|
||||
);
|
||||
let ids = gallery_ids(&styles);
|
||||
for id in ["Normal", "NoSpacing", "Heading1", "Heading2", "Title", "Subtitle"] {
|
||||
assert!(ids.iter().any(|i| i == id), "{id} in {ids:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom style called "Title" is not the built-in one: it stays out of the gallery, and the
|
||||
/// built-in Title is not added over its name.
|
||||
#[test]
|
||||
fn custom_style_named_like_a_quick_builtin_is_not_quick() {
|
||||
let styles = format!(
|
||||
r#"<w:styles {W_NS}>
|
||||
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
|
||||
<w:style w:type="paragraph" w:customStyle="1" w:styleId="MyTitle"><w:name w:val="Title"/></w:style>
|
||||
</w:styles>"#
|
||||
);
|
||||
let ids = gallery_ids(&styles);
|
||||
assert!(ids.iter().any(|i| i == "Normal"), "{ids:?}");
|
||||
assert!(!ids.iter().any(|i| i == "MyTitle" || i == "Title"), "{ids:?}");
|
||||
}
|
||||
|
||||
/// A file that uses `w:qFormat` (Word's own) keeps exactly the gallery it says.
|
||||
#[test]
|
||||
fn styles_with_qformat_keep_their_gallery() {
|
||||
let styles = format!(
|
||||
r#"<w:styles {W_NS}>
|
||||
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/></w:style>
|
||||
</w:styles>"#
|
||||
);
|
||||
assert_eq!(gallery_ids(&styles), vec!["Normal".to_string()]);
|
||||
}
|
||||
|
||||
/// Word starts every note with a `w:footnoteRef` / `w:endnoteRef` mark: the note's own number.
|
||||
/// It reads as a reference to the note itself, so the note text shows its number.
|
||||
#[test]
|
||||
@@ -598,11 +681,56 @@ fn unbalanced_fields_and_markers() {
|
||||
let d = read_body(body);
|
||||
let p = paras(&d);
|
||||
assert_eq!(p[0].text, "a");
|
||||
assert_eq!(p[1].objects, vec![InlineObject::Field { instr: "IF X = \"y\"".into(), result: String::new(), locked: false, code: false }]);
|
||||
assert_eq!(
|
||||
p[1].objects,
|
||||
vec![InlineObject::Field {
|
||||
instr: "IF X = \"y\"".into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new()
|
||||
}]
|
||||
);
|
||||
assert_eq!(p[2].objects, vec![InlineObject::BookmarkStart { name: "between".into() }, InlineObject::BookmarkEnd { name: "between".into() }]);
|
||||
assert_eq!(p[2].plain_text(), "after");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_code_spans_paragraphs() {
|
||||
let body = r#"
|
||||
<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText>IF</w:instrText></w:r></w:p>
|
||||
<w:p><w:r><w:instrText> MERGEFIELD x</w:instrText><w:br/><w:instrText> = "y"</w:instrText></w:r></w:p>
|
||||
<w:p><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>
|
||||
<w:p><w:r><w:t>Visible</w:t></w:r></w:p>"#;
|
||||
let doc = read_body(body);
|
||||
let p = paras(&doc);
|
||||
assert_eq!(p.len(), 4);
|
||||
for code in &p[..2] {
|
||||
assert!(code.plain_text().is_empty());
|
||||
assert_eq!(code.mark.hidden, Some(true));
|
||||
}
|
||||
assert_eq!(p[2].mark.hidden, None);
|
||||
assert_eq!(p[3].plain_text(), "Visible");
|
||||
assert_eq!(p[3].mark.hidden, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_field_results_keep_line() {
|
||||
let body = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/><w:instrText>PAGE</w:instrText><w:fldChar w:fldCharType="separate"/><w:fldChar w:fldCharType="end"/></w:r></w:p>
|
||||
<w:p><w:r><w:fldChar w:fldCharType="begin"/><w:instrText>IF</w:instrText></w:r></w:p>
|
||||
<w:p/>
|
||||
<w:p><w:r><w:instrText> x = y</w:instrText><w:fldChar w:fldCharType="separate"/><w:t>Result</w:t><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
|
||||
let doc = read_body(body);
|
||||
let p = paras(&doc);
|
||||
assert_eq!(p[0].mark.hidden, None);
|
||||
assert!(matches!(&p[0].objects[0], InlineObject::Field { instr, .. } if instr == "PAGE"));
|
||||
assert_eq!(p[1].mark.hidden, Some(true));
|
||||
assert_eq!(p[2].mark.hidden, Some(true));
|
||||
assert_eq!(p[3].mark.hidden, None);
|
||||
assert_eq!(p[3].plain_text(), "Result");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_self_reference_and_escaping_targets() {
|
||||
let hdr = format!(
|
||||
@@ -638,6 +766,20 @@ fn with_settings(settings: Option<&str>) -> Document {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_contextual_spacing_compatibility_flag_is_read() {
|
||||
assert!(!with_settings(None).settings.allow_space_of_same_style_in_table);
|
||||
for (flag, expected) in [
|
||||
("", false),
|
||||
(r#"<w:allowSpaceOfSameStyleInTable w:val="0"/>"#, false),
|
||||
(r#"<w:allowSpaceOfSameStyleInTable/>"#, true),
|
||||
(r#"<w:allowSpaceOfSameStyleInTable w:val="1"/>"#, true),
|
||||
] {
|
||||
let settings = format!("<w:compat>{flag}</w:compat>");
|
||||
assert_eq!(with_settings(Some(&settings)).settings.allow_space_of_same_style_in_table, expected, "{flag}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compatibility_mode_is_read_and_defaults_to_word_2007() {
|
||||
let compat = |v: &str| {
|
||||
@@ -742,6 +884,129 @@ fn bare_break_directly_in_paragraph() {
|
||||
assert_eq!(paras(&d2)[0].text, "First\nSecond\n\u{C}Third");
|
||||
}
|
||||
|
||||
/// Issue #1290: Word's text watermark, a VML shape with a `v:textpath` in a header or footer,
|
||||
/// becomes the document's watermark (drawn on every page) instead of being dropped; other WordArt
|
||||
/// is not a watermark, and hostile values don't panic.
|
||||
#[test]
|
||||
fn vml_textpath_in_header_is_the_watermark() {
|
||||
let read = |shape: &str, in_header: bool| {
|
||||
let pict = format!("<w:p><w:r><w:t>Header label</w:t></w:r><w:r><w:pict>{shape}</w:pict></w:r></w:p>");
|
||||
let header = format!(r#"<w:hdr {W_NS}>{}</w:hdr>"#, if in_header { pict.as_str() } else { "<w:p/>" });
|
||||
let body = format!(
|
||||
r#"{}<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="rIdH"/></w:sectPr>"#,
|
||||
if in_header { "" } else { pict.as_str() }
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(&body, &[("rIdH", "header", "header1.xml")], &[("word/header1.xml", &header)])).unwrap();
|
||||
let hid = d.last_section.headers.default.unwrap();
|
||||
let header_objects = d.parts.get(&hid).unwrap().blocks.iter().filter_map(|b| b.as_para()).map(|p| p.objects.len()).sum::<usize>();
|
||||
let header_text = d.parts.get(&hid).unwrap().blocks.first().and_then(|b| b.as_para()).map(|p| p.text.clone()).unwrap_or_default();
|
||||
(d.settings.watermark.clone(), header_objects, header_text)
|
||||
};
|
||||
|
||||
// Word's Design › Watermark shape: turned 315°, silver, semitransparent, quoted font name.
|
||||
let word = r##"<v:shape id="PowerPlusWaterMarkObject1" o:spid="_x0000_s1025" type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:412.4pt;height:247.4pt;rotation:315;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" o:allowincell="f" fillcolor="silver" stroked="f"><v:fill opacity=".5"/><v:textpath style="font-family:"Calibri Light";font-size:1pt" string="CONFIDENTIAL"/></v:shape>"##;
|
||||
let (wm, objects, text) = read(word, true);
|
||||
let wm = wm.expect("watermark");
|
||||
assert_eq!((wm.text.as_str(), wm.font.as_str(), wm.color), ("CONFIDENTIAL", "Calibri Light", Rgb(0xC0, 0xC0, 0xC0)));
|
||||
assert!(wm.diagonal && wm.semitransparent, "{wm:?}");
|
||||
// Consumed: not also drawn as a shape in the header, whose text stays.
|
||||
assert_eq!((objects, text.as_str()), (0, "Header label"));
|
||||
|
||||
// A page-centred, gray, opaque shape turned -40° (no `v:fill`).
|
||||
let gray = r##"<v:shape id="WaterMark" type="#_x0000_t136" style="width:500pt;height:100pt;margin-top:0;margin-left:0;mso-position-horizontal:center;mso-position-horizontal-relative:page;mso-position-vertical:center;mso-position-vertical-relative:page;position:absolute;rotation:-40" fillcolor="gray" strokecolor="gray"><v:textpath style="font-family:Arial" string="BOZZA"/></v:shape>"##;
|
||||
let wm = read(gray, true).0.expect("watermark");
|
||||
assert_eq!(
|
||||
(wm.text.as_str(), wm.font.as_str(), wm.color, wm.diagonal, wm.semitransparent),
|
||||
("BOZZA", "Arial", Rgb(0x80, 0x80, 0x80), true, false)
|
||||
);
|
||||
|
||||
// Horizontal, centred both ways without Word's id, opacity in 65536ths.
|
||||
let flat = r##"<v:shape type="#_x0000_t136" style="position:absolute;width:300pt;height:60pt;mso-position-horizontal:center;mso-position-vertical:center" fillcolor="#336699"><v:fill opacity="32768f"/><v:textpath string="ASAP"/></v:shape>"##;
|
||||
let wm = read(flat, true).0.expect("watermark");
|
||||
assert_eq!((wm.color, wm.diagonal, wm.semitransparent), (Rgb(0x33, 0x66, 0x99), false, true));
|
||||
|
||||
// Not watermarks: the same shape in the body (WordArt); header WordArt that isn't centred
|
||||
// and isn't Word's watermark (a logo); a textpath turned off; a watermark-like shape inside a
|
||||
// header's text box.
|
||||
assert_eq!(read(gray, false).0, None);
|
||||
let logo = r##"<v:shape type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:120pt;height:30pt;mso-position-horizontal:left;mso-position-horizontal-relative:margin" fillcolor="navy"><v:textpath string="ACME"/></v:shape>"##;
|
||||
assert_eq!(read(logo, true).0, None);
|
||||
assert_eq!(read(&word.replace(r#"<v:textpath "#, r#"<v:textpath on="f" "#), true).0, None);
|
||||
let boxed = format!(
|
||||
r##"<v:shape type="#_x0000_t202" style="width:200pt;height:100pt"><v:textbox><w:txbxContent><w:p><w:r><w:pict>{word}</w:pict></w:r></w:p></w:txbxContent></v:textbox></v:shape>"##
|
||||
);
|
||||
assert_eq!(read(&boxed, true).0, None);
|
||||
|
||||
// A footer's watermark counts too, and the first one found wins.
|
||||
let footer = format!(r#"<w:ftr {W_NS}><w:p><w:r><w:pict>{gray}</w:pict></w:r></w:p></w:ftr>"#);
|
||||
let header = format!(r#"<w:hdr {W_NS}><w:p><w:r><w:pict>{word}</w:pict></w:r></w:p></w:hdr>"#);
|
||||
let body = r#"<w:p/><w:sectPr><w:headerReference w:type="default" r:id="rIdH"/><w:footerReference w:type="default" r:id="rIdF"/></w:sectPr>"#;
|
||||
let only_footer = r#"<w:p/><w:sectPr><w:footerReference w:type="default" r:id="rIdF"/></w:sectPr>"#;
|
||||
let parts = [("word/header1.xml", header.as_str()), ("word/footer1.xml", footer.as_str())];
|
||||
let rels = [("rIdH", "header", "header1.xml"), ("rIdF", "footer", "footer1.xml")];
|
||||
let wm = |body: &str| wordcraft_docx::read(&docx(body, &rels, &parts)).unwrap().settings.watermark.map(|w| w.text);
|
||||
assert_eq!(wm(only_footer).as_deref(), Some("BOZZA"));
|
||||
assert_eq!(wm(body).as_deref(), Some("CONFIDENTIAL"));
|
||||
|
||||
// Hostile values: an oversized string is capped, garbage rotation/opacity/colour don't panic,
|
||||
// an empty string is no watermark.
|
||||
let long = "W".repeat(10_000);
|
||||
let hostile = format!(
|
||||
r##"<v:shape id="PowerPlusWaterMarkObject9" style="rotation:NaNfd;width:-1e40pt" fillcolor="#zz" ><v:fill opacity="1e99f"/><v:textpath style="font-family:;" string="{long}"/></v:shape>"##
|
||||
);
|
||||
let wm = read(&hostile, true).0.expect("watermark");
|
||||
assert_eq!(wm.text.chars().count(), 200);
|
||||
assert!(!wm.font.is_empty());
|
||||
assert_eq!(read(r#"<v:shape id="PowerPlusWaterMarkObject2"><v:textpath string=" "/></v:shape>"#, true).0, None);
|
||||
}
|
||||
|
||||
/// Issue #1290: a file with Word's watermark keeps it through save and reopen: the same
|
||||
/// watermark, the same headers with the same text and paragraphs, one shape per header written;
|
||||
/// header WordArt that isn't a watermark doesn't become one on the way.
|
||||
#[test]
|
||||
fn word_watermark_survives_save() {
|
||||
let shape = |id: &str, text: &str| {
|
||||
format!(
|
||||
r##"<w:r><w:pict><v:shapetype id="_x0000_t136" coordsize="21600,21600" o:spt="136" path="m0,0l21600,0m0,21600l21600,21600e"><v:textpath on="t" fitshape="t"/></v:shapetype><v:shape id="{id}" type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:412pt;height:247pt;rotation:315;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" o:allowincell="f" fillcolor="silver" stroked="f"><v:fill opacity=".5"/><v:textpath style="font-family:"Calibri Light";font-size:1pt" string="{text}"/></v:shape></w:pict></w:r>"##
|
||||
)
|
||||
};
|
||||
let hdr = |inner: &str| {
|
||||
format!(r#"<w:hdr {W_NS}><w:p>{inner}<w:r><w:t>Header label</w:t></w:r></w:p><w:p><w:r><w:t>Second line</w:t></w:r></w:p></w:hdr>"#)
|
||||
};
|
||||
let h1 = hdr(&shape("PowerPlusWaterMarkObject1", "CONFIDENTIAL"));
|
||||
let h2 = hdr(&shape("PowerPlusWaterMarkObject2", "CONFIDENTIAL"));
|
||||
let body = r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="rIdH"/><w:headerReference w:type="first" r:id="rIdF"/><w:titlePg/></w:sectPr>"#;
|
||||
let rels = [("rIdH", "header", "header1.xml"), ("rIdF", "header", "header2.xml")];
|
||||
let d = wordcraft_docx::read(&docx(body, &rels, &[("word/header1.xml", &h1), ("word/header2.xml", &h2)])).unwrap();
|
||||
let wm = d.settings.watermark.clone().expect("watermark");
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let d2 = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(d2.settings.watermark, Some(wm));
|
||||
let headers = |d: &Document| {
|
||||
let mut v: Vec<Vec<String>> = [d.last_section.headers.default, d.last_section.headers.first]
|
||||
.iter()
|
||||
.map(|id| d.parts[&id.unwrap()].blocks.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect())
|
||||
.collect();
|
||||
v.push(vec![d.parts.len().to_string()]);
|
||||
v
|
||||
};
|
||||
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();
|
||||
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();
|
||||
assert_eq!(xml.matches("<v:shape ").count(), 1, "{name}");
|
||||
}
|
||||
|
||||
// A header logo in WordArt isn't a watermark, so none is written.
|
||||
let logo = r##"<w:r><w:pict><v:shape type="#_x0000_t136" style="position:absolute;width:120pt;height:30pt;mso-position-horizontal:left" fillcolor="navy"><v:textpath string="ACME"/></v:shape></w:pict></w:r>"##;
|
||||
let d = wordcraft_docx::read(&docx(body, &rels, &[("word/header1.xml", &hdr(logo)), ("word/header2.xml", &hdr(""))])).unwrap();
|
||||
assert_eq!(d.settings.watermark, None);
|
||||
let d2 = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(d2.settings.watermark, None);
|
||||
}
|
||||
|
||||
/// Issue #149: an absolutely positioned VML text box in a header floats where its style puts it
|
||||
/// (relative to the page here, behind the text at a negative z-index, no wrapping) instead of
|
||||
/// sitting inline in the header's flow, and it keeps that placement when saved and read back.
|
||||
@@ -928,6 +1193,88 @@ fn chart_round_trips_with_its_parts() {
|
||||
check_chart(&again, &ids[0]);
|
||||
}
|
||||
|
||||
// ---- Office 2016 charts (cx:chart) written back with their fallback picture (#997) ----
|
||||
|
||||
const CHARTEX_NS: &str = "http://schemas.microsoft.com/office/drawing/2014/chartex";
|
||||
const CHARTEX_XML: &str = r#"<cx:chartSpace xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><cx:chartData><cx:externalData r:id="rId1" cx:autoUpdate="0"/></cx:chartData><cx:chart><cx:plotArea><cx:plotAreaRegion><cx:series layoutId="boxWhisker"/></cx:plotAreaRegion></cx:plotArea></cx:chart></cx:chartSpace>"#;
|
||||
const CT_CHARTEX: &str = "application/vnd.ms-office.chartex+xml";
|
||||
|
||||
/// A package holding one box & whisker chart the way Word writes it: the `cx:chart` in an
|
||||
/// `mc:Choice` requiring `requires` (bound to `requires_ns`), a picture of it in the `mc:Fallback`.
|
||||
fn chartex_docx(requires: &str, requires_ns: &str) -> Vec<u8> {
|
||||
let frame = r#"<wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="2743200" cy="1371600"/><wp:docPr id="1" name="Chart 1"/><wp:cNvGraphicFramePr/>"#;
|
||||
let body = format!(
|
||||
r#"<w:p><w:r><w:t>Spread</w:t></w:r><w:r><mc:AlternateContent><mc:Choice xmlns:{requires}="{requires_ns}" Requires="{requires}"><w:drawing>{frame}<a:graphic><a:graphicData uri="{CHARTEX_NS}"><cx:chart xmlns:cx="{CHARTEX_NS}" r:id="rIdCx"/></a:graphicData></a:graphic></wp:inline></w:drawing></mc:Choice><mc:Fallback><w:drawing>{frame}<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:nvPicPr><pic:cNvPr id="1" name="Chart 1"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rIdPic"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2743200" cy="1371600"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></mc:Fallback></mc:AlternateContent></w:r></w:p>"#
|
||||
);
|
||||
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document {W_NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let doc_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdCx" Type="http://schemas.microsoft.com/office/2014/relationships/chartEx" Target="charts/chartEx1.xml"/><Relationship Id="rIdPic" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/></Relationships>"#;
|
||||
let chart_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/package" Target="../embeddings/Microsoft_Excel_Worksheet.xlsx"/><Relationship Id="rId2" Type="http://schemas.microsoft.com/office/2011/relationships/chartColorStyle" Target="colors1.xml"/></Relationships>"#;
|
||||
let types = format!(
|
||||
r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="xlsx" ContentType="{CT_XLSX}"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/charts/chartEx1.xml" ContentType="{CT_CHARTEX}"/><Override PartName="/word/charts/colors1.xml" ContentType="application/vnd.ms-office.chartcolorstyle+xml"/></Types>"#
|
||||
);
|
||||
zip(&[
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", ROOT_RELS.as_bytes()),
|
||||
("word/document.xml", doc.as_bytes()),
|
||||
("word/_rels/document.xml.rels", doc_rels.as_bytes()),
|
||||
("word/charts/chartEx1.xml", CHARTEX_XML.as_bytes()),
|
||||
("word/charts/_rels/chartEx1.xml.rels", chart_rels.as_bytes()),
|
||||
("word/charts/colors1.xml", COLORS_XML.as_bytes()),
|
||||
("word/embeddings/Microsoft_Excel_Worksheet.xlsx", WORKBOOK.as_bytes()),
|
||||
("word/media/image1.png", b"fallback picture bytes"),
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn office_2016_chart_keeps_its_chart_part_and_fallback_through_saves() {
|
||||
// Word binds `cx1`… to the chart type's own namespace; Apache POI's sample binds `cx`.
|
||||
for (requires, requires_ns) in [("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex"), ("cx", CHARTEX_NS)] {
|
||||
let mut d = wordcraft_docx::read(&chartex_docx(requires, requires_ns)).unwrap();
|
||||
for _ in 0..2 {
|
||||
let g = graphics(&d);
|
||||
let [InlineObject::Graphic { w, graphic, .. }] = g.as_slice() else { panic!("{requires}: {g:?}") };
|
||||
assert_eq!(*w, 216.0);
|
||||
assert!(
|
||||
graphic.items.iter().any(|i| matches!(i, wordcraft_doc::graphic::GraphicItem::Image { media, .. } if d.media.contains_key(media))),
|
||||
"{requires}: the chart shows its fallback picture"
|
||||
);
|
||||
let files = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
let body = text(&files, "word/document.xml");
|
||||
assert_eq!(attr_values(&body, "mc:Choice", "Requires"), [requires], "{body}");
|
||||
assert!(body.contains(&format!(r#"xmlns:{requires}="{requires_ns}""#)), "{requires} is declared: {body}");
|
||||
let doc_rels = text(&files, "word/_rels/document.xml.rels");
|
||||
let [cx_id] = attr_values(&body, "cx:chart", "r:id").try_into().unwrap_or_else(|_| panic!("chart lost: {body}"));
|
||||
let (kind, target) = rel(&doc_rels, &cx_id);
|
||||
assert!(kind.ends_with("/chartEx"), "{kind}");
|
||||
let chart = part_at("word", &target);
|
||||
assert_eq!(text(&files, &chart), CHARTEX_XML);
|
||||
let types = text(&files, "[Content_Types].xml");
|
||||
assert!(types.contains(&format!(r#"PartName="/{chart}" ContentType="{CT_CHARTEX}""#)), "{types}");
|
||||
let (dir, file) = chart.rsplit_once('/').unwrap();
|
||||
let (_, wb) = rel(&text(&files, &format!("{dir}/_rels/{file}.rels")), "rId1");
|
||||
assert_eq!(files.get(&part_at(dir, &wb)).map(Vec::as_slice), Some(WORKBOOK.as_bytes()));
|
||||
let fallback = body.split("<mc:Fallback>").nth(1).unwrap_or_else(|| panic!("no fallback: {body}"));
|
||||
let [pic_id] = attr_values(fallback, "a:blip", "r:embed").try_into().unwrap_or_else(|_| panic!("fallback picture lost: {body}"));
|
||||
assert_eq!(files.get(&part_at("word", &rel(&doc_rels, &pic_id).1)).map(Vec::as_slice), Some(&b"fallback picture bytes"[..]));
|
||||
assert!(attr_values(&body, "wp:docPr", "name").iter().all(|n| n.starts_with("Chart ")), "{body}");
|
||||
let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect();
|
||||
d = wordcraft_docx::read(&zip(&entries)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_office_2016_chart_resizes_its_fallback_too() {
|
||||
let mut d = wordcraft_docx::read(&chartex_docx("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex")).unwrap();
|
||||
if let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut)
|
||||
&& let Some(InlineObject::Graphic { w, h, .. }) = p.objects.first_mut()
|
||||
{
|
||||
(*w, *h) = (288.0, 144.0);
|
||||
}
|
||||
let body = text(&unzip(&wordcraft_docx::write(&d).unwrap()), "word/document.xml");
|
||||
assert_eq!(attr_values(&body, "wp:extent", "cx"), ["3657600", "3657600"], "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moved_and_copied_chart_keeps_its_parts() {
|
||||
let d = wordcraft_docx::read(&chart_docx()).unwrap();
|
||||
@@ -1451,7 +1798,7 @@ fn includepicture_keeps_its_embedded_picture() {
|
||||
let p = paras(d);
|
||||
let objs = &p[0].objects;
|
||||
assert_eq!(objs.len(), 3, "{objs:?}");
|
||||
assert_eq!(objs[0], InlineObject::FieldStart { instr: "INCLUDEPICTURE \"picture.png\"".into(), locked });
|
||||
assert_eq!(objs[0], InlineObject::FieldStart { instr: "INCLUDEPICTURE \"picture.png\"".into(), locked, dirty: false });
|
||||
let InlineObject::Image { media, .. } = &objs[1] else { panic!("{objs:?}") };
|
||||
assert_eq!(d.media.get(media).unwrap().as_slice(), png);
|
||||
assert_eq!(objs[2], InlineObject::FieldEnd);
|
||||
@@ -1520,6 +1867,49 @@ fn theme_styled_connectors_and_callout_boxes_keep_their_paint() {
|
||||
assert!(matches!(¶s(&again)[0].objects[0], InlineObject::Shape { stroke, extra, .. } if *stroke == Some(theme[7]) && extra.arrow_end));
|
||||
}
|
||||
|
||||
/// A rounded rectangle's corner is its `adj` (100000ths of the shorter side), read, capped and
|
||||
/// written back; without one, and for presets only drawn as rounded rectangles, the default.
|
||||
#[test]
|
||||
fn rounded_rectangle_corners_are_read_and_saved() {
|
||||
let geom = |prst: &str, av: &str| {
|
||||
format!(r#"<a:prstGeom prst="{prst}"><a:avLst>{av}</a:avLst></a:prstGeom><a:solidFill><a:srgbClr val="D9D9D9"/></a:solidFill>"#)
|
||||
};
|
||||
let gd = |fmla: &str| format!(r#"<a:gd name="adj" fmla="{fmla}"/>"#);
|
||||
let body = [
|
||||
geom("roundRect", &gd("val 3565")),
|
||||
geom("roundRect", ""),
|
||||
geom("roundRect", &gd("val 90000")),
|
||||
geom("roundRect", &gd("val -20")),
|
||||
geom("roundRect", &gd("*/ 1 2 3")),
|
||||
geom("roundRect", r#"<a:gd name="adj1" fmla="val 100"/>"#),
|
||||
geom("wedgeRoundRectCallout", &gd("val 3565")),
|
||||
]
|
||||
.iter()
|
||||
.map(|sppr| anchored_wsp("Rounded", 2540000, 1270000, sppr, "", "<wps:cNvSpPr/>"))
|
||||
.collect::<String>();
|
||||
let corners = |d: &Document| -> Vec<(ShapeKind, Option<u32>)> {
|
||||
paras(d)[0]
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Shape { kind, extra, .. } => Some((*kind, extra.corner)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let rounded = ShapeKind::RoundedRectangle;
|
||||
let expected =
|
||||
vec![(rounded, Some(3565)), (rounded, None), (rounded, Some(50_000)), (rounded, Some(0)), (rounded, None), (rounded, None), (rounded, None)];
|
||||
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();
|
||||
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);
|
||||
}
|
||||
|
||||
/// #611: legacy VML lines and rectangles (documents without DrawingML).
|
||||
#[test]
|
||||
fn vml_lines_and_rectangles() {
|
||||
@@ -1539,6 +1929,159 @@ fn vml_lines_and_rectangles() {
|
||||
assert!(matches!(&objs[1], InlineObject::Shape { kind: ShapeKind::Rectangle, fill: Some(Rgb(255, 0, 0)), stroke: None, w: 30.0, h: 20.0, .. }));
|
||||
}
|
||||
|
||||
/// The right arrow's shapetype as Word writes it (ECMA-376 Part 4 `v:shapetype`, `o:spt` 13).
|
||||
const VML_RIGHT_ARROW_TYPE: &str = r#"<v:shapetype id="_x0000_t13" coordsize="21600,21600" o:spt="13" adj="16200,5400" path="m@0,l@0@1,0@1,0@2@0@2@0,21600,21600,10800xe"><v:stroke joinstyle="miter"/><v:formulas><v:f eqn="val #0"/><v:f eqn="val #1"/></v:formulas><v:path o:connecttype="custom"/></v:shapetype>"#;
|
||||
|
||||
/// #1377: a VML shape drawn from a preset shapetype (`type="#_x0000_t13"`) is the DrawingML
|
||||
/// preset WordCraft draws, with its fill, outline and size: from the shapetype beside it, from
|
||||
/// Word's shapetype id when the shapetype was written at an earlier use, or from its own `o:spt`.
|
||||
#[test]
|
||||
fn vml_preset_shapes_are_drawn() {
|
||||
let pict = |inner: &str| format!("<w:p><w:r><w:pict>{inner}</w:pict></w:r></w:p>");
|
||||
let body = [
|
||||
pict(&format!(r##"{VML_RIGHT_ARROW_TYPE}<v:shape id="_x0000_i1026" type="#_x0000_t13" style="width:120pt;height:40pt" fillcolor="#ffa500"/>"##)),
|
||||
pict(r##"<v:shape type="#_x0000_t13" style="position:absolute;margin-left:10pt;margin-top:5pt;width:60pt;height:20pt;z-index:2" fillcolor="#00ff00" strokecolor="#0000ff" strokeweight="2pt"/>"##),
|
||||
pict(r##"<v:shape o:spt="74" style="width:30pt;height:30pt" fillcolor="red" stroked="f"/>"##),
|
||||
pict(r##"<v:shapetype id="tri" o:spt="5" coordsize="21600,21600"/><v:shape type="#tri" style="width:20pt;height:10pt" filled="f"/>"##),
|
||||
pict(r##"<v:shape type="#_x0000_t4" style="width:50pt;height:50pt" fillcolor="#ffff00"><v:textbox><w:txbxContent><w:p><w:r><w:t>yes?</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape>"##),
|
||||
// A preset WordCraft has no shape for is drawn as the nearest one, as for DrawingML: a
|
||||
// right triangle (`o:spt` 6) as a triangle.
|
||||
pict(r##"<v:shape type="#_x0000_t6" style="width:20pt;height:20pt" fillcolor="red"/>"##),
|
||||
// Its own path wins over the shapetype's: not the preset.
|
||||
pict(r##"<v:shape type="#_x0000_t13" path="m,l21600,21600e" style="width:20pt;height:20pt"/>"##),
|
||||
// Lines from a shapetype (`o:spt` 20 and Word's line tool's 32) take the size of their box.
|
||||
pict(r##"<v:shape type="#_x0000_t20" style="width:40pt;height:10pt"/>"##),
|
||||
pict(r##"<v:shapetype id="_x0000_t32" coordsize="21600,21600" o:spt="32" o:oned="t" path="m,l21600,21600e" filled="f"/><v:shape type="#_x0000_t32" style="position:absolute;width:30pt;height:15pt" strokecolor="#ff0000"><v:stroke endarrow="block"/></v:shape>"##),
|
||||
// A text box's shapetype without text is still a text box.
|
||||
pict(r##"<v:shape type="#_x0000_t202" style="width:30pt;height:15pt"/>"##),
|
||||
// A shape that isn't a preset keeps its text, in a text box.
|
||||
pict(r##"<v:shape o:spt="0" style="width:50pt;height:50pt"><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape>"##),
|
||||
// Text in a preset with neither fill nor outline is kept.
|
||||
pict(r##"<v:shape type="#_x0000_t3" style="width:50pt;height:50pt" filled="f" stroked="f"><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape>"##),
|
||||
pict(r##"<v:oval style="width:50pt;height:40pt"><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:oval>"##),
|
||||
// Paint the shape leaves out comes from its shapetype.
|
||||
pict(r##"<v:shapetype id="_x0000_t1" o:spt="1" fillcolor="#0000ff" stroked="f"/><v:shape type="#_x0000_t1" style="width:9pt;height:9pt"/>"##),
|
||||
r##"<w:p><w:r><w:pict><v:shape type="#_x0000_t2" style="width:9pt;height:9pt"/></w:pict></w:r><w:r><w:pict><v:shape type="#_x0000_t12" style="width:9pt;height:9pt"/></w:pict></w:r></w:p>"##.to_string(),
|
||||
pict(r##"<v:shape type="#_x0000_t109" style="width:9pt;height:9pt"/>"##),
|
||||
pict(r##"<v:shape type="#_x0000_t110" style="width:9pt;height:9pt"/>"##),
|
||||
pict(r##"<v:shape type="#_x0000_t120" style="width:9pt;height:9pt"/>"##),
|
||||
// Nearest shapes: left arrow, rectangular callout, four-point star.
|
||||
pict(r##"<v:shape type="#_x0000_t66" style="width:60pt;height:20pt" fillcolor="#ffa500"/>"##),
|
||||
pict(r##"<v:shape type="#_x0000_t61" style="width:60pt;height:20pt"/>"##),
|
||||
pict(r##"<v:shape type="#_x0000_t187" style="width:20pt;height:20pt"/>"##),
|
||||
// Not drawn: WordArt text (136) and a picture frame without its picture (75).
|
||||
pict(r##"<v:shape type="#_x0000_t136" style="width:60pt;height:20pt" fillcolor="silver"/>"##),
|
||||
pict(r##"<v:shape type="#_x0000_t75" style="width:60pt;height:20pt"/>"##),
|
||||
]
|
||||
.concat();
|
||||
let d = read_body(&body);
|
||||
let ps = paras(&d);
|
||||
let shape = |i: usize| match ps[i].objects.first() {
|
||||
Some(InlineObject::Shape { kind, w, h, fill, stroke, stroke_width, float, story, .. }) => {
|
||||
Some((*kind, *w, *h, *fill, *stroke, *stroke_width, float.wrap == Wrap::Inline, story.is_some()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let kind = |i: usize| shape(i).map(|s| (s.0, s.7));
|
||||
let (black, white) = (Some(Rgb::BLACK), Some(Rgb::WHITE));
|
||||
assert_eq!(shape(0), Some((ShapeKind::Arrow, 120.0, 40.0, Some(Rgb(0xFF, 0xA5, 0x00)), black, 0.75, true, false)));
|
||||
assert_eq!(shape(1), Some((ShapeKind::Arrow, 60.0, 20.0, Some(Rgb(0, 0xFF, 0)), Some(Rgb(0, 0, 0xFF)), 2.0, false, false)));
|
||||
assert_eq!(shape(2), Some((ShapeKind::Heart, 30.0, 30.0, Some(Rgb(0xFF, 0, 0)), None, 0.75, true, false)));
|
||||
assert_eq!(shape(3), Some((ShapeKind::Triangle, 20.0, 10.0, None, black, 0.75, true, false)));
|
||||
// A preset holding text keeps its geometry around the text.
|
||||
assert_eq!(shape(4), Some((ShapeKind::Diamond, 50.0, 50.0, Some(Rgb(0xFF, 0xFF, 0)), black, 0.75, true, true)));
|
||||
assert_eq!(shape(5), Some((ShapeKind::RightTriangle, 20.0, 20.0, Some(Rgb(0xFF, 0, 0)), black, 0.75, true, false)));
|
||||
// Its own path is drawn as a freeform, not as the shapetype's arrow.
|
||||
assert_eq!(kind(6), Some((ShapeKind::Freeform, false)));
|
||||
assert_eq!(shape(7), Some((ShapeKind::Line, 40.0, 10.0, None, black, 0.75, true, false)));
|
||||
assert_eq!(shape(8), Some((ShapeKind::Line, 30.0, 15.0, None, Some(Rgb(0xFF, 0, 0)), 0.75, false, false)));
|
||||
assert!(matches!(ps[8].objects.first(), Some(InlineObject::Shape { extra, .. }) if extra.arrow_end && !extra.arrow_start));
|
||||
assert_eq!(shape(9), Some((ShapeKind::TextBox, 30.0, 15.0, white, black, 0.75, true, false)));
|
||||
assert_eq!(kind(10), Some((ShapeKind::TextBox, true)));
|
||||
assert_eq!(shape(11), Some((ShapeKind::Ellipse, 50.0, 50.0, None, None, 0.75, true, true)));
|
||||
assert_eq!(kind(12), Some((ShapeKind::Ellipse, true)));
|
||||
assert_eq!(shape(13), Some((ShapeKind::Rectangle, 9.0, 9.0, Some(Rgb(0, 0, 0xFF)), None, 0.75, true, false)));
|
||||
let kinds: Vec<_> = ps[14].objects.iter().filter_map(|o| if let InlineObject::Shape { kind, .. } = o { Some(*kind) } else { None }).collect();
|
||||
assert_eq!(kinds, [ShapeKind::RoundedRectangle, ShapeKind::Star]);
|
||||
assert_eq!(kind(15), Some((ShapeKind::Rectangle, false)));
|
||||
assert_eq!(kind(16), Some((ShapeKind::Diamond, false)));
|
||||
assert_eq!(kind(17), Some((ShapeKind::Ellipse, false)));
|
||||
assert_eq!(shape(18), Some((ShapeKind::Arrow, 60.0, 20.0, Some(Rgb(0xFF, 0xA5, 0x00)), black, 0.75, true, false)));
|
||||
assert_eq!(kind(19), Some((ShapeKind::Rectangle, false)));
|
||||
assert_eq!(kind(20), Some((ShapeKind::Star, false)));
|
||||
assert_eq!(shape(21), None);
|
||||
assert_eq!(shape(22), None);
|
||||
}
|
||||
|
||||
/// #1377: hostile shape type numbers and references are skipped, never a panic.
|
||||
#[test]
|
||||
fn vml_preset_hostile_types_never_panic() {
|
||||
let shapes = [
|
||||
r##"<v:shape o:spt="99999999999999999999999" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shape o:spt="-13" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shape o:spt="" type="#_x0000_t" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shape type="#_x0000_t13abc" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shape type="#" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shape type="#_x0000_tépée" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shapetype id="x" o:spt="nope"/><v:shape type="#x" style="width:9pt;height:9pt"/>"##,
|
||||
r##"<v:shape type="#_x0000_t13" style="width:-1e39pt;height:NaNpt" fillcolor="#zzz" strokeweight="1e30pt"/>"##,
|
||||
];
|
||||
let body: String = shapes.iter().map(|s| format!("<w:p><w:r><w:pict>{s}</w:pict></w:r></w:p>")).collect();
|
||||
let d = read_body(&body);
|
||||
for (i, p) in paras(&d).iter().enumerate().take(7) {
|
||||
assert!(p.objects.is_empty(), "shape {i}: {:?}", p.objects);
|
||||
}
|
||||
match paras(&d)[7].objects.first() {
|
||||
Some(InlineObject::Shape { kind: ShapeKind::Arrow, w, h, stroke_width, .. }) => {
|
||||
assert!(w.is_finite() && h.is_finite() && *w >= 0.0 && *h >= 0.0 && *stroke_width <= 100.0)
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// #1377: a VML preset shape is kept on save, as its DrawingML preset with its fill.
|
||||
#[test]
|
||||
fn vml_preset_shape_survives_saving() {
|
||||
let body = format!(
|
||||
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();
|
||||
assert!(xml.contains(r#"prst="rightArrow""#), "{xml}");
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
¶s(&again)[0].objects[..],
|
||||
[InlineObject::Shape { kind: ShapeKind::Arrow, w: 120.0, h: 40.0, fill: Some(Rgb(0xFF, 0xA5, 0x00)), stroke: Some(Rgb::BLACK), .. }]
|
||||
),
|
||||
"{:?}",
|
||||
paras(&again)[0].objects
|
||||
);
|
||||
}
|
||||
|
||||
/// #1377: a VML preset drawn as its nearest shape (a left arrow, `o:spt` 66) is kept on save as
|
||||
/// that shape's DrawingML preset, as a DrawingML left arrow is.
|
||||
#[test]
|
||||
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();
|
||||
assert!(xml.contains(r#"prst="rightArrow""#), "{xml}");
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
¶s(&again)[0].objects[..],
|
||||
[InlineObject::Shape { kind: ShapeKind::Arrow, w: 60.0, h: 20.0, fill: Some(Rgb(0xFF, 0xA5, 0x00)), .. }]
|
||||
),
|
||||
"{:?}",
|
||||
paras(&again)[0].objects
|
||||
);
|
||||
}
|
||||
|
||||
/// #743: a cover page from Word: a group holding a rectangle filled through its style, a
|
||||
/// freeform band and a title box, beside a box that resizes to fit its two lines and has no
|
||||
/// internal margins. The fills, the band's outline, the margins and the resizing are all read
|
||||
@@ -1691,6 +2234,28 @@ fn part_text_box(d: &Document) -> String {
|
||||
story.and_then(|id| d.parts.get(&id)).map(|p| p.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// #743: Word's cover pages place their shapes relative to the page's size, wrapped in
|
||||
/// `mc:AlternateContent` with an offset as the Fallback, and draw their freeforms back to the
|
||||
/// start without `a:close`. Both shapes are read: placed at the offset, and filled.
|
||||
#[test]
|
||||
fn cover_page_relative_position_and_freeform_drawn_back_to_its_start() {
|
||||
let geom = r#"<a:custGeom><a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/><a:rect l="0" t="0" r="r" b="b"/><a:pathLst><a:path w="100" h="100"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="0" y="90"/></a:lnTo><a:cubicBezTo><a:pt x="30" y="100"/><a:pt x="70" y="100"/><a:pt x="100" y="90"/></a:cubicBezTo><a:lnTo><a:pt x="100" y="0"/></a:lnTo><a:lnTo><a:pt x="0" y="0"/></a:lnTo></a:path><a:path w="100" h="100"><a:moveTo><a:pt x="0" y="50"/></a:moveTo><a:lnTo><a:pt x="100" y="50"/></a:lnTo></a:path></a:pathLst></a:custGeom><a:solidFill><a:srgbClr val="0E2841"/></a:solidFill>"#;
|
||||
let pct = r#"<mc:AlternateContent><mc:Choice Requires="wp14"><wp:positionV relativeFrom="page"><wp14:pctPosVOffset>4500</wp14:pctPosVOffset></wp:positionV></mc:Choice><mc:Fallback><wp:positionV relativeFrom="page"><wp:posOffset>480695</wp:posOffset></wp:positionV></mc:Fallback></mc:AlternateContent>"#;
|
||||
let shape = anchored_wsp("Freeform 1", 5486400, 5334000, geom, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"<wp:positionV relativeFrom="paragraph"><wp:posOffset>25400</wp:posOffset></wp:positionV>"#, pct);
|
||||
let check = |d: &Document| {
|
||||
let objs = ¶s(d)[0].objects;
|
||||
let InlineObject::Shape { kind, float, freeform: Some(f), .. } = &objs[0] else { panic!("{:?}", objs[0]) };
|
||||
assert_eq!(*kind, ShapeKind::Freeform);
|
||||
assert_eq!((float.v_rel, float.v_align, float.y), (Anchor::Page, None, 480695.0 / 12700.0), "the Fallback's offset");
|
||||
let closed: Vec<bool> = f.paths.iter().map(|p| p.closed).collect();
|
||||
assert_eq!(closed, [true, false], "a path back at its start is closed and filled; an open line isn't");
|
||||
};
|
||||
let d = read_body(&format!("<w:p>{shape}</w:p>"));
|
||||
check(&d);
|
||||
check(&wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_fonts_survive_a_round_trip() {
|
||||
let table = r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:font w:name="Roboto"><w:embedRegular r:id="rId1"/><w:embedBold r:id="rId2"/></w:font></w:fonts>"#;
|
||||
@@ -2068,3 +2633,200 @@ fn text_frames_read_and_round_trip() {
|
||||
assert_eq!(q[1].props.frame, p[1].props.frame);
|
||||
assert!(q.iter().any(|x| x.props.drop_cap == Some(2) && x.props.frame.is_none()));
|
||||
}
|
||||
|
||||
/// A legacy VML freeform (`v:shape` with a `path`, ECMA-376 Part 4): a rule across a header,
|
||||
/// drawn in a 1000 × 1000 coordinate space, outlined, its fill transparent. It is read as a
|
||||
/// freeform of the shape's size and kept when saved (as DrawingML custom geometry) and read back.
|
||||
#[test]
|
||||
fn vml_freeform_rule_in_header() {
|
||||
let w10 = r#"xmlns:w10="urn:schemas-microsoft-com:office:word""#;
|
||||
let rule = r##"<w:p><w:r><w:pict><v:shape style="position:absolute;margin-left:0;margin-top:30pt;width:360pt;height:12pt;z-index:2;mso-position-horizontal-relative:margin;mso-position-vertical-relative:margin" coordsize="1000,1000" path="m,500l1000,500xe" fillcolor="this" stroked="t" strokecolor="#3366cc" strokeweight="1.5pt"><v:fill opacity="0"/><w10:wrap anchorx="margin"/></v:shape></w:pict></w:r>
|
||||
<w:r><w:pict><v:shape style="width:20pt;height:10pt" coordorigin="100,100" coordsize="200,100" path="t100,100r100,0,0,100nfx e" strokecolor="red"><v:stroke opacity="32768f"/></v:shape></w:pict></w:r></w:p>"##;
|
||||
let header = format!(r#"<w:hdr {W_NS} {w10}><w:p><w:r><w:t>Header</w:t></w:r></w:p>{rule}</w:hdr>"#);
|
||||
let body = r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="rIdH"/></w:sectPr>"#;
|
||||
let bytes = docx(body, &[("rIdH", "header", "header1.xml")], &[("word/header1.xml", &header)]);
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 0.05;
|
||||
let check = |d: &Document| {
|
||||
let hid = d.last_section.headers.default.unwrap();
|
||||
let shapes: Vec<&InlineObject> = d.parts.get(&hid).unwrap().blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).collect();
|
||||
let [rule, tri] = shapes.as_slice() else { panic!("{shapes:?}") };
|
||||
let InlineObject::Shape { kind, w, h, fill, stroke, stroke_width, float, freeform: Some(f), .. } = rule else { panic!("{rule:?}") };
|
||||
assert_eq!((*kind, *fill, *stroke), (ShapeKind::Freeform, None, Some(Rgb(0x33, 0x66, 0xCC))));
|
||||
assert!(near(*w, 360.0) && near(*h, 12.0) && near(*stroke_width, 1.5), "{w} x {h}, {stroke_width}");
|
||||
assert_eq!((float.h_rel, float.v_rel, float.wrap), (Anchor::Margin, Anchor::Margin, Wrap::InFrontOfText));
|
||||
assert!(near(float.y, 30.0), "{float:?}");
|
||||
let [p] = f.paths.as_slice() else { panic!("{f:?}") };
|
||||
let pts = f.placed(0.0, 0.0, *w, *h);
|
||||
let [(pts, _)] = pts.as_slice() else { panic!("{pts:?}") };
|
||||
assert!(p.closed && pts.len() == 2, "{pts:?}");
|
||||
assert!(near(pts[0][0], 0.0) && near(pts[0][1], 6.0) && near(pts[1][0], 360.0) && near(pts[1][1], 6.0), "{pts:?}");
|
||||
// Relative moves and lines from the origin, `nf`: an outlined triangle, half opaque.
|
||||
let InlineObject::Shape { kind: ShapeKind::Freeform, fill: None, stroke: Some(Rgb(255, 0, 0)), w, h, freeform: Some(f), .. } = tri else {
|
||||
panic!("{tri:?}")
|
||||
};
|
||||
let placed = f.placed(0.0, 0.0, *w, *h);
|
||||
let [(pts, true)] = placed.as_slice() else { panic!("{placed:?}") };
|
||||
let want = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]];
|
||||
assert!(pts.len() == 3 && pts.iter().zip(want).all(|(a, b)| near(a[0], b[0]) && near(a[1], b[1])), "{pts:?}");
|
||||
assert!(near(f.alpha, 0.5), "{}", f.alpha);
|
||||
};
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
check(&d);
|
||||
check(&wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap());
|
||||
}
|
||||
|
||||
/// Hostile VML paths and coordinate spaces read without panicking and stay finite.
|
||||
#[test]
|
||||
fn hostile_vml_paths_stay_finite() {
|
||||
let paths = [
|
||||
"m,",
|
||||
"l",
|
||||
"mxe",
|
||||
"m99999999999999999999999999,0l-99999999999999999999,1e",
|
||||
"minf,nanlNaN,-inf",
|
||||
"m@1,@2l@3,@4nfnse",
|
||||
"wa1",
|
||||
"c1",
|
||||
"m١٢,٣l٤,٥",
|
||||
"m0,0c",
|
||||
"m0,0v1,2,3",
|
||||
"ar0,0,10,10,0,0,10,10at",
|
||||
"m0,0r1,1,1,1,1,1,1,1,1,1x x x l",
|
||||
"--..,,@@ ,,, xm1.5.5,2..3l+-+,-e",
|
||||
"\u{1F600}m1,1l2,2",
|
||||
"qbqxqyaeal1,2,3,4,5,6",
|
||||
];
|
||||
let spaces = [("0,0", "0,0"), ("-5,-5", "x,y"), ("1e39,x", "-99999999999999999999,99999999999999999999"), ("", ""), ("1,1", "1e308,1e308")];
|
||||
for path in paths {
|
||||
for (size, origin) in spaces {
|
||||
let body = format!(
|
||||
r#"<w:p><w:r><w:pict><v:shape style="width:1e30pt;height:-4pt" coordsize="{size}" coordorigin="{origin}" path="{path}" strokecolor="black"/></w:pict></w:r></w:p>"#
|
||||
);
|
||||
let d = read_body(&body);
|
||||
// A path with formulas isn't drawn (they aren't evaluated).
|
||||
if path.contains('@') {
|
||||
assert!(paras(&d)[0].objects.iter().all(|o| !matches!(o, InlineObject::Shape { freeform: Some(_), .. })), "{path}");
|
||||
}
|
||||
for o in ¶s(&d)[0].objects {
|
||||
if let InlineObject::Shape { w, h, freeform: Some(f), .. } = o {
|
||||
assert!(w.is_finite() && h.is_finite() && f.alpha.is_finite(), "{path}");
|
||||
assert!(f.paths.iter().flat_map(|p| &p.pts).all(|[x, y]| x.is_finite() && y.is_finite()), "{path} {size} {origin}");
|
||||
for (pts, _) in f.placed(0.0, 0.0, *w, *h) {
|
||||
assert!(pts.iter().all(|[x, y]| x.is_finite() && y.is_finite()), "{path}");
|
||||
}
|
||||
}
|
||||
}
|
||||
wordcraft_docx::write(&d).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Measured in Word: `w:asciiTheme="minorBidi"` names the theme's complex-script font (`a:cs`);
|
||||
/// when that is empty it names nothing, and the run keeps the font it inherits.
|
||||
#[test]
|
||||
fn bidi_theme_slots_name_the_complex_script_font() {
|
||||
let font = |cs: &str| {
|
||||
let theme = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="T"><a:themeElements><a:fontScheme name="F"><a:majorFont><a:latin typeface="Cambria"/><a:ea typeface=""/><a:cs typeface="{cs}"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface="{cs}"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
|
||||
);
|
||||
let rels = [("rId9", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", "theme/theme1.xml")];
|
||||
let body = r#"<w:p><w:r><w:rPr><w:rFonts w:asciiTheme="minorBidi" w:hAnsiTheme="minorBidi"/></w:rPr><w:t>x</w:t></w:r></w:p>"#;
|
||||
let d = wordcraft_docx::read(&docx(body, &rels, &[("word/theme/theme1.xml", &theme)])).unwrap();
|
||||
paras(&d)[0].runs[0].props.font.clone()
|
||||
};
|
||||
assert_eq!(font(""), None);
|
||||
assert_eq!(font("Times New Roman").as_deref(), Some("Times New Roman"));
|
||||
}
|
||||
|
||||
/// The font table's family classes: Word draws a missing roman font in a serif face.
|
||||
#[test]
|
||||
fn roman_fonts_are_read_from_the_font_table() {
|
||||
let fonts = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:font w:name="Brand Serif"><w:family w:val="roman"/></w:font><w:font w:name="Brand Sans"><w:family w:val="swiss"/></w:font></w:fonts>"#;
|
||||
let rels = [("rId9", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable", "fontTable.xml")];
|
||||
let d = wordcraft_docx::read(&docx("<w:p/>", &rels, &[("word/fontTable.xml", fonts)])).unwrap();
|
||||
assert_eq!(d.settings.roman_fonts, ["Brand Serif"]);
|
||||
}
|
||||
|
||||
/// `w:doNotUseHTMLParagraphAutoSpacing` in the settings' `w:compat`: paragraph spacing adds up.
|
||||
#[test]
|
||||
fn html_auto_spacing_off_is_read_and_kept() {
|
||||
let settings = |compat: &str| {
|
||||
let s = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:settings {W_NS}><w:compat>{compat}</w:compat></w:settings>"#);
|
||||
let rels = [("rId9", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings", "settings.xml")];
|
||||
let d = wordcraft_docx::read(&docx("<w:p/>", &rels, &[("word/settings.xml", &s)])).unwrap();
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
(d.settings.sum_paragraph_spacing, again.settings.sum_paragraph_spacing)
|
||||
};
|
||||
assert_eq!(settings("<w:doNotUseHTMLParagraphAutoSpacing/>"), (true, true));
|
||||
assert_eq!(settings(""), (false, false));
|
||||
}
|
||||
|
||||
/// A right triangle (`rtTriangle`) has its right angle at the bottom left: a cover page's white
|
||||
/// corner cut-outs drawn as isosceles triangles pointed the wrong way.
|
||||
#[test]
|
||||
fn a_right_triangle_keeps_its_right_angle() {
|
||||
let body = anchored_wsp("Corner", 1270000, 635000, r#"<a:prstGeom prst="rtTriangle"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>");
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
let kind = |d: &Document| match ¶s(d)[0].objects[0] {
|
||||
InlineObject::Shape { kind, .. } => *kind,
|
||||
o => panic!("{o:?}"),
|
||||
};
|
||||
assert_eq!(kind(&d), ShapeKind::RightTriangle);
|
||||
let saved = wordcraft_docx::write(&d).unwrap();
|
||||
assert_eq!(kind(&wordcraft_docx::read(&saved).unwrap()), ShapeKind::RightTriangle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperlink_with_empty_target_is_no_link() {
|
||||
// LibreOffice writes `Target=""` for the Hyperlink character style without an address (#1005).
|
||||
let body = r#"<w:p><w:hyperlink r:id="rId2"><w:r><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>plain</w:t></w:r></w:hyperlink><w:hyperlink r:id="rId3"><w:r><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>mail</w:t></w:r></w:hyperlink><w:hyperlink w:anchor="top"><w:r><w:t>jump</w:t></w:r></w:hyperlink></w:p>"#;
|
||||
let bytes = docx(body, &[("rId2", "hyperlink", "https://x"), ("rId3", "hyperlink", "mailto:[email protected]")], &[]);
|
||||
// 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 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" {
|
||||
buf = String::from_utf8(buf)
|
||||
.unwrap()
|
||||
.replace("Target=\"https://x\"", "Target=\"\"")
|
||||
.replace("[email protected]\"", "[email protected]\" TargetMode=\"External\"")
|
||||
.into_bytes();
|
||||
}
|
||||
entries.push((f.name().to_string(), buf));
|
||||
}
|
||||
let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (n.as_str(), b.as_slice())).collect();
|
||||
zip(&refs)
|
||||
};
|
||||
let doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.plain_text(), "plainmailjump");
|
||||
assert_eq!(p.props_of_char(0).link, None);
|
||||
assert_eq!(p.props_of_char(0).style.as_deref(), Some("Hyperlink"));
|
||||
assert_eq!(p.props_of_char(5).link.as_deref(), Some("mailto:[email protected]"));
|
||||
assert_eq!(p.props_of_char(9).link.as_deref(), Some("#top"));
|
||||
// Round trip keeps exactly the real links.
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
let p = back.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props_of_char(0).link, None);
|
||||
assert_eq!(p.props_of_char(5).link.as_deref(), Some("mailto:[email protected]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_table_borders_round_trip() {
|
||||
let d = read_body(
|
||||
r#"<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid>
|
||||
<w:tr><w:tblPrEx><w:tblBorders><w:top w:val="single" w:sz="8"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders></w:tblPrEx>
|
||||
<w:trPr><w:trHeight w:val="400"/></w:trPr><w:tc><w:p/></w:tc><w:tc><w:p/></w:tc></w:tr>
|
||||
<w:tr><w:tc><w:p/></w:tc><w:tc><w:p/></w:tc></w:tr></w:tbl><w:p/>"#,
|
||||
);
|
||||
let saved = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = text(&unzip(&saved), "word/document.xml");
|
||||
assert!(xml.contains("<w:tblPrEx>"), "row table borders were dropped: {xml}");
|
||||
assert!(xml.contains("<w:insideV"));
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert_eq!(d.body, again.body);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Word forms keep their legacy form fields (`w:ffData`) and their rows' skipped grid columns
|
||||
//! (`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};
|
||||
|
||||
const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
|
||||
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 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()));
|
||||
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.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn resaved(body: &str) -> String {
|
||||
document_xml(&write(&read(&package(body)).unwrap()).unwrap())
|
||||
}
|
||||
|
||||
fn t(s: &str) -> String {
|
||||
format!(r#"<w:r><w:t xml:space="preserve">{s}</w:t></w:r>"#)
|
||||
}
|
||||
|
||||
fn checkbox(name: &str, checked: bool) -> String {
|
||||
format!(
|
||||
r#"<w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:name w:val="{name}"/><w:enabled/><w:calcOnExit w:val="0"/><w:checkBox><w:sizeAuto/><w:default w:val="{}"/></w:checkBox></w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
|
||||
u8::from(checked)
|
||||
)
|
||||
}
|
||||
|
||||
fn text_input(name: &str, text: &str) -> String {
|
||||
format!(
|
||||
r#"<w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:name w:val="{name}"/><w:enabled/><w:calcOnExit w:val="0"/><w:textInput><w:maxLength w:val="40"/></w:textInput></w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMTEXT </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r>{}<w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
|
||||
t(text)
|
||||
)
|
||||
}
|
||||
|
||||
/// The `w:ffData` of each field begin, in document order.
|
||||
fn ff_data(xml: &str) -> Vec<&str> {
|
||||
xml.match_indices("<w:ffData>")
|
||||
.filter_map(|(at, _)| xml.get(at..).and_then(|s| s.find("</w:ffData>").and_then(|end| s.get(..end + 11))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_fields_keep_their_ff_data() {
|
||||
let body = format!(
|
||||
"<w:p>{}{}{}{}</w:p><w:p>{}{}</w:p>",
|
||||
t("Yes "),
|
||||
checkbox("Yes1", true),
|
||||
t(" No "),
|
||||
checkbox("No1", false),
|
||||
t("Name: "),
|
||||
text_input("Name1", "Example Ltd")
|
||||
);
|
||||
let xml = resaved(&body);
|
||||
let ff = ff_data(&xml);
|
||||
assert_eq!(ff.len(), 3, "{xml}");
|
||||
assert!(
|
||||
ff[0].contains(r#"<w:name w:val="Yes1"/>"#) && ff[0].contains(r#"<w:checkBox><w:sizeAuto/><w:default w:val="1"/></w:checkBox>"#),
|
||||
"{}",
|
||||
ff[0]
|
||||
);
|
||||
assert!(ff[1].contains(r#"<w:name w:val="No1"/>"#) && ff[1].contains(r#"<w:default w:val="0"/>"#), "{}", ff[1]);
|
||||
assert!(ff[2].contains(r#"<w:name w:val="Name1"/>"#) && ff[2].contains(r#"<w:maxLength w:val="40"/>"#), "{}", ff[2]);
|
||||
// Each definition stays inside its own field's begin, ahead of its code.
|
||||
let begin = xml.find(r#"w:fldCharType="begin"><w:ffData><w:name w:val="Name1"/>"#).expect("ffData inside fldChar");
|
||||
assert!(xml.get(begin..).is_some_and(|s| s.find("FORMTEXT") < s.find("Example Ltd")), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fields_without_ff_data_write_none() {
|
||||
let body = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
|
||||
let xml = resaved(body);
|
||||
assert!(xml.contains("PAGE") && !xml.contains("ffData"), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_keep_their_skipped_grid_columns() {
|
||||
let tc = |w: u32, span: u32, s: &str| {
|
||||
let gs = if span > 1 { format!(r#"<w:gridSpan w:val="{span}"/>"#) } else { String::new() };
|
||||
format!(r#"<w:tc><w:tcPr><w:tcW w:w="{w}" w:type="dxa"/>{gs}</w:tcPr><w:p>{}</w:p></w:tc>"#, t(s))
|
||||
};
|
||||
let body = format!(
|
||||
concat!(
|
||||
r#"<w:tbl><w:tblGrid><w:gridCol w:w="300"/><w:gridCol w:w="4200"/><w:gridCol w:w="4500"/></w:tblGrid>"#,
|
||||
"<w:tr>{}{}{}</w:tr>",
|
||||
r#"<w:tr><w:trPr><w:gridBefore w:val="1"/><w:wBefore w:w="300" w:type="dxa"/></w:trPr>{}</w:tr>"#,
|
||||
r#"<w:tr><w:trPr><w:gridAfter w:val="2"/><w:wAfter w:w="8700" w:type="dxa"/></w:trPr>{}</w:tr>"#,
|
||||
"</w:tbl><w:p/>"
|
||||
),
|
||||
tc(300, 1, "a"),
|
||||
tc(4200, 1, "b"),
|
||||
tc(4500, 1, "c"),
|
||||
tc(8700, 2, "Title"),
|
||||
tc(300, 1, "x"),
|
||||
);
|
||||
let d = read(&package(&body)).unwrap();
|
||||
let Some(Block::Table(tb)) = d.body.first().map(|b| b.as_ref()) else { panic!("table") };
|
||||
let (r1, r2) = (&tb.rows[1].props, &tb.rows[2].props);
|
||||
assert_eq!((r1.grid_before, r1.w_before, r1.grid_after, r1.w_after), (1, Some(15.0), 0, None));
|
||||
assert_eq!((r2.grid_before, r2.w_before, r2.grid_after, r2.w_after), (0, None, 2, Some(435.0)));
|
||||
assert_eq!(tb.rows[0].props, Default::default());
|
||||
|
||||
let xml = document_xml(&write(&d).unwrap());
|
||||
assert_eq!(xml.matches("<w:gridBefore ").count(), 1, "{xml}");
|
||||
assert!(xml.contains(r#"<w:gridBefore w:val="1"/><w:wBefore w:w="300" w:type="dxa"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:gridAfter w:val="2"/><w:wAfter w:w="8700" w:type="dxa"/>"#), "{xml}");
|
||||
let again = read(&write(&d).unwrap()).unwrap();
|
||||
let Some(Block::Table(tb2)) = again.body.first().map(|b| b.as_ref()) else { panic!("table") };
|
||||
assert_eq!(tb2.rows.iter().map(|r| r.props.clone()).collect::<Vec<_>>(), tb.rows.iter().map(|r| r.props.clone()).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -238,3 +238,30 @@ proptest! {
|
||||
let _ = read(&z);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_header_reference_chain_is_cut_off() {
|
||||
const HDR_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
|
||||
const RELS_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
|
||||
let rels_for = |next: usize| {
|
||||
let rel = format!(r#"<Relationship Id="rId1" Type="{HDR_REL}" Target="header{next}.xml"/>"#);
|
||||
format!(r#"<Relationships xmlns="{RELS_NS}">{rel}</Relationships>"#)
|
||||
};
|
||||
let sect = r#"<w:sectPr><w:headerReference w:type="default" r:id="rId1"/></w:sectPr>"#;
|
||||
let doc = format!("<w:document {W_NS}><w:body><w:p><w:r><w:t>body</w:t></w:r></w:p>{sect}</w:body></w:document>");
|
||||
// header0 -> header1 -> ... -> header59: every header's last paragraph holds a section that points at the next one.
|
||||
let mut entries: Vec<(String, Vec<u8>)> = vec![
|
||||
("_rels/.rels".into(), ROOT_RELS.as_bytes().to_vec()),
|
||||
("word/document.xml".into(), doc.into_bytes()),
|
||||
("word/_rels/document.xml.rels".into(), rels_for(0).into_bytes()),
|
||||
];
|
||||
for i in 0..60 {
|
||||
let hdr = format!("<w:hdr {W_NS}><w:p><w:pPr>{sect}</w:pPr><w:r><w:t>h{i}</w:t></w:r></w:p></w:hdr>");
|
||||
entries.push((format!("word/header{i}.xml"), hdr.into_bytes()));
|
||||
entries.push((format!("word/_rels/header{i}.xml.rels"), rels_for(i + 1).into_bytes()));
|
||||
}
|
||||
let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (n.as_str(), b.as_slice())).collect();
|
||||
let d = read(&zip(&refs)).unwrap();
|
||||
assert!(!d.parts.is_empty());
|
||||
assert!(d.parts.len() <= 8, "followed {} chained headers", d.parts.len());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! What a save keeps from a Word file beyond the document model (settings: `settings_merge.rs`):
|
||||
//! package parts WordCraft doesn't write (carried verbatim),
|
||||
//! comment durable ids and UTC dates, localized default styles, latent styles, list identities
|
||||
//! and extended properties. Hand-written 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()));
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
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());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn text(files: &BTreeMap<String, Vec<u8>>, name: &str) -> String {
|
||||
String::from_utf8(files.get(name).unwrap_or_else(|| panic!("no {name} in {:?}", files.keys())).clone()).unwrap()
|
||||
}
|
||||
|
||||
fn rels(list: &[(&str, &str, &str)]) -> Vec<u8> {
|
||||
let mut s =
|
||||
String::from(r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for (id, ty, target) in list {
|
||||
s.push_str(&format!(r#"<Relationship Id="{id}" Type="{ty}" Target="{target}"/>"#));
|
||||
}
|
||||
s.push_str("</Relationships>");
|
||||
s.into_bytes()
|
||||
}
|
||||
|
||||
/// A package: `body`, document relationships, root relationships after the main document's,
|
||||
/// and extra parts.
|
||||
fn package(body: &str, doc_rels: &[(&str, &str, &str)], root_rels: &[(&str, &str, &str)], extra: &[(&str, &str)]) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:r="{R_NS}" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut root = vec![("rIdMain", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "word/document.xml")];
|
||||
root.extend_from_slice(root_rels);
|
||||
let mut entries: Vec<(&str, Vec<u8>)> =
|
||||
vec![("_rels/.rels", rels(&root)), ("word/document.xml", doc.into_bytes()), ("word/_rels/document.xml.rels", rels(doc_rels))];
|
||||
for (p, c) in extra {
|
||||
entries.push((p, c.as_bytes().to_vec()));
|
||||
}
|
||||
zip(&entries)
|
||||
}
|
||||
|
||||
fn save(doc: &wordcraft_doc::Document) -> BTreeMap<String, Vec<u8>> {
|
||||
unzip(&wordcraft_docx::write(doc).expect("write"))
|
||||
}
|
||||
|
||||
const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
|
||||
fn pos(s: &str, needle: &str) -> usize {
|
||||
s.find(needle).unwrap_or_else(|| panic!("{needle} missing from {s}"))
|
||||
}
|
||||
|
||||
const CT: &str = r#"<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="jpeg" ContentType="image/jpeg"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"/><Override PartName="/word/stylesWithEffects.xml" ContentType="application/vnd.ms-word.stylesWithEffects+xml"/><Override PartName="/word/people.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.people+xml"/><Override PartName="/word/webextensions/taskpanes.xml" ContentType="application/vnd.ms-office.webextensiontaskpanes+xml"/><Override PartName="/word/webextensions/webextension1.xml" ContentType="application/vnd.ms-office.webextension+xml"/><Override PartName="/word/unknownPart.xml" ContentType="application/x-unknown+xml"/></Types>"#;
|
||||
|
||||
#[test]
|
||||
fn unmodelled_parts_are_carried_with_relationships_and_content_types() {
|
||||
let web = r#"<w:webSettings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:optimizeForBrowser/><w:allowPNG/></w:webSettings>"#;
|
||||
let swe =
|
||||
r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:styleId="X"/></w:styles>"#;
|
||||
let people = r#"<w15:people xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml"><w15:person w15:author="Ann"><w15:presenceInfo w15:providerId="None" w15:userId="Ann"/></w15:person></w15:people>"#;
|
||||
let panes = r#"<wetp:taskpanes xmlns:wetp="http://schemas.microsoft.com/office/webextensions/taskpanes/2010/11" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><wetp:taskpane dockstate="right" visibility="0" width="350" row="1"><wetp:webextensionref r:id="rId1"/></wetp:taskpane></wetp:taskpanes>"#;
|
||||
let ext = r#"<we:webextension xmlns:we="http://schemas.microsoft.com/office/webextensions/webextension/2010/11" id="{00000000-0000-0000-0000-000000000001}"><we:reference id="wa0" version="1.0.0.0" store="en-US" storeType="OMEX"/></we:webextension>"#;
|
||||
let unknown = r#"<x:thing xmlns:x="urn:example:future"/>"#;
|
||||
let thumb = "\u{ff}\u{d8}\u{ff}JPEG";
|
||||
let panes_rels =
|
||||
String::from_utf8(rels(&[("rId1", "http://schemas.microsoft.com/office/2011/relationships/webextension", "webextension1.xml")])).unwrap();
|
||||
let bytes = package(
|
||||
r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p>"#,
|
||||
&[
|
||||
("rId1", &format!("{REL}/webSettings"), "webSettings.xml"),
|
||||
("rId2", "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects", "stylesWithEffects.xml"),
|
||||
("rId3", "http://schemas.microsoft.com/office/2011/relationships/people", "people.xml"),
|
||||
("rId4", "urn:example:future-relationship", "unknownPart.xml"),
|
||||
],
|
||||
&[
|
||||
("rIdT", "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", "docProps/thumbnail.jpeg"),
|
||||
("rIdW", "http://schemas.microsoft.com/office/2011/relationships/webextensiontaskpanes", "word/webextensions/taskpanes.xml"),
|
||||
],
|
||||
&[
|
||||
("[Content_Types].xml", CT),
|
||||
("word/webSettings.xml", web),
|
||||
("word/stylesWithEffects.xml", swe),
|
||||
("word/people.xml", people),
|
||||
("word/unknownPart.xml", unknown),
|
||||
("docProps/thumbnail.jpeg", thumb),
|
||||
("word/webextensions/taskpanes.xml", panes),
|
||||
("word/webextensions/_rels/taskpanes.xml.rels", &panes_rels),
|
||||
("word/webextensions/webextension1.xml", ext),
|
||||
],
|
||||
);
|
||||
let doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
let files = save(&doc);
|
||||
let input = unzip(&bytes);
|
||||
for part in [
|
||||
"word/webSettings.xml",
|
||||
"word/stylesWithEffects.xml",
|
||||
"word/people.xml",
|
||||
"word/unknownPart.xml",
|
||||
"docProps/thumbnail.jpeg",
|
||||
"word/webextensions/taskpanes.xml",
|
||||
"word/webextensions/webextension1.xml",
|
||||
] {
|
||||
assert_eq!(files.get(part), input.get(part), "{part} not carried verbatim");
|
||||
}
|
||||
let doc_rels = text(&files, "word/_rels/document.xml.rels");
|
||||
for ty in ["/webSettings\"", "/stylesWithEffects\"", "/people\"", "urn:example:future-relationship"] {
|
||||
assert_eq!(doc_rels.matches(ty).count(), 1, "{ty}: {doc_rels}");
|
||||
}
|
||||
let root_rels = text(&files, "_rels/.rels");
|
||||
assert!(root_rels.contains(r#"Target="docProps/thumbnail.jpeg""#) && root_rels.contains("webextensiontaskpanes"), "{root_rels}");
|
||||
assert!(text(&files, "word/webextensions/_rels/taskpanes.xml.rels").contains("webextension1.xml"));
|
||||
let ct = text(&files, "[Content_Types].xml");
|
||||
for (part, ty) in [
|
||||
("/word/webSettings.xml", "webSettings+xml"),
|
||||
("/word/stylesWithEffects.xml", "stylesWithEffects+xml"),
|
||||
("/word/people.xml", "people+xml"),
|
||||
("/word/webextensions/taskpanes.xml", "webextensiontaskpanes+xml"),
|
||||
("/docProps/thumbnail.jpeg", "image/jpeg"),
|
||||
] {
|
||||
let entry = ct.split("<Override ").find(|o| o.contains(&format!(r#"PartName="{part}""#))).unwrap_or_else(|| panic!("{part}: {ct}"));
|
||||
assert!(entry.contains(ty), "{part}: {entry}");
|
||||
}
|
||||
// Saved again: the same parts, still once each (`unzip` rejects duplicates).
|
||||
let again = save(&wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap());
|
||||
assert_eq!(again.get("word/webSettings.xml"), input.get("word/webSettings.xml"));
|
||||
assert_eq!(text(&again, "word/_rels/document.xml.rels").matches("/webSettings\"").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_the_writer_owns_or_the_body_refers_to_are_not_carried() {
|
||||
// A second styles part, and an unknown part the body refers to by id: neither is carried
|
||||
// (the first would contradict the written styles, the second's element isn't kept).
|
||||
let bytes = package(
|
||||
r#"<w:p><w:r><w:t>Body</w:t></w:r><w:customThing r:id="rId8"/></w:p>"#,
|
||||
&[("rId7", &format!("{REL}/styles"), "other-styles.xml"), ("rId8", "urn:example:referenced", "referenced.xml")],
|
||||
&[],
|
||||
&[
|
||||
("word/other-styles.xml", r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>"#),
|
||||
("word/referenced.xml", "<x/>"),
|
||||
],
|
||||
);
|
||||
let files = save(&wordcraft_docx::read(&bytes).unwrap());
|
||||
assert!(!files.contains_key("word/other-styles.xml") && !files.contains_key("word/referenced.xml"), "{:?}", files.keys());
|
||||
assert_eq!(text(&files, "word/_rels/document.xml.rels").matches("/styles\"").count(), 1);
|
||||
}
|
||||
|
||||
fn comments_package(with_ids: bool) -> Vec<u8> {
|
||||
let comments = r#"<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:comment w:id="0" w:author="Ann" w:date="2026-01-02T10:00:00" w:initials="A"><w:p w14:paraId="11111111"><w:r><w:t>First</w:t></w:r></w:p></w:comment><w:comment w:id="1" w:author="Ben" w:date="2026-01-03T11:00:00" w:initials="B"><w:p w14:paraId="22222222"><w:r><w:t>Reply</w:t></w:r></w:p></w:comment></w:comments>"#;
|
||||
let ex = r#"<w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml"><w15:commentEx w15:paraId="11111111" w15:done="0"/><w15:commentEx w15:paraId="22222222" w15:paraIdParent="11111111" w15:done="0"/></w15:commentsEx>"#;
|
||||
let ids = r#"<w16cid:commentsIds xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid"><w16cid:commentId w16cid:paraId="11111111" w16cid:durableId="5A1B2C3D"/><w16cid:commentId w16cid:paraId="22222222" w16cid:durableId="0F00BA12"/></w16cid:commentsIds>"#;
|
||||
let cex = r#"<w16cex:commentsExtensible xmlns:w16cex="http://schemas.microsoft.com/office/word/2018/wordml/cex"><w16cex:commentExtensible w16cex:durableId="5A1B2C3D" w16cex:dateUtc="2026-01-02T09:00:00Z"/><w16cex:commentExtensible w16cex:durableId="0F00BA12" w16cex:dateUtc="2026-01-03T10:00:00Z"/></w16cex:commentsExtensible>"#;
|
||||
let body = r#"<w:p><w:commentRangeStart w:id="0"/><w:commentRangeStart w:id="1"/><w:r><w:t>Text</w:t></w:r><w:commentRangeEnd w:id="0"/><w:r><w:rPr><w:rStyle w:val="Odwoaniedokomentarza"/></w:rPr><w:commentReference w:id="0"/></w:r><w:commentRangeEnd w:id="1"/><w:r><w:rPr><w:rStyle w:val="Odwoaniedokomentarza"/></w:rPr><w:commentReference w:id="1"/></w:r></w:p>"#;
|
||||
let styles = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:default="1" w:styleId="Normalny"><w:name w:val="Normal"/></w:style><w:style w:type="character" w:default="1" w:styleId="Domylnaczcionkaakapitu"><w:name w:val="Default Paragraph Font"/></w:style><w:style w:type="character" w:styleId="Odwoaniedokomentarza"><w:name w:val="annotation reference"/><w:basedOn w:val="Domylnaczcionkaakapitu"/><w:rPr><w:sz w:val="16"/></w:rPr></w:style></w:styles>"#;
|
||||
let mut doc_rels = vec![
|
||||
("rId1", format!("{REL}/comments"), "comments.xml"),
|
||||
("rId2", "http://schemas.microsoft.com/office/2011/relationships/commentsExtended".to_string(), "commentsExtended.xml"),
|
||||
("rId5", format!("{REL}/styles"), "styles.xml"),
|
||||
];
|
||||
let mut extra = vec![("word/comments.xml", comments), ("word/commentsExtended.xml", ex), ("word/styles.xml", styles)];
|
||||
if with_ids {
|
||||
doc_rels.push(("rId3", "http://schemas.microsoft.com/office/2016/09/relationships/commentsIds".into(), "commentsIds.xml"));
|
||||
doc_rels.push(("rId4", "http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible".into(), "commentsExtensible.xml"));
|
||||
extra.push(("word/commentsIds.xml", ids));
|
||||
extra.push(("word/commentsExtensible.xml", cex));
|
||||
}
|
||||
let doc_rels: Vec<(&str, &str, &str)> = doc_rels.iter().map(|(a, b, c)| (*a, b.as_str(), *c)).collect();
|
||||
package(body, &doc_rels, &[], &extra)
|
||||
}
|
||||
|
||||
/// (paragraph id → durable id) from commentsIds, and (durable id → UTC date) from
|
||||
/// commentsExtensible, as written.
|
||||
fn written_ids(files: &BTreeMap<String, Vec<u8>>) -> (Vec<(String, String)>, Vec<(String, String)>) {
|
||||
let attr = |el: &str, name: &str| -> Option<String> { el.split(&format!("{name}=\"")).nth(1)?.split('"').next().map(str::to_string) };
|
||||
let ids = text(files, "word/commentsIds.xml")
|
||||
.split("<w16cid:commentId ")
|
||||
.skip(1)
|
||||
.filter_map(|e| Some((attr(e, "w16cid:paraId")?, attr(e, "w16cid:durableId")?)))
|
||||
.collect();
|
||||
let dates = text(files, "word/commentsExtensible.xml")
|
||||
.split("<w16cex:commentExtensible ")
|
||||
.skip(1)
|
||||
.filter_map(|e| Some((attr(e, "w16cex:durableId")?, attr(e, "w16cex:dateUtc").unwrap_or_default())))
|
||||
.collect();
|
||||
(ids, dates)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_durable_ids_and_utc_dates_survive_and_match_the_written_paragraph_ids() {
|
||||
let doc = wordcraft_docx::read(&comments_package(true)).unwrap();
|
||||
let c: Vec<_> = doc.comments.values().collect();
|
||||
assert_eq!(c[0].durable_id.as_deref(), Some("5A1B2C3D"));
|
||||
assert_eq!(c[1].date_utc.as_deref(), Some("2026-01-03T10:00:00Z"));
|
||||
let files = save(&doc);
|
||||
let (ids, dates) = written_ids(&files);
|
||||
assert_eq!(ids.iter().map(|(_, d)| d.as_str()).collect::<Vec<_>>(), ["5A1B2C3D", "0F00BA12"]);
|
||||
// Each paragraph id is the one the comment's paragraph got in comments.xml.
|
||||
let comments = text(&files, "word/comments.xml");
|
||||
for (pid, _) in &ids {
|
||||
assert!(comments.contains(&format!(r#"w14:paraId="{pid}""#)), "{pid}: {comments}");
|
||||
}
|
||||
assert_eq!(dates, [("5A1B2C3D".into(), "2026-01-02T09:00:00Z".into()), ("0F00BA12".into(), "2026-01-03T10:00:00Z".into())]);
|
||||
let rels = text(&files, "word/_rels/document.xml.rels");
|
||||
assert!(rels.contains("relationships/commentsIds") && rels.contains("relationships/commentsExtensible"), "{rels}");
|
||||
// Read back: the same durable ids and dates.
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
back.comments.values().map(|c| c.durable_id.clone()).collect::<Vec<_>>(),
|
||||
doc.comments.values().map(|c| c.durable_id.clone()).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
back.comments.values().map(|c| c.date_utc.clone()).collect::<Vec<_>>(),
|
||||
doc.comments.values().map(|c| c.date_utc.clone()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_without_durable_ids_get_unique_ones() {
|
||||
let doc = wordcraft_docx::read(&comments_package(false)).unwrap();
|
||||
let (ids, dates) = written_ids(&save(&doc));
|
||||
assert_eq!(ids.len(), 2);
|
||||
assert_ne!(ids[0].1, ids[1].1);
|
||||
for (_, d) in &ids {
|
||||
let v = u32::from_str_radix(d, 16).unwrap();
|
||||
assert!(v != 0 && v < 0x7FFF_FFFF, "{d}");
|
||||
}
|
||||
// Local dates without a zone aren't passed off as UTC.
|
||||
assert!(dates.iter().all(|(_, utc)| utc.is_empty()), "{dates:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_references_use_the_documents_annotation_reference_style() {
|
||||
let files = save(&wordcraft_docx::read(&comments_package(true)).unwrap());
|
||||
let body = text(&files, "word/document.xml");
|
||||
assert!(body.contains(r#"<w:rStyle w:val="Odwoaniedokomentarza"/>"#), "{body}");
|
||||
assert!(!body.contains(r#"w:val="CommentReference""#), "{body}");
|
||||
// A document without that style keeps the English id.
|
||||
let mut doc = wordcraft_doc::Document::new();
|
||||
doc.styles.styles.retain(|s| !s.name.eq_ignore_ascii_case("annotation reference"));
|
||||
let rebuilt = wordcraft_docx::read(&comments_package(true)).unwrap();
|
||||
doc.body = rebuilt.body.clone();
|
||||
doc.parts = rebuilt.parts.clone();
|
||||
doc.comments = rebuilt.comments.clone();
|
||||
assert!(text(&save(&doc), "word/document.xml").contains(r#"w:val="CommentReference""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_default_styles_keep_their_default_flag() {
|
||||
let styles = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:latentStyles w:defLockedState="0" w:defUIPriority="99" w:defSemiHidden="0" w:defUnhideWhenUsed="0" w:defQFormat="0" w:count="376"><w:lsdException w:name="Normal" w:uiPriority="0" w:qFormat="1"/><w:lsdException w:name="heading 1" w:uiPriority="9" w:qFormat="1"/></w:latentStyles><w:style w:type="paragraph" w:default="1" w:styleId="Normalny"><w:name w:val="Normal"/></w:style><w:style w:type="character" w:default="1" w:styleId="Domylnaczcionkaakapitu"><w:name w:val="Default Paragraph Font"/></w:style><w:style w:type="table" w:default="1" w:styleId="Standardowy"><w:name w:val="Normal Table"/></w:style><w:style w:type="numbering" w:default="1" w:styleId="Bezlisty"><w:name w:val="No List"/></w:style></w:styles>"#;
|
||||
let bytes =
|
||||
package("<w:p><w:r><w:t>x</w:t></w:r></w:p>", &[("rId1", &format!("{REL}/styles"), "styles.xml")], &[], &[("word/styles.xml", styles)]);
|
||||
let doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
let s = text(&save(&doc), "word/styles.xml");
|
||||
for id in ["Domylnaczcionkaakapitu", "Standardowy", "Bezlisty"] {
|
||||
assert!(s.contains(&format!(r#"w:default="1" w:styleId="{id}""#)) || s.contains(&format!(r#"w:styleId="{id}" w:default="1""#)), "{id}: {s}");
|
||||
}
|
||||
assert_eq!(s.matches(r#"w:default="1""#).count(), 4, "{s}");
|
||||
// Latent styles come back as they were, before the styles.
|
||||
assert!(s.contains(r#"<w:lsdException w:name="heading 1" w:uiPriority="9" w:qFormat="1"/>"#), "{s}");
|
||||
assert!(pos(&s, "<w:latentStyles") < pos(&s, "<w:style "), "{s}");
|
||||
// A new document still flags the English defaults.
|
||||
let fresh = text(&save(&wordcraft_doc::Document::new()), "word/styles.xml");
|
||||
assert!(fresh.contains(r#"w:styleId="Normal" w:default="1""#) || fresh.contains(r#"w:default="1" w:styleId="Normal""#), "{fresh}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_identities_survive_and_a_copied_definition_gets_none() {
|
||||
let numbering = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="0"><w:nsid w:val="1F2E3D4C"/><w:multiLevelType w:val="hybridMultilevel"/><w:tmpl w:val="0415000F"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#;
|
||||
let bytes = package(
|
||||
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>x</w:t></w:r></w:p>"#,
|
||||
&[("rId1", &format!("{REL}/numbering"), "numbering.xml")],
|
||||
&[],
|
||||
&[("word/numbering.xml", numbering)],
|
||||
);
|
||||
let mut doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
let n = text(&save(&doc), "word/numbering.xml");
|
||||
assert!(n.contains(r#"<w:nsid w:val="1F2E3D4C"/><w:multiLevelType w:val="hybridMultilevel"/><w:tmpl w:val="0415000F"/>"#), "{n}");
|
||||
// A copy of the definition (as the engine makes when restarting a list) doesn't reuse the nsid.
|
||||
let mut copy = doc.numbering.abstracts[0].clone();
|
||||
copy.id = 7;
|
||||
doc.numbering.abstracts.push(copy);
|
||||
let n = text(&save(&doc), "word/numbering.xml");
|
||||
assert_eq!(n.matches("1F2E3D4C").count(), 1, "{n}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extended_properties_are_kept_without_words_counts_and_personal_ones_follow_the_privacy_setting() {
|
||||
let app = r#"<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Template>Normal.dotm</Template><TotalTime>42</TotalTime><Pages>107</Pages><Words>40000</Words><Characters>250000</Characters><Application>Microsoft Office Word</Application><DocSecurity>0</DocSecurity><Lines>2000</Lines><Paragraphs>1700</Paragraphs><ScaleCrop>false</ScaleCrop><Manager>M</Manager><Company>Firma</Company><LinksUpToDate>false</LinksUpToDate><CharactersWithSpaces>290000</CharactersWithSpaces><SharedDoc>false</SharedDoc><HyperlinkBase>https://example.com/</HyperlinkBase><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0000</AppVersion></Properties>"#;
|
||||
let make = |settings: &str| {
|
||||
let mut entries = vec![("docProps/app.xml", app)];
|
||||
let mut doc_rels = vec![];
|
||||
let s;
|
||||
if !settings.is_empty() {
|
||||
s = settings.to_string();
|
||||
entries.push(("word/settings.xml", s.as_str()));
|
||||
doc_rels.push(("rId1", format!("{REL}/settings"), "settings.xml"));
|
||||
}
|
||||
let doc_rels: Vec<(&str, &str, &str)> = doc_rels.iter().map(|(a, b, c)| (*a, b.as_str(), *c)).collect();
|
||||
let b = package(
|
||||
"<w:p><w:r><w:t>x</w:t></w:r></w:p>",
|
||||
&doc_rels,
|
||||
&[("rIdA", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml")],
|
||||
&entries,
|
||||
);
|
||||
text(&save(&wordcraft_docx::read(&b).unwrap()), "docProps/app.xml")
|
||||
};
|
||||
let a = make("");
|
||||
for kept in [
|
||||
"<Template>Normal.dotm</Template>",
|
||||
"<Company>Firma</Company>",
|
||||
"<Manager>M</Manager>",
|
||||
"<HyperlinkBase>https://example.com/</HyperlinkBase>",
|
||||
] {
|
||||
assert!(a.contains(kept), "{kept}: {a}");
|
||||
}
|
||||
for gone in ["Pages", "Characters", "Lines", "TotalTime", "AppVersion", "Microsoft Office Word", "40000"] {
|
||||
assert!(!a.contains(gone), "{gone}: {a}");
|
||||
}
|
||||
assert!(a.contains("<Application>WordCraft</Application>"));
|
||||
let private = make(SETTINGS);
|
||||
assert!(!private.contains("Company") && !private.contains("Manager"), "{private}");
|
||||
assert!(private.contains("<Template>Normal.dotm</Template>"));
|
||||
}
|
||||
+411
-19
@@ -8,7 +8,7 @@ use wordcraft_doc::props::{
|
||||
Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, Rgb, RowProps, TabAlign, TabLeader,
|
||||
TabStop, TableLook, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign,
|
||||
};
|
||||
use wordcraft_doc::section::{Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, NumFormat, SectionProps, SectionStart};
|
||||
use wordcraft_doc::section::{Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, NumFormat, PageVAlign, SectionProps, SectionStart};
|
||||
use wordcraft_doc::styles::{Style, StyleKind};
|
||||
use wordcraft_doc::table::{Cell, Table};
|
||||
use wordcraft_doc::{Block, Blocks, Comment, Document, InlineObject, Paragraph, PartKind, Revision, RevisionKind, Source, Watermark, para_block};
|
||||
@@ -230,6 +230,7 @@ fn styles_and_lists_round_trip() {
|
||||
hidden: false,
|
||||
builtin: false,
|
||||
locked: true,
|
||||
default: false,
|
||||
table: None,
|
||||
});
|
||||
d.styles.upsert(Style {
|
||||
@@ -278,14 +279,14 @@ fn tables_with_merges_round_trip() {
|
||||
t.props.look = TableLook { header_row: true, total_row: true, banded_rows: false, first_column: false, last_column: true, banded_columns: true };
|
||||
t.props.shading = Some(Rgb(1, 1, 1));
|
||||
t.props.caption = Some("Sales".into());
|
||||
t.rows[0].props = RowProps { height: Some(20.0), height_rule: HeightRule::Exact, header: true, cant_split: true, fmt_change: None };
|
||||
t.rows[0].props = RowProps { height: Some(20.0), height_rule: HeightRule::Exact, header: true, cant_split: true, ..Default::default() };
|
||||
t.rows[1].props = RowProps { height: Some(15.0), height_rule: HeightRule::AtLeast, ..Default::default() };
|
||||
t.merge(0, 0, 0, 1); // horizontal
|
||||
t.merge(1, 2, 2, 2); // vertical
|
||||
{
|
||||
let c = &mut t.rows[1].cells[0];
|
||||
c.props.shading = Some(Rgb(0xFF, 0, 0));
|
||||
c.props.valign = VAlign::Bottom;
|
||||
c.props.valign = Some(VAlign::Bottom);
|
||||
c.props.text_direction = TextDirection::Up;
|
||||
c.props.no_wrap = true;
|
||||
c.props.margins = Some([2.0, 3.0, 4.0, 5.0]);
|
||||
@@ -321,8 +322,12 @@ fn sections_headers_footers_round_trip() {
|
||||
let mut d = Document::new();
|
||||
let page = |instr: &str| {
|
||||
let mut p = Paragraph::with_text("Page ", CharProps::default());
|
||||
p.insert_object(5, InlineObject::Field { instr: instr.into(), result: "1".into(), locked: false, code: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
p.insert_object(
|
||||
5,
|
||||
InlineObject::Field { instr: instr.into(), result: "1".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
p
|
||||
};
|
||||
let h1 = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("Header one", CharProps::default()))]);
|
||||
@@ -333,7 +338,7 @@ fn sections_headers_footers_round_trip() {
|
||||
title_page: true,
|
||||
page_num_start: Some(3),
|
||||
page_num_format: NumFormat::UpperRoman,
|
||||
valign: VAlign::Center,
|
||||
valign: PageVAlign::Center,
|
||||
page_borders: Some(Borders::box_(Border::single(1.0))),
|
||||
line_numbers: Some(LineNumbering { count_by: 5, start: 1, distance: 18.0, restart: LineNumberRestart::Section }),
|
||||
gutter: 18.0,
|
||||
@@ -369,7 +374,10 @@ fn sections_headers_footers_round_trip() {
|
||||
assert_eq!(part_text(&r, secs[0].1.headers.first), "First page header");
|
||||
assert_eq!(secs[0].1.headers.default, secs[1].1.headers.default, "shared header part stays shared");
|
||||
let fp = r.parts.get(&secs[0].1.footers.default.unwrap()).unwrap().blocks[0].as_para().unwrap();
|
||||
assert_eq!(fp.objects, vec![InlineObject::Field { instr: "PAGE".into(), result: "1".into(), locked: false, code: false }]);
|
||||
assert_eq!(
|
||||
fp.objects,
|
||||
vec![InlineObject::Field { instr: "PAGE".into(), result: "1".into(), locked: false, dirty: false, code: false, form: String::new() }]
|
||||
);
|
||||
assert_eq!(part_text(&r, secs[1].1.footers.default), "Page 1");
|
||||
assert_eq!(r.parts.get(&secs[0].1.headers.default.unwrap()).unwrap().kind, PartKind::Header);
|
||||
}
|
||||
@@ -470,11 +478,27 @@ fn comments_round_trip() {
|
||||
let c1 = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Done.", CharProps::default()))]);
|
||||
d.comments.insert(
|
||||
0,
|
||||
Comment { author: "Ann".into(), initials: "A".into(), date: "2026-01-02T03:04:05Z".into(), parent: None, resolved: true, part: c0 },
|
||||
Comment {
|
||||
author: "Ann".into(),
|
||||
initials: "A".into(),
|
||||
date: "2026-01-02T03:04:05Z".into(),
|
||||
parent: None,
|
||||
resolved: true,
|
||||
part: c0,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
d.comments.insert(
|
||||
1,
|
||||
Comment { author: "Ben".into(), initials: "B".into(), date: "2026-01-03T00:00:00Z".into(), parent: Some(0), resolved: false, part: c1 },
|
||||
Comment {
|
||||
author: "Ben".into(),
|
||||
initials: "B".into(),
|
||||
date: "2026-01-03T00:00:00Z".into(),
|
||||
parent: Some(0),
|
||||
resolved: false,
|
||||
part: c1,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let mut p = Paragraph::with_text("commented text", CharProps::default());
|
||||
p.insert_object(0, InlineObject::CommentStart { id: 0 }, &CharProps::default()).unwrap();
|
||||
@@ -530,6 +554,49 @@ fn table_style_formatting_round_trips() {
|
||||
assert_eq!(got.table.as_ref(), Some(&parts));
|
||||
}
|
||||
|
||||
/// #714: every table style part (ECMA-376 §17.7.6 `w:tblStylePr` types) keeps its run
|
||||
/// formatting, cell shading, cell borders and horizontal and vertical alignment through a save.
|
||||
#[test]
|
||||
fn every_table_style_part_round_trips() {
|
||||
use wordcraft_doc::styles::{PartFormat, TablePart};
|
||||
let mut d = doc_with(vec![Paragraph::with_text("x", CharProps::default())]);
|
||||
let mut st = Style { id: "Parts".into(), name: "Parts".into(), kind: StyleKind::Table, based_on: Some("TableGrid".into()), ..Default::default() };
|
||||
let aligns = [Align::Left, Align::Center, Align::Right];
|
||||
let valigns = [VAlign::Top, VAlign::Center, VAlign::Bottom];
|
||||
for (i, part) in TablePart::ALL.into_iter().enumerate() {
|
||||
let n = i as u8;
|
||||
let f = PartFormat {
|
||||
chr: CharProps {
|
||||
bold: Some(i % 2 == 0),
|
||||
italic: Some(i % 3 == 0),
|
||||
underline: (i % 4 == 0).then_some(Underline::Single),
|
||||
size: Some(8.0 + i as f32),
|
||||
font: Some(format!("Face {i}")),
|
||||
color: Some(TextColor::Rgb(Rgb(n, 0x20, 0x40))),
|
||||
..Default::default()
|
||||
},
|
||||
fill: Some(Rgb(0x10 + n, 0x80, 0xF0 - n)),
|
||||
borders: Some(Borders {
|
||||
top: Some(Border { style: BorderStyle::Double, width: 1.5, color: Some(Rgb(n, 0, 0)), space: 0.0 }),
|
||||
bottom: Some(Border::single(0.5 + i as f32 / 4.0)),
|
||||
left: Some(Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 }),
|
||||
inside_v: (i % 2 == 1).then(|| Border::single(0.25)),
|
||||
..Default::default()
|
||||
}),
|
||||
align: aligns.get(i % 3).copied(),
|
||||
v_align: valigns.get(i % 3).copied(),
|
||||
};
|
||||
st.set_table_part(part, f);
|
||||
}
|
||||
d.styles.upsert(st.clone());
|
||||
let r = rt(&d);
|
||||
let got = r.styles.get("Parts").unwrap();
|
||||
for part in TablePart::ALL {
|
||||
assert_eq!(got.table_part(part), st.table_part(part), "{}", part.ooxml());
|
||||
}
|
||||
assert_eq!(got.table, st.table);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_round_trip() {
|
||||
let mut d = Document::new();
|
||||
@@ -706,7 +773,14 @@ fn toc_field_wraps_its_entries() {
|
||||
let end = head.len();
|
||||
head.insert_object(
|
||||
end,
|
||||
InlineObject::Field { instr: "TOC \\o \"1-2\" \\h \\z \\u".into(), result: String::new(), locked: false, code: false },
|
||||
InlineObject::Field {
|
||||
instr: "TOC \\o \"1-2\" \\h \\z \\u".into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -791,7 +865,14 @@ fn toc_field_skips_nested_stories() {
|
||||
let end = head.len();
|
||||
head.insert_object(
|
||||
end,
|
||||
InlineObject::Field { instr: "TOC \\o \"1-1\" \\h \\z \\u".into(), result: String::new(), locked: false, code: false },
|
||||
InlineObject::Field {
|
||||
instr: "TOC \\o \"1-1\" \\h \\z \\u".into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -830,7 +911,12 @@ fn tracked_changes_round_trip() {
|
||||
let p = para_runs(&[("kept ", CharProps::default()), ("added\t", ins.clone()), ("removed", del.clone()), ("gone", both.clone())]);
|
||||
let mut p = p;
|
||||
let end = p.len();
|
||||
p.insert_object(end, InlineObject::Field { instr: "DATE".into(), result: "today".into(), locked: false, code: false }, &del).unwrap();
|
||||
p.insert_object(
|
||||
end,
|
||||
InlineObject::Field { instr: "DATE".into(), result: "today".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&del,
|
||||
)
|
||||
.unwrap();
|
||||
d.body = vec![para_block(p.clone())];
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.revisions, d.revisions);
|
||||
@@ -877,9 +963,16 @@ fn tracked_paragraph_marks_round_trip() {
|
||||
fn fields_and_special_chars_round_trip() {
|
||||
let mut p = Paragraph::with_text("a\tb\nc\u{000C}d\u{000E}e\u{2011}f\u{00AD}g spaced ", CharProps::default());
|
||||
let fields = [
|
||||
InlineObject::Field { instr: "PAGE".into(), result: "4".into(), locked: false, code: false },
|
||||
InlineObject::Field { instr: "DATE \\@ \"M/d/yyyy\"".into(), result: "1/2/2026".into(), locked: true, code: false },
|
||||
InlineObject::Field { instr: "NUMPAGES".into(), result: String::new(), locked: false, code: false },
|
||||
InlineObject::Field { instr: "PAGE".into(), result: "4".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
InlineObject::Field {
|
||||
instr: "DATE \\@ \"M/d/yyyy\"".into(),
|
||||
result: "1/2/2026".into(),
|
||||
locked: true,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
InlineObject::Field { instr: "NUMPAGES".into(), result: String::new(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
];
|
||||
for f in &fields {
|
||||
let end = p.len();
|
||||
@@ -892,6 +985,74 @@ fn fields_and_special_chars_round_trip() {
|
||||
assert_eq!(got.runs, p.runs);
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// #877: a field begin marker's `w:dirty` (the cached result is stale; Word refreshes it on
|
||||
/// open) survives a round trip, and a field without the flag doesn't gain one. Generators that
|
||||
/// can't paginate (pandoc-style pipelines, python-docx templates) set the flag instead of a result.
|
||||
#[test]
|
||||
fn field_dirty_flag_round_trips() {
|
||||
let mut p = Paragraph::with_text("", CharProps::default());
|
||||
for instr in ["PAGE", "DATE"] {
|
||||
let end = p.len();
|
||||
p.insert_object(
|
||||
end,
|
||||
InlineObject::Field { instr: instr.into(), result: "7".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
// Another producer marks the first field's begin as dirty.
|
||||
let xml = document_xml(&bytes);
|
||||
let marked = xml.replacen(r#"<w:fldChar w:fldCharType="begin"/>"#, r#"<w:fldChar w:fldCharType="begin" w:dirty="true"/>"#, 1);
|
||||
assert_ne!(&marked, &xml, "the written begin marker must be bare: {xml}");
|
||||
let r = wordcraft_docx::read(&replace_part(&bytes, "word/document.xml", marked.as_bytes())).expect("read");
|
||||
let out = document_xml(&wordcraft_docx::write(&r).expect("write"));
|
||||
assert_eq!(out.matches("w:dirty").count(), 1, "the dirty field keeps its flag, the other gains none: {out}");
|
||||
assert!(out.contains(r#"<w:fldChar w:fldCharType="begin" w:dirty="true"/>"#), "{out}");
|
||||
}
|
||||
|
||||
/// #877: a TOC imported as a range field keeps `w:dirty` through a round trip — the flag sits on
|
||||
/// the begin marker Word rebuilds the field from (#878's fixture shape: a placeholder result).
|
||||
#[test]
|
||||
fn range_toc_dirty_flag_round_trips() {
|
||||
let mut toc = Paragraph::new();
|
||||
toc.insert_object(0, InlineObject::FieldStart { instr: r#"TOC \o "1-3" \h \z \u"#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
let end = toc.len();
|
||||
toc.insert_text(end, "Placeholder: update fields (F9).", &CharProps::default()).unwrap();
|
||||
let end = toc.len();
|
||||
toc.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
let mut blocks = vec![toc];
|
||||
for (t, style) in [("Alpha", Some("Heading1")), ("Body text.", None), ("Beta", Some("Heading2")), ("Gamma", Some("Heading1"))] {
|
||||
let mut h = Paragraph::with_text(t, CharProps::default());
|
||||
h.props.style = style.map(str::to_string);
|
||||
blocks.push(h);
|
||||
}
|
||||
let bytes = wordcraft_docx::write(&doc_with(blocks)).expect("write");
|
||||
let xml = document_xml(&bytes);
|
||||
let marked = xml.replacen(r#"<w:fldChar w:fldCharType="begin"/>"#, r#"<w:fldChar w:fldCharType="begin" w:dirty="true"/>"#, 1);
|
||||
assert_ne!(&marked, &xml, "the written begin marker must be bare: {xml}");
|
||||
let marked = replace_part(&bytes, "word/document.xml", marked.as_bytes());
|
||||
let r = wordcraft_docx::read(&marked).expect("read");
|
||||
// Still the imported shape: a range field holding the placeholder as ordinary content.
|
||||
assert!(matches!(paras(&r)[0].objects.first(), Some(InlineObject::FieldStart { .. })), "{:?}", paras(&r)[0].objects);
|
||||
assert!(paras(&r)[0].objects.last().is_some_and(|o| matches!(o, InlineObject::FieldEnd)));
|
||||
assert_eq!(paras(&r)[0].plain_text(), "Placeholder: update fields (F9).");
|
||||
let out = document_xml(&wordcraft_docx::write(&r).expect("write"));
|
||||
assert_eq!(out.matches("w:dirty").count(), 1, "the TOC keeps its flag: {out}");
|
||||
let (begin, placeholder) = (out.find("fldCharType=\"begin\"").unwrap(), out.find("Placeholder").unwrap());
|
||||
let (separate, end) = (out.find("fldCharType=\"separate\"").unwrap(), out.find("fldCharType=\"end\"").unwrap());
|
||||
assert!(begin < separate && separate < placeholder && placeholder < end, "the placeholder stays the field's result: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_textboxes_equations_dropcaps_round_trip() {
|
||||
let mut d = Document::new();
|
||||
@@ -1151,6 +1312,28 @@ fn rotated_drawing_canvas_round_trips() {
|
||||
assert_eq!(children[0].obj.frame().unwrap().2.rot, 15.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_contextual_spacing_compatibility_flag_round_trips() {
|
||||
for mode in [11, 12, 14, 15] {
|
||||
for allow in [false, true] {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = mode;
|
||||
d.settings.allow_space_of_same_style_in_table = allow;
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.allow_space_of_same_style_in_table, allow);
|
||||
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();
|
||||
// CT_Compat requires the boolean option before compatSetting.
|
||||
assert!(xml.find("<w:allowSpaceOfSameStyleInTable").unwrap() < xml.find("<w:compatSetting").unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compatibility_mode_round_trips() {
|
||||
// New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't
|
||||
@@ -1195,6 +1378,31 @@ fn attached_template_and_link_styles_round_trip() {
|
||||
assert!(!plain.settings.link_styles);
|
||||
}
|
||||
|
||||
/// #995: the zoom a document was saved at (`w:zoom`), One Page (`fullPage`) included, is read
|
||||
/// and written back.
|
||||
#[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 plain = wordcraft_docx::write(&Document::new()).unwrap();
|
||||
let xml = settings(&plain);
|
||||
assert!(xml.contains(r#"<w:zoom w:percent="100"/>"#), "{xml}");
|
||||
for (zoom, written) in [
|
||||
(r#"<w:zoom w:val="fullPage" w:percent="62"/>"#, r#"<w:zoom w:val="fullPage" w:percent="62"/>"#),
|
||||
(r#"<w:zoom w:percent="75%"/>"#, r#"<w:zoom w:percent="75"/>"#),
|
||||
(r#"<w:zoom w:val="bestFit" w:percent="99999"/>"#, r#"<w:zoom w:val="bestFit" w:percent="500"/>"#),
|
||||
(r#"<w:zoom w:val="sideways" w:percent="80"/>"#, r#"<w:zoom w:percent="80"/>"#),
|
||||
] {
|
||||
let file = replace_part(&plain, "word/settings.xml", xml.replace(r#"<w:zoom w:percent="100"/>"#, zoom).as_bytes());
|
||||
let back = settings(&wordcraft_docx::write(&wordcraft_docx::read(&file).unwrap()).unwrap());
|
||||
assert!(back.contains(written), "{zoom}: {back}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_core_theme_round_trip() {
|
||||
let mut d = Document::new();
|
||||
@@ -1234,10 +1442,173 @@ fn settings_core_theme_round_trip() {
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings, d.settings);
|
||||
assert_eq!(r.core, d.core);
|
||||
// Watermarks aren't stored in DOCX by this crate (yet).
|
||||
// #1290: the watermark is written as a VML text shape in the headers and read back.
|
||||
let mut w = d.clone();
|
||||
w.settings.watermark = Some(Watermark::default());
|
||||
assert_eq!(rt(&w).settings.watermark, None);
|
||||
assert_eq!(rt(&w).settings.watermark, w.settings.watermark);
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// Header parts in the document, by id.
|
||||
fn header_ids(doc: &Document) -> Vec<u32> {
|
||||
doc.parts.iter().filter(|(_, p)| p.kind == PartKind::Header).map(|(id, _)| *id).collect()
|
||||
}
|
||||
|
||||
/// #1290: a watermark round-trips through Word's VML text shape: text, font, colour, diagonal and
|
||||
/// semitransparent, defaults or not.
|
||||
#[test]
|
||||
fn watermark_roundtrips() {
|
||||
for wm in [
|
||||
Watermark::default(),
|
||||
Watermark {
|
||||
text: "Riservato & <interno>".into(),
|
||||
font: "Georgia".into(),
|
||||
color: Rgb(0x80, 0x10, 0x20),
|
||||
diagonal: false,
|
||||
semitransparent: false,
|
||||
},
|
||||
] {
|
||||
let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]);
|
||||
d.settings.watermark = Some(wm.clone());
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.watermark, Some(wm));
|
||||
assert_eq!(paras(&r).len(), 1, "the body gains nothing");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1290: a document without headers gains one default header holding only the watermark (an
|
||||
/// empty paragraph once read back); saving again neither adds another nor duplicates the shape.
|
||||
#[test]
|
||||
fn watermark_without_header_gains_one() {
|
||||
let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]);
|
||||
d.settings.watermark = Some(Watermark::default());
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let hdr = part_xml(&bytes, "word/header1.xml");
|
||||
assert_eq!(hdr.matches("<v:shape ").count(), 1);
|
||||
assert!(hdr.contains(r#"id="PowerPlusWaterMarkObject1""#) && hdr.contains("rotation:315") && hdr.contains(r#"<v:fill opacity=".5"/>"#));
|
||||
// The text sits between the top and bottom edges: on one line Word gives it no height.
|
||||
assert!(hdr.contains(r#"path="m0,0l21600,0m0,21600l21600,21600e""#));
|
||||
assert!(part_xml(&bytes, "word/document.xml").contains(r#"<w:headerReference w:type="default""#));
|
||||
let r = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(r.settings.watermark, d.settings.watermark);
|
||||
let ids = header_ids(&r);
|
||||
assert_eq!(ids.len(), 1);
|
||||
assert_eq!(r.last_section.headers.default, ids.first().copied());
|
||||
let blocks = &r.parts[&ids[0]].blocks;
|
||||
assert_eq!(blocks.len(), 1);
|
||||
let p = blocks[0].as_para().unwrap();
|
||||
assert!(p.text.is_empty() && p.objects.is_empty(), "the shape leaves nothing behind: {p:?}");
|
||||
// Second generation: stable.
|
||||
let r2 = rt(&r);
|
||||
assert_eq!(r2.settings.watermark, d.settings.watermark);
|
||||
assert_eq!(header_ids(&r2).len(), 1);
|
||||
assert_eq!(r2.parts[&header_ids(&r2)[0]].blocks.len(), 1);
|
||||
}
|
||||
|
||||
/// #1290: a header keeps its own text, and the watermark goes into its first paragraph (no extra
|
||||
/// line). Each header part carries the shape; footers don't.
|
||||
#[test]
|
||||
fn watermark_joins_existing_headers() {
|
||||
let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]);
|
||||
let h = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("Head", CharProps::default()))]);
|
||||
let hf = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("First", CharProps::default()))]);
|
||||
let f = d.add_part(PartKind::Footer, vec![para_block(Paragraph::with_text("Foot", CharProps::default()))]);
|
||||
d.last_section.headers.default = Some(h);
|
||||
d.last_section.headers.first = Some(hf);
|
||||
d.last_section.title_page = true;
|
||||
d.last_section.footers.default = Some(f);
|
||||
d.settings.watermark = Some(Watermark::default());
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
for name in ["word/header1.xml", "word/header2.xml"] {
|
||||
assert_eq!(part_xml(&bytes, name).matches("<v:shape ").count(), 1, "{name}");
|
||||
}
|
||||
assert!(!part_xml(&bytes, "word/footer1.xml").contains("v:shape"));
|
||||
let r = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(r.settings.watermark, d.settings.watermark);
|
||||
assert_eq!(header_ids(&r).len(), 2, "no header was added");
|
||||
assert_eq!(part_text(&r, r.last_section.headers.default), "Head");
|
||||
assert_eq!(part_text(&r, r.last_section.headers.first), "First");
|
||||
for id in header_ids(&r) {
|
||||
assert_eq!(r.parts[&id].blocks.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// #1290: only the slots the pages show and nothing fills get the watermark's own header: a
|
||||
/// later section still links to the earlier one's header, and a title page with no first-page
|
||||
/// header gets one.
|
||||
#[test]
|
||||
fn watermark_header_respects_linking() {
|
||||
let mut d = Document::new();
|
||||
let h = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("Head", CharProps::default()))]);
|
||||
let mut s1 = SectionProps::default();
|
||||
s1.headers.default = Some(h);
|
||||
s1.title_page = true;
|
||||
let mut p1 = Paragraph::with_text("One", CharProps::default());
|
||||
p1.section = Some(Box::new(s1));
|
||||
d.body = vec![para_block(p1), para_block(Paragraph::with_text("Two", CharProps::default()))];
|
||||
d.last_section.title_page = true;
|
||||
d.settings.watermark = Some(Watermark::default());
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.watermark, d.settings.watermark);
|
||||
let secs = r.sections();
|
||||
assert_eq!(part_text(&r, secs[0].1.headers.default), "Head");
|
||||
let first = secs[0].1.headers.first.expect("a first-page header for the watermark");
|
||||
assert_eq!(part_text(&r, Some(first)), "");
|
||||
assert_eq!(secs[1].1.headers, Default::default(), "the second section still links to the first");
|
||||
assert_eq!(header_ids(&r).len(), 2);
|
||||
}
|
||||
|
||||
/// #1290: a header holding only a table takes the watermark in the paragraph after the table
|
||||
/// (one every story ends with), so it gains no line.
|
||||
#[test]
|
||||
fn watermark_in_table_only_header() {
|
||||
let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]);
|
||||
let t = Table::new(1, 2, 400.0);
|
||||
let h = d.add_part(PartKind::Header, vec![Arc::new(Block::Table(t))]);
|
||||
d.last_section.headers.default = Some(h);
|
||||
let blocks = |d: &Document| d.parts[&d.last_section.headers.default.unwrap()].blocks.len();
|
||||
let plain = blocks(&rt(&d));
|
||||
d.settings.watermark = Some(Watermark::default());
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.watermark, d.settings.watermark);
|
||||
assert_eq!(blocks(&r), plain);
|
||||
}
|
||||
|
||||
/// #1290: with different odd and even pages, a document with only a default header gains an
|
||||
/// even-page header for the watermark; a later section stays linked to both.
|
||||
#[test]
|
||||
fn watermark_even_pages_header() {
|
||||
let mut d = Document::new();
|
||||
let h = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("Head", CharProps::default()))]);
|
||||
let mut s1 = SectionProps::default();
|
||||
s1.headers.default = Some(h);
|
||||
let mut p1 = Paragraph::with_text("One", CharProps::default());
|
||||
p1.section = Some(Box::new(s1));
|
||||
d.body = vec![para_block(p1), para_block(Paragraph::with_text("Two", CharProps::default()))];
|
||||
d.settings.even_odd_headers = true;
|
||||
d.settings.watermark = Some(Watermark::default());
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.watermark, d.settings.watermark);
|
||||
let secs = r.sections();
|
||||
assert_eq!(part_text(&r, secs[0].1.headers.default), "Head");
|
||||
assert!(secs[0].1.headers.even.is_some() && secs[0].1.headers.first.is_none());
|
||||
assert_eq!(secs[1].1.headers, Default::default());
|
||||
}
|
||||
|
||||
/// #1290: a blank watermark isn't written (it wouldn't read back), and adds no header.
|
||||
#[test]
|
||||
fn blank_watermark_writes_nothing() {
|
||||
let mut d = doc_with(vec![Paragraph::with_text("Body", CharProps::default())]);
|
||||
d.settings.watermark = Some(Watermark { text: " ".into(), ..Watermark::default() });
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.watermark, None);
|
||||
assert!(header_ids(&r).is_empty());
|
||||
}
|
||||
|
||||
/// A document that uses everything, for second-generation stability checks.
|
||||
@@ -1926,7 +2297,7 @@ fn wrap_polygons_round_trip() {
|
||||
let got = paras(&r)[0];
|
||||
let floats: Vec<Float> = got.objects.iter().filter_map(|o| o.frame().map(|(_, _, f)| f.clone())).collect();
|
||||
assert_eq!(floats[0], edited);
|
||||
let ellipse = WrapPolygon::from_unit(false, &shape_outline(ShapeKind::Ellipse, 80.0, 40.0).unwrap());
|
||||
let ellipse = WrapPolygon::from_unit(false, &shape_outline(ShapeKind::Ellipse, 80.0, 40.0, None).unwrap());
|
||||
assert_eq!(floats[1].wrap, Wrap::Through);
|
||||
assert_eq!(floats[1].wrap_polygon.as_deref(), ellipse.as_ref());
|
||||
}
|
||||
@@ -1949,7 +2320,7 @@ fn enclosed_characters_round_trip_in_words_structure() {
|
||||
let off = p.len();
|
||||
p.insert_object(
|
||||
off,
|
||||
InlineObject::Field { instr: e.instr(), result: "字".into(), locked: false, code: false },
|
||||
InlineObject::Field { instr: e.instr(), result: "字".into(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&CharProps { size, ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
@@ -2214,3 +2585,24 @@ fn replace_part(zip_bytes: &[u8], name: &str, data: &[u8]) -> Vec<u8> {
|
||||
}
|
||||
out.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// 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 mut d = Document::new();
|
||||
d.settings.page_color = Some(Rgb(0xFF, 0xFF, 0xCC));
|
||||
d.media.insert("paper.png".into(), Arc::new(png.clone()));
|
||||
d.settings.page_picture = Some(wordcraft_doc::PagePicture { media: "paper.png".into(), fill_type: "tile".into(), title: "Paper".into() });
|
||||
let r = rt(&d);
|
||||
let pic = r.settings.page_picture.as_ref().expect("picture kept");
|
||||
assert_eq!((pic.fill_type.as_str(), pic.title.as_str()), ("tile", "Paper"));
|
||||
assert_eq!(r.media.get(&pic.media).map(|b| b.as_slice()), Some(png.as_slice()));
|
||||
assert_eq!(r.settings.page_color, d.settings.page_color);
|
||||
// Saved again, it is still there.
|
||||
assert!(rt(&r).settings.page_picture.is_some());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! 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()));
|
||||
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.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn row(ex: &str, text: &str) -> String {
|
||||
format!(
|
||||
r#"<w:tr>{ex}<w:trPr><w:cantSplit/></w:trPr><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:tc></w:tr>"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_property_exceptions_round_trip_before_the_row_properties() {
|
||||
let ex = r#"<w:tblPrEx><w:tblW w:w="3000" w:type="dxa"/><w:jc w:val="center"/><w:tblInd w:w="240" w:type="dxa"/><w:tblLayout w:type="fixed"/></w:tblPrEx>"#;
|
||||
let body = format!(r#"<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid>{}{}</w:tbl><w:p/>"#, row(ex, "A"), row("", "B"));
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = document_xml(&out);
|
||||
assert_eq!(xml.matches("<w:tblPrEx>").count(), 1, "{xml}");
|
||||
assert!(xml.contains(r#"<w:tr><w:tblPrEx><w:tblW w:w="3000" w:type="dxa"/><w:jc w:val="center"/><w:tblInd w:w="240" w:type="dxa"/><w:tblLayout w:type="fixed"/></w:tblPrEx><w:trPr>"#), "{xml}");
|
||||
// Reading the output again gives the same exception on the first row only.
|
||||
let back = wordcraft_docx::read(&out).unwrap();
|
||||
let t = back.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
let x = t.rows[0].props.exceptions.as_ref().expect("first row keeps its exceptions");
|
||||
assert_eq!(x.width, Some(150.0));
|
||||
assert!(x.fixed);
|
||||
assert!(t.rows[1].props.exceptions.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_row_exception_element_is_kept() {
|
||||
let body = format!(r#"<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid>{}</w:tbl><w:p/>"#, row("<w:tblPrEx/>", "A"));
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains("<w:tblPrEx></w:tblPrEx>") || xml.contains("<w:tblPrEx/>"), "{xml}");
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! 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()));
|
||||
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.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_protection_round_trips_in_schema_order() {
|
||||
// Three sections: protected, explicitly unprotected, and one that says nothing.
|
||||
let body = concat!(
|
||||
r#"<w:p><w:pPr><w:sectPr><w:formProt/><w:titlePg/></w:sectPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#,
|
||||
r#"<w:p><w:pPr><w:sectPr><w:formProt w:val="0"/></w:sectPr></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
|
||||
r#"<w:p><w:r><w:t>C</w:t></w:r></w:p><w:sectPr/>"#
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(body)).unwrap();
|
||||
let flags: Vec<Option<bool>> = d.sections().iter().map(|(_, s)| s.form_prot).collect();
|
||||
assert_eq!(flags, vec![Some(true), Some(false), None]);
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = document_xml(&out);
|
||||
// Before w:titlePg in CT_SectPr's sequence; a section that never said it writes none.
|
||||
assert!(xml.contains(r#"<w:formProt/><w:titlePg/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:formProt w:val="0"/>"#), "{xml}");
|
||||
assert_eq!(xml.matches("w:formProt").count(), 2);
|
||||
let again: Vec<Option<bool>> = wordcraft_docx::read(&out).unwrap().sections().iter().map(|(_, s)| s.form_prot).collect();
|
||||
assert_eq!(again, flags);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! 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()));
|
||||
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.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_number_type_is_kept_even_when_it_only_repeats_the_defaults() {
|
||||
// A decimal format with no start changes nothing, but the file said it, so saving says it too.
|
||||
let body = r#"<w:p><w:r><w:t>One</w:t></w:r></w:p><w:sectPr><w:pgNumType w:fmt="decimal"/></w:sectPr>"#;
|
||||
let d = wordcraft_docx::read(&docx(body)).unwrap();
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains(r#"<w:pgNumType w:fmt="decimal"/>"#), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_number_type_with_a_start_and_format_still_round_trips() {
|
||||
let body = r#"<w:p><w:r><w:t>One</w:t></w:r></w:p><w:sectPr><w:pgNumType w:fmt="upperRoman" w:start="3"/></w:sectPr>"#;
|
||||
let d = wordcraft_docx::read(&docx(body)).unwrap();
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains(r#"w:fmt="upperRoman""#) && xml.contains(r#"w:start="3""#), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_section_without_page_number_type_writes_none() {
|
||||
let body = r#"<w:p><w:r><w:t>One</w:t></w:r></w:p><w:sectPr/>"#;
|
||||
let d = wordcraft_docx::read(&docx(body)).unwrap();
|
||||
assert!(!document_xml(&wordcraft_docx::write(&d).unwrap()).contains("pgNumType"));
|
||||
}
|
||||
@@ -48,3 +48,14 @@ fn section_text_direction_round_trips_in_schema_order() {
|
||||
let again: Vec<TextDirection> = back.sections().iter().map(|(_, s)| s.text_direction).collect();
|
||||
assert_eq!(again, dirs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_horizontal_direction_is_kept_in_sections_and_cells() {
|
||||
let body = r#"<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:textDirection w:val="lrTb"/></w:tcPr><w:p><w:r><w:t>Cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr><w:textDirection w:val="lrTb"/></w:sectPr>"#;
|
||||
let d = wordcraft_docx::read(&docx(body)).unwrap();
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert_eq!(xml.matches(r#"<w:textDirection w:val="lrTb"/>"#).count(), 2, "{xml}");
|
||||
// A horizontal section or cell that never said so still writes nothing.
|
||||
let plain = wordcraft_docx::read(&docx(r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr/>"#)).unwrap();
|
||||
assert!(!document_xml(&wordcraft_docx::write(&plain).unwrap()).contains("textDirection"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! 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> {
|
||||
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()));
|
||||
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.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// #1320: "both" (Justified) reads as Justify and writes back as "both"; the others keep theirs.
|
||||
#[test]
|
||||
fn section_vertical_alignment_round_trips_with_justified() {
|
||||
let sect = |v: &str| format!(r#"<w:sectPr><w:vAlign w:val="{v}"/></w:sectPr>"#);
|
||||
let body = format!(
|
||||
r#"<w:p><w:pPr>{}</w:pPr><w:r><w:t>A</w:t></w:r></w:p><w:p><w:pPr>{}</w:pPr><w:r><w:t>B</w:t></w:r></w:p><w:p><w:pPr>{}</w:pPr><w:r><w:t>C</w:t></w:r></w:p><w:p><w:pPr>{}</w:pPr><w:r><w:t>D</w:t></w:r></w:p><w:p><w:r><w:t>E</w:t></w:r></w:p>{}"#,
|
||||
sect("both"),
|
||||
sect("center"),
|
||||
sect("bottom"),
|
||||
sect("top"),
|
||||
sect("sideways")
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
let got: Vec<PageVAlign> = d.sections().iter().map(|(_, s)| s.valign).collect();
|
||||
let want = vec![PageVAlign::Justify, PageVAlign::Center, PageVAlign::Bottom, PageVAlign::Top, PageVAlign::Top];
|
||||
assert_eq!(got, want);
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = document_xml(&out);
|
||||
assert_eq!(xml.matches(r#"<w:vAlign w:val="both"/>"#).count(), 1, "{xml}");
|
||||
assert_eq!(xml.matches(r#"<w:vAlign w:val="center"/>"#).count(), 1, "{xml}");
|
||||
assert_eq!(xml.matches(r#"<w:vAlign w:val="bottom"/>"#).count(), 1, "{xml}");
|
||||
assert_eq!(xml.matches("w:vAlign").count(), 3, "top writes nothing: {xml}");
|
||||
let back = wordcraft_docx::read(&out).unwrap();
|
||||
assert_eq!(back.sections().iter().map(|(_, s)| s.valign).collect::<Vec<_>>(), want);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Settings a save used to drop: `word/settings.xml` is merged into the file's original, so
|
||||
//! settings the model doesn't hold (compatibility options, rsids, document variables, proofing
|
||||
//! state, "remove personal information"…) survive, and owned ones follow the model. Hand-written
|
||||
//! 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()));
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
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());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn text(files: &BTreeMap<String, Vec<u8>>, name: &str) -> String {
|
||||
String::from_utf8(files.get(name).unwrap_or_else(|| panic!("no {name} in {:?}", files.keys())).clone()).unwrap()
|
||||
}
|
||||
|
||||
fn rels(list: &[(&str, &str, &str)]) -> Vec<u8> {
|
||||
let mut s =
|
||||
String::from(r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for (id, ty, target) in list {
|
||||
s.push_str(&format!(r#"<Relationship Id="{id}" Type="{ty}" Target="{target}"/>"#));
|
||||
}
|
||||
s.push_str("</Relationships>");
|
||||
s.into_bytes()
|
||||
}
|
||||
|
||||
/// A package: `body`, document relationships, root relationships after the main document's,
|
||||
/// and extra parts.
|
||||
fn package(body: &str, doc_rels: &[(&str, &str, &str)], root_rels: &[(&str, &str, &str)], extra: &[(&str, &str)]) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:r="{R_NS}" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut root = vec![("rIdMain", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "word/document.xml")];
|
||||
root.extend_from_slice(root_rels);
|
||||
let mut entries: Vec<(&str, Vec<u8>)> =
|
||||
vec![("_rels/.rels", rels(&root)), ("word/document.xml", doc.into_bytes()), ("word/_rels/document.xml.rels", rels(doc_rels))];
|
||||
for (p, c) in extra {
|
||||
entries.push((p, c.as_bytes().to_vec()));
|
||||
}
|
||||
zip(&entries)
|
||||
}
|
||||
|
||||
fn save(doc: &wordcraft_doc::Document) -> BTreeMap<String, Vec<u8>> {
|
||||
unzip(&wordcraft_docx::write(doc).expect("write"))
|
||||
}
|
||||
|
||||
const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
|
||||
fn with_settings(settings: &str) -> Vec<u8> {
|
||||
package("<w:p><w:r><w:t>Text</w:t></w:r></w:p>", &[("rId1", &format!("{REL}/settings"), "settings.xml")], &[], &[("word/settings.xml", settings)])
|
||||
}
|
||||
|
||||
fn pos(s: &str, needle: &str) -> usize {
|
||||
s.find(needle).unwrap_or_else(|| panic!("{needle} missing from {s}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
|
||||
let mut doc = wordcraft_docx::read(&with_settings(SETTINGS)).unwrap();
|
||||
assert!(doc.settings.track_changes);
|
||||
doc.settings.track_changes = false;
|
||||
let files = save(&doc);
|
||||
let s = text(&files, "word/settings.xml");
|
||||
// Kept byte for byte: everything the model doesn't hold, the original root and zoom.
|
||||
for kept in [
|
||||
r#"<w:zoom w:percent="120"/>"#,
|
||||
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
|
||||
r#"w:name="overrideTableStyleFontSizeAndJustification""#,
|
||||
r#"w:name="enableOpenTypeFeatures""#,
|
||||
r#"<w:docVar w:name="ClauseSet" w:val="B"/>"#,
|
||||
r#"<w:rsidRoot w:val="00A1B2C3"/>"#,
|
||||
r#"<m:mathFont m:val="Cambria Math"/>"#,
|
||||
r#"<w:themeFontLang w:val="pl-PL"/>"#,
|
||||
r#"<w:decimalSymbol w:val=","/>"#,
|
||||
r#"<w:listSeparator w:val=";"/>"#,
|
||||
r#"<w14:docId w14:val="1A2B3C4D"/>"#,
|
||||
r#"mc:Ignorable="w14 w15""#,
|
||||
] {
|
||||
assert!(s.contains(kept), "{kept} lost: {s}");
|
||||
}
|
||||
// Owned: Track Changes was turned off; one compatibility mode; the mail merge source (a
|
||||
// relationship that isn't carried) is dropped rather than left dangling.
|
||||
assert!(!s.contains("trackRevisions"), "{s}");
|
||||
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
|
||||
assert!(!s.contains("mailMerge") && !s.contains("rId9"), "{s}");
|
||||
// The privacy options are the model's (#1062): written once each, and gone when turned off.
|
||||
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
|
||||
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
|
||||
// CT_Settings order holds for kept and owned children.
|
||||
assert!(pos(&s, "removePersonalInformation") < pos(&s, "defaultTabStop"));
|
||||
assert!(pos(&s, "defaultTabStop") < pos(&s, "<w:compat>"));
|
||||
assert!(pos(&s, "<w:compat>") < pos(&s, "<w:rsids>"));
|
||||
// Turning Track Changes back on inserts it at its place.
|
||||
doc.settings.track_changes = true;
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert!(pos(&s, "proofState") < pos(&s, "<w:trackRevisions/>") && pos(&s, "<w:trackRevisions/>") < pos(&s, "defaultTabStop"), "{s}");
|
||||
let mut private = doc.clone();
|
||||
private.settings.remove_personal_info = false;
|
||||
private.settings.remove_date_time = false;
|
||||
let p = text(&save(&private), "word/settings.xml");
|
||||
assert!(!p.contains("removePersonalInformation") && !p.contains("removeDateAndTime"), "{p}");
|
||||
// A second generation is identical.
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(text(&save(&again), "word/settings.xml"), s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_written_by_wordcraft_keep_no_original() {
|
||||
let doc = wordcraft_doc::Document::new();
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert!(!back.passthrough.contains_key("wordcraft:settings.orig"), "{:?}", back.passthrough.keys());
|
||||
assert_eq!(text(&save(&back), "word/settings.xml"), text(&save(&doc), "word/settings.xml"));
|
||||
}
|
||||
@@ -213,3 +213,50 @@ fn hostile_word_xml_is_an_error_not_a_panic() {
|
||||
many.push_str("</pkg:package>");
|
||||
assert!(matches!(read_xml(many.as_bytes()), Err(DocxError::Limit(_))));
|
||||
}
|
||||
|
||||
/// A Flat OPC package of one paragraph with a picture, whose `pkg:binaryData` holds `data` as
|
||||
/// written, and `extra` after the parts.
|
||||
fn picture_package(data: &str, extra: &str) -> String {
|
||||
format!(
|
||||
r#"<pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
|
||||
<pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml"><pkg:xmlData><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></pkg:xmlData></pkg:part>
|
||||
<pkg:part pkg:name="/word/_rels/document.xml.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml"><pkg:xmlData><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/dot.png"/></Relationships></pkg:xmlData></pkg:part>
|
||||
<pkg:part pkg:name="/word/document.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"><pkg:xmlData><w:document xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:v="urn:schemas-microsoft-com:vml"><w:body><w:p><w:r><w:t>Seed</w:t></w:r><w:r><w:pict><v:shape style="width:24pt;height:12pt"><v:imagedata r:id="rId6"/></v:shape></w:pict></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part>
|
||||
<pkg:part pkg:name="/word/media/dot.png" pkg:contentType="image/png" pkg:compression="store"><pkg:binaryData>{data}</pkg:binaryData></pkg:part>{extra}
|
||||
</pkg:package>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// A binary part's base64 reads the same as plain text, as CDATA or with character references;
|
||||
/// an entity in it is an error rather than bytes gone missing (#1353).
|
||||
#[test]
|
||||
fn flat_opc_binary_data_reads_the_same_in_cdata_and_character_references() {
|
||||
let png = tiny_png_b64();
|
||||
let media = |data: &str| read_xml(picture_package(data, "").as_bytes()).map(|d| d.media.values().cloned().collect::<Vec<_>>());
|
||||
let plain = media(&png).unwrap();
|
||||
assert_eq!(plain.len(), 1);
|
||||
let (head, tail) = png.split_at(png.len() / 2);
|
||||
let first = png.chars().next().unwrap();
|
||||
for other in
|
||||
[format!("<![CDATA[{png}]]>"), format!("{head}<![CDATA[{tail}]]>"), format!("&#{};{}", u32::from(first), &png[1..]).replace('\n', "
")]
|
||||
{
|
||||
assert_eq!(media(&other).unwrap(), plain, "{other}");
|
||||
}
|
||||
assert!(media(&format!("&{png}")).is_err());
|
||||
}
|
||||
|
||||
/// Work anywhere in a Flat OPC file is bounded, not only in the parts that are kept: nesting
|
||||
/// and elements no part reader looks at, and repeated part names, count too (#1353).
|
||||
#[test]
|
||||
fn flat_opc_limits_count_what_is_not_kept() {
|
||||
let png = tiny_png_b64();
|
||||
let limited = |extra: &str| matches!(read_xml(picture_package(&png, extra).as_bytes()), Err(DocxError::Limit(_)));
|
||||
assert!(read_xml(picture_package(&png, "<x/>").as_bytes()).is_ok());
|
||||
// Deep nesting outside the parts.
|
||||
assert!(limited(&format!("<x>{}{}</x>", "<y>".repeat(1000), "</y>".repeat(1000))));
|
||||
// One part name over and over, or other elements, past the part count.
|
||||
assert!(limited(&r#"<pkg:part pkg:name="/word/media/dot.png"><pkg:binaryData>AA==</pkg:binaryData></pkg:part>"#.repeat(20_000)));
|
||||
assert!(limited(&"<x/>".repeat(20_000)));
|
||||
// A part nothing reads, one element over what the XML tree reader takes in a part (8 000 000).
|
||||
assert!(limited(&format!(r#"<pkg:part pkg:name="/word/unused.xml"><pkg:xmlData><r>{}</r></pkg:xmlData></pkg:part>"#, "<y/>".repeat(8_000_000))));
|
||||
}
|
||||
|
||||
@@ -32,5 +32,10 @@ zeroize = { workspace = true }
|
||||
# The browser clock for `now_iso` (`SystemTime::now()` panics on wasm32).
|
||||
js-sys = "0.3"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
getrandom = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
encoding_rs = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
|
||||
@@ -265,6 +265,8 @@ Mailings|Create|Labels|mailings.labels
|
||||
Mailings|Start Mail Merge|Start Mail Merge|mailings.start
|
||||
Mailings|Start Mail Merge|Select Recipients|mailings.recipients
|
||||
Mailings|Start Mail Merge|Edit Recipient List|mailings.editRecipients
|
||||
Mailings|Start Mail Merge|Filter Recipients|mailings.filterRecipients
|
||||
Mailings|Start Mail Merge|Sort Recipients|mailings.sortRecipients
|
||||
Mailings|Write & Insert Fields|Highlight Merge Fields|mailings.highlightFields
|
||||
Mailings|Write & Insert Fields|Address Block|mailings.addressBlock
|
||||
Mailings|Write & Insert Fields|Greeting Line|mailings.greetingLine
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user