mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-17 11:22:56 -06:00
Compare commits
145
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
587845cee3 | ||
|
|
8b212e6665 | ||
|
|
26b3ae2cc2 | ||
|
|
e784a2aaed | ||
|
|
65212d6856 | ||
|
|
5c8a6e1d75 | ||
|
|
83f18db12d | ||
|
|
1a56d041de | ||
|
|
880cda902f | ||
|
|
24885e830c | ||
|
|
40fd69b6d8 | ||
|
|
b7b528fbcf | ||
|
|
c7e84ae43d | ||
|
|
c7c7421acf | ||
|
|
bbfacd8f62 | ||
|
|
4029e29905 | ||
|
|
328e3738a0 | ||
|
|
0b99c871e9 | ||
|
|
c99dd5cc6e | ||
|
|
53e05c2420 | ||
|
|
8fced5d045 | ||
|
|
de694152a9 | ||
|
|
a216825578 | ||
|
|
ebe2f430d8 | ||
|
|
8fa2895202 | ||
|
|
d7215f4441 | ||
|
|
be7624eb96 | ||
|
|
aeb9704d82 | ||
|
|
221faf2901 | ||
|
|
a5753be57e | ||
|
|
caa4c4b114 | ||
|
|
ca075db458 | ||
|
|
4e2a5c2b8f | ||
|
|
54e82f7131 | ||
|
|
224bfdb2a0 | ||
|
|
abc04c1b41 | ||
|
|
29d862fabc | ||
|
|
406befeaa2 | ||
|
|
93bf14883c | ||
|
|
0cb315edaf | ||
|
|
2dd0f9a67b | ||
|
|
739cdcad0b | ||
|
|
b3f31666d3 | ||
|
|
68f758928e | ||
|
|
840efd03fb | ||
|
|
8e8ab631fd | ||
|
|
8a9d04eeb1 | ||
|
|
266407e840 | ||
|
|
c817cc95c6 | ||
|
|
ff0823f40d | ||
|
|
211f62231d | ||
|
|
9144b9bfda | ||
|
|
a61cef5d45 | ||
|
|
739491f5c7 | ||
|
|
8377ea8e8f | ||
|
|
4357166531 | ||
|
|
5d871d0519 | ||
|
|
ae2d2b43d6 | ||
|
|
cd23034f65 | ||
|
|
b2306fe5ef | ||
|
|
646fbc7cd5 | ||
|
|
4a347e070a | ||
|
|
3bf4c05461 | ||
|
|
7b26a94193 | ||
|
|
ace000b4a4 | ||
|
|
7adbdc574c | ||
|
|
f77eef9cb6 | ||
|
|
a2f41d728e | ||
|
|
9fe9bd5042 | ||
|
|
83c3b5890b | ||
|
|
f472620ac0 | ||
|
|
5467f998a0 | ||
|
|
78dfa8f648 | ||
|
|
82f0c467be | ||
|
|
837a610133 | ||
|
|
de977bcde6 | ||
|
|
4ba0595760 | ||
|
|
6854bd1fb3 | ||
|
|
4356771236 | ||
|
|
cdf146cabd | ||
|
|
54e3e1cf34 | ||
|
|
97c13a2990 | ||
|
|
fe8a8a838c | ||
|
|
2bd6f372c5 | ||
|
|
8a1f101c46 | ||
|
|
42f8559b97 | ||
|
|
bf8b37759c | ||
|
|
1ed889c24c | ||
|
|
6a7af0d679 | ||
|
|
ce6e4094d5 | ||
|
|
9088ed777d | ||
|
|
cc90520b9d | ||
|
|
a95b065c2b | ||
|
|
84026f98b2 | ||
|
|
5f228a0e24 | ||
|
|
b354e0f870 | ||
|
|
86352d5cf3 | ||
|
|
3e776e4c7d | ||
|
|
a9a1aa36a2 | ||
|
|
bc0e51ee4d | ||
|
|
ed66198574 | ||
|
|
d53a740be1 | ||
|
|
e9750c5cb7 | ||
|
|
3d5a153e3d | ||
|
|
7bff3b53e9 | ||
|
|
0909b15eae | ||
|
|
52d17a91df | ||
|
|
323cf78232 | ||
|
|
e6e8c61dbf | ||
|
|
42a5df5f94 | ||
|
|
1d150004f7 | ||
|
|
0aefd4d025 | ||
|
|
235a38c665 | ||
|
|
3bf7a5dbbe | ||
|
|
e40199bf6f | ||
|
|
e2f94ecef9 | ||
|
|
7ccfd4caef | ||
|
|
7b3b6f8041 | ||
|
|
f8c66d0692 | ||
|
|
fecb717f99 | ||
|
|
aba890e8a6 | ||
|
|
0cc92c9744 | ||
|
|
b02baeba43 | ||
|
|
3c77297b83 | ||
|
|
60415e055c | ||
|
|
0db15a1d5e | ||
|
|
33afe69094 | ||
|
|
669d5df0b1 | ||
|
|
d1a36fd0c6 | ||
|
|
beae4b82fa | ||
|
|
514085ca44 | ||
|
|
953f43baed | ||
|
|
acf5eb8727 | ||
|
|
bd188c19d8 | ||
|
|
56a28f33b7 | ||
|
|
cd4ab71552 | ||
|
|
6272c9a4da | ||
|
|
172e56f12e | ||
|
|
b66122f718 | ||
|
|
4e1b6a71ab | ||
|
|
b2ec73926f | ||
|
|
7f90fd0bf1 | ||
|
|
4388fba5b2 | ||
|
|
c341669dbd | ||
|
|
a4d28e2586 |
+5
-1
@@ -1 +1,5 @@
|
||||
craft-i18n.rev text eol=lf
|
||||
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
|
||||
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
|
||||
* text=auto
|
||||
|
||||
craft-i18n.rev text eol=lf
|
||||
@@ -18,4 +18,7 @@ jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets: inherit
|
||||
|
||||
@@ -138,3 +138,7 @@ Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/targe
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
|
||||
|
||||
## Shared-library reuse
|
||||
|
||||
Before implementing file formats, codecs, protocols or reusable UI components, check [storytold/craft-libs](https://github.com/storytold/craft-libs) and relevant open PRs; reuse or extend shared APIs instead of duplicating app-local implementations. Keep app-specific policy and adapters local, preserve behavior and format fidelity, security and resource limits, repository layering and regression tests, and document any shared-API gap rather than silently reducing functionality.
|
||||
|
||||
Generated
+458
-116
File diff suppressed because it is too large
Load Diff
+33
-18
@@ -24,19 +24,19 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# Proofing is craft-libs' craft-proof (it was crates/proof); its Language data is craft-i18n's
|
||||
# language-data/, embedded from CRAFT_I18N_DIR (craft-i18n.rev). The package keeps the
|
||||
# `wordcraft-proof` name here so `wordcraft_proof::` paths are unchanged.
|
||||
# craft-proof is storytold/craft-libs main at the merge of #590 (ca-ES-valencia reads the ca-valencia
|
||||
# pack), after #589 (French elision suggestions first) and #497 (flag-based compounding), which also
|
||||
# has #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font store's
|
||||
# `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "01315d9c92b5b0e69082d35ca56099461a1efd45", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" }
|
||||
# craft-proof is storytold/craft-libs main at 453b0da782. That commit has #590 (ca-ES-valencia
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-metafile = { path = "crates/metafile" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -66,16 +66,29 @@ wuff = "0.2.9"
|
||||
# `forbid(unsafe_code)` in its default build, no_std-capable (builds for wasm), BSD-3-Clause/MIT.
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "bmp", "tiff"] }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "75c70fa6a786240eb853e6267e25fc445f510cd0", version = "=0.1.0" }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -110,6 +123,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
@@ -138,7 +153,7 @@ 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 = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -124,7 +124,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
|
||||
| **References** | Table of contents, footnotes and endnotes, citations and bibliography (APA, MLA, Chicago, IEEE), captions, table of figures, cross-references, index, table of authorities |
|
||||
| **Review** | Spelling and grammar with suggestions (English and Polish, by each run's language), thesaurus, word count, comments in margin balloons or a pane, track changes, accept/reject, compare documents, restrict editing, accessibility checker, document inspector |
|
||||
| **Mailings** | Mail merge from CSV, merge fields, address block, greeting line, rules, preview, finish to a document; envelopes and labels |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) or Slovenščina (follows the system language by default) |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) Slovenščina or Bosanski (follows the system language by default) |
|
||||
| **Files** | .docx read/write, legacy 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
|
||||
|
||||
The honest picture, area by area, is in [ROADMAP.md](ROADMAP.md), the
|
||||
@@ -451,8 +451,10 @@ Copyright (c) 2026 ArtCraft Team and the WordCraft contributors. Required notice
|
||||
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
|
||||
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
The English spelling dictionary and hyphenation come from Grady Ward's public-domain Moby
|
||||
Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
|
||||
English spelling first tries a matching Hunspell dictionary from the Dictionaries folder.
|
||||
Otherwise it uses dialect-specific SCOWL 2026 dictionaries when built with language data;
|
||||
without it, spelling falls back to system Hunspell dictionaries or Grady Ward's public-domain
|
||||
Moby Hyphenator II word list. English hyphenation uses the Moby list and patterns trained from it. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
|
||||
do Russian, Portuguese, Czech, Italian, Croatian and Turkish spelling (how to install them:
|
||||
[docs/spelling-dictionaries.md](docs/spelling-dictionaries.md)), and
|
||||
Polish hyphenation the TeX patterns by Hanna Kołodziejska, Bogusław Jackowski and Marek Ryćko (MIT
|
||||
|
||||
+18
-3
File diff suppressed because one or more lines are too long
@@ -24,5 +24,6 @@ sys-locale = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
|
||||
@@ -35,10 +35,11 @@ USAGE:
|
||||
--strict writes nothing and exits 3 if a character on the
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] --cmd 'id={json}' [--cmd …]
|
||||
[--save OUT] [--print] [--author NAME]
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
|
||||
@@ -265,7 +266,7 @@ fn parse_scale_arg(command: &str, args: &[String]) -> Result<Option<f64>, String
|
||||
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"));
|
||||
return Err(format!("{command}: invalid --scale `{val}`: scale must be a finite positive number"));
|
||||
}
|
||||
Ok(Some(scale))
|
||||
}
|
||||
@@ -602,6 +603,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
write_stdout(|o| writeln!(o, "{r}"))
|
||||
}
|
||||
"run" => {
|
||||
for (i, arg) in rest.iter().enumerate() {
|
||||
if arg == "--cmd" && rest.get(i + 1).is_none_or(|value| value.starts_with("--")) {
|
||||
return Err("--cmd needs a value".into());
|
||||
}
|
||||
}
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
@@ -635,7 +641,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
let mut i = 0;
|
||||
while i < rest.len() {
|
||||
if rest.get(i).map(String::as_str) == Some("--cmd") {
|
||||
let spec = rest.get(i + 1).ok_or("--cmd needs a value")?;
|
||||
let spec = rest.get(i + 1).filter(|value| !value.starts_with("--")).ok_or("--cmd needs a value")?;
|
||||
let (id, params) = match spec.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
(id.to_string(), serde_json::from_str::<Value>(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?)
|
||||
|
||||
@@ -267,19 +267,19 @@ fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
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())
|
||||
Err("render: invalid --scale `0`: scale must be a finite 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())
|
||||
Err("render: invalid --scale `-2`: scale must be a finite 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())
|
||||
Err("render: invalid --scale `NaN`: scale must be a finite 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())
|
||||
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
@@ -322,19 +322,19 @@ fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a positive number".into())
|
||||
Err("run: invalid --scale `0`: scale must be a finite 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())
|
||||
Err("run: invalid --scale `-1`: scale must be a finite 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())
|
||||
Err("run: invalid --scale `NaN`: scale must be a finite 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())
|
||||
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
@@ -497,6 +497,27 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
@@ -64,11 +63,11 @@ fn uncovered() -> char {
|
||||
}
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 90, 200, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn pic(rid: &str) -> String {
|
||||
@@ -106,7 +105,7 @@ fn package(document: &str, document_rels: &str, extra: &[(&str, &[u8])]) -> Vec<
|
||||
r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{REL}/officeDocument" Target="word/document.xml"/></Relationships>"#
|
||||
);
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/octet-stream"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
let mut parts: Vec<(&str, &[u8])> = vec![
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", rels.as_bytes()),
|
||||
@@ -115,10 +114,9 @@ fn package(document: &str, document_rels: &str, extra: &[(&str, &[u8])]) -> Vec<
|
||||
];
|
||||
parts.extend_from_slice(extra);
|
||||
for (name, bytes) in parts {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -372,7 +370,7 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains("\\u{1b}") || text.contains("\\u{1b}[2J"), "{text}");
|
||||
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
|
||||
assert!(!out.exists());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
|
||||
@@ -18,8 +18,8 @@ wordcraft-engine = { workspace = true }
|
||||
wordcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.wordcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -84,9 +84,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfi
|
||||
clipboard-win = { version = "5.4", features = ["std"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Pinned apart from craft-ui, which doesn't depend on it: `printer_queues`, the printer list that
|
||||
# At the same craft-libs commit as the workspace's crates: `printer_queues`, the printer list that
|
||||
# asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622).
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a3e0b5a9440d18f19422a9dca13516747b7d3181" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
rfd = { workspace = true }
|
||||
# Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94);
|
||||
# rfd itself already depends on it.
|
||||
|
||||
@@ -369,8 +369,11 @@ mod tests {
|
||||
|
||||
impl Conn {
|
||||
fn open(port: u16) -> Self {
|
||||
Self::open_within(port, Duration::from_secs(5))
|
||||
}
|
||||
fn open_within(port: u16, read_timeout: Duration) -> Self {
|
||||
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
s.set_read_timeout(Some(read_timeout)).unwrap();
|
||||
Self(BufReader::new(s.try_clone().unwrap()), s)
|
||||
}
|
||||
fn send(&mut self, line: &str) {
|
||||
@@ -388,7 +391,24 @@ mod tests {
|
||||
/// The server closed the connection.
|
||||
fn closed(&mut self) -> bool {
|
||||
let mut r = String::new();
|
||||
matches!(self.0.read_line(&mut r), Ok(0))
|
||||
closed_by_peer(self.0.read_line(&mut r))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
|
||||
/// which is how Windows can deliver a close when the writer had nothing to read back (the
|
||||
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
|
||||
/// not UTF-8, leaves the connection open.
|
||||
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
|
||||
match read {
|
||||
Ok(n) => n == 0,
|
||||
Err(e) => matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::ConnectionAborted
|
||||
| std::io::ErrorKind::NotConnected
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,13 +493,29 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closure_errors_mean_the_peer_closed() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert!(closed_by_peer(Ok(0)), "end of stream");
|
||||
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
|
||||
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
|
||||
}
|
||||
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
|
||||
// Not UTF-8, a timeout or a would-block leave the socket open.
|
||||
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
|
||||
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_connection_is_closed() {
|
||||
let (port, rx) = boot_with(Duration::from_millis(300));
|
||||
let mut quiet = Conn::open(port);
|
||||
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
|
||||
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
|
||||
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
|
||||
let t0 = Instant::now();
|
||||
assert!(quiet.closed());
|
||||
assert!(t0.elapsed() < Duration::from_secs(3));
|
||||
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
|
||||
// After an authorised request the connection may stay idle.
|
||||
let mut busy = Conn::open(port);
|
||||
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Linux: draw on the GPU that drives the screen.
|
||||
//!
|
||||
//! egui-wgpu picks the discrete GPU by default (`PowerPreference::HighPerformance`). On a laptop
|
||||
//! whose integrated GPU drives the panel, every frame drawn on the discrete one is copied across
|
||||
//! to it, and the discrete GPU leaves its idle state whenever the window redraws: on an Intel HD
|
||||
//! 530 + NVIDIA Quadro M4000M laptop, from 7 W at P8 to over 20 W at P0/P1. Forcing the integrated
|
||||
//! GPU instead breaks desktops whose screen is on the discrete card (storytold/pdfcraft#96), and a
|
||||
//! desktop with a monitor on each card needs the discrete one (storytold/pdfcraft#445). So the
|
||||
//! choice follows the connected displays, as in craft-anything (storytold/craft-anything#571):
|
||||
//!
|
||||
//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`,
|
||||
//! `none`), when set, decide;
|
||||
//! 2. a connected built-in panel: the GPU behind it;
|
||||
//! 3. displays on only one GPU: that GPU;
|
||||
//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as before.
|
||||
|
||||
mod drm;
|
||||
|
||||
use drm::DisplayCard;
|
||||
use eframe::wgpu::{DeviceType, PowerPreference};
|
||||
|
||||
/// What we know of one adapter wgpu offers.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Candidate {
|
||||
pub name: String,
|
||||
pub vendor: u32,
|
||||
pub device: u32,
|
||||
/// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL).
|
||||
pub pci_slot: String,
|
||||
pub device_type: DeviceType,
|
||||
pub gl: bool,
|
||||
}
|
||||
|
||||
/// What the person asked for through wgpu's environment variables.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Asked {
|
||||
pub adapter_name: Option<String>,
|
||||
pub power: Option<PowerPreference>,
|
||||
}
|
||||
|
||||
/// Why an adapter was chosen, for the log.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Why {
|
||||
AskedByName,
|
||||
AskedPower,
|
||||
BuiltInPanel,
|
||||
OnlyGpuWithDisplays,
|
||||
Fallback,
|
||||
}
|
||||
|
||||
/// The index of the adapter to draw with, and why; `None` when there is none.
|
||||
pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> {
|
||||
if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) {
|
||||
// As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice.
|
||||
if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) {
|
||||
return Some((i, Why::AskedByName));
|
||||
}
|
||||
log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name");
|
||||
}
|
||||
if let Some(power) = asked.power {
|
||||
return by_kind(candidates, power).map(|i| (i, Why::AskedPower));
|
||||
}
|
||||
let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect();
|
||||
let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect();
|
||||
let target = if !panels.is_empty() {
|
||||
Some((panels, Why::BuiltInPanel))
|
||||
} else if with_displays.len() == 1 {
|
||||
Some((with_displays, Why::OnlyGpuWithDisplays))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((wanted, why)) = target {
|
||||
// Vulkan before GL for the same card; otherwise wgpu's order.
|
||||
let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl);
|
||||
if let Some((i, _)) = found {
|
||||
return Some((i, why));
|
||||
}
|
||||
}
|
||||
by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback))
|
||||
}
|
||||
|
||||
/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by
|
||||
/// PCI ids, which count only when no other card has the same ids (two cards of one model); GL
|
||||
/// gives only a vendor, which counts only when no other card has that vendor.
|
||||
fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool {
|
||||
if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() {
|
||||
return adapter.pci_slot == card.pci_slot;
|
||||
}
|
||||
if adapter.device != 0 {
|
||||
return adapter.vendor == card.vendor
|
||||
&& adapter.device == card.device
|
||||
&& all.iter().filter(|c| c.vendor == card.vendor && c.device == card.device).count() == 1;
|
||||
}
|
||||
adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1
|
||||
}
|
||||
|
||||
/// The first adapter in wgpu's own order for that power preference.
|
||||
fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
|
||||
let rank = |t: DeviceType| match (power, t) {
|
||||
(PowerPreference::None, _) => 0,
|
||||
(PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1,
|
||||
(_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2,
|
||||
(_, DeviceType::Other) => 3,
|
||||
(_, DeviceType::VirtualGpu) => 4,
|
||||
(_, DeviceType::Cpu) => 5,
|
||||
};
|
||||
candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Candidate {
|
||||
fn of(info: &eframe::wgpu::AdapterInfo) -> Self {
|
||||
Candidate {
|
||||
name: info.name.clone(),
|
||||
vendor: info.vendor,
|
||||
device: info.device,
|
||||
pci_slot: info.device_pci_bus_id.to_ascii_lowercase(),
|
||||
device_type: info.device_type,
|
||||
gl: info.backend == eframe::wgpu::Backend::Gl,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Asked {
|
||||
fn from_env() -> Self {
|
||||
Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The adapter that draws the window, among those that can draw to it.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result<eframe::wgpu::Adapter, String> {
|
||||
let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
|
||||
let candidates: Vec<Candidate> = usable.iter().map(|a| Candidate::of(&a.get_info())).collect();
|
||||
let cards = drm::display_cards();
|
||||
let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why)));
|
||||
match picked {
|
||||
Some((a, why)) => {
|
||||
log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info());
|
||||
Ok(a.clone())
|
||||
}
|
||||
None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0");
|
||||
const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0");
|
||||
const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0");
|
||||
|
||||
fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate {
|
||||
Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false }
|
||||
}
|
||||
|
||||
fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate {
|
||||
Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true }
|
||||
}
|
||||
|
||||
fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard {
|
||||
DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel }
|
||||
}
|
||||
|
||||
/// What wgpu offers on a laptop whose AMD iGPU drives the panel, in its order (Vulkan, then GL).
|
||||
fn laptop_adapters() -> Vec<Candidate> {
|
||||
vec![
|
||||
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
|
||||
vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu),
|
||||
gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu),
|
||||
]
|
||||
}
|
||||
|
||||
/// The iGPU drives the panel; egui-wgpu's default drew on the discrete GPU.
|
||||
#[test]
|
||||
fn a_laptop_draws_on_the_gpu_behind_its_panel() {
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
|
||||
// The same with the discrete GPU listed first.
|
||||
let mut swapped = laptop_adapters();
|
||||
swapped.swap(0, 1);
|
||||
assert_eq!(choose(&swapped, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// The panel's GPU stays the choice with an external monitor on the discrete card as well.
|
||||
#[test]
|
||||
fn the_panel_wins_over_a_monitor_on_the_other_card() {
|
||||
let cards = [card(NVIDIA, 1, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// A desktop with its monitor on the discrete card and the iGPU left on (a low-power default
|
||||
/// draws on the iGPU there, and the window can't start: the case the panel rule must not break).
|
||||
#[test]
|
||||
fn a_desktop_draws_on_the_only_card_with_a_monitor() {
|
||||
let adapters =
|
||||
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
|
||||
let cards = [card(INTEL, 0, false), card(NVIDIA, 1, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
// And on the iGPU when that's where the only monitor is.
|
||||
let cards = [card(INTEL, 2, false), card(NVIDIA, 0, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((0, Why::OnlyGpuWithDisplays)));
|
||||
}
|
||||
|
||||
/// A desktop with a monitor on each card: the discrete GPU, as before (an iGPU choice there
|
||||
/// lost its surface as soon as it was set up).
|
||||
#[test]
|
||||
fn monitors_on_two_cards_keep_the_discrete_gpu() {
|
||||
let adapters =
|
||||
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
|
||||
let cards = [card(INTEL, 1, false), card(NVIDIA, 1, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// Nothing readable (no `/sys`, or a card the drivers don't name): the discrete GPU, as before.
|
||||
#[test]
|
||||
fn without_display_facts_the_old_choice_stands() {
|
||||
assert_eq!(choose(&laptop_adapters(), &[], &Asked::default()), Some((1, Why::Fallback)));
|
||||
let unknown = [card((0x1234, 0x1, "0000:09:00.0"), 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &unknown, &Asked::default()), Some((1, Why::Fallback)));
|
||||
assert_eq!(choose(&[], &[card(AMD, 1, true)], &Asked::default()), None);
|
||||
}
|
||||
|
||||
/// The environment variables still decide: prime-run style requests reach the NVIDIA card.
|
||||
#[test]
|
||||
fn wgpu_environment_variables_decide_when_set() {
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
let asked = |name: Option<&str>, power: Option<PowerPreference>| Asked { adapter_name: name.map(Into::into), power };
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))), Some((2, Why::AskedByName)));
|
||||
// A name nothing has: the usual choice, not a failure.
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some(""), None)), Some((0, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// Under `WGPU_BACKEND=gl` there's no PCI address or device id: the vendor alone finds the
|
||||
/// card, but only when no other card shares it.
|
||||
#[test]
|
||||
fn gl_adapters_are_matched_by_vendor_only_when_unambiguous() {
|
||||
let adapters =
|
||||
[gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)];
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
// Two AMD cards: the vendor can't tell them apart, so the old choice stands.
|
||||
let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)];
|
||||
let adapters = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)];
|
||||
assert_eq!(choose(&adapters, &two_amd, &Asked::default()), Some((1, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// Two adapters for the panel's card (Vulkan and GL): Vulkan, whatever the order.
|
||||
#[test]
|
||||
fn vulkan_comes_before_gl_for_the_same_card() {
|
||||
let adapters = [
|
||||
gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu),
|
||||
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
|
||||
];
|
||||
assert_eq!(choose(&adapters, &[card(AMD, 1, true)], &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// A laptop with the lid closed and a monitor on the NVIDIA card: the switched-off panel isn't
|
||||
/// read as one (`drm` skips it), so the card with the monitor draws.
|
||||
#[test]
|
||||
fn a_closed_laptop_draws_on_the_card_with_the_monitor() {
|
||||
let cards = [card(NVIDIA, 1, false), card(AMD, 0, false)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
}
|
||||
|
||||
/// Two cards of one model have the same PCI ids: only the PCI address tells them apart. Without
|
||||
/// one from the driver the display rule gives way to the old choice instead of guessing.
|
||||
#[test]
|
||||
fn identical_cards_are_told_apart_only_by_pci_address() {
|
||||
const SECOND: (u32, u32, &str) = (0x10de, 0x25a2, "0000:02:00.0");
|
||||
let cards = [card(NVIDIA, 0, false), card(SECOND, 1, false)];
|
||||
let with_slots = [vulkan("NVIDIA A", NVIDIA, DeviceType::DiscreteGpu), vulkan("NVIDIA B", SECOND, DeviceType::DiscreteGpu)];
|
||||
assert_eq!(choose(&with_slots, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
let without: Vec<Candidate> = with_slots.iter().cloned().map(|c| Candidate { pci_slot: String::new(), ..c }).collect();
|
||||
assert_eq!(choose(&without, &cards, &Asked::default()), Some((0, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// The laptop this was measured on: Intel HD 530 behind the panel (`card2-eDP-1`), a Quadro
|
||||
/// M4000M with nothing connected, and the Quadro offered first by wgpu.
|
||||
#[test]
|
||||
fn an_intel_and_nvidia_laptop_draws_on_intel() {
|
||||
const HD530: (u32, u32, &str) = (0x8086, 0x191b, "0000:00:02.0");
|
||||
const M4000M: (u32, u32, &str) = (0x10de, 0x13f9, "0000:01:00.0");
|
||||
let adapters = [
|
||||
vulkan("Quadro M4000M", M4000M, DeviceType::DiscreteGpu),
|
||||
vulkan("Intel(R) HD Graphics 530 (SKL GT2)", HD530, DeviceType::IntegratedGpu),
|
||||
];
|
||||
let cards = [card(M4000M, 0, false), card(HD530, 1, true)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`).
|
||||
//!
|
||||
//! A window drawn on one card and shown on a screen attached to another is copied across on every
|
||||
//! frame, so the app draws on the card that drives the screen (see the parent module).
|
||||
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
/// A graphics card and the displays connected to it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct DisplayCard {
|
||||
/// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel.
|
||||
pub vendor: u32,
|
||||
/// PCI device id.
|
||||
pub device: u32,
|
||||
/// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one.
|
||||
pub pci_slot: String,
|
||||
/// Connected displays that are switched on, of any kind, built-in panel included.
|
||||
pub displays: u32,
|
||||
/// A connected, switched-on built-in panel (eDP, LVDS or DSI): this card drives a laptop's
|
||||
/// own screen.
|
||||
pub built_in_panel: bool,
|
||||
}
|
||||
|
||||
/// Connector kinds that are a computer's own screen rather than a monitor plugged into it.
|
||||
const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"];
|
||||
|
||||
/// At most this many entries are read from the DRM folder.
|
||||
const MAX_ENTRIES: usize = 512;
|
||||
|
||||
/// At most this many bytes are read from one sysfs file.
|
||||
const MAX_FILE: u64 = 4096;
|
||||
|
||||
/// The graphics cards on this computer and what's connected to them. Empty where the system
|
||||
/// doesn't say (a sandbox without `/sys`).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn display_cards() -> Vec<DisplayCard> {
|
||||
display_cards_in(Path::new("/sys/class/drm"))
|
||||
}
|
||||
|
||||
/// [`display_cards`] read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per
|
||||
/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN-<kind>-<n>` entry per
|
||||
/// connector, with `connected` or `disconnected` in its `status` and, where the kernel gives it,
|
||||
/// `enabled` or `disabled` in its `enabled`. Cards without PCI ids (a firmware framebuffer) are
|
||||
/// left out.
|
||||
pub(crate) fn display_cards_in(drm: &Path) -> Vec<DisplayCard> {
|
||||
let Ok(entries) = std::fs::read_dir(drm) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut names: Vec<String> = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
|
||||
names.sort();
|
||||
let cards = names.iter().filter(|n| is_card(n));
|
||||
cards
|
||||
.filter_map(|card| {
|
||||
let uevent = read_small(&drm.join(card).join("device").join("uevent"))?;
|
||||
let (vendor, device) = pci_ids(&uevent)?;
|
||||
let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase();
|
||||
let prefix = format!("{card}-");
|
||||
let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false };
|
||||
for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) {
|
||||
let dir = drm.join(format!("{prefix}{connector}"));
|
||||
let status = read_small(&dir.join("status")).unwrap_or_default();
|
||||
// A panel can be connected but switched off (a closed lid with a monitor in use):
|
||||
// `enabled` then reads `disabled`, and it drives nothing. No `enabled`: as before.
|
||||
let enabled = read_small(&dir.join("enabled")).unwrap_or_default();
|
||||
if status.trim() != "connected" || enabled.trim() == "disabled" {
|
||||
continue;
|
||||
}
|
||||
out.displays = out.displays.saturating_add(1);
|
||||
if BUILT_IN_PANELS.contains(&connector_kind(connector)) {
|
||||
out.built_in_panel = true;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node.
|
||||
fn is_card(name: &str) -> bool {
|
||||
name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number.
|
||||
fn connector_kind(connector: &str) -> &str {
|
||||
match connector.rsplit_once('-') {
|
||||
Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind,
|
||||
_ => connector,
|
||||
}
|
||||
}
|
||||
|
||||
/// `PCI_ID=1002:1638` → (0x1002, 0x1638).
|
||||
fn pci_ids(uevent: &str) -> Option<(u32, u32)> {
|
||||
let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?;
|
||||
Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?))
|
||||
}
|
||||
|
||||
fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
|
||||
uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim)
|
||||
}
|
||||
|
||||
fn read_small(path: &Path) -> Option<String> {
|
||||
let mut text = String::new();
|
||||
std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?;
|
||||
Some(text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// A folder of its own under the system's temporary folder, removed when dropped.
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-drm-test-{}-{n}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
TempDir(dir)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as
|
||||
/// (name, status).
|
||||
fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
for (card, id, slot) in cards {
|
||||
let device = dir.path().join(card).join("device");
|
||||
fs::create_dir_all(&device).expect("card folder");
|
||||
fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).expect("uevent");
|
||||
}
|
||||
for (connector, status) in connectors {
|
||||
let c = dir.path().join(connector);
|
||||
fs::create_dir_all(&c).expect("connector folder");
|
||||
fs::write(c.join("status"), format!("{status}\n")).expect("status");
|
||||
}
|
||||
fs::create_dir_all(dir.path().join("renderD128")).expect("render node");
|
||||
fs::write(dir.path().join("version"), "drm 1.1.0\n").expect("version");
|
||||
dir
|
||||
}
|
||||
|
||||
/// A laptop whose AMD iGPU drives the panel, with an NVIDIA card that has no outputs.
|
||||
#[test]
|
||||
fn a_laptop_panel_is_found_on_the_integrated_gpu() {
|
||||
let d = drm(
|
||||
&[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
|
||||
&[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")],
|
||||
);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(
|
||||
cards,
|
||||
vec![
|
||||
DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false },
|
||||
DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A desktop with a monitor on each card: displays on both, no built-in panel.
|
||||
#[test]
|
||||
fn monitors_on_two_cards_are_counted_on_each() {
|
||||
let d = drm(
|
||||
&[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")],
|
||||
&[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")],
|
||||
);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(1, false), (2, false)]);
|
||||
}
|
||||
|
||||
/// `card10` is a different card from `card1`, and its connectors aren't `card1`'s.
|
||||
#[test]
|
||||
fn card_numbers_are_not_prefixes_of_each_other() {
|
||||
let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.vendor, c.displays)).collect::<Vec<_>>(), vec![(0x1002, 0), (0x10de, 1)]);
|
||||
}
|
||||
|
||||
/// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number.
|
||||
#[test]
|
||||
fn built_in_panels_are_told_from_monitors_by_connector_kind() {
|
||||
assert_eq!(connector_kind("eDP-1"), "eDP");
|
||||
assert_eq!(connector_kind("HDMI-A-1"), "HDMI-A");
|
||||
assert_eq!(connector_kind("DSI-12"), "DSI");
|
||||
assert_eq!(connector_kind("Virtual"), "Virtual");
|
||||
let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]);
|
||||
assert!(display_cards_in(d.path()).iter().all(|c| c.built_in_panel));
|
||||
}
|
||||
|
||||
/// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped, never a panic.
|
||||
#[test]
|
||||
fn what_cant_be_read_is_left_out() {
|
||||
let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]);
|
||||
fs::create_dir_all(d.path().join("card2")).expect("card without device");
|
||||
fs::create_dir_all(d.path().join("card")).expect("bare name");
|
||||
assert!(display_cards_in(d.path()).is_empty());
|
||||
assert!(display_cards_in(&d.path().join("missing")).is_empty());
|
||||
assert_eq!(pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2)));
|
||||
assert_eq!(pci_ids("PCI_IDX=10de:25a2"), None);
|
||||
}
|
||||
|
||||
/// A status of `unknown` (some virtual outputs) isn't a connected display.
|
||||
#[test]
|
||||
fn only_connected_counts() {
|
||||
let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]);
|
||||
assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0));
|
||||
}
|
||||
|
||||
/// A laptop with its lid closed and a monitor on the discrete card: the panel still reads
|
||||
/// `connected` but is switched off, so it neither counts nor marks its card as the panel's.
|
||||
#[test]
|
||||
fn a_switched_off_panel_does_not_count() {
|
||||
let d = drm(
|
||||
&[("card0", "10de:25a2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
|
||||
&[("card0-HDMI-A-1", "connected"), ("card1-eDP-1", "connected")],
|
||||
);
|
||||
fs::write(d.path().join("card0-HDMI-A-1").join("enabled"), "enabled\n").expect("enabled");
|
||||
fs::write(d.path().join("card1-eDP-1").join("enabled"), "disabled\n").expect("enabled");
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.vendor, c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(0x10de, 1, false), (0x1002, 0, false)]);
|
||||
}
|
||||
}
|
||||
+173
-16
@@ -20,9 +20,12 @@ mod default_apps;
|
||||
mod file_dialogs;
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", test))]
|
||||
mod graphics;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux_gpu;
|
||||
mod logging;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod portal_save;
|
||||
mod prefs_merge;
|
||||
mod print;
|
||||
mod region;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -222,31 +225,44 @@ fn user_dict_path() -> Option<std::path::PathBuf> {
|
||||
wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE))
|
||||
}
|
||||
|
||||
fn load_user_dictionary(app: &mut WordApp) {
|
||||
if !prefs_enabled() {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = user_dict_path() {
|
||||
wordcraft_proof::load_user_dictionary(&p);
|
||||
app.session.user_dict_path = Some(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them.
|
||||
fn prefs_enabled() -> bool {
|
||||
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
}
|
||||
|
||||
/// The preferences as this process last loaded or saved them, which `save_prefs` compares with
|
||||
/// to write only what this process changed since (#3773, see `prefs_merge`).
|
||||
static LOADED_PREFS: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// Apply the saved preferences (`ui.json`) and the user dictionary to `app`, and remember the
|
||||
/// result for `save_prefs`. Runs without preferences neither read nor keep them.
|
||||
fn load_prefs(app: &mut WordApp) {
|
||||
if !prefs_enabled() {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = prefs_path()
|
||||
&& let Ok(bytes) = std::fs::read(&p)
|
||||
let loaded = load_prefs_from(app, prefs_path().as_deref(), user_dict_path());
|
||||
if let Ok(mut slot) = LOADED_PREFS.lock() {
|
||||
*slot = loaded;
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the preferences saved at `prefs` to `app`, then load the user dictionary at `dict`
|
||||
/// (`custom-dictionary.txt`, #40), and give back the preferences as `prefs()` does after both:
|
||||
/// the words only the dictionary file has are part of what was loaded, so a word another process
|
||||
/// removes from `ui.json` isn't written back as one added here (#3773).
|
||||
fn load_prefs_from(app: &mut WordApp, prefs: Option<&std::path::Path>, dict: Option<std::path::PathBuf>) -> Option<serde_json::Value> {
|
||||
if let Some(p) = prefs
|
||||
&& let Ok(bytes) = std::fs::read(p)
|
||||
&& let Some(ui) = UiState::from_json(&bytes)
|
||||
{
|
||||
app.apply_prefs(ui);
|
||||
}
|
||||
if let Some(p) = dict {
|
||||
wordcraft_proof::load_user_dictionary(&p);
|
||||
app.session.user_dict_path = Some(p);
|
||||
}
|
||||
// As `prefs()` gives them back, so a setting nobody touched compares equal at exit.
|
||||
serde_json::to_value(app.prefs()).ok()
|
||||
}
|
||||
|
||||
/// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts
|
||||
@@ -332,6 +348,8 @@ fn x11_libraries() -> Result<(), String> {
|
||||
if missing.is_empty() { Ok(()) } else { Err(missing.join("; ")) }
|
||||
}
|
||||
|
||||
/// Write `app`'s preferences to `ui.json`, merged with what other processes saved since this one
|
||||
/// loaded it (`merged_prefs`).
|
||||
fn save_prefs(app: &WordApp) {
|
||||
if let Err(e) = try_save_prefs(app) {
|
||||
log::warn!("preferences: {e}");
|
||||
@@ -348,11 +366,79 @@ fn try_save_prefs(app: &WordApp) -> Result<bool, String> {
|
||||
if let Some(dir) = p.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(&app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
|
||||
write_prefs(&p, &bytes).map_err(|e| format!("cannot save {}: {e}", p.display()))?;
|
||||
let ours = serde_json::to_value(app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
|
||||
let mut base = LOADED_PREFS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
save_merged(&p, &mut base, ours)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Writes `ours` to `path`, merged with what other WordCraft processes saved there since this one
|
||||
/// loaded or saved `base` (`merged_prefs`), and makes `ours` the new `base`: a setting changed here
|
||||
/// before this save and by another process after it then takes the other's value at the next save.
|
||||
/// Holds `lock_prefs` from the read to the rename.
|
||||
fn save_merged(path: &std::path::Path, base: &mut Option<serde_json::Value>, ours: serde_json::Value) -> Result<(), String> {
|
||||
let _lock = lock_prefs(path);
|
||||
let merged = merged_prefs(path, base.as_ref(), ours.clone());
|
||||
let bytes = serde_json::to_vec_pretty(&merged).map_err(|e| format!("cannot serialize: {e}"))?;
|
||||
write_prefs(path, &bytes).map_err(|e| format!("cannot save {}: {e}", path.display()))?;
|
||||
*base = Some(ours);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `ours` with what other WordCraft processes saved to `path` since this one loaded or saved
|
||||
/// `base`, for the settings this one left alone (#3773, see `prefs_merge`). `ours` as it is when
|
||||
/// there's no `base`, or the file is missing or isn't preferences now.
|
||||
fn merged_prefs(path: &std::path::Path, base: Option<&serde_json::Value>, ours: serde_json::Value) -> serde_json::Value {
|
||||
let Some(base) = base else { return ours };
|
||||
let disk = match std::fs::read(path) {
|
||||
Ok(bytes) => prefs_merge::as_read(&bytes),
|
||||
Err(e) => {
|
||||
if e.kind() != std::io::ErrorKind::NotFound {
|
||||
log::debug!("preferences: cannot read {} to merge, saving this process's: {e}", path.display());
|
||||
}
|
||||
return ours;
|
||||
}
|
||||
};
|
||||
match disk {
|
||||
Some(disk) => prefs_merge::merge(base, ours, &disk),
|
||||
None => {
|
||||
log::debug!("preferences: {} isn't preferences, saving this process's", path.display());
|
||||
ours
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a save waits for another process's save to finish before going ahead anyway: a save
|
||||
/// takes milliseconds, and a process stuck holding the lock mustn't stop this one from saving.
|
||||
const PREFS_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// An advisory lock beside `path` (`.ui.json.lock`), held while it is returned, so that two
|
||||
/// processes saving at once (logging out closes every window together) take turns at reading,
|
||||
/// merging and replacing `ui.json` instead of one losing the other's changes. `None` (save
|
||||
/// unlocked) when the lock file can't be opened or the lock isn't free within [`PREFS_LOCK_WAIT`].
|
||||
fn lock_prefs(path: &std::path::Path) -> Option<std::fs::File> {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into());
|
||||
let lock = path.with_file_name(format!(".{name}.lock"));
|
||||
let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
log::debug!("preferences: cannot open {}, saving without it: {e}", lock.display());
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Some(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < PREFS_LOCK_WAIT => std::thread::sleep(std::time::Duration::from_millis(10)),
|
||||
Err(e) => {
|
||||
log::warn!("preferences: {} is held, saving without it: {e}", lock.display());
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -601,6 +687,13 @@ fn main() -> eframe::Result {
|
||||
}));
|
||||
}
|
||||
}
|
||||
// egui-wgpu draws on the discrete GPU by default; on a laptop whose integrated GPU drives the
|
||||
// panel, that wakes the discrete GPU whenever the window redraws. Draw on the GPU that drives
|
||||
// the screen; `WGPU_ADAPTER_NAME` and `WGPU_POWER_PREF` still decide (see linux_gpu.rs).
|
||||
#[cfg(target_os = "linux")]
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
|
||||
setup.native_adapter_selector = Some(std::sync::Arc::new(linux_gpu::pick_adapter));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -626,7 +719,6 @@ fn main() -> eframe::Result {
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
load_user_dictionary(&mut app);
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
@@ -839,7 +931,72 @@ mod launch_arg_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod prefs_tests {
|
||||
use super::write_prefs;
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_ui_egui::{UiState, theme::Appearance};
|
||||
|
||||
use super::{load_prefs_from, lock_prefs, prefs_merge, save_merged, write_prefs};
|
||||
|
||||
/// The preferences saved with `theme` (every other setting at its default).
|
||||
fn with_theme(theme: &str) -> Value {
|
||||
prefs_merge::as_read(&serde_json::to_vec(&json!({"theme": theme})).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The theme the next process loads from `path`.
|
||||
fn saved_theme(path: &std::path::Path) -> Appearance {
|
||||
UiState::from_json(&std::fs::read(path).unwrap()).unwrap().theme
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_changed_by_another_process_after_a_save_here_keeps_its_value() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("ui.json");
|
||||
std::fs::write(&path, serde_json::to_vec(&with_theme("light")).unwrap()).unwrap();
|
||||
// A loads Light, switches to Dark and saves before exiting (taking a document off the
|
||||
// recent list does).
|
||||
let mut a = Some(with_theme("light"));
|
||||
save_merged(&path, &mut a, with_theme("dark")).unwrap();
|
||||
assert_eq!(saved_theme(&path), Appearance::Dark);
|
||||
// B starts, loads Dark, switches to Light and exits.
|
||||
save_merged(&path, &mut Some(with_theme("dark")), with_theme("light")).unwrap();
|
||||
// A exits without touching the theme since its save: B's choice, made later, stays.
|
||||
save_merged(&path, &mut a, with_theme("dark")).unwrap();
|
||||
assert_eq!(saved_theme(&path), Appearance::Light);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loaded_preferences_include_the_words_of_the_dictionary_file() {
|
||||
// A word only `custom-dictionary.txt` has is loaded, not added here: if another process
|
||||
// removes it from `ui.json`, this one mustn't write it back.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (prefs, dict) = (dir.path().join("ui.json"), dir.path().join("custom-dictionary.txt"));
|
||||
std::fs::write(&prefs, br#"{"dictionary": ["zqxinjson"]}"#).unwrap();
|
||||
std::fs::write(&dict, "zqxinfile\n").unwrap();
|
||||
let mut app = wordcraft_ui_egui::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let loaded = load_prefs_from(&mut app, Some(&prefs), Some(dict)).unwrap();
|
||||
let words = loaded["dictionary"].as_array().unwrap();
|
||||
for word in ["zqxinjson", "zqxinfile"] {
|
||||
assert!(words.contains(&json!(word)), "{word}: {words:?}");
|
||||
}
|
||||
wordcraft_engine::proof::remove_word("zqxinjson");
|
||||
wordcraft_engine::proof::remove_word("zqxinfile");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_waits_for_another_process_saving_at_the_same_moment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("ui.json");
|
||||
// Another process is between reading and replacing `ui.json`.
|
||||
let held = lock_prefs(&path).expect("the lock is free");
|
||||
let saver = {
|
||||
let path = path.clone();
|
||||
std::thread::spawn(move || save_merged(&path, &mut None, with_theme("dark")))
|
||||
};
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
assert!(!path.exists(), "saved while another process held the lock");
|
||||
drop(held);
|
||||
saver.join().unwrap().unwrap();
|
||||
assert_eq!(saved_theme(&path), Appearance::Dark);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() {
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts
|
||||
//! another). Each reads it at start-up and writes it at exit (and when a change must survive a
|
||||
//! crash, like taking a document off the recent list), so without a merge the process that writes
|
||||
//! last writes back what it loaded and loses the others' changes (#3773).
|
||||
//!
|
||||
//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting
|
||||
//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are
|
||||
//! left out), and write it with only what this process changed since it last loaded or saved its
|
||||
//! preferences (`base`). Every other setting keeps what the file holds now, including the absence
|
||||
//! of one another process removed (a shortcut, a task pane's place).
|
||||
//!
|
||||
//! - A setting both changed takes this process's value.
|
||||
//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon,
|
||||
//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the
|
||||
//! window's size and place, or one task pane's place, are never mixed from two processes.
|
||||
//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed
|
||||
//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens,
|
||||
//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process
|
||||
//! added are kept, entries either process removed stay removed, and an entry both changed takes
|
||||
//! this process's version. A ribbon or toolbar left as it comes counts as its default entries.
|
||||
//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used
|
||||
//! again first, then the file's, without duplicates, without the entries this process removed,
|
||||
//! and within each list's limit ([`merge_recent`]).
|
||||
//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting.
|
||||
//!
|
||||
//! What this process changed is found by comparing with `base`, not by recording each change: a
|
||||
//! setting changed and then changed back counts as untouched, so the file's value stays, and a
|
||||
//! recent entry used again without moving (it was already first) counts as not used.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout};
|
||||
use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert};
|
||||
|
||||
/// Whether two entries of a recent list are the same entry.
|
||||
type Same = fn(&Value, &Value) -> bool;
|
||||
|
||||
/// What tells an entry of a list of user entries from the others. Entries with the same key are
|
||||
/// told apart by their order ([`ids`]).
|
||||
type Key = fn(&Value) -> String;
|
||||
|
||||
/// How a setting this process changed merges with the file's.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Rule {
|
||||
/// A group of settings: each entry on its own.
|
||||
Group,
|
||||
/// A recent list, most recent first: how many entries it keeps, and when two are the same.
|
||||
Recent(usize, Same),
|
||||
/// A list of user entries: each entry on its own.
|
||||
Entries(Key),
|
||||
/// One setting: this process's value.
|
||||
Whole,
|
||||
}
|
||||
|
||||
/// The rule for the setting at `path` (`ui.json`'s keys from the top).
|
||||
fn rule(path: &[&str]) -> Rule {
|
||||
match path {
|
||||
[] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => {
|
||||
Rule::Group
|
||||
}
|
||||
["recent"] => Rule::Recent(MAX_RECENT, same_entry),
|
||||
["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry),
|
||||
["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry),
|
||||
["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font),
|
||||
["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text),
|
||||
["ribbon", "tabs"] => Rule::Entries(tab_name),
|
||||
["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"]
|
||||
| ["keyboard", "removed"]
|
||||
| ["ribbon", "qat"]
|
||||
| ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry),
|
||||
_ => Rule::Whole,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a setting saved only when it isn't its default stands for when it is missing: the
|
||||
/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the
|
||||
/// default merge entry by entry.
|
||||
fn when_missing(path: &[&str]) -> Option<Value> {
|
||||
match path {
|
||||
["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(),
|
||||
["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries saved alike (colours are saved normalised, `colors::push_recent`).
|
||||
fn same_entry(a: &Value, b: &Value) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// Font names ignoring case, as `push_recent_font` compares them.
|
||||
fn same_font(a: &Value, b: &Value) -> bool {
|
||||
match (a.as_str(), b.as_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry as saved.
|
||||
fn whole_entry(v: &Value) -> String {
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// An AutoCorrect entry `[from, to]` by the text it replaces.
|
||||
fn replaced_text(v: &Value) -> String {
|
||||
v.get(0).unwrap_or(v).to_string()
|
||||
}
|
||||
|
||||
/// A ribbon tab by its name, ignoring case as the ribbon does.
|
||||
fn tab_name(v: &Value) -> String {
|
||||
v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase)
|
||||
}
|
||||
|
||||
/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't
|
||||
/// preferences at all.
|
||||
pub fn as_read(bytes: &[u8]) -> Option<Value> {
|
||||
serde_json::to_value(UiState::from_json(bytes)?).ok()
|
||||
}
|
||||
|
||||
/// The preferences to write: `ours` (this process's, now), with every value it left as it was in
|
||||
/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]).
|
||||
pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value {
|
||||
let fallback = ours.clone();
|
||||
merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback)
|
||||
}
|
||||
|
||||
/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it
|
||||
/// alone and another process removed it).
|
||||
fn merge_setting(path: &mut Vec<String>, base: Option<&Value>, ours: Option<Value>, disk: Option<&Value>) -> Option<Value> {
|
||||
if base == ours.as_ref() {
|
||||
// Unchanged here: whatever the file holds now.
|
||||
return disk.cloned();
|
||||
}
|
||||
let ours = ours?;
|
||||
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
Some(match (rule(&keys), ours, base, disk) {
|
||||
(Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => {
|
||||
Value::Object(merge_group(path, base, ours, disk))
|
||||
}
|
||||
(Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
|
||||
Value::Array(merge_recent(base, ours, disk, cap, same))
|
||||
}
|
||||
(Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
|
||||
Value::Array(merge_entries(base, &ours, disk, key))
|
||||
}
|
||||
(_, ours, ..) => ours,
|
||||
})
|
||||
}
|
||||
|
||||
/// A group of settings, entry by entry: this process's entries in their order, then those only
|
||||
/// the file or `base` has.
|
||||
fn merge_group(path: &mut Vec<String>, base: &Map<String, Value>, mut ours: Map<String, Value>, disk: &Map<String, Value>) -> Map<String, Value> {
|
||||
let mut names: Vec<String> = ours.keys().cloned().collect();
|
||||
let mut seen: HashSet<String> = names.iter().cloned().collect();
|
||||
for k in disk.keys().chain(base.keys()) {
|
||||
if seen.insert(k.clone()) {
|
||||
names.push(k.clone());
|
||||
}
|
||||
}
|
||||
let mut merged = Map::new();
|
||||
for k in names {
|
||||
path.push(k.clone());
|
||||
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
let missing = when_missing(&keys);
|
||||
let base_v = base.get(&k).cloned().or_else(|| missing.clone());
|
||||
let disk_v = disk.get(&k).cloned().or_else(|| missing.clone());
|
||||
let ours_v = ours.remove(&k).or_else(|| missing.clone());
|
||||
let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref());
|
||||
path.pop();
|
||||
// A setting saved only when it isn't its default is left out when it is.
|
||||
if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) {
|
||||
merged.insert(k, v);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// A list entry: its key, and how many entries before it have the same key.
|
||||
type Id = (String, usize);
|
||||
|
||||
/// The entries of `list` told apart by `key`, in order.
|
||||
fn ids(list: &[Value], key: Key) -> Vec<Id> {
|
||||
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||
list.iter()
|
||||
.map(|v| {
|
||||
let k = key(v);
|
||||
let n = seen.entry(k.clone()).or_default();
|
||||
*n += 1;
|
||||
(k, *n - 1)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A list of user entries, entry by entry. An entry either process added is kept, one either
|
||||
/// removed stays removed, and one this process changed takes its version (else the file's). The
|
||||
/// order is this process's if it reordered the entries it loaded, else the file's; an entry only
|
||||
/// the other list has goes after the entry it follows there.
|
||||
fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec<Value> {
|
||||
let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key));
|
||||
let index = |ids: &[Id], list: &[Value]| -> HashMap<Id, Value> { ids.iter().cloned().zip(list.iter().cloned()).collect() };
|
||||
let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk));
|
||||
let value = |id: &Id| -> Option<&Value> {
|
||||
match (b.get(id), o.get(id), d.get(id)) {
|
||||
// Left alone here: the file's, or gone if the other process removed it.
|
||||
(Some(b), Some(o), d) if b == o => d,
|
||||
// Added or changed here.
|
||||
(_, Some(o), _) => Some(o),
|
||||
// Removed here.
|
||||
(Some(_), None, _) => None,
|
||||
// Added there.
|
||||
(None, None, d) => d,
|
||||
}
|
||||
};
|
||||
let common = |ids: &[Id], other: &HashMap<Id, Value>| -> Vec<Id> { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() };
|
||||
let reordered = common(&ours_ids, &b) != common(&base_ids, &o);
|
||||
let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) };
|
||||
let in_first: HashSet<&Id> = first.iter().collect();
|
||||
let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect();
|
||||
// Entries only `second` has, by the kept entry they follow there (`None`: at the start).
|
||||
let mut after: HashMap<Option<&Id>, Vec<&Id>> = HashMap::new();
|
||||
let mut anchor = None;
|
||||
for id in second {
|
||||
if kept.contains(id) {
|
||||
anchor = Some(id);
|
||||
} else if !in_first.contains(id) && value(id).is_some() {
|
||||
after.entry(anchor).or_default().push(id);
|
||||
}
|
||||
}
|
||||
let mut merged = Vec::new();
|
||||
let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned()));
|
||||
emit(after.get(&None).map_or(&[], Vec::as_slice));
|
||||
for id in first.iter().filter(|id| kept.contains(id)) {
|
||||
emit(&[id]);
|
||||
emit(after.get(&Some(id)).map_or(&[], Vec::as_slice));
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving
|
||||
/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at
|
||||
/// most `cap` entries. Entries are told apart by `same`.
|
||||
fn merge_recent(base: &[Value], ours: Vec<Value>, disk: &[Value], cap: usize, same: Same) -> Vec<Value> {
|
||||
let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v));
|
||||
let removed = |v: &Value| has(base, v) && !has(&ours, v);
|
||||
let touched = &ours[..touched_len(base, &ours, same)];
|
||||
let mut merged: Vec<Value> = Vec::new();
|
||||
for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) {
|
||||
if merged.len() == cap {
|
||||
break;
|
||||
}
|
||||
if !has(&merged, &v) {
|
||||
merged.push(v);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// How many of `ours`'s first entries this process added or used again. Each use moves an entry
|
||||
/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the
|
||||
/// longest such tail is untouched, and everything before it (new entries, and entries that moved
|
||||
/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded
|
||||
/// (the first entry used again) can't be told from no use, and merges as none.
|
||||
fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize {
|
||||
let mut end = base.len();
|
||||
for (i, v) in ours.iter().enumerate().rev() {
|
||||
match base[..end].iter().rposition(|b| same(b, v)) {
|
||||
Some(at) => end = at,
|
||||
None => return i + 1,
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_ui_egui::UiState;
|
||||
|
||||
use super::{as_read, merge};
|
||||
|
||||
/// The preferences a process holds after loading a `ui.json` with `settings` (every other
|
||||
/// setting at its default), as it saves them.
|
||||
fn prefs(settings: Value) -> Value {
|
||||
as_read(&serde_json::to_vec(&settings).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// What the next process loads from the merged preferences.
|
||||
fn reloaded(merged: &Value) -> UiState {
|
||||
UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`.
|
||||
fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value {
|
||||
let after_b = merge(loaded, b, loaded);
|
||||
merge(loaded, a, &after_b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_processes_keep_each_others_changes() {
|
||||
// #3773: A and B both start from the same file.
|
||||
let loaded =
|
||||
json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}});
|
||||
// B changes the theme and opens c.docx, then exits first.
|
||||
let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}});
|
||||
// A changes the author name and opens d.docx, then exits.
|
||||
let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}});
|
||||
assert_eq!(
|
||||
b_then_a(&loaded, b, a),
|
||||
json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() {
|
||||
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
|
||||
let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]});
|
||||
assert_eq!(merge(&loaded, loaded.clone(), &disk), disk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_process_wins_a_setting_both_changed() {
|
||||
let loaded = json!({"theme": "light"});
|
||||
assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_changed_and_changed_back_counts_as_untouched() {
|
||||
// Changes are found by comparing with what was loaded: A switched to dark and back.
|
||||
let loaded = json!({"theme": "light"});
|
||||
assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_entry_removed_here_stays_removed() {
|
||||
let loaded = json!({"recent": ["a.docx", "b.docx"]});
|
||||
let ours = json!({"recent": ["b.docx"]});
|
||||
let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]}));
|
||||
// Clear Recent clears what the other process had added too only if it was loaded here.
|
||||
assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_entry_used_again_here_moves_to_the_front() {
|
||||
// Applying a font already in Recently Used Fonts moves it to the front without adding one.
|
||||
let loaded = json!({"recentFonts": ["A", "B"]});
|
||||
assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]}));
|
||||
// Here C was used again, D opened and A removed; the other process used B again and added E.
|
||||
let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]});
|
||||
let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]});
|
||||
let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]}));
|
||||
// Entries this process only kept, in the order it loaded them, don't override the file's order.
|
||||
let loaded = json!({"recentSymbols": ["x", "y", "z"]});
|
||||
let ours = json!({"recentSymbols": ["w", "x", "z"]});
|
||||
let disk = json!({"recentSymbols": ["z", "x", "y"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_fonts_are_one_entry_whatever_their_case() {
|
||||
// Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and
|
||||
// there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten.
|
||||
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]});
|
||||
let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}));
|
||||
// Other lists compare their entries as saved.
|
||||
let loaded = json!({"recent": ["a.docx"]});
|
||||
assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_recent_lists_keep_their_limit() {
|
||||
// Recently Used Fonts keeps ten.
|
||||
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]});
|
||||
let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_recent_entry_in_the_file_is_not_carried_forward() {
|
||||
// A non-string entry makes the whole list read as empty (`options::lenient` falls back per
|
||||
// setting). Merging it in would keep Recent empty in every later session; instead the
|
||||
// list reads as this version reads it, and the next save heals it.
|
||||
let loaded = prefs(json!({"recent": []}));
|
||||
let ours = prefs(json!({"recent": ["x.docx"]}));
|
||||
let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap();
|
||||
let merged = merge(&loaded, ours, &disk);
|
||||
assert_eq!(merged["recent"], json!(["x.docx"]));
|
||||
assert_eq!(loaded_recent(&merged), ["x.docx"]);
|
||||
// Same for recent symbols.
|
||||
let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]}));
|
||||
let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap();
|
||||
assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1);
|
||||
}
|
||||
|
||||
/// The recent documents the next process loads.
|
||||
fn loaded_recent(merged: &Value) -> Vec<String> {
|
||||
reloaded(merged).recent
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_keys_this_version_writes_are_kept() {
|
||||
// A legacy key read once to migrate, and junk, are not written back, even from the file.
|
||||
let loaded = prefs(json!({"theme": "light"}));
|
||||
let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap();
|
||||
let merged = merge(&loaded, loaded.clone(), &disk);
|
||||
for gone in ["dark", "interfaceSize", "junk"] {
|
||||
assert!(merged.get(gone).is_none(), "{gone}");
|
||||
}
|
||||
assert_eq!(merged["theme"], "light");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_another_process_damaged_gives_way_to_ours() {
|
||||
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
|
||||
let ours = json!({"theme": "dark", "recent": ["a.docx"]});
|
||||
// Not preferences at all: everything comes from this process.
|
||||
assert_eq!(as_read(b"\"garbage\""), None);
|
||||
assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours);
|
||||
// A list replaced by something else keeps ours.
|
||||
assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() {
|
||||
let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}}));
|
||||
// B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and
|
||||
// removes `approx.`. Each added entry follows the entry it was added after.
|
||||
let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}}));
|
||||
let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}}));
|
||||
let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect;
|
||||
let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect();
|
||||
assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]);
|
||||
assert_eq!(ac.exceptions, ["fig."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_customisations_merge_key_by_key() {
|
||||
let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}}));
|
||||
// B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and
|
||||
// assigns Mod+Shift+J.
|
||||
let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}}));
|
||||
let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}}));
|
||||
let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard;
|
||||
assert_eq!(keys.assigned.into_iter().collect::<Vec<_>>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]);
|
||||
assert_eq!(keys.removed.into_iter().collect::<Vec<_>>(), ["Mod+B", "Mod+I"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ribbon_changes_from_both_processes_are_kept() {
|
||||
// Both start from the default ribbon. B hides Draw; A adds a custom tab after Home.
|
||||
let loaded = prefs(json!({}));
|
||||
let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}}));
|
||||
let mut a_tabs = default_tabs();
|
||||
a_tabs.insert(1, json!({"name": "Mine", "custom": true}));
|
||||
let a = prefs(json!({"ribbon": {"tabs": a_tabs}}));
|
||||
let mut want = hide(default_tabs(), "Draw");
|
||||
want.insert(1, json!({"name": "Mine", "custom": true}));
|
||||
assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_toolbar_reset_by_one_process_stays_reset() {
|
||||
// B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a
|
||||
// custom tab. The toolbar stays the default.
|
||||
let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}}));
|
||||
let b = prefs(json!({}));
|
||||
let mut a_tabs = default_tabs();
|
||||
a_tabs.push(json!({"name": "Mine", "custom": true}));
|
||||
let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}}));
|
||||
let merged = b_then_a(&loaded, b, a);
|
||||
assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]);
|
||||
let ribbon = loaded_ribbon(&merged);
|
||||
assert_eq!(ribbon.qat, None);
|
||||
assert!(ribbon.tabs.iter().any(|t| t.name == "Mine"));
|
||||
// Two processes customizing the default toolbar: both commands, Save removed by A gone.
|
||||
let loaded = prefs(json!({}));
|
||||
let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}}));
|
||||
let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}}));
|
||||
assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]);
|
||||
}
|
||||
|
||||
/// The default ribbon tabs, as saved once the ribbon is customized.
|
||||
fn default_tabs() -> Vec<Value> {
|
||||
serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `tabs` with the tab `name` hidden.
|
||||
fn hide(mut tabs: Vec<Value>, name: &str) -> Vec<Value> {
|
||||
for t in &mut tabs {
|
||||
if t["name"] == name {
|
||||
t["hidden"] = json!(true);
|
||||
}
|
||||
}
|
||||
tabs
|
||||
}
|
||||
|
||||
/// The ribbon the next process loads.
|
||||
fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout {
|
||||
reloaded(merged).ribbon
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pane_order_changed_by_the_other_process_is_kept() {
|
||||
// `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and
|
||||
// switches to dark.
|
||||
let loaded = prefs(json!({}));
|
||||
let order = json!(["styles", "navigation"]);
|
||||
let b = prefs(json!({"paneOrder": order}));
|
||||
let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"})));
|
||||
assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark")));
|
||||
// B goes back to the default order; A, which loaded B's order and left it, doesn't bring
|
||||
// it back.
|
||||
let loaded = prefs(json!({"paneOrder": order}));
|
||||
let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"})));
|
||||
assert!(merged.get("paneOrder").is_none(), "{merged}");
|
||||
assert_eq!(merged["theme"], "dark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_and_a_pane_place_are_one_setting_each() {
|
||||
// A moved its window and B resized its own: the window is A's, not A's place with B's size.
|
||||
let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}});
|
||||
let loaded = prefs(window(0.0, 800.0));
|
||||
let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0)));
|
||||
assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pens_labels_and_dictionary_words_from_both_processes_are_kept() {
|
||||
let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0});
|
||||
let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]}));
|
||||
// B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a
|
||||
// label of its own. Identical pens stay apart, by their order.
|
||||
let b = prefs(
|
||||
json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}),
|
||||
);
|
||||
let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]}));
|
||||
let merged = b_then_a(&loaded, b, a);
|
||||
let ui = reloaded(&merged);
|
||||
let colors: Vec<String> = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]);
|
||||
assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]);
|
||||
assert_eq!(merged["dictionary"], json!(["foo", "baz"]));
|
||||
}
|
||||
}
|
||||
@@ -89,9 +89,11 @@ pub fn submit() -> Submit {
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
grey_pages: false,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "WordCraft document".into(),
|
||||
options,
|
||||
driver_settings: None,
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let sent = craft_print::submit_cancellable(&bytes, &job, &mut |_, _| {}, &token).map_err(|error| error.to_string());
|
||||
|
||||
@@ -15,6 +15,8 @@ use serde::{Deserialize, Serialize};
|
||||
const FLAG: &str = "--wordcraft-print-worker";
|
||||
const PREFIX: &str = "WORDCRAFT_PRINT:";
|
||||
const MAX_MESSAGE: u64 = 64 * 1024;
|
||||
/// The job's options, and a driver's settings of up to 1 MiB written as hex.
|
||||
const MAX_REQUEST: u64 = MAX_MESSAGE + 2 * 1024 * 1024;
|
||||
const MAX_PDF: u64 = 512 * 1024 * 1024;
|
||||
const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer";
|
||||
|
||||
@@ -32,9 +34,12 @@ struct Request {
|
||||
collate: bool,
|
||||
duplex: Option<Duplex>,
|
||||
grayscale: bool,
|
||||
grey_pages: bool,
|
||||
shrink: bool,
|
||||
title: String,
|
||||
options: Vec<(String, String)>,
|
||||
/// The printer the driver's settings were chosen for, and their DEVMODE as hex.
|
||||
driver_settings: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -50,15 +55,21 @@ impl Request {
|
||||
craft_print::Duplex::ShortEdge => Duplex::ShortEdge,
|
||||
}),
|
||||
grayscale: job.grayscale,
|
||||
grey_pages: job.grey_pages,
|
||||
shrink: job.scaling == craft_print::Scaling::ShrinkToFit,
|
||||
title: job.title.clone(),
|
||||
options: job.options.clone(),
|
||||
driver_settings: job.driver_settings.as_ref().map(|settings| (settings.printer().to_owned(), settings.dev_mode().to_hex())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the job without substituting printer defaults or changing copy semantics.
|
||||
fn job(self) -> craft_print::Job {
|
||||
craft_print::Job {
|
||||
fn job(self) -> Result<craft_print::Job, String> {
|
||||
let driver_settings = match self.driver_settings {
|
||||
Some((printer, hex)) => Some(craft_print::DriverSettings::new(printer, craft_print::rgb::DevMode::from_hex(&hex).map_err(error)?)),
|
||||
None => None,
|
||||
};
|
||||
Ok(craft_print::Job {
|
||||
printer: self.printer,
|
||||
copies: self.copies,
|
||||
collate: self.collate,
|
||||
@@ -68,10 +79,12 @@ impl Request {
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
}),
|
||||
grayscale: self.grayscale,
|
||||
grey_pages: self.grey_pages,
|
||||
scaling: if self.shrink { craft_print::Scaling::ShrinkToFit } else { craft_print::Scaling::Exact },
|
||||
title: self.title,
|
||||
options: self.options,
|
||||
}
|
||||
driver_settings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +179,7 @@ impl Submission {
|
||||
return Err("the print PDF exceeds the 512 MiB helper limit".into());
|
||||
}
|
||||
let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?;
|
||||
if request.len() as u64 > MAX_MESSAGE {
|
||||
if request.len() as u64 > MAX_REQUEST {
|
||||
return Err("the print settings exceed the helper message limit".into());
|
||||
}
|
||||
let directory = tempfile::tempdir().map_err(error)?;
|
||||
@@ -323,10 +336,10 @@ fn helper(
|
||||
})
|
||||
.map_err(error)?;
|
||||
let request: Request =
|
||||
serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_MESSAGE)?).map_err(error)?;
|
||||
serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_REQUEST)?).map_err(error)?;
|
||||
let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?;
|
||||
remove_inputs(directory)?;
|
||||
let result = submit(&pdf, &request.job(), &cancel);
|
||||
let result = submit(&pdf, &request.job()?, &cancel);
|
||||
emit(&Event::Done(result))
|
||||
}
|
||||
|
||||
@@ -463,21 +476,40 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Job transport preserves every explicit setting, including Unicode and duplex direction.
|
||||
/// Job transport preserves every explicit setting, including Unicode, duplex direction and the
|
||||
/// driver's own settings.
|
||||
fn job_options_survive_the_process_boundary() {
|
||||
// A DEVMODEW header of 156 bytes (`dmSize` at 68) and a 4-byte private part (`dmDriverExtra` at 70).
|
||||
let mut dev_mode = vec![0u8; 160];
|
||||
dev_mode[68..70].copy_from_slice(&156u16.to_le_bytes());
|
||||
dev_mode[70..72].copy_from_slice(&4u16.to_le_bytes());
|
||||
dev_mode[156..].copy_from_slice(&[1, 2, 3, 4]);
|
||||
let dev_mode = craft_print::rgb::DevMode::from_bytes(dev_mode).unwrap();
|
||||
let expected = craft_print::Job {
|
||||
printer: Some("Office λ".into()),
|
||||
copies: 3,
|
||||
collate: false,
|
||||
duplex: Some(craft_print::Duplex::ShortEdge),
|
||||
grayscale: true,
|
||||
grey_pages: true,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "A document".into(),
|
||||
options: vec![("media".into(), "iso_a4_210x297mm".into())],
|
||||
driver_settings: Some(craft_print::DriverSettings::new("Office λ", dev_mode)),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&Request::from_job(&expected)).unwrap();
|
||||
let received: Request = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(received.job(), expected);
|
||||
assert_eq!(received.job(), Ok(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Damaged driver settings on the wire are an error, not a job printed with other settings.
|
||||
fn damaged_driver_settings_are_refused() {
|
||||
for hex in ["", "0", "zz", "00"] {
|
||||
let mut request = Request::from_job(&job());
|
||||
request.driver_settings = Some(("Office".into(), hex.into()));
|
||||
assert!(request.job().is_err(), "{hex:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1e515422afdda2f317af430c1f9d68a5f83935b4
|
||||
e56d26244bbac099bfd42e23fb12f78a4be418a7
|
||||
|
||||
+259
-5
@@ -11,6 +11,8 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::Rgb;
|
||||
|
||||
/// Most series in a chart.
|
||||
pub const MAX_SERIES: usize = 255;
|
||||
/// Most categories (points per series) in a chart.
|
||||
@@ -123,17 +125,119 @@ impl LegendPos {
|
||||
}
|
||||
}
|
||||
|
||||
/// One series: its name and a value per category (`None` = no value, a gap).
|
||||
/// One series: its name, a value per category (`None` = no value, a gap) and how it is drawn:
|
||||
/// fill, line, markers, smooth lines, its own data labels and number format. Unset fields follow
|
||||
/// the chart's defaults.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartSeries {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub values: Vec<Option<f64>>,
|
||||
/// Fill color; `None`: the chart's accent color for the series.
|
||||
#[serde(default)]
|
||||
pub fill: Option<Rgb>,
|
||||
/// "None" fill: the series draws no fill.
|
||||
#[serde(default)]
|
||||
pub no_fill: bool,
|
||||
/// Line width in points; `None`: the chart's default.
|
||||
#[serde(default)]
|
||||
pub line_w: Option<f32>,
|
||||
/// "None" line: the series draws no line.
|
||||
#[serde(default)]
|
||||
pub no_line: bool,
|
||||
/// Markers on points; `None`: unset (scatter charts draw them; a saved scatter series then has
|
||||
/// no `c:marker`).
|
||||
#[serde(default)]
|
||||
pub markers: Option<bool>,
|
||||
/// Draw the line as a smooth curve.
|
||||
#[serde(default)]
|
||||
pub smooth: bool,
|
||||
/// Data labels for this series; `None`: follow the chart's setting.
|
||||
#[serde(default)]
|
||||
pub labels: Option<bool>,
|
||||
/// Number format of this series's labels and values; `None`: linked to the source.
|
||||
#[serde(default)]
|
||||
pub fmt: Option<String>,
|
||||
}
|
||||
|
||||
impl ChartSeries {
|
||||
/// A new series of a `kind` chart: a scatter series is drawn as markers without a line.
|
||||
pub fn new(kind: ChartType, name: String, values: Vec<Option<f64>>) -> ChartSeries {
|
||||
ChartSeries { name, values, no_line: kind == ChartType::Scatter, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One chart axis: title, scale bounds, tick-label number format, gridlines, tick labels and the
|
||||
/// axis line.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartAxis {
|
||||
/// `None`: no axis title; text cut to [`MAX_TEXT`] characters.
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
/// Fixed lower bound; `None`: automatic.
|
||||
#[serde(default)]
|
||||
pub min: Option<f64>,
|
||||
/// Fixed upper bound; `None`: automatic.
|
||||
#[serde(default)]
|
||||
pub max: Option<f64>,
|
||||
/// Tick-label number format (`#,##0`, `0.00`, `0%`…); `None`: linked to the source data.
|
||||
#[serde(default)]
|
||||
pub fmt: Option<String>,
|
||||
/// Major gridlines drawn along this axis.
|
||||
#[serde(default)]
|
||||
pub gridlines: bool,
|
||||
/// Tick labels; `false` hides them.
|
||||
#[serde(default = "the_true")]
|
||||
pub labels: bool,
|
||||
/// The axis line.
|
||||
#[serde(default = "the_true")]
|
||||
pub line: bool,
|
||||
}
|
||||
|
||||
fn the_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for ChartAxis {
|
||||
fn default() -> Self {
|
||||
ChartAxis { title: None, min: None, max: None, fmt: None, gridlines: false, labels: true, line: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The value axis as a new chart has it: gridlines, labels, no axis line.
|
||||
pub fn value_axis() -> ChartAxis {
|
||||
ChartAxis { gridlines: true, line: false, ..ChartAxis::default() }
|
||||
}
|
||||
|
||||
impl ChartAxis {
|
||||
/// Make the axis safe to store: texts cleaned, bounds finite, `min` under `max` (an
|
||||
/// impossible pair drops both), the format code cut to [`MAX_FMT`] characters.
|
||||
pub fn sanitize(&mut self) {
|
||||
self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty());
|
||||
self.min = self.min.filter(|v| v.is_finite());
|
||||
self.max = self.max.filter(|v| v.is_finite());
|
||||
if matches!((self.min, self.max), (Some(lo), Some(hi)) if lo >= hi) {
|
||||
self.min = None;
|
||||
self.max = None;
|
||||
}
|
||||
self.fmt = self.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest axis number format kept, characters.
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters.
|
||||
pub fn clean_fmt(s: &str) -> String {
|
||||
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
|
||||
}
|
||||
|
||||
/// A chart WordCraft can edit.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartSpec {
|
||||
#[serde(rename = "type")]
|
||||
@@ -151,6 +255,78 @@ pub struct ChartSpec {
|
||||
/// Show each point's value next to it.
|
||||
#[serde(default)]
|
||||
pub data_labels: bool,
|
||||
/// The category axis (scatter charts: the x axis).
|
||||
#[serde(default)]
|
||||
pub cat_axis: ChartAxis,
|
||||
/// The value axis (scatter charts: the y axis); gridlines on and no axis line in a new chart.
|
||||
#[serde(default = "value_axis")]
|
||||
pub val_axis: ChartAxis,
|
||||
}
|
||||
|
||||
/// A [`ChartSpec`] as stored. A scatter series saved without `noLine` (by a version without
|
||||
/// series formatting) is drawn as markers without a line, as that version drew it.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StoredSpec {
|
||||
#[serde(rename = "type")]
|
||||
kind: ChartType,
|
||||
#[serde(default)]
|
||||
categories: Vec<String>,
|
||||
#[serde(default)]
|
||||
series: Vec<StoredSeries>,
|
||||
#[serde(default)]
|
||||
title: Option<String>,
|
||||
#[serde(default)]
|
||||
legend: Option<LegendPos>,
|
||||
#[serde(default)]
|
||||
data_labels: bool,
|
||||
#[serde(default)]
|
||||
cat_axis: ChartAxis,
|
||||
#[serde(default = "value_axis")]
|
||||
val_axis: ChartAxis,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StoredSeries {
|
||||
#[serde(default)]
|
||||
no_line: Option<bool>,
|
||||
#[serde(flatten)]
|
||||
series: ChartSeries,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ChartSpec {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let s = StoredSpec::deserialize(deserializer)?;
|
||||
let scatter = s.kind == ChartType::Scatter;
|
||||
Ok(ChartSpec {
|
||||
kind: s.kind,
|
||||
categories: s.categories,
|
||||
series: s.series.into_iter().map(|x| ChartSeries { no_line: x.no_line.unwrap_or(scatter), ..x.series }).collect(),
|
||||
title: s.title,
|
||||
legend: s.legend,
|
||||
data_labels: s.data_labels,
|
||||
cat_axis: s.cat_axis,
|
||||
val_axis: s.val_axis,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ChartSpec {
|
||||
/// An empty chart whose value axis is the one a new chart (and a missing JSON field) has:
|
||||
/// gridlines on, no axis line.
|
||||
fn default() -> Self {
|
||||
ChartSpec {
|
||||
kind: ChartType::default(),
|
||||
categories: Vec::new(),
|
||||
series: Vec::new(),
|
||||
title: None,
|
||||
legend: None,
|
||||
data_labels: false,
|
||||
cat_axis: ChartAxis::default(),
|
||||
val_axis: value_axis(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChartSpec {
|
||||
@@ -168,10 +344,14 @@ impl ChartSpec {
|
||||
ChartSpec {
|
||||
kind,
|
||||
categories: categories.into_iter().map(str::to_string).collect(),
|
||||
series: series.into_iter().map(|(n, v)| ChartSeries { name: n.to_string(), values: v.into_iter().map(Some).collect() }).collect(),
|
||||
series: series.into_iter().map(|(n, v)| ChartSeries::new(kind, n.to_string(), v.into_iter().map(Some).collect())).collect(),
|
||||
title: None,
|
||||
legend: Some(LegendPos::Bottom),
|
||||
data_labels: false,
|
||||
cat_axis: ChartAxis::default(),
|
||||
// Pie and doughnut charts have no axes: their axes stay plain, so the chart reads back
|
||||
// as the same model.
|
||||
val_axis: if kind.is_round() { ChartAxis::default() } else { value_axis() },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,8 +383,12 @@ impl ChartSpec {
|
||||
*v = v.filter(|x| x.is_finite());
|
||||
}
|
||||
s.values.resize(n, None);
|
||||
s.fmt = s.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty());
|
||||
s.line_w = s.line_w.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 20.0));
|
||||
}
|
||||
self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty());
|
||||
self.cat_axis.sanitize();
|
||||
self.val_axis.sanitize();
|
||||
}
|
||||
|
||||
/// The chart after `sanitize`.
|
||||
@@ -229,7 +413,11 @@ mod tests {
|
||||
let mut c = ChartSpec {
|
||||
categories: vec!["a".into(); MAX_POINTS + 10],
|
||||
series: (0..MAX_SERIES + 5)
|
||||
.map(|i| ChartSeries { name: format!("{}\n{}", "x".repeat(400), i), values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)] })
|
||||
.map(|i| ChartSeries {
|
||||
name: format!("{}\n{}", "x".repeat(400), i),
|
||||
values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)],
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
title: Some(" ".into()),
|
||||
..Default::default()
|
||||
@@ -250,7 +438,7 @@ mod tests {
|
||||
fn short_categories_are_padded_to_the_longest_series() {
|
||||
let c = ChartSpec {
|
||||
categories: vec!["a".into()],
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)] }],
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)], ..Default::default() }],
|
||||
..Default::default()
|
||||
}
|
||||
.sanitized();
|
||||
@@ -258,4 +446,70 @@ mod tests {
|
||||
assert_eq!(ChartType::from_id("BARSTACKED"), Some(ChartType::BarStacked));
|
||||
assert_eq!(LegendPos::from_id("top"), Some(LegendPos::Top));
|
||||
}
|
||||
|
||||
/// A scatter series stored without `noLine` reads as markers without a line; a stored value
|
||||
/// and the other chart types keep theirs.
|
||||
#[test]
|
||||
fn stored_scatter_series_without_a_line_setting_draw_no_line() {
|
||||
let read = |json: &str| -> Vec<bool> { serde_json::from_str::<ChartSpec>(json).unwrap().series.iter().map(|s| s.no_line).collect() };
|
||||
let series = r#"[{"name":"a","values":[1,null,2.5]},{"name":"b","values":[3],"noLine":false}]"#;
|
||||
assert_eq!(read(&format!(r#"{{"type":"scatter","series":{series}}}"#)), [true, false]);
|
||||
assert_eq!(read(&format!(r#"{{"type":"line","series":{series}}}"#)), [false, false]);
|
||||
let c: ChartSpec = serde_json::from_str(&format!(r#"{{"type":"scatter","series":{series}}}"#)).unwrap();
|
||||
assert_eq!(c.series[0].values, [Some(1.0), None, Some(2.5)]);
|
||||
// What this version writes reads back as itself.
|
||||
for kind in ChartType::ALL {
|
||||
let spec = ChartSpec::sample(kind);
|
||||
assert_eq!(serde_json::from_str::<ChartSpec>(&serde_json::to_string(&spec).unwrap()).unwrap(), spec, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_and_missing_json_axis_fields_agree() {
|
||||
let from_json: ChartSpec = serde_json::from_str(r#"{"type":"column"}"#).unwrap();
|
||||
let d = ChartSpec::default();
|
||||
assert_eq!((d.cat_axis.clone(), d.val_axis.clone()), (from_json.cat_axis, from_json.val_axis));
|
||||
assert!(d.val_axis.gridlines && !d.val_axis.line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_bounds_and_formats_are_cleaned() {
|
||||
let mut a = ChartAxis {
|
||||
title: Some(" Sales\n".into()),
|
||||
min: Some(f64::NAN),
|
||||
max: Some(50.0),
|
||||
fmt: Some("x".repeat(MAX_FMT + 40)),
|
||||
gridlines: true,
|
||||
labels: false,
|
||||
line: true,
|
||||
};
|
||||
a.sanitize();
|
||||
assert_eq!(a.title.as_deref(), Some("Sales"));
|
||||
assert_eq!(a.min, None);
|
||||
assert_eq!(a.max, Some(50.0));
|
||||
assert_eq!(a.fmt.as_deref().map(|f| f.chars().count()), Some(MAX_FMT));
|
||||
|
||||
// min not under max drops the pair; a format of only spaces is no format.
|
||||
let mut b = ChartAxis { min: Some(50.0), max: Some(50.0), fmt: Some(" ".into()), ..Default::default() };
|
||||
b.sanitize();
|
||||
assert_eq!((b.min, b.max), (None, None));
|
||||
assert_eq!(b.fmt, None);
|
||||
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], ..Default::default() }],
|
||||
categories: vec!["a".into()],
|
||||
..Default::default()
|
||||
};
|
||||
spec.series[0].line_w = Some(f32::NAN);
|
||||
spec.series[0].fmt = Some("0.00".into());
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, None);
|
||||
assert_eq!(spec.series[0].fmt.as_deref(), Some("0.00"));
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![], line_w: Some(100.0), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,8 +270,11 @@ 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;
|
||||
/// A rounded rectangle's corner radius without its own: a sixth of the shorter side, the preset's
|
||||
/// default `adj` of 16667 (ECMA-376 §20.1.10.56). Measured in Word for Windows: a 300 × 100 pt
|
||||
/// rounded rectangle without `adj` is drawn with corners of 16.67 pt, a 300 × 40 pt one of 6.67
|
||||
/// pt and a 60 × 150 pt one of 10 pt.
|
||||
pub const DEFAULT_CORNER: f32 = 16_667.0 / 100_000.0;
|
||||
|
||||
/// The corner radius, in points, of a `w` × `h` rounded rectangle with `corner` (see
|
||||
/// [`ShapeExtra::corner`]).
|
||||
@@ -521,7 +524,10 @@ 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(None, 200.0, 100.0), 16.667));
|
||||
assert!(near(corner_radius(None, 300.0, 40.0), 6.6668));
|
||||
assert!(near(corner_radius(None, 60.0, 150.0), 10.0002));
|
||||
assert!(near(corner_radius(None, 200.0, 100.0), corner_radius(Some(16_667), 200.0, 100.0)), "the preset's default");
|
||||
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));
|
||||
|
||||
+16
-1
@@ -727,9 +727,16 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Split the paragraph at `pos`; returns the start of the new (second) paragraph.
|
||||
///
|
||||
/// A split after the first letters leaves the drop cap on the first paragraph only: the new
|
||||
/// one is plain (Word: Enter makes a normal paragraph). A split at offset 0 is unchanged.
|
||||
/// A drop cap that comes from a paragraph style, not the paragraph, is not cleared.
|
||||
pub fn split_paragraph(&mut self, pos: &Pos) -> Result<Pos> {
|
||||
let i = pos.path.last();
|
||||
let tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?;
|
||||
let mut tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?;
|
||||
if pos.off > 0 {
|
||||
clear_drop_cap(&mut tail.props);
|
||||
}
|
||||
let bl = self.container_mut(pos.story, &pos.path)?;
|
||||
bl.insert((i + 1).min(bl.len()), para_block(tail));
|
||||
Ok(Pos { story: pos.story, path: pos.path.with_last(i + 1), off: 0 })
|
||||
@@ -1599,5 +1606,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the drop cap (and its options) off a paragraph's properties.
|
||||
fn clear_drop_cap(props: &mut crate::props::ParaProps) {
|
||||
props.drop_cap = None;
|
||||
props.drop_cap_margin = None;
|
||||
props.drop_cap_distance = None;
|
||||
props.drop_cap_font = None;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -988,3 +988,38 @@ fn insert_fragment_remaps_conflicting_media_keys() {
|
||||
let remapped = para.objects.iter().find_map(|o| if let InlineObject::Image { media, .. } = o { Some(media.as_str()) } else { None }).unwrap();
|
||||
assert_eq!(remapped, other_key);
|
||||
}
|
||||
|
||||
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
|
||||
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
|
||||
#[test]
|
||||
fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
|
||||
let drop_cap = |d: &Document, i: usize| {
|
||||
let p = d.body.get(i).and_then(|b| b.as_para()).map(|p| p.props.clone()).unwrap_or_default();
|
||||
(p.drop_cap, p.drop_cap_margin, p.drop_cap_distance, p.drop_cap_font)
|
||||
};
|
||||
let capped = |text: &str| {
|
||||
let mut d = doc(&[text]);
|
||||
if let Ok(p) = d.para_mut(StoryRef::Body, &Path::top(0)) {
|
||||
p.props.drop_cap = Some(3);
|
||||
p.props.drop_cap_margin = Some(true);
|
||||
p.props.drop_cap_distance = Some(4.0);
|
||||
p.props.drop_cap_font = Some("Serif".into());
|
||||
}
|
||||
d
|
||||
};
|
||||
let cap = (Some(3), Some(true), Some(4.0), Some("Serif".to_string()));
|
||||
let plain = (None, None, None, None);
|
||||
|
||||
let mut d = capped("Sugar and knowledge");
|
||||
d.split_paragraph(&Pos::body(0, 10)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone()));
|
||||
|
||||
let mut d = capped("Sugar");
|
||||
d.split_paragraph(&Pos::body(0, 5)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone()));
|
||||
|
||||
// At offset 0 nothing changes: both paragraphs keep the properties, as before.
|
||||
let mut d = capped("Sugar");
|
||||
d.split_paragraph(&Pos::body(0, 0)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
|
||||
}
|
||||
|
||||
@@ -127,6 +127,10 @@ pub enum GraphicItem {
|
||||
align: TextAlign,
|
||||
#[serde(default)]
|
||||
font: Option<String>,
|
||||
/// Degrees clockwise the text turns about `rect`'s center as it is drawn (a chart's vertical
|
||||
/// axis title is turned -90°).
|
||||
#[serde(default)]
|
||||
angle: f32,
|
||||
},
|
||||
/// A picture (`Document::media` key) stretched into `rect`.
|
||||
Image { rect: [f32; 4], media: String },
|
||||
|
||||
@@ -94,8 +94,8 @@ pub use settings::{
|
||||
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
|
||||
THEME_COLORS, Watermark, Zoom, ZoomFit,
|
||||
};
|
||||
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
|
||||
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
|
||||
pub(crate) use text_walk::walk_between;
|
||||
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
|
||||
|
||||
/// A document.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -610,11 +610,12 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
}
|
||||
MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => {
|
||||
s.push(*chr);
|
||||
if !sub_hide && !sub.is_empty() {
|
||||
// A shown limit is written even when empty (`_()`): left out, it reads back hidden (#6076).
|
||||
if !sub_hide {
|
||||
s.push('_');
|
||||
lin_script(sub, s, depth);
|
||||
}
|
||||
if !sup_hide && !sup.is_empty() {
|
||||
if !sup_hide {
|
||||
s.push('^');
|
||||
lin_script(sup, s, depth);
|
||||
}
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct Settings {
|
||||
pub default_tab: f32,
|
||||
pub even_odd_headers: bool,
|
||||
pub mirror_margins: bool,
|
||||
/// The gutter is added to the top margin instead of the left one (`w:gutterAtTop`).
|
||||
pub gutter_at_top: bool,
|
||||
pub auto_hyphenation: bool,
|
||||
/// Hyphenation zone (`w:hyphenationZone`), points: a line is hyphenated only when breaking
|
||||
/// it at a word boundary would leave more than this empty at its end.
|
||||
@@ -137,6 +139,12 @@ pub struct Settings {
|
||||
/// 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,
|
||||
/// `w:doNotSuppressIndentation` (a `.doc`'s `Copts.fWW11IndentRules`): Word 2003's indent
|
||||
/// rules beside floating objects. An unnumbered paragraph's line starts right after a floating
|
||||
/// object before it on the line, its own indent ignored (ECMA-376 Part 4 §14.8.3.12). Word 2013's
|
||||
/// layout (compatibility mode 15) does not use it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub do_not_suppress_indentation: 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,
|
||||
@@ -296,6 +304,7 @@ impl Default for Settings {
|
||||
default_tab: 36.0,
|
||||
even_odd_headers: false,
|
||||
mirror_margins: false,
|
||||
gutter_at_top: false,
|
||||
auto_hyphenation: false,
|
||||
hyphenation_zone: DEFAULT_HYPHENATION_ZONE,
|
||||
hyphenate_caps: true,
|
||||
@@ -319,6 +328,7 @@ impl Default for Settings {
|
||||
sum_paragraph_spacing: false,
|
||||
do_not_expand_shift_return: false,
|
||||
allow_space_of_same_style_in_table: false,
|
||||
do_not_suppress_indentation: false,
|
||||
grid_h: DEFAULT_GRID,
|
||||
grid_v: DEFAULT_GRID,
|
||||
math: None,
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
|
||||
}
|
||||
|
||||
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
|
||||
pub(crate) const PARA_WALK_DEPTH: usize = 16;
|
||||
pub const PARA_WALK_DEPTH: usize = 16;
|
||||
|
||||
/// The note and text box stories an object shows, for `Document::reachable`.
|
||||
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
|
||||
|
||||
@@ -265,10 +265,10 @@ mod tests {
|
||||
}
|
||||
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.
|
||||
// a sixth of the height (8.33 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));
|
||||
assert!((corner_pt(None).0 - 0.916_67).abs() < 0.0001, "{:?}", corner_pt(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//! An n-ary operator's empty but shown limit survives linear text (#6076): half-typed `∑_` has an
|
||||
//! empty lower limit that is shown, and `to_linear` writes it as `_()`. Left out, it reads back as a
|
||||
//! hidden limit.
|
||||
|
||||
use wordcraft_doc::math::{MNode, MRun, parse_linear, to_linear};
|
||||
|
||||
#[test]
|
||||
fn an_empty_shown_limit_prints_back_the_same() {
|
||||
for s in ["∑_", "∑^", "∫_0^▒x", "∑_()^n▒i"] {
|
||||
let n = parse_linear(s);
|
||||
assert_eq!(parse_linear(&to_linear(&n)), n, "{s} → {}", to_linear(&n));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_filled_limits_print_as_before() {
|
||||
let nary = |sub_hide, sup_hide, sub: &str, sup: &str| {
|
||||
let arg = |t: &str| if t.is_empty() { Vec::new() } else { vec![MNode::Run(MRun::new(t))] };
|
||||
vec![MNode::Nary { chr: '∑', lim_loc: None, grow: false, sub_hide, sup_hide, sub: arg(sub), sup: arg(sup), e: arg("x") }]
|
||||
};
|
||||
assert_eq!(to_linear(&nary(true, true, "", "")), "∑▒x");
|
||||
assert_eq!(to_linear(&nary(false, false, "i", "n")), "∑_i^n▒x");
|
||||
assert_eq!(to_linear(&nary(false, true, "", "")), "∑_()▒x");
|
||||
}
|
||||
@@ -12,16 +12,16 @@ workspace = true
|
||||
craft-docx = { workspace = true }
|
||||
craft-wordmodel = { workspace = true }
|
||||
wordcraft-doc = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-doc = { workspace = true, features = ["test-support"] }
|
||||
wordcraft-geom = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
base64 = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
log = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
image = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
|
||||
+7
-29
@@ -19,40 +19,18 @@ pub(crate) const KIND: &str = "wordcraft-fit-v1";
|
||||
/// Serialize `fit` as the custom XML store.
|
||||
pub(crate) fn write(fit: &FitState) -> Result<Vec<u8>, DocxError> {
|
||||
let json = serde_json::to_string(fit).map_err(|e| DocxError::Xml(e.to_string()))?;
|
||||
let esc_json = quick_xml::escape::escape(&json);
|
||||
Ok(format!(r#"<?xml version="1.0" encoding="UTF-8"?><{ROOT} xmlns="{NS}" kind="{KIND}"><fitState>{}</fitState></{ROOT}>"#, esc_json)
|
||||
.into_bytes())
|
||||
let esc_json = craft_xml::esc(&json);
|
||||
Ok(format!(r#"<?xml version="1.0" encoding="UTF-8"?><{ROOT} xmlns="{NS}" kind="{KIND}"><fitState>{}</fitState></{ROOT}>"#, esc_json).into_bytes())
|
||||
}
|
||||
|
||||
/// Read the state from a custom XML part's bytes, if it is ours.
|
||||
pub(crate) fn read_from_bytes(bytes: &[u8]) -> Option<FitState> {
|
||||
let mut reader = quick_xml::Reader::from_reader(bytes);
|
||||
let mut buf = Vec::new();
|
||||
let mut is_our_kind = false;
|
||||
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Ok(quick_xml::events::Event::Start(ref e)) => {
|
||||
let name = e.local_name();
|
||||
if name.as_ref() == ROOT.as_bytes() {
|
||||
for attr in e.attributes().flatten() {
|
||||
if attr.key.local_name().as_ref() == b"kind" && attr.value.as_ref() == KIND.as_bytes() {
|
||||
is_our_kind = true;
|
||||
}
|
||||
}
|
||||
} else if name.as_ref() == b"fitState" && is_our_kind {
|
||||
let text = reader.read_text(e.to_end().name()).ok()?;
|
||||
let s = std::str::from_utf8(text.as_ref()).ok()?;
|
||||
let unescaped = quick_xml::escape::unescape(s).ok()?;
|
||||
return serde_json::from_str(&unescaped).ok();
|
||||
}
|
||||
}
|
||||
Ok(quick_xml::events::Event::Eof) | Err(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
buf.clear();
|
||||
let root = craft_xml::parse(bytes).ok()?;
|
||||
if root.local() != ROOT || root.attr("kind") != Some(KIND) {
|
||||
return None;
|
||||
}
|
||||
None
|
||||
let text = root.child_text("fitState")?;
|
||||
serde_json::from_str(text.as_ref()).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+25
-30
@@ -8,10 +8,9 @@ mod fit;
|
||||
mod model_bridge;
|
||||
|
||||
pub use craft_docx::{
|
||||
DEFAULT_SPIN_COUNT, DocxError, EmbeddedFont, Flavor, MAX_PASSWORD_CHARS, MAX_SOURCES,
|
||||
MAX_XML_FILE, PASSWORD_REQUIRED, PasswordCheck, WRONG_PASSWORD, XmlKind, check_password,
|
||||
check_protection_password, encrypt, encrypt_standard_for_tests,
|
||||
encrypt_with_spin_count, package_title, protection_hash, sniff_xml,
|
||||
DEFAULT_SPIN_COUNT, DocxError, EmbeddedFont, Flavor, MAX_PASSWORD_CHARS, MAX_SOURCES, MAX_XML_FILE, PASSWORD_REQUIRED, PasswordCheck,
|
||||
WRONG_PASSWORD, XmlKind, check_password, check_protection_password, encrypt, encrypt_standard_for_tests, encrypt_with_spin_count, package_title,
|
||||
protection_hash, sniff_xml,
|
||||
};
|
||||
|
||||
pub fn decrypt(bytes: &[u8], password: Option<&str>) -> Result<Vec<u8>, DocxError> {
|
||||
@@ -56,19 +55,13 @@ pub fn read_with_password(bytes: &[u8], password: Option<&str>) -> Result<wordcr
|
||||
pub fn read_with(bytes: &[u8], opts: &ReadOptions) -> Result<wordcraft_doc::Document, DocxError> {
|
||||
let bridge_importer = |shared_chunk: &craft_docx::AltChunk| -> Option<craft_wordmodel::Document> {
|
||||
let importer = opts.chunks?;
|
||||
let chunk = AltChunk {
|
||||
content_type: shared_chunk.content_type,
|
||||
part: shared_chunk.part,
|
||||
bytes: shared_chunk.bytes,
|
||||
};
|
||||
let chunk = AltChunk { content_type: shared_chunk.content_type, part: shared_chunk.part, bytes: shared_chunk.bytes };
|
||||
let doc = importer(&chunk)?;
|
||||
to_shared_model(&doc).ok()
|
||||
};
|
||||
|
||||
let shared_opts = craft_docx::ReadOptions {
|
||||
password: opts.password,
|
||||
chunks: opts.chunks.as_ref().map(|_| &bridge_importer as craft_docx::ChunkImporter),
|
||||
};
|
||||
let shared_opts =
|
||||
craft_docx::ReadOptions { password: opts.password, chunks: opts.chunks.as_ref().map(|_| &bridge_importer as craft_docx::ChunkImporter) };
|
||||
|
||||
let shared = craft_docx::read_with(bytes, &shared_opts)?;
|
||||
from_shared_model(shared)
|
||||
@@ -105,21 +98,22 @@ pub fn write_wordml2003(doc: &wordcraft_doc::Document) -> Result<Vec<u8>, DocxEr
|
||||
}
|
||||
|
||||
/// Draw a chart.
|
||||
pub fn chart_items(
|
||||
spec: &wordcraft_doc::chart::ChartSpec,
|
||||
theme: &[wordcraft_doc::Rgb],
|
||||
w: f32,
|
||||
h: f32,
|
||||
) -> Vec<wordcraft_doc::graphic::GraphicItem> {
|
||||
let shared_spec: craft_wordmodel::chart::ChartSpec = model_bridge::convert_ref(spec).expect("chart spec convert");
|
||||
let shared_theme: Vec<craft_wordmodel::props::Rgb> = model_bridge::convert_ref(theme).expect("theme convert");
|
||||
pub fn chart_items(spec: &wordcraft_doc::chart::ChartSpec, theme: &[wordcraft_doc::Rgb], w: f32, h: f32) -> Vec<wordcraft_doc::graphic::GraphicItem> {
|
||||
let (Ok(shared_spec), Ok(shared_theme)) = (
|
||||
model_bridge::convert_ref::<_, craft_wordmodel::chart::ChartSpec>(spec),
|
||||
model_bridge::convert_ref::<_, Vec<craft_wordmodel::props::Rgb>>(theme),
|
||||
) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let shared_items = craft_docx::chart_items(&shared_spec, &shared_theme, w, h);
|
||||
model_bridge::convert(shared_items).expect("chart items convert")
|
||||
model_bridge::convert(shared_items).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Write a chart part.
|
||||
pub fn chart_xml(spec: &wordcraft_doc::chart::ChartSpec) -> Vec<u8> {
|
||||
let shared_spec: craft_wordmodel::chart::ChartSpec = model_bridge::convert_ref(spec).expect("chart spec convert");
|
||||
let Ok(shared_spec) = model_bridge::convert_ref(spec) else {
|
||||
return Vec::new();
|
||||
};
|
||||
craft_docx::chart_xml(&shared_spec).into_bytes()
|
||||
}
|
||||
|
||||
@@ -130,19 +124,20 @@ pub fn smart_art_items(
|
||||
w: f32,
|
||||
h: f32,
|
||||
) -> Vec<wordcraft_doc::graphic::GraphicItem> {
|
||||
let shared_spec: craft_wordmodel::smart_art::SmartArtSpec = model_bridge::convert_ref(spec).expect("smart art spec convert");
|
||||
let shared_theme: Vec<craft_wordmodel::props::Rgb> = model_bridge::convert_ref(theme).expect("theme convert");
|
||||
let (Ok(shared_spec), Ok(shared_theme)) = (
|
||||
model_bridge::convert_ref::<_, craft_wordmodel::smart_art::SmartArtSpec>(spec),
|
||||
model_bridge::convert_ref::<_, Vec<craft_wordmodel::props::Rgb>>(theme),
|
||||
) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let shared_items = craft_docx::smart_art_items(&shared_spec, &shared_theme, w, h);
|
||||
model_bridge::convert(shared_items).expect("smart art items convert")
|
||||
model_bridge::convert(shared_items).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Read bibliography sources from a `b:Sources` file.
|
||||
pub fn read_sources(bytes: &[u8]) -> Result<Sources, DocxError> {
|
||||
let shared = craft_docx::read_sources(bytes)?;
|
||||
Ok(Sources {
|
||||
sources: model_bridge::convert(shared.sources).map_err(|e| DocxError::Xml(e.to_string()))?,
|
||||
style: shared.style,
|
||||
})
|
||||
Ok(Sources { sources: model_bridge::convert(shared.sources).map_err(|e| DocxError::Xml(e.to_string()))?, style: shared.style })
|
||||
}
|
||||
|
||||
/// The font files embedded in the document's font table.
|
||||
|
||||
+195
-72
@@ -1,5 +1,6 @@
|
||||
//! Bounded conversion between craft-wordmodel and WordCraft's document model.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_docx::DocxError;
|
||||
@@ -29,24 +30,29 @@ where
|
||||
// From Shared Model -> WordCraft Document
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn blocks_from_shared(source: craft_wordmodel::Blocks) -> Result<wordcraft_doc::Blocks, DocxError> {
|
||||
type GraphicCache = HashMap<usize, Arc<wordcraft_doc::graphic::Graphic>>;
|
||||
|
||||
fn blocks_from_shared(source: craft_wordmodel::Blocks, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Blocks, DocxError> {
|
||||
source
|
||||
.into_iter()
|
||||
.map(|block| {
|
||||
let block = Arc::try_unwrap(block).unwrap_or_else(|shared| (*shared).clone());
|
||||
block_value_from_shared(block).map(Arc::new)
|
||||
block_value_from_shared(block, graphics).map(Arc::new)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn block_value_from_shared(source: craft_wordmodel::Block) -> Result<wordcraft_doc::Block, DocxError> {
|
||||
fn block_value_from_shared(source: craft_wordmodel::Block, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Block, DocxError> {
|
||||
match source {
|
||||
craft_wordmodel::Block::Para(paragraph) => paragraph_value_from_shared(paragraph).map(wordcraft_doc::Block::Para),
|
||||
craft_wordmodel::Block::Table(table) => table_value_from_shared(table).map(wordcraft_doc::Block::Table),
|
||||
craft_wordmodel::Block::Para(paragraph) => paragraph_value_from_shared(paragraph, graphics).map(wordcraft_doc::Block::Para),
|
||||
craft_wordmodel::Block::Table(table) => table_value_from_shared(table, graphics).map(wordcraft_doc::Block::Table),
|
||||
}
|
||||
}
|
||||
|
||||
fn paragraph_value_from_shared(source: craft_wordmodel::para::Paragraph) -> Result<wordcraft_doc::para::Paragraph, DocxError> {
|
||||
fn paragraph_value_from_shared(
|
||||
source: craft_wordmodel::para::Paragraph,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::Paragraph, DocxError> {
|
||||
let craft_wordmodel::para::Paragraph { text, runs, props, mark, objects, section, .. } = source;
|
||||
let mut paragraph = wordcraft_doc::para::Paragraph::new();
|
||||
paragraph.text = text;
|
||||
@@ -54,26 +60,20 @@ fn paragraph_value_from_shared(source: craft_wordmodel::para::Paragraph) -> Resu
|
||||
runs.into_iter().map(|run| Ok(wordcraft_doc::para::Run { len: run.len, props: convert(run.props)? })).collect::<Result<_, DocxError>>()?;
|
||||
paragraph.props = convert(props)?;
|
||||
paragraph.mark = convert(mark)?;
|
||||
paragraph.objects = objects.into_iter().map(object_value_from_shared).collect::<Result<_, _>>()?;
|
||||
paragraph.objects = objects.into_iter().map(|o| object_value_from_shared(o, graphics)).collect::<Result<_, _>>()?;
|
||||
paragraph.section = section.map(|section| convert(*section).map(Box::new)).transpose()?;
|
||||
Ok(paragraph)
|
||||
}
|
||||
|
||||
fn object_value_from_shared(source: craft_wordmodel::para::InlineObject) -> Result<wordcraft_doc::para::InlineObject, DocxError> {
|
||||
fn object_value_from_shared(
|
||||
source: craft_wordmodel::para::InlineObject,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::InlineObject, DocxError> {
|
||||
use craft_wordmodel::para::InlineObject as Source;
|
||||
use wordcraft_doc::para::InlineObject as Target;
|
||||
|
||||
match source {
|
||||
Source::Image {
|
||||
media,
|
||||
w,
|
||||
h,
|
||||
alt,
|
||||
float,
|
||||
crop,
|
||||
fx,
|
||||
ole,
|
||||
} => Ok(Target::Image {
|
||||
Source::Image { media, w, h, alt, float, crop, fx, ole } => Ok(Target::Image {
|
||||
media,
|
||||
w,
|
||||
h,
|
||||
@@ -83,49 +83,79 @@ fn object_value_from_shared(source: craft_wordmodel::para::InlineObject) -> Resu
|
||||
fx: convert(fx)?,
|
||||
ole: ole.map(|o| convert(Arc::try_unwrap(o).unwrap_or_else(|s| (*s).clone())).map(Arc::new)).transpose()?,
|
||||
}),
|
||||
Source::Graphic { w, h, alt, float, graphic } => {
|
||||
let key = Arc::as_ptr(&graphic) as usize;
|
||||
let graphic = if let Some(cached) = graphics.get(&key) {
|
||||
Arc::clone(cached)
|
||||
} else {
|
||||
let converted: Arc<wordcraft_doc::graphic::Graphic> = Arc::new(convert(Arc::try_unwrap(graphic).unwrap_or_else(|s| (*s).clone()))?);
|
||||
graphics.insert(key, Arc::clone(&converted));
|
||||
converted
|
||||
};
|
||||
Ok(Target::Graphic { w, h, alt, float: convert(float)?, graphic })
|
||||
}
|
||||
// This model has no picture frame shape: DrawingML's `frame` preset is read as a
|
||||
// rectangle, without the frame's border width.
|
||||
mut shape @ Source::Shape { kind: craft_wordmodel::para::ShapeKind::Frame, .. } => {
|
||||
if let Source::Shape { kind, extra, .. } = &mut shape {
|
||||
*kind = craft_wordmodel::para::ShapeKind::Rectangle;
|
||||
extra.corner = None;
|
||||
}
|
||||
convert(shape)
|
||||
}
|
||||
Source::Group { w, h, float, ch_w, ch_h, children, canvas } => Ok(Target::Group {
|
||||
w,
|
||||
h,
|
||||
float: convert(float)?,
|
||||
ch_w,
|
||||
ch_h,
|
||||
children: children.into_iter().map(group_child_value_from_shared).collect::<Result<_, _>>()?,
|
||||
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
canvas: canvas.map(convert).transpose()?,
|
||||
}),
|
||||
other => convert(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn group_child_value_from_shared(source: craft_wordmodel::para::GroupChild) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj)? })
|
||||
fn group_child_value_from_shared(
|
||||
source: craft_wordmodel::para::GroupChild,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
|
||||
}
|
||||
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
Ok(wordcraft_doc::table::Table {
|
||||
props: convert(source.props)?,
|
||||
grid: source.grid,
|
||||
rows: source.rows.into_iter().map(row_value_from_shared).collect::<Result<_, _>>()?,
|
||||
rows: source.rows.into_iter().map(|r| row_value_from_shared(r, graphics)).collect::<Result<_, _>>()?,
|
||||
controls: convert(source.controls)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn row_value_from_shared(source: craft_wordmodel::table::Row) -> Result<wordcraft_doc::table::Row, DocxError> {
|
||||
fn row_value_from_shared(source: craft_wordmodel::table::Row, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Row, DocxError> {
|
||||
Ok(wordcraft_doc::table::Row {
|
||||
props: convert(source.props)?,
|
||||
cells: source.cells.into_iter().map(cell_value_from_shared).collect::<Result<_, _>>()?,
|
||||
cells: source.cells.into_iter().map(|c| cell_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
controls: convert(source.controls)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_value_from_shared(source: craft_wordmodel::table::Cell) -> Result<wordcraft_doc::table::Cell, DocxError> {
|
||||
Ok(wordcraft_doc::table::Cell { props: convert(source.props)?, blocks: blocks_from_shared(source.blocks)?, controls: convert(source.controls)? })
|
||||
fn cell_value_from_shared(source: craft_wordmodel::table::Cell, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Cell, DocxError> {
|
||||
Ok(wordcraft_doc::table::Cell {
|
||||
props: convert(source.props)?,
|
||||
blocks: blocks_from_shared(source.blocks, graphics)?,
|
||||
controls: convert(source.controls)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn part_value_from_shared(source: craft_wordmodel::Part) -> Result<wordcraft_doc::Part, DocxError> {
|
||||
Ok(wordcraft_doc::Part { kind: convert(source.kind)?, blocks: blocks_from_shared(source.blocks)?, body: convert(source.body)? })
|
||||
fn part_value_from_shared(source: craft_wordmodel::Part, graphics: &mut GraphicCache) -> Result<wordcraft_doc::Part, DocxError> {
|
||||
Ok(wordcraft_doc::Part { kind: convert(source.kind)?, blocks: blocks_from_shared(source.blocks, graphics)?, body: convert(source.body)? })
|
||||
}
|
||||
|
||||
fn glossary_value_from_shared(source: craft_wordmodel::BuildingBlock) -> Result<wordcraft_doc::BuildingBlock, DocxError> {
|
||||
fn glossary_value_from_shared(
|
||||
source: craft_wordmodel::BuildingBlock,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::BuildingBlock, DocxError> {
|
||||
Ok(wordcraft_doc::BuildingBlock {
|
||||
name: source.name,
|
||||
gallery: source.gallery,
|
||||
@@ -135,7 +165,7 @@ fn glossary_value_from_shared(source: craft_wordmodel::BuildingBlock) -> Result<
|
||||
style: source.style,
|
||||
types: source.types,
|
||||
behaviors: source.behaviors,
|
||||
blocks: blocks_from_shared(source.blocks)?,
|
||||
blocks: blocks_from_shared(source.blocks, graphics)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -147,7 +177,7 @@ fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Res
|
||||
target.part_names = source.part_names;
|
||||
target.media_parts = source.media_parts;
|
||||
for item in source.list {
|
||||
target.push(convert(item)?);
|
||||
target.list.push(convert(item)?);
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
@@ -156,13 +186,12 @@ fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Res
|
||||
pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcraft_doc::Document, DocxError> {
|
||||
let mut fit_state = None;
|
||||
let fit_key = source.passthrough.keys().find(|k| k.eq_ignore_ascii_case(crate::fit::PART)).cloned();
|
||||
if let Some(key) = fit_key {
|
||||
if let Some(xml_bytes) = source.passthrough.get(&key) {
|
||||
if let Some(state) = crate::fit::read_from_bytes(xml_bytes) {
|
||||
fit_state = Some(state);
|
||||
source.passthrough.remove(&key);
|
||||
}
|
||||
}
|
||||
if let Some(key) = fit_key
|
||||
&& let Some(xml_bytes) = source.passthrough.get(&key)
|
||||
&& let Some(state) = crate::fit::read_from_bytes(xml_bytes)
|
||||
{
|
||||
fit_state = Some(state);
|
||||
source.passthrough.remove(&key);
|
||||
}
|
||||
|
||||
let craft_wordmodel::Document {
|
||||
@@ -186,10 +215,11 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
..
|
||||
} = source;
|
||||
|
||||
let mut graphics = GraphicCache::new();
|
||||
let mut document = wordcraft_doc::Document::new();
|
||||
document.body = blocks_from_shared(body)?;
|
||||
document.body = blocks_from_shared(body, &mut graphics)?;
|
||||
document.last_section = convert(last_section)?;
|
||||
document.parts = parts.into_iter().map(|(id, part)| Ok((id, part_value_from_shared(part)?))).collect::<Result<_, DocxError>>()?;
|
||||
document.parts = parts.into_iter().map(|(id, part)| Ok((id, part_value_from_shared(part, &mut graphics)?))).collect::<Result<_, DocxError>>()?;
|
||||
document.styles = Arc::new(convert((*styles).clone())?);
|
||||
document.numbering = Arc::new(convert((*numbering).clone())?);
|
||||
document.comments = convert(comments)?;
|
||||
@@ -202,7 +232,7 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
document.endnote_separators = convert(endnote_separators)?;
|
||||
document.media = media;
|
||||
document.passthrough = passthrough;
|
||||
document.glossary = glossary.into_iter().map(glossary_value_from_shared).collect::<Result<_, _>>()?;
|
||||
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
|
||||
document.missing_pictures = missing_pictures_from_shared(missing_pictures)?;
|
||||
document.fit_state = fit_state;
|
||||
Ok(document)
|
||||
@@ -235,17 +265,24 @@ fn sanitize_para_props(mut props: wordcraft_doc::ParaProps) -> wordcraft_doc::Pa
|
||||
wordcraft_doc::props::LineSpacing::AtLeast(v) => *v = finite(*v),
|
||||
}
|
||||
}
|
||||
if let Some(v) = &mut props.indent_left { if !v.is_finite() { *v = 0.0; } }
|
||||
if let Some(v) = &mut props.indent_right { if !v.is_finite() { *v = 0.0; } }
|
||||
if let Some(v) = &mut props.indent_first { if !v.is_finite() { *v = 0.0; } }
|
||||
if let Some(v) = &mut props.space_before { if !v.is_finite() { *v = 0.0; } }
|
||||
if let Some(v) = &mut props.space_after { if !v.is_finite() { *v = 0.0; } }
|
||||
for field in [&mut props.indent_left, &mut props.indent_right, &mut props.indent_first, &mut props.space_before, &mut props.space_after] {
|
||||
if let Some(v) = field
|
||||
&& !v.is_finite()
|
||||
{
|
||||
*v = 0.0;
|
||||
}
|
||||
}
|
||||
props
|
||||
}
|
||||
|
||||
fn sanitize_char_props(mut props: wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
|
||||
if let Some(v) = &mut props.size { if !v.is_finite() { *v = 0.0; } }
|
||||
if let Some(v) = &mut props.spacing { if !v.is_finite() { *v = 0.0; } }
|
||||
for field in [&mut props.size, &mut props.spacing] {
|
||||
if let Some(v) = field
|
||||
&& !v.is_finite()
|
||||
{
|
||||
*v = 0.0;
|
||||
}
|
||||
}
|
||||
props
|
||||
}
|
||||
|
||||
@@ -265,31 +302,17 @@ fn paragraph_value_to_shared(source: &wordcraft_doc::para::Paragraph) -> Result<
|
||||
}
|
||||
|
||||
fn object_value_to_shared(source: &wordcraft_doc::para::InlineObject) -> Result<craft_wordmodel::para::InlineObject, DocxError> {
|
||||
use wordcraft_doc::para::InlineObject as Source;
|
||||
use craft_wordmodel::para::InlineObject as Target;
|
||||
use wordcraft_doc::para::InlineObject as Source;
|
||||
|
||||
match source {
|
||||
Source::Image {
|
||||
media,
|
||||
w,
|
||||
h,
|
||||
alt,
|
||||
float,
|
||||
crop,
|
||||
fx,
|
||||
ole,
|
||||
} => Ok(Target::Image {
|
||||
Source::Image { media, w, h, alt, float, crop, fx, ole } => Ok(Target::Image {
|
||||
media: media.clone(),
|
||||
w: finite(*w),
|
||||
h: finite(*h),
|
||||
alt: alt.clone(),
|
||||
float: convert_ref(float)?,
|
||||
crop: [
|
||||
finite(crop[0]),
|
||||
finite(crop[1]),
|
||||
finite(crop[2]),
|
||||
finite(crop[3]),
|
||||
],
|
||||
crop: [finite(crop[0]), finite(crop[1]), finite(crop[2]), finite(crop[3])],
|
||||
fx: convert_ref(fx)?,
|
||||
ole: ole.as_ref().map(|o| convert_ref(o.as_ref()).map(Arc::new)).transpose()?,
|
||||
}),
|
||||
@@ -336,11 +359,7 @@ fn cell_value_to_shared(source: &wordcraft_doc::table::Cell) -> Result<craft_wor
|
||||
}
|
||||
|
||||
fn part_value_to_shared(source: &wordcraft_doc::Part) -> Result<craft_wordmodel::Part, DocxError> {
|
||||
Ok(craft_wordmodel::Part {
|
||||
kind: convert_ref(&source.kind)?,
|
||||
blocks: blocks_to_shared(&source.blocks)?,
|
||||
body: convert_ref(&source.body)?,
|
||||
})
|
||||
Ok(craft_wordmodel::Part { kind: convert_ref(&source.kind)?, blocks: blocks_to_shared(&source.blocks)?, body: convert_ref(&source.body)? })
|
||||
}
|
||||
|
||||
fn glossary_value_to_shared(source: &wordcraft_doc::BuildingBlock) -> Result<craft_wordmodel::BuildingBlock, DocxError> {
|
||||
@@ -365,7 +384,7 @@ fn missing_pictures_to_shared(source: &wordcraft_doc::MissingPictures) -> Result
|
||||
target.part_names = source.part_names.clone();
|
||||
target.media_parts = source.media_parts.clone();
|
||||
for item in &source.list {
|
||||
target.push(convert_ref(item)?);
|
||||
target.list.push(convert_ref(item)?);
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
@@ -432,6 +451,110 @@ pub fn to_shared_model(source: &wordcraft_doc::Document) -> Result<craft_wordmod
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn doc_with(objects: Vec<craft_wordmodel::para::InlineObject>) -> craft_wordmodel::Document {
|
||||
let mut source = craft_wordmodel::Document::new();
|
||||
let mut para = craft_wordmodel::para::Paragraph::new();
|
||||
para.objects = objects;
|
||||
source.body = vec![Arc::new(craft_wordmodel::Block::Para(para))];
|
||||
source
|
||||
}
|
||||
|
||||
fn objects(doc: &wordcraft_doc::Document) -> Vec<wordcraft_doc::para::InlineObject> {
|
||||
doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn chart_object(spec: craft_wordmodel::chart::ChartSpec) -> craft_wordmodel::para::InlineObject {
|
||||
let graphic = craft_wordmodel::graphic::Graphic { chart: Some(Arc::new(spec)), ..Default::default() };
|
||||
craft_wordmodel::para::InlineObject::Graphic { w: 100.0, h: 60.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }
|
||||
}
|
||||
|
||||
fn charts(doc: &wordcraft_doc::Document) -> Vec<Option<wordcraft_doc::chart::ChartSpec>> {
|
||||
objects(doc)
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
wordcraft_doc::para::InlineObject::Graphic { graphic, .. } => Some(graphic.chart.as_deref().cloned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A picture frame shape opens as a rectangle instead of failing the whole document.
|
||||
#[test]
|
||||
fn a_frame_shape_reads_as_a_rectangle() {
|
||||
let shape = |kind| craft_wordmodel::para::InlineObject::Shape {
|
||||
kind,
|
||||
w: 40.0,
|
||||
h: 30.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: Default::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: craft_wordmodel::connector::ShapeExtra { corner: Some(2604), ..Default::default() },
|
||||
};
|
||||
let doc = from_shared_model(doc_with(vec![shape(craft_wordmodel::para::ShapeKind::Frame)])).expect("from_shared_model");
|
||||
let found = objects(&doc);
|
||||
let [wordcraft_doc::para::InlineObject::Shape { kind, w, extra, .. }] = found.as_slice() else { panic!("{found:?}") };
|
||||
assert_eq!((*kind, *w, extra.corner), (wordcraft_doc::para::ShapeKind::Rectangle, 40.0, None));
|
||||
}
|
||||
|
||||
/// A chart's series formatting and axis settings survive the trip through this model, so
|
||||
/// saving writes the chart part the reader read.
|
||||
#[test]
|
||||
fn chart_formatting_survives_the_bridge() {
|
||||
use craft_wordmodel::chart::{ChartSpec, ChartType};
|
||||
let mut formatted = ChartSpec::sample(ChartType::Line);
|
||||
formatted.series[0].fill = Some(craft_wordmodel::props::Rgb(0x12, 0x34, 0x56));
|
||||
formatted.series[0].line_w = Some(2.5);
|
||||
formatted.series[1].smooth = true;
|
||||
formatted.series[1].markers = Some(true);
|
||||
formatted.series[2].labels = Some(true);
|
||||
formatted.series[2].fmt = Some("0.0".into());
|
||||
formatted.val_axis.title = Some("Sales".into());
|
||||
formatted.val_axis.min = Some(0.0);
|
||||
formatted.cat_axis.gridlines = true;
|
||||
let mut scatter_lines = ChartSpec::sample(ChartType::Scatter);
|
||||
scatter_lines.series[0].no_line = false;
|
||||
let all = [formatted, ChartSpec::sample(ChartType::Scatter), ChartSpec::sample(ChartType::Pie), scatter_lines];
|
||||
let doc = from_shared_model(doc_with(all.iter().cloned().map(chart_object).collect())).expect("from_shared_model");
|
||||
assert!(charts(&doc).iter().all(Option::is_some));
|
||||
let back = to_shared_model(&doc).expect("to_shared_model");
|
||||
let back: Vec<ChartSpec> = back
|
||||
.body
|
||||
.first()
|
||||
.and_then(|b| b.as_para())
|
||||
.map(|p| {
|
||||
p.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
craft_wordmodel::para::InlineObject::Graphic { graphic, .. } => graphic.chart.as_deref().cloned(),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
assert_eq!(back, all);
|
||||
}
|
||||
|
||||
/// A scatter chart this model makes is written as markers without lines, the same part the
|
||||
/// shared model writes for its own new scatter chart.
|
||||
#[test]
|
||||
fn a_new_scatter_chart_is_written_without_lines() {
|
||||
let local = wordcraft_doc::chart::ChartSpec::sample(wordcraft_doc::chart::ChartType::Scatter);
|
||||
assert!(!local.series.is_empty() && local.series.iter().all(|s| s.no_line));
|
||||
assert_eq!(
|
||||
crate::chart_xml(&local),
|
||||
craft_docx::chart_xml(&craft_wordmodel::chart::ChartSpec::sample(craft_wordmodel::chart::ChartType::Scatter)).into_bytes()
|
||||
);
|
||||
for kind in wordcraft_doc::chart::ChartType::ALL {
|
||||
let local = wordcraft_doc::chart::ChartSpec::sample(kind);
|
||||
let shared: craft_wordmodel::chart::ChartSpec = convert_ref(&local).expect("convert");
|
||||
assert_eq!(shared, craft_wordmodel::chart::ChartSpec::sample(shared.kind), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridges_nested_stories_and_moves_media_both_directions() {
|
||||
let mut source = craft_wordmodel::Document::new();
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Alternative format chunks (`w:altChunk`, ECMA-376 §17.17.2.1): content in another format that
|
||||
//! is brought in where the chunk stands. All markup here is synthetic.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::{Block, Document, InlineObject, StoryRef};
|
||||
use wordcraft_docx::{AltChunk, ReadOptions, read, read_with};
|
||||
|
||||
@@ -46,12 +44,11 @@ fn package_styled(body: &str, chunk: Option<(&str, &str, &[u8])>, styles: Option
|
||||
}
|
||||
types.push_str(r#"<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#);
|
||||
files.push(("[Content_Types].xml".into(), types.into_bytes()));
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in files {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(&bytes).unwrap();
|
||||
zw.add(&name, &bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
const CHUNK: &str = r#"<w:altChunk r:id="rIdC"/>"#;
|
||||
@@ -144,12 +141,11 @@ fn package_with_stories(body: &str, stories: &[(&str, &str, String)], chunk: Opt
|
||||
if let Some(c) = chunk {
|
||||
files.push(("word/afchunk.docx".into(), c.to_vec()));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in files {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(&bytes).unwrap();
|
||||
zw.add(&name, &bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A paragraph `text` that comment `id` (in the file) is anchored around.
|
||||
@@ -395,17 +391,16 @@ fn inner_with_dropped_pictures(n: usize, external: bool) -> Vec<u8> {
|
||||
(0..n).map(image).collect::<String>()
|
||||
);
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", ROOT_RELS.as_bytes()),
|
||||
("word/document.xml", doc.as_bytes()),
|
||||
("word/_rels/document.xml.rels", rels.as_bytes()),
|
||||
] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A picture the chunk's own reader dropped is the file's too (#6005), named by the chunk part.
|
||||
|
||||
@@ -2,18 +2,15 @@
|
||||
//! complex-script font, size, bold and italic, and the bidi language. Fixtures are hand-written
|
||||
//! from ECMA-376 Part 1 §17.3.1.6 (bidi), §17.3.2 (run properties).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::{Align, CharProps, ParaProps};
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A package whose body is `body`.
|
||||
@@ -31,10 +28,9 @@ fn paras(d: &Document) -> Vec<&Paragraph> {
|
||||
|
||||
/// `word/document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Persian text with a ZWNJ (نیمفاصله), Persian digits, Latin and punctuation.
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
//! direction changes and marks the right-to-left pieces `w:rtl`, as Word does with text typed
|
||||
//! in a right-to-left paragraph.
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::props::CharProps;
|
||||
@@ -14,10 +13,9 @@ use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
/// `word/document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The runs of the first paragraph of `xml`: (has `w:rtl`, text with `w:br` as `\n`).
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! `thinThickThinLargeGap`, ECMA-376 Part 1 §17.18.2 ST_Border) on paragraphs, table cells and
|
||||
//! pages: written back as read, not as a single line. Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::BorderStyle;
|
||||
|
||||
const LINES: [(&str, BorderStyle); 9] = [
|
||||
@@ -23,19 +21,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn side(name: &str, val: &str) -> String {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
//! Original partial-cell-margin fixture (ECMA-376 §17.4.69).
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
fn fixture() -> Vec<u8> {
|
||||
let document = r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl><w:tblPr><w:tblCellMar><w:top w:w="55" w:type="dxa"/><w:left w:w="45" w:type="dxa"/><w:bottom w:w="55" w:type="dxa"/><w:right w:w="55" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="4320"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcMar><w:left w:w="0" w:type="dxa"/></w:tcMar></w:tcPr><w:p><w:r><w:t>Point</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>"#;
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(document.as_bytes()).unwrap();
|
||||
zip.finish().unwrap().into_inner()
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
zip.add("word/document.xml", document.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -19,9 +17,8 @@ fn partial_margin_stays_partial() {
|
||||
let reopened = wordcraft_docx::read(&bytes).unwrap();
|
||||
let cell = &reopened.body[0].as_table().unwrap().rows[0].cells[0];
|
||||
assert_eq!(cell.props.resolved_margins([6.0, 7.0, 8.0, 9.0]), [6.0, 0.0, 8.0, 9.0]);
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let margins = xml.split("<w:tcMar>").nth(1).unwrap().split("</w:tcMar>").next().unwrap();
|
||||
assert!(margins.contains("<w:left w:w=\"0\""));
|
||||
assert!(!margins.contains("<w:top"));
|
||||
|
||||
@@ -2,18 +2,15 @@
|
||||
//! `w:ind` `w:firstLineChars`, `w:hangingChars`, `w:leftChars` and `w:rightChars`, in hundredths
|
||||
//! of a character. Fixtures are hand-written.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::Document;
|
||||
use wordcraft_doc::props::ParaProps;
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A package whose body is `body`.
|
||||
@@ -44,9 +41,9 @@ fn character_indents_read_and_round_trip() {
|
||||
// Hostile values are clamped or dropped.
|
||||
assert_eq!((p[3].indent_first_chars, p[3].indent_left_chars), (Some(1584.0), None));
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let _z_bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for attr in [r#"w:firstLineChars="200""#, r#"w:leftChars="150""#, r#"w:rightChars="50""#, r#"w:hangingChars="100""#, r#"w:firstLineChars="0""#] {
|
||||
assert!(xml.contains(attr), "{attr} missing: {xml}");
|
||||
}
|
||||
@@ -71,9 +68,9 @@ fn automatic_spacing_reads_and_round_trips() {
|
||||
assert_eq!((rp.space_before, rp.space_after, rp.before_auto), (14.0, 14.0, true), "automatic spacing is 14 pt");
|
||||
assert_eq!(d.styles.resolve_para(&p[2]).space_after, 5.0);
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let _z_bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for attr in [r#"w:beforeAutospacing="1""#, r#"w:afterAutospacing="1""#, r#"w:beforeAutospacing="0""#] {
|
||||
assert!(xml.contains(attr), "{attr} missing");
|
||||
}
|
||||
@@ -90,9 +87,8 @@ fn adjust_right_indent_is_preserved() {
|
||||
assert_eq!(props(&d).iter().map(|p| p.adjust_right_indent).collect::<Vec<_>>(), [Some(false), Some(true), None]);
|
||||
for _ in 0..2 {
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out.clone())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:adjustRightInd w:val="0""#), "explicit false was lost: {xml}");
|
||||
assert!(xml.contains("<w:adjustRightInd/>"), "explicit true was lost: {xml}");
|
||||
let tags = ["<w:adjustRightInd", "<w:snapToGrid", "<w:spacing", "<w:ind"];
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! multi-paragraph results, and custom document properties round-trip. All markup here is
|
||||
//! synthetic, written from ECMA-376.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::{CharProps, Document, InlineObject, Path, StoryRef};
|
||||
use wordcraft_docx::{read, write};
|
||||
@@ -16,12 +14,11 @@ const CITE_B: &str = r#""citationItems":[{"id":7,"uris":["http://zotero.org/user
|
||||
const BIBL: &str = r#" ADDIN ZOTERO_BIBL {"uncited":[],"omitted":[],"custom":[]} CSL_BIBLIOGRAPHY "#;
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn fld(kind: &str) -> String {
|
||||
@@ -129,10 +126,9 @@ fn count(xml: &str, kind: &str) -> usize {
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -174,9 +170,8 @@ fn custom_property_bookmark_links_survive_saves_and_value_edits() {
|
||||
let before = d.custom_props.clone();
|
||||
for _ in 0..2 {
|
||||
let out = write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&out)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("docProps/custom.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("docProps/custom.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"linkTarget="OriginalBookmark""#), "{xml}");
|
||||
assert!(xml.contains(r#"linkTarget="RawBookmark""#), "{xml}");
|
||||
assert_eq!(xml.matches("linkTarget=").count(), 2, "unlinked properties stay unlinked");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Independent complex-script formatting through style inheritance and DOCX round trips.
|
||||
//! Synthetic packages, written here; no external documents or installed fonts are needed.
|
||||
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_doc::{Document, Paragraph, Run};
|
||||
|
||||
@@ -13,17 +12,16 @@ fn package(run: &str, defaults: &str, styles: &str, paragraph_style: &str) -> Ve
|
||||
r#"<w:document {ns}><w:body><w:p><w:pPr>{paragraph_style}<w:bidi/></w:pPr><w:r><w:rPr>{run}</w:rPr><w:t>שָׁלוֹם ABC 123</w:t></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let styles = format!("<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults>{styles}</w:styles>");
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, data) in [
|
||||
("_rels/.rels", root),
|
||||
("word/_rels/document.xml.rels", rels),
|
||||
("word/document.xml", document.as_str()),
|
||||
("word/styles.xml", styles.as_str()),
|
||||
] {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(data.as_bytes()).unwrap();
|
||||
z.add(name, data.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn paragraph(d: &Document) -> &Paragraph {
|
||||
@@ -180,9 +178,14 @@ fn split_runs_add_no_phantom_tracked_formatting() {
|
||||
let run = r#"<w:sz w:val="24"/><w:rPrChange w:id="7" w:author="Synthetic Author" w:date="2026-10-11T00:00:00Z"><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrChange>"#;
|
||||
let d = wordcraft_docx::read(&package(run, "", "", "")).unwrap();
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("word/document.xml").unwrap(), &mut xml)
|
||||
.unwrap();
|
||||
let xml = String::from_utf8(
|
||||
craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 })
|
||||
.unwrap()
|
||||
.read("word/document.xml", 16 << 20)
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let runs: Vec<&str> = xml.split("<w:r>").skip(1).map(|r| r.split("</w:r>").next().unwrap()).collect();
|
||||
assert!(runs.len() >= 2, "the mixed run is split: {xml}");
|
||||
assert!(runs.iter().any(|r| r.contains("<w:rtl/>")), "{xml}");
|
||||
|
||||
@@ -136,18 +136,14 @@ fn the_controls_are_written_where_they_were() {
|
||||
|
||||
/// The names of the parts of a package, in the order they are in it.
|
||||
fn part_names(bytes: &[u8]) -> Vec<String> {
|
||||
let z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip");
|
||||
z.file_names().map(str::to_string).collect()
|
||||
let z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).expect("zip");
|
||||
z.names().map(|n| n.into_owned()).collect()
|
||||
}
|
||||
|
||||
/// The body of the document part of a package.
|
||||
fn document_body(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip");
|
||||
let mut xml = String::new();
|
||||
{
|
||||
use std::io::Read;
|
||||
z.by_name("word/document.xml").expect("the document part").read_to_string(&mut xml).expect("read");
|
||||
}
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).expect("zip");
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).expect("read").expect("the document part")).expect("utf8");
|
||||
let rest = xml.split_once("<w:body>").expect("the body").1;
|
||||
let body = rest.split_once("</w:body>").expect("the end of the body").0;
|
||||
format!("<w:body>{body}</w:body>")
|
||||
@@ -221,6 +217,8 @@ const PINNED_PARTS: &[&str] = &[
|
||||
"word/styles.xml",
|
||||
"word/settings.xml",
|
||||
"word/theme/theme1.xml",
|
||||
// The fonts the document uses, with their families: it brings no font table of its own.
|
||||
"word/fontTable.xml",
|
||||
"docProps/core.xml",
|
||||
"docProps/app.xml",
|
||||
];
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! All markup here is synthetic, written from ECMA-376 §17.5.2 and the [MS-DOCX] `w14`/`w15`
|
||||
//! extensions.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::control::{ControlKind, ControlLock, ListItem};
|
||||
use wordcraft_doc::{Block, ContentControl, Document, StoryRef};
|
||||
use wordcraft_docx::{read, write};
|
||||
@@ -13,12 +11,11 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn t(s: &str) -> String {
|
||||
@@ -90,10 +87,9 @@ fn form() -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn controls(d: &Document) -> Vec<ContentControl> {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Original synthetic custom XML stores, written from the public OOXML package contract.
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use wordcraft_doc::{Path, StoryRef};
|
||||
|
||||
const REL_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
|
||||
@@ -36,22 +35,19 @@ fn fixture() -> BTreeMap<String, Vec<u8>> {
|
||||
}
|
||||
|
||||
fn zip(parts: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, bytes) in parts {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(bytes).unwrap();
|
||||
z.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut parts = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let mut bytes = Vec::new();
|
||||
f.read_to_end(&mut bytes).unwrap();
|
||||
for name in names {
|
||||
let bytes = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(parts.insert(name, bytes).is_none(), "duplicate ZIP entry");
|
||||
}
|
||||
parts
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! The document default font size (`w:docDefaults/w:rPrDefault/w:rPr/w:sz`) across a save and
|
||||
//! reopen. An unset default is resolved as `DEFAULT_FONT_SIZE`; the writer must say so, because
|
||||
//! the reader reads an omitted size as 10 pt.
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::Document;
|
||||
use wordcraft_doc::props::{CharProps, DEFAULT_FONT_SIZE};
|
||||
@@ -9,10 +8,9 @@ fn resolved(d: &Document) -> f32 {
|
||||
d.styles.resolve_char(None, &CharProps::default()).size
|
||||
}
|
||||
fn styles_xml(bytes: &[u8]) -> String {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
archive.by_name("word/styles.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
xml
|
||||
let mut archive = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(archive.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
fn defaults(xml: &str) -> &str {
|
||||
xml.split("<w:docDefaults>").nth(1).unwrap().split("</w:docDefaults>").next().unwrap()
|
||||
@@ -47,12 +45,11 @@ fn a_file_that_omits_the_default_size_is_still_read_as_ten_points() {
|
||||
let doc = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>x</w:t></w:r></w:p></w:body></w:document>"#;
|
||||
let styles = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults></w:styles>"#;
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, body) in [("_rels/.rels", root), ("word/document.xml", doc), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles)] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(body.as_bytes()).unwrap();
|
||||
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let d = wordcraft_docx::read(&zw.finish().unwrap().into_inner()).unwrap();
|
||||
let d = wordcraft_docx::read(&zw.finish().unwrap()).unwrap();
|
||||
assert_eq!(d.styles.default_chr.size, Some(10.0));
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Original nested-picture controls. No native output or external assets are embedded.
|
||||
use std::{io::Write, sync::Arc};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::para::{Anchor, CanvasStyle, Float, GroupChild, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
use wordcraft_doc::{Document, InlineObject, Paragraph, PartKind, Pos, StoryRef, TextBody, para_block};
|
||||
@@ -71,7 +71,7 @@ fn check_box(doc: &Document) {
|
||||
assert_eq!(doc.media[media].as_slice(), BLUE_PNG);
|
||||
}
|
||||
fn package(xml: &str) -> Vec<u8> {
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let docrels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdIsolationRect" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/isolation-blue.png"/></Relationships>"#;
|
||||
let types = br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
@@ -82,10 +82,9 @@ fn package(xml: &str) -> Vec<u8> {
|
||||
("word/_rels/document.xml.rels", docrels.as_slice()),
|
||||
("word/media/isolation-blue.png", BLUE_PNG),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn model_nested_picture_roundtrip() {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! East Asian language attribute of a run (`w:lang/@w:eastAsia`, ISO/IEC 29500-1 §17.3.2.20).
|
||||
//! Verifies that saving DOCX documents preserves the East Asian language of `w:lang`.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
@@ -17,19 +15,17 @@ fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
|
||||
));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in &parts {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn run(text: &str, rpr: &str) -> String {
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! two lines in one and horizontal in vertical are read and saved again. Fixtures are
|
||||
//! hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::{CombineBrackets, EastAsianLayout};
|
||||
|
||||
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
@@ -20,19 +18,17 @@ fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
|
||||
));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in &parts {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn run(text: &str, rpr: &str) -> String {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Emphasis marks (`w:em`, ISO/IEC 29500-1 §17.3.2.12: Font › Emphasis mark) are read and
|
||||
//! saved again, in their place in `w:rPr`. Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::EmphasisMark;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -10,12 +8,11 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in [("_rels/.rels", root.to_string()), ("word/document.xml", doc)] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn marks(d: &wordcraft_doc::Document) -> Vec<Option<EmphasisMark>> {
|
||||
@@ -39,9 +36,8 @@ fn emphasis_marks_are_read_and_saved() {
|
||||
let want = [EmphasisMark::Dot, EmphasisMark::Comma, EmphasisMark::Circle, EmphasisMark::UnderDot, EmphasisMark::None].map(Some);
|
||||
assert_eq!(marks(&d), want);
|
||||
let saved = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
// In its place: after w:cs, before w:lang.
|
||||
assert!(xml.contains(r#"<w:cs/><w:em w:val="underDot"/><w:lang"#), "{xml}");
|
||||
assert_eq!(marks(&wordcraft_docx::read(&saved).unwrap()), want);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Hand-written minimal WordprocessingML fixtures (written for these tests from the spec).
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::fill::Fill;
|
||||
@@ -13,12 +12,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm
|
||||
const ROOT_RELS: &str = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
|
||||
pub fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn rels(list: &[(&str, &str, &str)]) -> String {
|
||||
@@ -1483,10 +1481,9 @@ fn word_watermark_survives_save() {
|
||||
};
|
||||
assert_eq!(headers(&d2), headers(&d));
|
||||
assert_eq!(headers(&d2)[0], vec!["Header label".to_string(), "Second line".to_string()]);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
for name in ["word/header1.xml", "word/header2.xml"] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
let xml = String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<v:shape ").count(), 1, "{name}");
|
||||
}
|
||||
|
||||
@@ -1662,14 +1659,12 @@ fn chart_docx() -> Vec<u8> {
|
||||
|
||||
/// The entries of a zip, by name.
|
||||
fn unzip(bytes: &[u8]) -> std::collections::BTreeMap<String, Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
out.insert(f.name().to_string(), b);
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
out.insert(name, b);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -2174,9 +2169,8 @@ fn formatting_revisions_round_trip() {
|
||||
|
||||
// Written back: each change is the last child of its parent, and reads back the same.
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for (tag, parent) in [
|
||||
("w:rPrChange", "</w:rPr></w:rPrChange></w:rPr>"),
|
||||
("w:pPrChange", "</w:pPr></w:pPrChange></w:pPr>"),
|
||||
@@ -2432,10 +2426,9 @@ fn note_separators_and_continuation_notice_round_trip() {
|
||||
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let part = |name: &str| {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&out)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let notes = part("word/footnotes.xml");
|
||||
for (kind, id) in [("separator", "-1"), ("continuationSeparator", "0"), ("continuationNotice", "1")] {
|
||||
@@ -2558,13 +2551,12 @@ fn includepicture_keeps_its_embedded_picture() {
|
||||
let bytes = docx(&format!("<w:p>{field}</w:p><w:sectPr/>"), &[("rIdPic", "image", "media/picture.png")], &[]);
|
||||
let bytes = {
|
||||
// `docx` takes text parts; add the picture bytes as a binary part.
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut entries: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut v = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut v).unwrap();
|
||||
entries.push((f.name().to_string(), v));
|
||||
for name in names {
|
||||
let v = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
entries.push((name, v));
|
||||
}
|
||||
entries.push(("word/media/picture.png".into(), png.to_vec()));
|
||||
zip(&entries.iter().map(|(n, v)| (n.as_str(), v.as_slice())).collect::<Vec<_>>())
|
||||
@@ -2678,9 +2670,8 @@ fn rounded_rectangle_corners_are_read_and_saved() {
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
assert_eq!(corners(&d), expected);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 3565"/></a:avLst></a:prstGeom>"#), "{xml}");
|
||||
assert_eq!(corners(&wordcraft_docx::read(&bytes).unwrap()), expected);
|
||||
}
|
||||
@@ -2745,9 +2736,8 @@ fn arrowheads_keep_their_kind_and_size() {
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
assert_eq!(ends(&d), expected);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<a:headEnd type="stealth" w="sm" len="lg"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:tailEnd type="diamond" w="lg" len="sm"/>"#), "{xml}");
|
||||
assert_eq!(ends(&wordcraft_docx::read(&bytes).unwrap()), expected);
|
||||
@@ -2870,9 +2860,8 @@ fn vml_preset_shape_survives_saving() {
|
||||
r##"<w:p><w:r><w:pict>{VML_RIGHT_ARROW_TYPE}<v:shape type="#_x0000_t13" style="width:120pt;height:40pt" fillcolor="#ffa500"/></w:pict></w:r></w:p>"##
|
||||
);
|
||||
let saved = wordcraft_docx::write(&read_body(&body)).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"prst="rightArrow""#), "{xml}");
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert!(
|
||||
@@ -2898,9 +2887,8 @@ fn vml_preset_shape_survives_saving() {
|
||||
fn vml_nearest_preset_shape_survives_saving() {
|
||||
let body = r##"<w:p><w:r><w:pict><v:shape type="#_x0000_t66" style="width:60pt;height:20pt" fillcolor="#ffa500"/></w:pict></w:r></w:p>"##;
|
||||
let saved = wordcraft_docx::write(&read_body(body)).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(saved.as_slice())).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&saved, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"prst="leftArrow""#), "{xml}");
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert!(
|
||||
@@ -3047,9 +3035,8 @@ fn drawingml_shapes_survive_saving() {
|
||||
let again = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(shapes(&again), read, "every shape survives saving");
|
||||
assert_eq!(part_text_box(&again), "Floating text box");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes[..], craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<wps:wsp>").count(), 7);
|
||||
for p in presets.iter().chain(&["straightConnector1"]) {
|
||||
assert!(xml.contains(&format!(r#"<a:prstGeom prst="{p}">"#)), "{p} is written");
|
||||
@@ -4044,20 +4031,19 @@ fn hyperlink_with_empty_target_is_no_link() {
|
||||
let bytes = docx(body, &[("rId2", "hyperlink", "https://x"), ("rId3", "hyperlink", "mailto:a@example.com")], &[]);
|
||||
// Blank the first target and mark the mailto one external (the helper only does that for http).
|
||||
let bytes = {
|
||||
let mut zr = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut zr = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = zr.names().map(|n| n.into_owned()).collect();
|
||||
let mut entries = Vec::new();
|
||||
for i in 0..zr.len() {
|
||||
let mut f = zr.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
if f.name() == "word/_rels/document.xml.rels" {
|
||||
for name in names {
|
||||
let mut buf = zr.read(&name, 16 << 20).unwrap().unwrap();
|
||||
if name == "word/_rels/document.xml.rels" {
|
||||
buf = String::from_utf8(buf)
|
||||
.unwrap()
|
||||
.replace("Target=\"https://x\"", "Target=\"\"")
|
||||
.replace("a@example.com\"", "a@example.com\" TargetMode=\"External\"")
|
||||
.into_bytes();
|
||||
}
|
||||
entries.push((f.name().to_string(), buf));
|
||||
entries.push((name, buf));
|
||||
}
|
||||
let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (n.as_str(), b.as_slice())).collect();
|
||||
zip(&refs)
|
||||
@@ -4575,7 +4561,7 @@ fn shape_gradients_and_transparency_are_read_and_survive_saving() {
|
||||
rot_with_shape: false,
|
||||
flip: GradientFlip::Xy,
|
||||
}))),
|
||||
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, Rgb(0x20, 0x40, 0x60), 0.0)], lin(90.0, false), true)),
|
||||
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, Rgb(44, 92, 140), 0.0)], lin(90.0, false), true)),
|
||||
Some(grad(vec![stop(0.0, ph, 0.0), stop(100.0, black, 0.0)], centre, true)),
|
||||
None,
|
||||
];
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
//! edited. Hand-written fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::{Block, BuildingBlock, CharProps, Document, Paragraph, para_block};
|
||||
@@ -15,22 +14,20 @@ const GLOSSARY_REL: &str = "http://schemas.openxmlformats.org/officeDocument/200
|
||||
const GLOSSARY_CT: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//! `styles.xml` doesn't write `w:outlineLvl` (some producers leave it out). Word for Windows,
|
||||
//! opening such a file, reports `OutlineLevel` 1 and 2 for "heading 1" and "heading 2" (whatever
|
||||
//! their style ids) and body text for a custom style.
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::Paragraph;
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
@@ -12,14 +11,13 @@ fn package(styles: &str, body: &str) -> Vec<u8> {
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}"><w:body>{body}</w:body></w:document>"#);
|
||||
let styles = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="{W}">{styles}</w:styles>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, body) in
|
||||
[("_rels/.rels", root), ("word/document.xml", doc.as_str()), ("word/_rels/document.xml.rels", rels), ("word/styles.xml", styles.as_str())]
|
||||
{
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(body.as_bytes()).unwrap();
|
||||
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn para(style: &str, text: &str) -> String {
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! (`w:gridBefore`/`w:wBefore`, `w:gridAfter`/`w:wAfter`) through a round trip (#1174). All
|
||||
//! markup here is synthetic, written from ECMA-376 §17.16.17 and §17.4.14-17.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::Block;
|
||||
use wordcraft_docx::{read, write};
|
||||
|
||||
@@ -12,19 +10,17 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn resaved(body: &str) -> String {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! OpenType ligatures (`w14:ligatures`, [MS-DOCX]) in document defaults, styles and runs.
|
||||
//! Synthetic packages, written here; no external documents are needed.
|
||||
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::Ligatures;
|
||||
use wordcraft_doc::{Document, Paragraph};
|
||||
|
||||
@@ -15,17 +14,16 @@ fn package(defaults: &str, style: &str, run: &str) -> Vec<u8> {
|
||||
let styles = format!(
|
||||
r#"<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="character" w:styleId="Fancy"><w:name w:val="Fancy"/><w:rPr>{style}</w:rPr></w:style></w:styles>"#
|
||||
);
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, data) in [
|
||||
("_rels/.rels", root),
|
||||
("word/_rels/document.xml.rels", rels),
|
||||
("word/document.xml", document.as_str()),
|
||||
("word/styles.xml", styles.as_str()),
|
||||
] {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(data.as_bytes()).unwrap();
|
||||
z.add(name, data.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn paragraph(d: &Document) -> &Paragraph {
|
||||
@@ -68,10 +66,9 @@ fn unknown_ligature_values_are_ignored() {
|
||||
fn no_ligatures_element_without_a_value() {
|
||||
let d = wordcraft_docx::read(&package("", "", "")).unwrap();
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&out, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
for name in ["word/document.xml", "word/styles.xml"] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
let xml = String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(!xml.contains("ligatures"), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm
|
||||
const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn doc_zip(document_xml: &[u8]) -> Vec<u8> {
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
//! Pictures dropped at open are recorded for strict export (#6005): a missing part, an external
|
||||
//! target and a link-only picture (ECMA-376 Part 1 §20.1.8.13 `a:blip` `r:embed`/`r:link`).
|
||||
//! Original synthetic packages; nothing is fetched, the reader has no network code.
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::{Document, InlineObject, MissingPictureReason};
|
||||
|
||||
const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:v="urn:schemas-microsoft-com:vml""#;
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn blip(attrs: &str) -> String {
|
||||
@@ -32,10 +31,9 @@ fn package(body: &str, doc_rels: &str, header: Option<(&str, &str)>, extra: &[(&
|
||||
);
|
||||
let drels = format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{doc_rels}{hdr_rel}</Relationships>"#);
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="bin" ContentType="application/octet-stream"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
let mut put = |name: &str, bytes: &[u8]| {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
};
|
||||
put("[Content_Types].xml", types.as_bytes());
|
||||
put("_rels/.rels", rels.as_bytes());
|
||||
@@ -51,7 +49,7 @@ fn package(body: &str, doc_rels: &str, header: Option<(&str, &str)>, extra: &[(&
|
||||
for (n, b) in extra {
|
||||
put(n, b);
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
fn image_rel(id: &str, target: &str, external: bool) -> String {
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//! saved, even when it holds a single paragraph (ECMA-376 §17.5.2.29-30; [MS-DOCX] `w15`
|
||||
//! repeating sections, which must wrap whole paragraphs or rows). All markup here is synthetic.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::{ContentControl, Document, StoryRef};
|
||||
use wordcraft_docx::{read, write};
|
||||
|
||||
@@ -13,19 +11,17 @@ const ROOT_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.o
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let doc = format!(r#"<w:document {NS}><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(docx: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut s = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(docx, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn t(s: &str) -> String {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! and extended properties. Hand-written fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
@@ -12,22 +11,20 @@ const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relati
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
//! A picture's hyperlink (#5267): Word keeps it on the drawing (`wp:docPr/a:hlinkClick`,
|
||||
//! ECMA-376 Part 1 §20.4.2.5) rather than in a `w:hyperlink` around the run. Original
|
||||
//! synthetic packages; the 2×2 picture is generated in code.
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::{CharProps, Document, InlineObject, Pos};
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 90, 200, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// An inline picture's run; `link` goes into its `wp:docPr`.
|
||||
@@ -28,7 +27,7 @@ fn package(body: &str) -> Vec<u8> {
|
||||
let doc_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdPic" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/square.png"/><Relationship Id="rIdWeb" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/picture" TargetMode="External"/><Relationship Id="rIdRun" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/run" TargetMode="External"/></Relationships>"#;
|
||||
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
|
||||
let png = png();
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, bytes) in [
|
||||
("[Content_Types].xml", types.as_bytes()),
|
||||
("_rels/.rels", rels.as_bytes()),
|
||||
@@ -36,10 +35,9 @@ fn package(body: &str) -> Vec<u8> {
|
||||
("word/_rels/document.xml.rels", doc_rels.as_bytes()),
|
||||
("word/media/square.png", png.as_slice()),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
zip.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
/// The link on each picture of the first paragraph, in order.
|
||||
@@ -53,10 +51,9 @@ fn picture_links(doc: &Document) -> Vec<Option<String>> {
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -109,19 +106,16 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() {
|
||||
// The drawing's link alone (as Word writes it) reads back the same.
|
||||
let without_run_link = xml.replace(&format!(r#"<w:hyperlink r:id="{rid}" w:history="1">"#), "").replacen("</w:hyperlink>", "", 1);
|
||||
assert_ne!(without_run_link, xml);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = craft_zip::Writer::new();
|
||||
for name in names {
|
||||
let mut data = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
if name == "word/document.xml" {
|
||||
data = without_run_link.clone().into_bytes();
|
||||
}
|
||||
out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
out.write_all(&data).unwrap();
|
||||
out.add(&name, &data, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let edited = out.finish().unwrap().into_inner();
|
||||
let edited = out.finish().unwrap();
|
||||
assert_eq!(picture_links(&wordcraft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string()));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Positional tabs (`w:ptab`, ECMA-376 Part 1 §17.3.3.23). Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::InlineObject;
|
||||
use wordcraft_doc::para::{PTabAlign, PTabBase};
|
||||
use wordcraft_doc::props::TabLeader;
|
||||
@@ -11,19 +9,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn ptab(relative_to: &str, alignment: &str, leader: &str) -> String {
|
||||
|
||||
@@ -2,28 +2,27 @@
|
||||
//! (ECMA-376 Part 1 §17.15.1.69–70) are kept on save and honoured by the writer. Synthetic
|
||||
//! fixtures written for these tests from the spec; the names are made up.
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;
|
||||
const RT: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
|
||||
|
||||
fn zip(entries: &[(&str, String)]) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, text) in entries {
|
||||
z.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(text.as_bytes()).unwrap();
|
||||
z.add(name, text.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, String> {
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut parts = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut s = String::new();
|
||||
if f.read_to_string(&mut s).is_ok() {
|
||||
parts.insert(f.name().to_string(), s);
|
||||
for name in names {
|
||||
if let Ok(Some(bytes)) = z.read(&name, 16 << 20)
|
||||
&& let Ok(s) = String::from_utf8(bytes)
|
||||
{
|
||||
parts.insert(name, s);
|
||||
}
|
||||
}
|
||||
parts
|
||||
|
||||
+137
-122
@@ -63,7 +63,11 @@ fn para_runs(runs: &[(&str, CharProps)]) -> Paragraph {
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut out,
|
||||
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
@@ -324,9 +328,8 @@ fn tracked_style_definition_change_round_trips() {
|
||||
});
|
||||
d.body = vec![para_block(Paragraph::with_text("x", CharProps::default()))];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/styles.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains("<w:pPrChange") && xml.contains("<w:rPrChange"), "{xml}");
|
||||
assert!(!xml.contains("stylePrChange"), "CT_Style has no such element: {xml}");
|
||||
drop(zip);
|
||||
@@ -748,9 +751,8 @@ fn note_options_round_trip_per_section() {
|
||||
assert!(sections[1].1.footnote_pr.is_empty() && sections[1].1.endnote_pr.is_empty());
|
||||
assert_eq!(r.note_options(sections[0].1, false).num_start, 7);
|
||||
assert_eq!(r.note_options(sections[1].1, false).num_start, 4);
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let at = |s: &str| xml.find(s).unwrap_or_else(|| panic!("{s} missing"));
|
||||
assert!(
|
||||
at("<w:footnotePr><w:numFmt w:val=\"lowerRoman\"/><w:numStart w:val=\"7\"/><w:numRestart w:val=\"eachSect\"/></w:footnotePr>")
|
||||
@@ -773,9 +775,8 @@ fn note_never_references_itself() {
|
||||
d.body = vec![para_block(p)];
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/footnotes.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/footnotes.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(!xml.contains("<w:footnoteReference"), "a footnote cites itself: {xml}");
|
||||
assert_eq!(xml.matches("<w:footnoteRef/>").count(), 1, "{xml}");
|
||||
|
||||
@@ -840,13 +841,12 @@ fn word_note_mark_round_trips_once() {
|
||||
let mut doc = d;
|
||||
for pass in 0..2 {
|
||||
let bytes = wordcraft_docx::write(&doc).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
for (file, mark, reference, style) in [
|
||||
("word/footnotes.xml", "<w:footnoteRef/>", "<w:footnoteReference", "FootnoteReference"),
|
||||
("word/endnotes.xml", "<w:endnoteRef/>", "<w:endnoteReference", "EndnoteReference"),
|
||||
] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name(file).unwrap(), &mut xml).unwrap();
|
||||
let xml = String::from_utf8(zip.read(file, 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches(mark).count(), 1, "pass {pass}: {xml}");
|
||||
assert!(!xml.contains(reference), "pass {pass}: a note cites itself: {xml}");
|
||||
assert!(xml.contains(&format!(r#"<w:rStyle w:val="{style}"/></w:rPr>{mark}"#)), "pass {pass}: {xml}");
|
||||
@@ -894,9 +894,8 @@ fn toc_field_wraps_its_entries() {
|
||||
let d = doc_with(blocks);
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let sdt = xml.find("<w:sdt>").expect("TOC content control");
|
||||
assert!(xml.contains(r#"<w:docPartGallery w:val="Table of Contents"/>"#), "{xml}");
|
||||
let (begin, fend) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap());
|
||||
@@ -933,9 +932,8 @@ fn cell_text_direction_round_trips() {
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:textDirection w:val="btLr"/>"#), "{xml}");
|
||||
assert_eq!(xml.matches("w:textDirection").count(), 2, "horizontal cells write nothing: {xml}");
|
||||
@@ -988,11 +986,11 @@ fn toc_field_skips_nested_stories() {
|
||||
d.body = vec![para_block(head), para_block(last), para_block(Paragraph::with_text("Body", CharProps::default()))];
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let boxes: Vec<(usize, usize)> = xml.match_indices("<w:txbxContent>").map(|(a, _)| (a, a + xml[a..].find("</w:txbxContent>").unwrap())).collect();
|
||||
assert_eq!(boxes.len(), 2, "{xml}");
|
||||
// Each text box is written twice: in the drawing and in its VML fallback.
|
||||
assert_eq!(boxes.len(), 4, "{xml}");
|
||||
let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i));
|
||||
for kind in ["begin", "separate", "end"] {
|
||||
let at: Vec<usize> = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect();
|
||||
@@ -1000,7 +998,7 @@ fn toc_field_skips_nested_stories() {
|
||||
assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}");
|
||||
}
|
||||
let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap());
|
||||
assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
|
||||
assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1054,9 +1052,8 @@ fn tracked_equations_round_trip() {
|
||||
p.insert_object(end, InlineObject::Equation { linear: "z=1".into(), display: false, math: Default::default() }, &plain).unwrap();
|
||||
d.body = vec![para_block(p.clone())];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:ins w:id="1" w:author="Alice" w:date="2026-05-01T10:00:00Z"><m:oMath>"#), "ins directly encloses inline math: {xml}");
|
||||
assert!(
|
||||
xml.contains(r#"<w:del w:id="2" w:author="Bob" w:date="2026-05-02T10:00:00Z"><m:oMathPara>"#),
|
||||
@@ -1119,9 +1116,8 @@ fn tracked_paragraph_marks_round_trip() {
|
||||
let last = Paragraph::with_text("plain", CharProps::default());
|
||||
d.body = vec![para_block(split), para_block(joined), para_block(last)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:rPr><w:ins w:id="#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:rPr><w:del w:id="#), "{xml}");
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
@@ -1165,10 +1161,9 @@ fn fields_and_special_chars_round_trip() {
|
||||
|
||||
/// The `document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// #877: a field begin marker's `w:dirty` (the cached result is stale; Word refreshes it on
|
||||
@@ -1446,9 +1441,8 @@ fn drawing_canvas_round_trips() {
|
||||
p.insert_object(end, canvas, &CharProps::default()).unwrap();
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains("wordprocessingCanvas") && xml.contains("<wpc:wpc>") && xml.contains("<wpc:bg>") && xml.contains("<wpc:whole>"), "{xml}");
|
||||
let r = wordcraft_docx::read(&bytes).unwrap();
|
||||
let got = paras(&r);
|
||||
@@ -1494,9 +1488,8 @@ fn rotated_drawing_canvas_round_trips() {
|
||||
let end = p.len();
|
||||
p.insert_object(end, canvas(square), &CharProps::default()).unwrap();
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(
|
||||
xml.contains(r#"<wpc:extLst><a:ext uri="urn:wordcraft:canvas-xfrm"><a:xfrm rot="1800000" flipH="1"/></a:ext></wpc:extLst></wpc:wpc>"#),
|
||||
"{xml}"
|
||||
@@ -1524,9 +1517,8 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
|
||||
assert_eq!(r.settings.compat_mode, mode);
|
||||
if allow {
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
// CT_Compat requires the boolean option before compatSetting.
|
||||
assert!(xml.find("<w:allowSpaceOfSameStyleInTable").unwrap() < xml.find("<w:compatSetting").unwrap());
|
||||
}
|
||||
@@ -1557,15 +1549,13 @@ fn attached_template_and_link_styles_round_trip() {
|
||||
d.settings.mirror_margins = true;
|
||||
d.settings.track_changes = true;
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let at = |tag: &str| xml.find(tag).unwrap_or_else(|| panic!("{tag} missing: {xml}"));
|
||||
assert!(at("<w:mirrorMargins") < at("<w:attachedTemplate"));
|
||||
assert!(at("<w:attachedTemplate") < at("<w:linkStyles"));
|
||||
assert!(at("<w:linkStyles") < at("<w:trackRevisions"));
|
||||
let mut rels = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/_rels/settings.xml.rels").unwrap(), &mut rels).unwrap();
|
||||
let rels = String::from_utf8(zip.read("word/_rels/settings.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(rels.contains("relationships/attachedTemplate") && rels.contains("TargetMode=\"External\""), "{rels}");
|
||||
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
@@ -1578,15 +1568,37 @@ fn attached_template_and_link_styles_round_trip() {
|
||||
assert!(!plain.settings.link_styles);
|
||||
}
|
||||
|
||||
/// Gutter position Top (`w:gutterAtTop`) is kept when a document is opened and saved again, and
|
||||
/// is not written when it is off.
|
||||
#[test]
|
||||
fn gutter_at_top_survives_open_and_save() {
|
||||
let settings_xml = |bytes: &[u8]| {
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let mut d = Document::new();
|
||||
d.settings.gutter_at_top = true;
|
||||
let first = wordcraft_docx::write(&d).expect("write");
|
||||
assert_eq!(settings_xml(&first).matches("<w:gutterAtTop/>").count(), 1);
|
||||
|
||||
let opened = wordcraft_docx::read(&first).expect("read");
|
||||
assert!(opened.settings.gutter_at_top);
|
||||
let saved = wordcraft_docx::write(&opened).expect("write again");
|
||||
assert_eq!(settings_xml(&saved).matches("<w:gutterAtTop/>").count(), 1);
|
||||
assert!(wordcraft_docx::read(&saved).expect("read again").settings.gutter_at_top);
|
||||
|
||||
let plain = wordcraft_docx::write(&Document::new()).expect("write plain");
|
||||
assert!(!settings_xml(&plain).contains("gutterAtTop"));
|
||||
}
|
||||
|
||||
/// #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 mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let plain = wordcraft_docx::write(&Document::new()).unwrap();
|
||||
let xml = settings(&plain);
|
||||
@@ -1649,10 +1661,9 @@ fn settings_core_theme_round_trip() {
|
||||
}
|
||||
|
||||
fn part_xml(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Header parts in the document, by id.
|
||||
@@ -1935,8 +1946,21 @@ fn flat_opc_round_trip_equals_docx() {
|
||||
assert!(text.starts_with("<?xml") && text.contains("<?mso-application progid=\"Word.Document\"?>"));
|
||||
assert!(text.contains("pkg:name=\"/word/document.xml\"") && text.contains("<pkg:binaryData>"));
|
||||
assert_eq!(wordcraft_docx::sniff_xml(&xml), wordcraft_docx::XmlKind::FlatOpc);
|
||||
let back = wordcraft_docx::read_xml(&xml).expect("read flat");
|
||||
assert_eq!(back, rt(&d));
|
||||
let mut back = wordcraft_docx::read_xml(&xml).expect("read flat");
|
||||
// `pkg:xmlData` inlines a part without its XML declaration, so a kept XML part (the font
|
||||
// table) comes back without one; the markup is the same.
|
||||
let mut want = rt(&d);
|
||||
for doc in [&mut back, &mut want] {
|
||||
for v in doc.passthrough.values_mut() {
|
||||
if let Some(rest) =
|
||||
v.strip_prefix(b"<?xml").and_then(|r| r.iter().position(|&b| b == b'>').map(|e| r[e + 1..].trim_ascii_start().to_vec()))
|
||||
{
|
||||
*v = Arc::new(rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(back.passthrough.contains_key("word/fontTable.xml"));
|
||||
assert_eq!(back, want);
|
||||
assert_eq!(back.media.len(), 1);
|
||||
}
|
||||
|
||||
@@ -2047,9 +2071,8 @@ fn char_border_written_between_u_and_shd() {
|
||||
let c =
|
||||
CharProps { border: Some(Border::single(0.5)), underline: Some(Underline::Single), shading: Some(Rgb(0xFF, 0xFF, 0)), ..Default::default() };
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![para_runs(&[("x", c)])])).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let bdr = r#"<w:bdr w:val="single" w:sz="4" w:space="0" w:color="auto"/>"#;
|
||||
assert_eq!(xml.matches(bdr).count(), 1, "{xml}");
|
||||
let at = xml.find(bdr).unwrap();
|
||||
@@ -2146,9 +2169,8 @@ fn ink_and_freeforms_round_trip_as_custom_geometry() {
|
||||
}
|
||||
let d = doc_with(vec![p]);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(xml.matches("<a:custGeom>").count(), 3, "{xml}");
|
||||
assert!(xml.contains(r#"<a:path w="762000" h="254000" fill="none"><a:moveTo><a:pt x="12700" y="12700"/></a:moveTo><a:lnTo>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:alpha val="50000"/>"#) && xml.contains(r#"cap="rnd""#), "{xml}");
|
||||
@@ -2188,9 +2210,8 @@ fn shape_effects_round_trip() {
|
||||
let mut p = Paragraph::with_text("x", CharProps::default());
|
||||
p.insert_object(1, shape, &CharProps::default()).unwrap();
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(
|
||||
xml.contains(
|
||||
r#"<a:outerShdw blurRad="50800" dist="38100" dir="8100000" algn="tr" rotWithShape="0"><a:srgbClr val="203040"><a:alpha val="40000"/>"#
|
||||
@@ -2281,9 +2302,8 @@ fn rotation_and_flips_round_trip() {
|
||||
}
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<a:xfrm rot="1800000">"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:xfrm rot="5400000" flipH="1">"#), "{xml}");
|
||||
assert!(xml.contains(r#"<a:xfrm rot="18930000" flipV="1">"#), "{xml}");
|
||||
@@ -2334,9 +2354,8 @@ fn rotated_group_and_shadow_rotation_round_trip() {
|
||||
let mut p = Paragraph::with_text("g", CharProps::default());
|
||||
p.insert_object(1, group, &CharProps::default()).unwrap();
|
||||
let bytes = wordcraft_docx::write(&doc_with(vec![p])).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<wpg:grpSpPr><a:xfrm rot="8100000" flipH="1">"#), "{xml}");
|
||||
assert!(xml.contains(r#"rotWithShape="1""#) && xml.contains(r#"rotWithShape="0""#), "{xml}");
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
@@ -2416,6 +2435,10 @@ fn bibliography_sources_round_trip() {
|
||||
|
||||
assert_bibliography_parts(&bytes);
|
||||
assert_bibliography_sources_round_trip(&bytes);
|
||||
// Saved again after reading, the store keeps one relationship, from the main part.
|
||||
let again = wordcraft_docx::write(&wordcraft_docx::read(&bytes).expect("read")).expect("write again");
|
||||
assert_bibliography_parts(&again);
|
||||
assert_eq!(wordcraft_docx::read(&again).expect("read again").sources.len(), d.sources.len());
|
||||
}
|
||||
|
||||
/// #4848: a corporate author saves as Word's `b:Corporate`, in place of a name list (a role holds
|
||||
@@ -2440,9 +2463,8 @@ fn a_corporate_author_round_trips() {
|
||||
..Default::default()
|
||||
});
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
|
||||
let mut item_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("customXml/item1.xml").unwrap(), &mut item_xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes[..], craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let item_xml = String::from_utf8(zip.read("customXml/item1.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(item_xml.contains("<b:Author><b:Author><b:Corporate>World Health Organization</b:Corporate></b:Author><b:Editor>"), "{item_xml}");
|
||||
assert!(item_xml.contains("<b:Corporate>Harbor Guild, Inc.</b:Corporate>"), "{item_xml}");
|
||||
assert!(!item_xml.contains("<b:Last>Rivera</b:Last>"), "the corporate author takes the person authors' place: {item_xml}");
|
||||
@@ -2452,23 +2474,23 @@ fn a_corporate_author_round_trips() {
|
||||
}
|
||||
|
||||
fn assert_bibliography_parts(bytes: &[u8]) {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
assert!(zip.by_name("customXml/item1.xml").is_ok());
|
||||
assert!(zip.by_name("customXml/itemProps1.xml").is_ok());
|
||||
assert!(zip.by_name("customXml/_rels/item1.xml.rels").is_ok());
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
assert!(zip.contains("customXml/item1.xml"));
|
||||
assert!(zip.contains("customXml/itemProps1.xml"));
|
||||
assert!(zip.contains("customXml/_rels/item1.xml.rels"));
|
||||
|
||||
let mut rels_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("_rels/.rels").unwrap(), &mut rels_xml).unwrap();
|
||||
assert!(rels_xml.contains("relationships/customXml"), "{rels_xml}");
|
||||
assert!(rels_xml.contains("Target=\"customXml/item1.xml\""), "{rels_xml}");
|
||||
// The sources' data store is related from the main part's relationships only.
|
||||
let rels_xml = String::from_utf8(zip.read("word/_rels/document.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(rels_xml.matches("relationships/customXml\"").count(), 1, "{rels_xml}");
|
||||
assert!(rels_xml.contains("Target=\"../customXml/item1.xml\""), "{rels_xml}");
|
||||
let root_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(!root_xml.contains("relationships/customXml\""), "{root_xml}");
|
||||
|
||||
let mut ct_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut ct_xml).unwrap();
|
||||
let ct_xml = String::from_utf8(zip.read("[Content_Types].xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(ct_xml.contains("PartName=\"/customXml/item1.xml\""), "{ct_xml}");
|
||||
assert!(ct_xml.contains("PartName=\"/customXml/itemProps1.xml\""), "{ct_xml}");
|
||||
|
||||
let mut item_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("customXml/item1.xml").unwrap(), &mut item_xml).unwrap();
|
||||
let item_xml = String::from_utf8(zip.read("customXml/item1.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_bibliography_types(&item_xml);
|
||||
assert_bibliography_people(&item_xml);
|
||||
assert_bibliography_details(&item_xml);
|
||||
@@ -2596,9 +2618,8 @@ fn wrap_polygons_round_trip() {
|
||||
}
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<wp:wrapPolygon edited="1"><wp:start x="-300" y="0"/><wp:lineTo x="21600" y="1200"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<wp:lineTo x="-300" y="0"/></wp:wrapPolygon>"#), "closed: {xml}");
|
||||
let r = unstacked(wordcraft_docx::read(&bytes).expect("read"));
|
||||
@@ -2635,9 +2656,8 @@ fn enclosed_characters_round_trip_in_words_structure() {
|
||||
}
|
||||
let doc = doc_with(vec![p]);
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"<w:instrText xml:space="preserve"> eq \o\ac(○</w:instrText>"#), "{xml}");
|
||||
assert!(!xml.contains("separate") && !xml.contains("enlarge"), "{xml}");
|
||||
// Shrink text at 11 pt: the character at 7.5 pt (half-points 15), raised.
|
||||
@@ -2670,9 +2690,8 @@ fn ruby_phonetic_guide_round_trips_as_w_ruby() {
|
||||
p.insert_object(5, ruby.clone(), &bold).unwrap();
|
||||
let d = doc_with(vec![p]);
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for part in [
|
||||
r#"<w:rubyAlign w:val="distributeSpace"/><w:hps w:val="11"/><w:hpsRaise w:val="20"/><w:hpsBaseText w:val="22"/><w:lid w:val="ja-JP"/>"#,
|
||||
"<w:rt><w:r>",
|
||||
@@ -2717,9 +2736,8 @@ fn wrap_text_sides_round_trip() {
|
||||
}
|
||||
d.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
for tag in [
|
||||
r#"<wp:wrapSquare wrapText="left"/>"#,
|
||||
r#"<wp:wrapTight wrapText="right">"#,
|
||||
@@ -2784,9 +2802,8 @@ fn alt_text_title_and_decorative_round_trip_for_every_object() {
|
||||
t.props.description = Some("Prices by year".into());
|
||||
d.body = vec![para_block(p), Arc::new(Block::Table(t))];
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"{C183D7F6-B498-43B3-948B-1728B52AA6E4}"><adec:decorative xmlns:adec="http://schemas.microsoft.com/office/drawing/2017/decorative" val="1"/>"#), "{xml}");
|
||||
assert!(
|
||||
xml.contains(r#"<w:tblLook "#) && xml.contains(r#"<w:tblCaption w:val="Prices"/><w:tblDescription w:val="Prices by year"/></w:tblPr>"#),
|
||||
@@ -2865,9 +2882,8 @@ fn warps_and_glued_connectors_round_trip() {
|
||||
|
||||
// Hostile: an unknown warp, a huge adjust value, a glue to a missing shape.
|
||||
let xml = wordcraft_docx::write(&r).unwrap();
|
||||
let mut pkg = zip::ZipArchive::new(std::io::Cursor::new(xml)).unwrap();
|
||||
let mut doc_xml = String::new();
|
||||
std::io::Read::read_to_string(&mut pkg.by_name("word/document.xml").unwrap(), &mut doc_xml).unwrap();
|
||||
let mut pkg = craft_zip::Archive::open(&xml, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let doc_xml = String::from_utf8(pkg.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let doc_xml = doc_xml
|
||||
.replace("prst=\"textArchUp\"", "prst=\"textNotAWarp\"")
|
||||
.replace("a:stCxn id=\"5\" idx=\"3\"", "a:stCxn id=\"404\" idx=\"99999999999\"");
|
||||
@@ -2880,29 +2896,29 @@ fn warps_and_glued_connectors_round_trip() {
|
||||
|
||||
/// `zip` with part `name` replaced by `data`.
|
||||
fn replace_part(zip_bytes: &[u8], name: &str, data: &[u8]) -> Vec<u8> {
|
||||
let mut src = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).unwrap();
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..src.len() {
|
||||
let mut f = src.by_index(i).unwrap();
|
||||
let n = f.name().to_string();
|
||||
out.start_file(n.as_str(), zip::write::SimpleFileOptions::default()).unwrap();
|
||||
let mut src = craft_zip::Archive::open(zip_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = src.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = craft_zip::Writer::new();
|
||||
for n in names {
|
||||
if n == name {
|
||||
std::io::Write::write_all(&mut out, data).unwrap();
|
||||
out.add(&n, data, craft_zip::Compression::Deflated).unwrap();
|
||||
} else {
|
||||
std::io::copy(&mut f, &mut out).unwrap();
|
||||
let bytes = src.read(&n, 16 << 20).unwrap().unwrap();
|
||||
out.add(&n, &bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
}
|
||||
out.finish().unwrap().into_inner()
|
||||
out.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A texture or picture page background (`v:background/v:fill`) survives a save (#999): the image
|
||||
/// part, its relationship and the fill attributes.
|
||||
#[test]
|
||||
fn page_background_picture_round_trips() {
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 150, 100, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let png = wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 150, 100, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = Document::new();
|
||||
d.settings.page_color = Some(Rgb(0xFF, 0xFF, 0xCC));
|
||||
d.media.insert("paper.png".into(), Arc::new(png.clone()));
|
||||
@@ -2932,9 +2948,8 @@ fn drop_cap_options_round_trip() {
|
||||
margin.props.drop_cap_margin = Some(true);
|
||||
let d = doc_with(vec![dropped, margin]);
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(xml.contains(r#"w:dropCap="drop" w:lines="2" w:hSpace="120""#), "{xml}");
|
||||
assert!(xml.contains(r#"w:dropCap="margin" w:lines="4""#), "{xml}");
|
||||
assert!(xml.contains(r#"w:ascii="Liberation Mono""#), "the letter's font on its run: {xml}");
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
//! Row-level table property exceptions (`w:tblPrEx` in `w:tr`, ECMA-376 Part 1 §17.4.61).
|
||||
//! Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn row(ex: &str, text: &str) -> String {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Run and style properties that must survive repeated DOCX saves.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str, styles: &str) -> Vec<u8> {
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
@@ -9,24 +7,22 @@ fn docx(body: &str, styles: &str) -> Vec<u8> {
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}<w:sectPr/></w:body></w:document>"#
|
||||
);
|
||||
let styles = format!(r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#);
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, xml) in [
|
||||
("_rels/.rels", root.to_string()),
|
||||
("word/document.xml", document),
|
||||
("word/_rels/document.xml.rels", rels.to_string()),
|
||||
("word/styles.xml", styles),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(xml.as_bytes()).unwrap();
|
||||
zip.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip.by_name(name).unwrap().read_to_string(&mut xml).unwrap();
|
||||
xml
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(zip.read(name, 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
//! Section form protection (`w:formProt` in `w:sectPr`, ECMA-376 Part 1 §17.6.6). Fixtures are
|
||||
//! hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Section line numbering (`w:lnNumType` in `w:sectPr`, ECMA-376 Part 1 §17.6.8).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::section::{LineNumberRestart, LineNumbering};
|
||||
|
||||
/// Builds a minimal in-memory DOCX package archive containing the given XML body.
|
||||
@@ -10,20 +8,18 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// Extracts the `word/document.xml` content string from a serialized DOCX package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// #6209: `<w:lnNumType>` without `w:countBy` leaves line numbering off, as Word does.
|
||||
|
||||
@@ -1,25 +1,21 @@
|
||||
//! Section printer, note and chapter-number metadata survives DOCX and native JSON saves.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="w15"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
//! Section page-number settings (`w:pgNumType` in `w:sectPr`, ECMA-376 Part 1 §17.6.12).
|
||||
//! Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -34,10 +30,16 @@ fn page_number_type_is_kept_even_when_it_only_repeats_the_defaults() {
|
||||
|
||||
#[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}");
|
||||
for (format, start) in [("decimal", 0), ("upperRoman", 3)] {
|
||||
let page_number_type = format!(r#"<w:pgNumType w:fmt="{format}" w:start="{start}"/>"#);
|
||||
let body = format!(r#"<w:p><w:r><w:t>One</w:t></w:r></w:p><w:sectPr>{page_number_type}</w:sectPr>"#);
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
assert_eq!(d.last_section.page_num_start, Some(start));
|
||||
let saved = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = document_xml(&saved);
|
||||
assert!(xml.contains(&page_number_type), "{xml}");
|
||||
assert_eq!(wordcraft_docx::read(&saved).unwrap().last_section.page_num_start, Some(start));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Section text direction (`w:textDirection` in `w:sectPr`, ECMA-376 Part 1 §17.6.20). Fixtures
|
||||
//! are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -10,16 +8,15 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
|
||||
let mut bytes = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut bytes = craft_zip::Writer::new();
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let document_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
@@ -31,17 +28,15 @@ fn docx_with_styles(body: &str, styles: &str) -> Vec<u8> {
|
||||
("word/document.xml", doc.as_bytes()),
|
||||
("word/styles.xml", styles.as_bytes()),
|
||||
] {
|
||||
bytes.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
bytes.write_all(value).unwrap();
|
||||
bytes.add(name, value, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
bytes.finish().unwrap().into_inner()
|
||||
bytes.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -122,8 +117,8 @@ fn paragraph_style_text_direction_is_preserved_and_direct_value_overrides_it() {
|
||||
assert_eq!(xml.matches(r#"<w:pStyle w:val="Vertical"/>"#).count(), 2, "both paragraphs keep their style: {xml}");
|
||||
assert!(xml.contains(r#"<w:pStyle w:val="Vertical"/><w:textDirection w:val="lrTb"/>"#), "direct horizontal is explicit: {xml}");
|
||||
assert_eq!(xml.matches("w:textDirection").count(), 1, "only the direct paragraph writes a direction: {xml}");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(wordcraft_docx::write(&d).unwrap())).unwrap();
|
||||
let mut styles_xml = String::new();
|
||||
z.by_name("word/styles.xml").unwrap().read_to_string(&mut styles_xml).unwrap();
|
||||
let _z_bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&_z_bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let styles_xml = String::from_utf8(z.read("word/styles.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(styles_xml.contains(r#"<w:textDirection w:val="tbRl"/>"#), "style value survives: {styles_xml}");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Section vertical alignment (`w:vAlign` in `w:sectPr`, ECMA-376 Part 1 §17.6.23, values from
|
||||
//! ST_VerticalJc). Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::section::PageVAlign;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -10,19 +8,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// #1320: "both" (Justified) reads as Justify and writes back as "both"; the others keep theirs.
|
||||
|
||||
@@ -4,29 +4,26 @@
|
||||
//! fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let names: Vec<String> = z.names().map(|n| n.into_owned()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
for name in names {
|
||||
let b = z.read(&name, 16 << 20).unwrap().unwrap();
|
||||
assert!(out.insert(name.clone(), b).is_none(), "duplicate part {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
//! ECMA-376 Part 1, 5th edition (`dml-wordprocessingDrawing.xsd`, Strict and Transitional): each
|
||||
//! drawing is written once and filled in with either set of namespaces.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::{Document, InlineObject, PartKind};
|
||||
|
||||
const STRICT_NS: &str = r#"xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main" xmlns:r="http://purl.oclc.org/ooxml/officeDocument/relationships" xmlns:wp="http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing" xmlns:a="http://purl.oclc.org/ooxml/drawingml/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" w:conformance="strict""#;
|
||||
@@ -33,19 +31,17 @@ const TRANSITIONAL: Names =
|
||||
Names { ns: TRANSITIONAL_NS, rels: TRANSITIONAL_RELS, shape: "wps", group: "wpg", canvas: "wpc", content: "w:txbxContent" };
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn solid(rgb: &str) -> String {
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
//! Word sizes a line by it when a list label is larger than the text, so a save that drops it
|
||||
//! moves every line after. Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::TextAlignment;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
@@ -12,19 +10,17 @@ fn docx(body: &str) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,26 +2,22 @@
|
||||
//! `wps:txbx/@id`, `wps:linkedTxbx`). Fixtures are hand-written from ECMA-376 Part 1 §20.4
|
||||
//! (DrawingML WordprocessingML drawing) and §21.1.2.1.1 (`bodyPr`).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::props::{TextVert, VAlign};
|
||||
use wordcraft_doc::{Document, InlineObject, PartKind, TextBody, para_block};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
let mut z = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The text boxes' stories in body order, a group's members among them
|
||||
@@ -217,7 +213,15 @@ fn picture_in_box_keeps_its_frame() {
|
||||
let outer = text_box(&mut d, "Label", body);
|
||||
let id = outer.text_box().unwrap();
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
image::RgbaImage::from_pixel(10, 4, image::Rgba([20, 40, 60, 255])).write_to(&mut bytes, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut bytes,
|
||||
&wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(10, 4, image::Rgba([20, 40, 60, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let media = d.add_media(bytes.into_inner(), "png");
|
||||
let image = InlineObject::Image {
|
||||
media: media.clone(),
|
||||
@@ -257,5 +261,7 @@ fn story_shared_by_many_shapes_is_written_once() {
|
||||
}
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.len() < 2_000_000, "document.xml is {} bytes", xml.len());
|
||||
assert_eq!(xml.matches(text.as_str()).count(), 1);
|
||||
// The story is written for the first shape only: in its drawing and in that drawing's VML
|
||||
// fallback. The other shapes do not repeat it.
|
||||
assert_eq!(xml.matches(text.as_str()).count(), 2);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Original field-boundary fixtures from the public OOXML complex-field contract.
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::{InlineObject, Path, StoryRef};
|
||||
|
||||
fn package(body: &str) -> Vec<u8> {
|
||||
let xml = format!(r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#);
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, value) in [
|
||||
("word/document.xml", xml.as_str()),
|
||||
(
|
||||
@@ -13,10 +12,9 @@ fn package(body: &str) -> Vec<u8> {
|
||||
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="main" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
|
||||
),
|
||||
] {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(value.as_bytes()).unwrap();
|
||||
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
zip.finish().unwrap()
|
||||
}
|
||||
|
||||
fn start(code: &str) -> String {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! A paragraph whose `w:pStyle` names a style `styles.xml` doesn't define is formatted as Normal,
|
||||
//! as in Word, not with the document defaults alone (#5077). Pandoc writes footers as
|
||||
//! `<w:pStyle w:val="Footer"/>` without defining Footer.
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::{Block, Document, PartKind};
|
||||
|
||||
@@ -20,7 +19,7 @@ fn package(normal_id: &str) -> Vec<u8> {
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="24"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="200"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="{normal_id}"><w:name w:val="Normal"/><w:pPr><w:spacing w:before="20" w:after="40" w:line="259" w:lineRule="auto"/></w:pPr><w:rPr><w:sz w:val="26"/></w:rPr></w:style></w:styles>"#
|
||||
);
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/></Relationships>"#;
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, body) in [
|
||||
("_rels/.rels", root),
|
||||
("word/document.xml", doc.as_str()),
|
||||
@@ -28,10 +27,9 @@ fn package(normal_id: &str) -> Vec<u8> {
|
||||
("word/styles.xml", styles.as_str()),
|
||||
("word/footer1.xml", footer.as_str()),
|
||||
] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(body.as_bytes()).unwrap();
|
||||
zw.add(name, body.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
fn footer_para(d: &Document) -> &wordcraft_doc::Paragraph {
|
||||
|
||||
@@ -2,18 +2,15 @@
|
||||
//! `coordsize`/`coordorigin` give them. Fixtures are hand-written from ECMA-376 Part 4
|
||||
//! (VML, §14.1 `v:group`, `coordsize`, `coordorigin`; §14.2 shapes).
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::{Document, InlineObject, Paragraph};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
zw.add(name, bytes, craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
zw.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A document whose body is `body`.
|
||||
|
||||
@@ -20,7 +20,11 @@ fn part_text(doc: &Document, id: Option<u32>) -> String {
|
||||
fn tiny_png_b64() -> String {
|
||||
let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([x as u8 * 100, y as u8 * 100, 50, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut out,
|
||||
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(out.into_inner());
|
||||
// Line breaks inside base64, as the formats write it.
|
||||
b64.as_bytes().chunks(20).map(|c| std::str::from_utf8(c).unwrap()).collect::<Vec<_>>().join("\n")
|
||||
|
||||
@@ -13,7 +13,11 @@ use wordcraft_docx::{XmlKind, read_xml, sniff_xml, write_wordml2003};
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
std::io::Write::write_all(
|
||||
&mut out,
|
||||
&wordcraft_geom::picture::encode_format(&image::DynamicImage::from(img.clone()), image::ImageFormat::Png).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ fn ragged_matrix_save_stays_small() {
|
||||
let mut doc = Document::new();
|
||||
doc.body = vec![para_block(p)];
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let size = zip.by_name("word/document.xml").unwrap().size();
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let size = zip.declared_size("word/document.xml").unwrap();
|
||||
assert!(size < 1_000_000, "document.xml is {size} bytes");
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ workspace = true
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -58,6 +59,7 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-doc = { workspace = true, features = ["test-support"] }
|
||||
wordcraft-formats = { workspace = true, features = ["test-support"] }
|
||||
encoding_rs = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Typing timing: opens a document, types at the middle of it, and prints the layout time of
|
||||
//! each keystroke (the pagination every edit pays for).
|
||||
//!
|
||||
//! `cargo run --release -p wordcraft-engine --example typing_bench -- doc.docx [keys]`
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
fn main() -> Result<(), String> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let path = args.first().ok_or("usage: typing_bench doc.docx [keys]")?;
|
||||
let keys: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(40);
|
||||
let mut s = Session::new(wordcraft_engine::doc::Document::new());
|
||||
s.run("file.open", &json!({"path": path})).map_err(|e| e.to_string())?;
|
||||
let first = s.layout().ms;
|
||||
let mid = s.doc.body.len() / 2;
|
||||
let block = (mid..s.doc.body.len()).chain((0..mid).rev()).find(|&i| s.doc.body.get(i).and_then(|b| b.as_para()).is_some()).unwrap_or(mid);
|
||||
s.run("caret.set", &json!({"pos": {"story": "body", "path": [block], "off": 0}})).map_err(|e| e.to_string())?;
|
||||
let mut ms = Vec::with_capacity(keys);
|
||||
for _ in 0..keys {
|
||||
s.run("text.insert", &json!({"text": "a"})).map_err(|e| e.to_string())?;
|
||||
ms.push(s.layout().ms);
|
||||
}
|
||||
ms.sort_by(f64::total_cmp);
|
||||
let med = ms.get(ms.len() / 2).copied().unwrap_or(0.0);
|
||||
println!(
|
||||
"blocks {}, first layout {first:.1} ms, per key: median {med:.1} ms, min {:.1} ms",
|
||||
s.doc.body.len(),
|
||||
ms.first().copied().unwrap_or(0.0)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.when(has_canvas)
|
||||
.pure(),
|
||||
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
|
||||
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
|
||||
.params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#)
|
||||
.when(has_canvas),
|
||||
]
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult {
|
||||
result(&o)
|
||||
}
|
||||
|
||||
/// `canvas.member`: move, resize or remove one member; with no change, list the members.
|
||||
/// `canvas.member`: move, resize or remove one member; without index, list the members.
|
||||
fn member(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let pos = canvas_pos(s)?;
|
||||
let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else {
|
||||
|
||||
@@ -68,6 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Escape")
|
||||
.params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#)
|
||||
.pure(),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::chart::{ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES};
|
||||
use wordcraft_doc::chart::{ChartAxis, ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES, value_axis};
|
||||
use wordcraft_doc::graphic::{Graphic, GraphicKind};
|
||||
use wordcraft_doc::para::{Float, InlineObject};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
@@ -33,6 +33,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("chart.type", "Change Chart Type", "Chart Design › Type", |s, v| {
|
||||
let kind = chart_type(v)?.ok_or_else(|| CmdError::Params(format!("`type` is required: {TYPES}")))?;
|
||||
edit(s, |c| {
|
||||
// A scatter series is drawn as markers without a line; the other types draw it.
|
||||
if (c.kind == ChartType::Scatter) != (kind == ChartType::Scatter) {
|
||||
for series in &mut c.series {
|
||||
series.no_line = kind == ChartType::Scatter;
|
||||
if series.no_line && series.markers == Some(false) {
|
||||
series.markers = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pie and doughnut charts have a plain value axis and the other types a new
|
||||
// chart's value axis; an axis left as the old type had it takes the new type's.
|
||||
if c.kind.is_round() != kind.is_round() {
|
||||
let (from, to) = if kind.is_round() { (value_axis(), ChartAxis::default()) } else { (ChartAxis::default(), value_axis()) };
|
||||
if c.val_axis == from {
|
||||
c.val_axis = to;
|
||||
}
|
||||
}
|
||||
c.kind = kind;
|
||||
Ok(())
|
||||
})
|
||||
@@ -52,7 +69,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c.categories = cats.clone();
|
||||
}
|
||||
if let Some(series) = &series {
|
||||
c.series = series.clone();
|
||||
// Each series keeps the formatting of the one it replaces.
|
||||
c.series = series
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, values))| match c.series.get(i) {
|
||||
Some(old) => ChartSeries { name: name.clone(), values: values.clone(), ..old.clone() },
|
||||
None => ChartSeries::new(c.kind, name.clone(), values.clone()),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
@@ -99,6 +124,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let on = p::bool(v, "on").or_else(|| p::bool(v, "value"));
|
||||
edit(s, move |c| {
|
||||
c.data_labels = on.unwrap_or(!c.data_labels);
|
||||
// The chart's setting replaces each series' own.
|
||||
for series in &mut c.series {
|
||||
series.labels = None;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
@@ -152,7 +181,14 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let mut spec = ChartSpec::sample(kind);
|
||||
if let Some(d) = v.get("data") {
|
||||
spec.categories = d.get("categories").map(categories).transpose()?.unwrap_or_default();
|
||||
spec.series = d.get("series").map(series_list).transpose()?.unwrap_or_default();
|
||||
spec.series = d
|
||||
.get("series")
|
||||
.map(series_list)
|
||||
.transpose()?
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(name, values)| ChartSeries::new(kind, name, values))
|
||||
.collect();
|
||||
if spec.series.is_empty() {
|
||||
return Err(CmdError::Params(format!("`data.series` needs at least one series: {DATA}")));
|
||||
}
|
||||
@@ -220,8 +256,8 @@ fn cell_text(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Series from JSON: `[{"name", "values": [number|null|numeric string]}]`.
|
||||
fn series_list(v: &Value) -> Result<Vec<ChartSeries>, CmdError> {
|
||||
/// Series names and values from JSON: `[{"name", "values": [number|null|numeric string]}]`.
|
||||
fn series_list(v: &Value) -> Result<Vec<(String, Vec<Option<f64>>)>, CmdError> {
|
||||
let a = v.as_array().ok_or_else(|| CmdError::Params(format!("`series`: {DATA}")))?;
|
||||
a.iter()
|
||||
.take(MAX_SERIES)
|
||||
@@ -232,7 +268,7 @@ fn series_list(v: &Value) -> Result<Vec<ChartSeries>, CmdError> {
|
||||
None | Some(Value::Null) => Vec::new(),
|
||||
Some(_) => return Err(CmdError::Params("`values`: an array of numbers (null for none)".into())),
|
||||
};
|
||||
Ok(ChartSeries { name, values })
|
||||
Ok((name, values))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ mod sources;
|
||||
mod styles;
|
||||
|
||||
use cross_refs::cross_ref;
|
||||
pub(crate) use cross_refs::leading_breaks;
|
||||
pub use cross_refs::{caption_labels, ref_targets};
|
||||
#[cfg(test)]
|
||||
use generated::ENTRY_STYLE;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::generated::page_of;
|
||||
use super::{CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p};
|
||||
use crate::cmd::references::page_label;
|
||||
|
||||
pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let to = p::str(v, "to").unwrap_or("heading");
|
||||
@@ -10,9 +10,10 @@ pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let find = |ts: Vec<(String, Pos)>| ts.into_iter().find(|(t, _)| t == target || t.starts_with(target));
|
||||
let (text, pos) = find(targets).ok_or_else(|| CmdError::Params(format!("no {to} `{target}`")))?;
|
||||
let show = p::str(v, "show").unwrap_or("text");
|
||||
let page = page_of(s, &pos);
|
||||
let result = match show {
|
||||
"page" => page.to_string(),
|
||||
// The page the target's text starts on (after its leading page breaks), as its footer
|
||||
// shows it.
|
||||
"page" => page_label(s, &Pos { off: leading_breaks(&s.doc, &pos), ..pos.clone() }),
|
||||
"number" => text.split(':').next().unwrap_or(&text).trim().to_string(),
|
||||
"aboveBelow" => {
|
||||
if pos < s.sel.focus {
|
||||
@@ -152,6 +153,23 @@ pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> {
|
||||
targets
|
||||
}
|
||||
|
||||
/// The offset just past the page breaks at the start of the paragraph at `pos`, skipping bookmark
|
||||
/// marks among them (a `_Ref` bookmark may start before the breaks): its text starts there.
|
||||
pub(crate) fn leading_breaks(doc: &Document, pos: &Pos) -> usize {
|
||||
let Some(p) = doc.para(pos.story, &pos.path) else { return 0 };
|
||||
let mut after = 0;
|
||||
for (i, c) in p.text.char_indices() {
|
||||
if c == '\u{0C}' {
|
||||
after = i.saturating_add(c.len_utf8());
|
||||
} else if c != wordcraft_doc::para::OBJ
|
||||
|| !matches!(p.object_at(i), Some(InlineObject::BookmarkStart { .. } | InlineObject::BookmarkEnd { .. }))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
/// The hidden `_Ref` bookmark around the target paragraph at `pos` (its label and number only
|
||||
/// when `number_only`), reusing one already there. Returns its name and `at` moved past the
|
||||
/// bookmark marks inserted before it.
|
||||
@@ -159,16 +177,22 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R
|
||||
const MARK: usize = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let para = s.doc.para(pos.story, &pos.path).ok_or_else(|| CmdError::Params("cross-reference target is gone".into()))?;
|
||||
let end = if number_only { para.text.find(':').unwrap_or(para.len()) } else { para.len() };
|
||||
if let Some(InlineObject::BookmarkStart { name }) = para.object_at(0)
|
||||
&& name.starts_with("_Ref")
|
||||
{
|
||||
// Reuse it when it covers the same extent: up to the colon, or the whole paragraph.
|
||||
let same = para.object_offsets().into_iter().any(|o| {
|
||||
matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name)
|
||||
&& para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() })
|
||||
});
|
||||
if same {
|
||||
return Ok((name.clone(), at));
|
||||
// The bookmark starts after the leading page breaks, so `PAGEREF` reads the page the text is on.
|
||||
let start = leading_breaks(&s.doc, pos).min(end);
|
||||
// Reuse one that starts there or at the paragraph's start (before the breaks): the field's
|
||||
// result still reads the page the text is on.
|
||||
for from in [start, 0] {
|
||||
if let Some(InlineObject::BookmarkStart { name }) = para.object_at(from)
|
||||
&& name.starts_with("_Ref")
|
||||
{
|
||||
// Reuse it when it covers the same extent: up to the colon, or the whole paragraph.
|
||||
let same = para.object_offsets().into_iter().any(|o| {
|
||||
matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name)
|
||||
&& para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() })
|
||||
});
|
||||
if same {
|
||||
return Ok((name.clone(), at));
|
||||
}
|
||||
}
|
||||
}
|
||||
let next =
|
||||
@@ -176,11 +200,11 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R
|
||||
let name = format!("_Ref{next:09}");
|
||||
let props = CharProps::default();
|
||||
s.doc.insert_object(&Pos { off: end, ..pos.clone() }, InlineObject::BookmarkEnd { name: name.clone() }, &props)?;
|
||||
s.doc.insert_object(&Pos { off: 0, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?;
|
||||
s.doc.insert_object(&Pos { off: start, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?;
|
||||
if at.story == pos.story && at.path == pos.path {
|
||||
if at.off >= end {
|
||||
at.off = at.off.saturating_add(2 * MARK);
|
||||
} else if at.off > 0 {
|
||||
} else if at.off > start {
|
||||
at.off = at.off.saturating_add(MARK);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ use super::{
|
||||
Block, CharProps, CmdError, CmdResult, Document, FieldCode, InlineObject, Paragraph, Path, Pos, Session, SortKey, StoryRef, TabAlign, TabLeader,
|
||||
TabStop, Value, delete_selection, heading_letter, p, sel_result, sort_key,
|
||||
};
|
||||
use crate::cmd::references::{page_at, page_formats, page_text};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
/// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "<label>"` lists the
|
||||
/// captions that label's SEQ field numbers, `\a "<label>"` lists them without their label and
|
||||
@@ -331,9 +333,11 @@ fn add_entry_style(s: &mut Session) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn page_of(s: &mut Session, pos: &Pos) -> u32 {
|
||||
/// The page holding `pos`: its index in the layout (to order and deduplicate by) and its number
|
||||
/// in its section's format (`ii`), as the list writes it. Page "1" (index 0) when no page holds it.
|
||||
fn page_of(s: &mut Session, formats: &[NumFormat], pos: &Pos) -> (usize, String) {
|
||||
let l = s.layout();
|
||||
l.caret(pos).and_then(|c| l.pages.get(c.page)).map(|p| p.number).unwrap_or(1)
|
||||
page_at(&l, formats, pos).map_or_else(|| (0, "1".into()), |(i, n, fmt)| (i, page_text(n, fmt)))
|
||||
}
|
||||
|
||||
/// Entry lines (text, hanging indent) for a generated list.
|
||||
@@ -370,7 +374,7 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut with_pages: Vec<(String, u32)> = marks.into_iter().map(|(e, _)| (e, 0)).collect();
|
||||
let mut with_pages: Vec<(String, (usize, String))> = marks.into_iter().map(|(e, _)| (e, (0, String::new()))).collect();
|
||||
// Pages (layout once).
|
||||
let positions: Vec<Pos> = {
|
||||
let mut v = Vec::new();
|
||||
@@ -393,8 +397,9 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
}
|
||||
v
|
||||
};
|
||||
let formats = page_formats(s);
|
||||
for (i, pos) in positions.iter().enumerate() {
|
||||
let pg = page_of(s, pos);
|
||||
let pg = page_of(s, &formats, pos);
|
||||
if let Some(x) = with_pages.get_mut(i) {
|
||||
x.1 = pg;
|
||||
}
|
||||
@@ -403,14 +408,15 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
// `\n` without page numbers; `\p` the separator before them (a tab by default).
|
||||
let f = FieldCode::parse(kind);
|
||||
let sep = f.arg('p').unwrap_or("\t");
|
||||
return with_pages.into_iter().map(|(t, p)| (if f.has('n') { t } else { format!("{t}{sep}{p}") }, false)).collect();
|
||||
return with_pages.into_iter().map(|(t, p)| (if f.has('n') { t } else { format!("{t}{sep}{}", p.1) }, false)).collect();
|
||||
}
|
||||
// Index / TOA: group by entry, sort, list pages.
|
||||
let lang = crate::cmd::default_lang(s);
|
||||
let mut grouped: std::collections::BTreeMap<(SortKey, String), Vec<u32>> = Default::default();
|
||||
// Each page once, in page order (by its place in the layout, not its label: `ii` before `1`).
|
||||
let mut grouped: std::collections::BTreeMap<(SortKey, String), Vec<(usize, String)>> = Default::default();
|
||||
for (e, p) in with_pages {
|
||||
let pages = grouped.entry((sort_key(&e, lang.as_deref()), e)).or_default();
|
||||
if !pages.contains(&p) {
|
||||
if !pages.iter().any(|(i, _)| *i == p.0) {
|
||||
pages.push(p);
|
||||
}
|
||||
}
|
||||
@@ -424,7 +430,7 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
out.push((l, false));
|
||||
}
|
||||
}
|
||||
let list = pages.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let list = pages.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>().join(", ");
|
||||
out.push(if kind.starts_with("INDEX") { (format!("{e}, {list}"), true) } else { (format!("{e}\t{list}"), false) });
|
||||
}
|
||||
out
|
||||
|
||||
@@ -488,6 +488,32 @@ fn table_of_authorities_updates() {
|
||||
assert!(after.matches("Doe v. Roe").count() > t.matches("Doe v. Roe").count(), "{after}");
|
||||
}
|
||||
|
||||
/// #3856: the table of figures and the table of authorities write each page as its footer shows
|
||||
/// it, in the section's number format; the authority cited on pages i and ii lists both.
|
||||
#[test]
|
||||
fn figures_and_authorities_follow_the_page_number_format() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Smith v. Jones held it.\nSmith v. Jones again."));
|
||||
s.run("select.text", &json!({"text": "Smith v. Jones again"})).unwrap();
|
||||
s.run("caret.home", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "page"})).unwrap();
|
||||
s.run("references.caption", &json!({"label": "Figure", "text": "The court"})).unwrap();
|
||||
for occurrence in [1, 2] {
|
||||
s.run("select.text", &json!({"text": "Smith v. Jones", "occurrence": occurrence})).unwrap();
|
||||
s.run("references.markCitation", &json!({})).unwrap();
|
||||
}
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 1})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("references.tableOfFigures", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("references.tableOfAuthorities", &json!({})).unwrap();
|
||||
let t = s.doc.plain_text(StoryRef::Body);
|
||||
assert!(t.contains("Figure 1: The court\tii"), "{t}");
|
||||
assert!(t.contains("Smith v. Jones\ti, ii"), "{t}");
|
||||
}
|
||||
|
||||
/// Field instructions and results in the body, in order.
|
||||
fn fields(s: &Session) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
@@ -900,3 +926,42 @@ fn citation_refresh_source_lookup_work_scales_with_document_size() {
|
||||
let p = big.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert!(p.objects.iter().enumerate().all(|(i, o)| matches!(o, InlineObject::Field { result, .. } if result == &format!("[{}]", i + 1))));
|
||||
}
|
||||
|
||||
/// A heading that starts with a page break and has a `_Ref` bookmark from before the break: the
|
||||
/// page cross-reference reuses it and reads the heading's page, and still does after Update Field.
|
||||
#[test]
|
||||
fn a_ref_bookmark_before_a_page_break_reads_the_heading_page() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface"));
|
||||
s.run("select.text", &json!({"text": "Preface"})).unwrap();
|
||||
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.run("caret.home", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "page"})).unwrap();
|
||||
let path =
|
||||
s.doc.para_paths(StoryRef::Body).into_iter().find(|p| s.doc.para(StoryRef::Body, p).is_some_and(|p| p.text.contains("Preface"))).unwrap();
|
||||
let len = s.doc.para(StoryRef::Body, &path).unwrap().len();
|
||||
let props = CharProps::default();
|
||||
s.doc
|
||||
.insert_object(
|
||||
&Pos { story: StoryRef::Body, path: path.clone(), off: len },
|
||||
InlineObject::BookmarkEnd { name: "_Ref000000003".into() },
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
s.doc.insert_object(&Pos { story: StoryRef::Body, path, off: 0 }, InlineObject::BookmarkStart { name: "_Ref000000003".into() }, &props).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.crossReference", &json!({"to": "heading", "target": "Preface", "show": "page"})).unwrap();
|
||||
let pageref = |s: &Session| {
|
||||
s.doc
|
||||
.para_paths(StoryRef::Body)
|
||||
.into_iter()
|
||||
.flat_map(|p| s.doc.para(StoryRef::Body, &p).map(|p| p.objects.clone()).unwrap_or_default())
|
||||
.find_map(|o| match o {
|
||||
InlineObject::Field { instr, result, .. } if instr.starts_with("PAGEREF") => Some((instr, result)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(pageref(&s), ("PAGEREF _Ref000000003 \\h".to_string(), "2".to_string()));
|
||||
crate::cmd::references::update_fields_in(&mut s, true).unwrap();
|
||||
assert_eq!(pageref(&s).1, "2");
|
||||
}
|
||||
|
||||
@@ -20,9 +20,12 @@ pub const SNAP: f32 = 12.0;
|
||||
/// Largest offset a routed connector gets, points.
|
||||
const MAX_OFFSET: f32 = 4000.0;
|
||||
|
||||
/// `shape.connect` is offered for what it runs on: a floating connector or line in the body text.
|
||||
fn has_connector(s: &Session) -> Option<&'static str> {
|
||||
match super::objects::selected(s) {
|
||||
Some((_, InlineObject::Shape { kind, .. })) if kind.is_connector() => None,
|
||||
Some((pos, InlineObject::Shape { kind, float, .. })) if kind.is_open() => {
|
||||
(pos.story != StoryRef::Body || float.wrap == Wrap::Inline).then_some("only floating connectors in the body text can be glued")
|
||||
}
|
||||
_ => Some("select a connector first"),
|
||||
}
|
||||
}
|
||||
@@ -31,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("shape.connect", "Connect Shapes", "Shape Format › Insert Shapes", connect)
|
||||
.params(
|
||||
r#"{"start"?: end, "end"?: end} end: {"path": [..], "off": n, "site"?: n} (glue to that body shape's connection site; nearest one when omitted) | {"x": pt, "y": pt, "page"?: n} (drag the end there: it glues to a shape's site within 12 pt, else stays free there) | null (unglue)"#,
|
||||
r#"{"start"?: end, "end"?: end} end: {"path": [..], "off": n, "site"?: n} (glue to that body shape's connection site; nearest one when omitted) | {"x": pt, "y": pt, "page"?: n} (drag the end there: it glues to a shape's site within 12 pt, else stays free there) | null (unglue). A plain line's ends only move to points: lines don't glue"#,
|
||||
)
|
||||
.when(has_connector),
|
||||
]
|
||||
@@ -186,13 +189,23 @@ fn ensure_id(s: &mut Session, pos: &Pos) -> Result<u32, CmdError> {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// `shape.connect`: glue, move or unglue the selected connector's ends.
|
||||
/// A floating line or connector's start and end on its page: its frame's ends (flips
|
||||
/// included), turned with the frame by `deg` about its centre.
|
||||
pub fn page_ends(r: wordcraft_geom::Rect, flip_h: bool, flip_v: bool, deg: f32) -> ((f32, f32), (f32, f32)) {
|
||||
let (a, b) = ends(r.x, r.y, r.w, r.h, flip_h, flip_v);
|
||||
let turn = wordcraft_geom::Spin::new(deg, false, false);
|
||||
let (cx, cy) = (r.x + r.w / 2.0, r.y + r.h / 2.0);
|
||||
(turn.apply(cx, cy, a.0, a.1), turn.apply(cx, cy, b.0, b.1))
|
||||
}
|
||||
|
||||
/// `shape.connect`: glue, move or unglue the selected connector's ends, or move a line's.
|
||||
fn connect(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (pos, obj) = super::objects::selected(s).ok_or_else(|| CmdError::Disabled("select a connector first".into()))?;
|
||||
let InlineObject::Shape { kind, float, .. } = &obj else { return Err(CmdError::Disabled("select a connector first".into())) };
|
||||
if !kind.is_connector() {
|
||||
if !kind.is_open() {
|
||||
return Err(CmdError::Disabled("select a connector first".into()));
|
||||
}
|
||||
let line = !kind.is_connector();
|
||||
if pos.story != StoryRef::Body || float.wrap == Wrap::Inline {
|
||||
return Err(CmdError::Disabled("only floating connectors in the body text can be glued".into()));
|
||||
}
|
||||
@@ -200,7 +213,7 @@ fn connect(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let layout = s.layout();
|
||||
let hit = layout.object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the connector isn't laid out".into()))?;
|
||||
let r = hit.rect;
|
||||
let (mut p0, mut p1) = ends(r.x, r.y, r.w, r.h, fh, fv);
|
||||
let (mut p0, mut p1) = page_ends(r, fh, fv, hit.spin.deg);
|
||||
let mut glue: [Option<Option<ConnEnd>>; 2] = [None, None];
|
||||
for (i, key) in ["start", "end"].into_iter().enumerate() {
|
||||
let Some(e) = v.get(key) else { continue };
|
||||
@@ -209,6 +222,9 @@ fn connect(s: &mut Session, v: &Value) -> CmdResult {
|
||||
continue;
|
||||
}
|
||||
let here = if i == 0 { p0 } else { p1 };
|
||||
if line && e.get("path").is_some() {
|
||||
return Err(CmdError::Params(format!("`{key}`: a line's ends move to points; lines don't glue to shapes")));
|
||||
}
|
||||
let (target, site) = if e.get("path").is_some() {
|
||||
let at = body_pos(e).ok_or_else(|| CmdError::Params(format!("`{key}`: no shape there")))?;
|
||||
let th = layout
|
||||
@@ -234,9 +250,9 @@ fn connect(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if page != hit.page {
|
||||
return Err(CmdError::Params("a connector's ends stay on its page".into()));
|
||||
}
|
||||
// The nearest site of a shape (not a connector) within reach.
|
||||
// The nearest site of a shape (not a connector) within reach; a line's end stays free.
|
||||
let mut best: Option<(Pos, u32, f32)> = None;
|
||||
if let Some(pg) = layout.pages.get(page) {
|
||||
if !line && let Some(pg) = layout.pages.get(page) {
|
||||
for it in &pg.items {
|
||||
let wordcraft_layout::Placed::Object { rect, spin, story: StoryRef::Body, path, off, .. } = it else { continue };
|
||||
let at = Pos { story: StoryRef::Body, path: path.clone(), off: *off };
|
||||
|
||||
@@ -63,7 +63,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?;
|
||||
set_accent(s, t.3[0]);
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"name": string (see design.themes)}"#),
|
||||
CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set)
|
||||
.params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#),
|
||||
CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing)
|
||||
|
||||
@@ -7,6 +7,13 @@ use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
use super::{delete_selection, find_pattern, pos_json, sel_result};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
|
||||
/// advertise a web alternative through the same registry/keymap as every other command.
|
||||
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
|
||||
fn copy_format_shortcut(web: bool) -> &'static str {
|
||||
if web { "Mod+Alt+Shift+C / Mod+Shift+C" } else { "Mod+Shift+C" }
|
||||
}
|
||||
|
||||
/// Undo several steps at once: the Undo button's list (#701). `count` is validated here and
|
||||
/// clamped to the undo depth, so hostile numbers never reach the stack.
|
||||
fn undo_to(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -134,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp"))
|
||||
.params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(
|
||||
r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#,
|
||||
),
|
||||
// Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening
|
||||
// it changes nothing, so it is its own command and never marks the document edited.
|
||||
CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| {
|
||||
@@ -165,10 +174,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
|
||||
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
|
||||
painter_pick(s);
|
||||
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
|
||||
s.painter = None;
|
||||
s.copied_format = Some(picked_format(s));
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Mod+Shift+C")
|
||||
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
|
||||
.pure(),
|
||||
CommandSpec::new("edit.pasteFormat", "Paste Formatting", "Home › Clipboard", paste_format).key("Mod+Shift+V"),
|
||||
]
|
||||
@@ -737,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let story = s.sel.focus.story;
|
||||
let results = search_full(s, story, true)?;
|
||||
let (a, b) = s.sel.ordered();
|
||||
// Replace the current match if selected, then move to the next.
|
||||
// Replace the current match if selected, then move to the next. The result says which
|
||||
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
|
||||
let mut replaced = 0;
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
|
||||
super::paste_text(s, &f.rep.unwrap_or_default())?;
|
||||
replaced = 1;
|
||||
}
|
||||
let _ = step(s, 1);
|
||||
Ok(json!({"remaining": search(s, story)?.len()}))
|
||||
let selected = match step(s, 1) {
|
||||
Ok(_) => {
|
||||
let (start, end) = s.sel.ordered();
|
||||
json!({"start": pos_json(&start), "end": pos_json(&end)})
|
||||
}
|
||||
Err(_) => Value::Null,
|
||||
};
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
@@ -825,11 +845,21 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
/// The character and paragraph formatting at the start of the selection.
|
||||
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
|
||||
let f = s.sel.ordered().0;
|
||||
// A symbol's own font isn't formatting to paint onto text.
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
|
||||
// Formatting only: not the source's hyperlink or revision marks (#5616).
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
|
||||
(chr, para)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
let (chr, para) = picked_format(s);
|
||||
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
|
||||
// and stays after the brush is used up or cancelled.
|
||||
s.copied_format = Some((chr.clone(), para.clone()));
|
||||
s.painter = Some((chr, para, false));
|
||||
}
|
||||
|
||||
@@ -845,24 +875,28 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"active": true}))
|
||||
}
|
||||
|
||||
/// Apply the format painter's formatting to the selection.
|
||||
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
|
||||
/// up (which stays for the next Paste Formatting).
|
||||
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
|
||||
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
|
||||
(Some(brush), _) => brush,
|
||||
(None, Some((chr, para))) => (chr, para, true),
|
||||
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
|
||||
};
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b {
|
||||
// No selection: apply paragraph formatting (and word formatting like Word).
|
||||
let f = s.sel.focus.clone();
|
||||
if let Some(pp) = s.doc.para_at(&f) {
|
||||
let (x, y) = pp.word_at(f.off);
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: y, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
|
||||
// Word selection includes trailing spaces; a painter click formats just the word,
|
||||
// matching the ordinary collapsed-caret formatting target.
|
||||
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
}
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
} else {
|
||||
s.doc.format_range(&a, &b, &|c| {
|
||||
let link = c.link.clone();
|
||||
*c = c.cleared().overlaid(&chr);
|
||||
c.link = link;
|
||||
})?;
|
||||
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
if a.path != b.path || a.off == 0 {
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
}
|
||||
@@ -872,3 +906,49 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shortcut_tests {
|
||||
use super::*;
|
||||
use crate::{KeyMap, Registry};
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_is_unique_and_keeps_existing_shortcuts() {
|
||||
for web in [false, true] {
|
||||
let mut commands = super::super::registry().all().to_vec();
|
||||
let copy = commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap();
|
||||
copy.shortcut = copy_format_shortcut(web);
|
||||
let registry = Registry::new(commands);
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for command in registry.all() {
|
||||
for key in command.shortcut.split(" / ").filter_map(crate::keymap::normalize) {
|
||||
assert!(seen.insert(key.clone()), "duplicate binding: {key}");
|
||||
}
|
||||
}
|
||||
let keys = KeyMap::default();
|
||||
let resolve = |key| keys.resolve(®istry, key).map(|c| c.id);
|
||||
assert_eq!(resolve("Mod+Shift+C"), Some("edit.copyFormat"));
|
||||
assert_eq!(resolve("Mod+Alt+Shift+C"), web.then_some("edit.copyFormat"));
|
||||
assert_eq!(resolve("Mod+Shift+V"), Some("edit.pasteFormat"));
|
||||
assert_eq!(resolve("Mod+Alt+Shift+V"), Some("edit.pasteText"));
|
||||
if !cfg!(target_os = "macos") {
|
||||
assert_eq!(resolve("Mod+Alt+C"), Some("text.copyright"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
|
||||
let mut commands = super::super::registry().all().to_vec();
|
||||
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
|
||||
let registry = Registry::new(commands);
|
||||
let mut keys = KeyMap::default();
|
||||
assert_eq!(keys.keys_for(®istry, "edit.copyFormat").first().map(String::as_str), Some("Mod+Alt+Shift+C"));
|
||||
assert!(keys.remove(®istry, "edit.copyFormat", "Mod+Alt+Shift+C").unwrap());
|
||||
assert!(keys.resolve(®istry, "Mod+Alt+Shift+C").is_none());
|
||||
keys.assign(®istry, "format.bold", "Mod+Alt+Shift+C").unwrap();
|
||||
let restored = KeyMap::from_value(&serde_json::to_value(&keys).unwrap());
|
||||
assert_eq!(restored.resolve(®istry, "Mod+Alt+Shift+C").map(|c| c.id), Some("format.bold"));
|
||||
assert_eq!(restored.resolve(®istry, "Mod+Shift+C").map(|c| c.id), Some("edit.copyFormat"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,6 @@ fn gallery_lists_everything() {
|
||||
|
||||
/// A session on a DOCX whose only paragraph is `<m:oMath>{math}</m:oMath>`.
|
||||
fn imported(math: &str) -> Session {
|
||||
use std::io::Write;
|
||||
let w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
let m = "http://schemas.openxmlformats.org/officeDocument/2006/math";
|
||||
let parts = [
|
||||
@@ -117,24 +116,21 @@ fn imported(math: &str) -> Session {
|
||||
),
|
||||
("word/document.xml", format!(r#"<w:document xmlns:w="{w}" xmlns:m="{m}"><w:body><w:p><m:oMath>{math}</m:oMath></w:p><w:sectPr/></w:body></w:document>"#)),
|
||||
];
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let mut zw = craft_zip::Writer::new();
|
||||
for (name, xml) in parts {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
zw.add(name, xml.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
let bytes = zw.finish().unwrap().into_inner();
|
||||
let bytes = zw.finish().unwrap();
|
||||
let mut s = Session::new(wordcraft_docx::read(&bytes).unwrap());
|
||||
s.run("equation.edit", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn document_xml(s: &Session) -> String {
|
||||
use std::io::Read;
|
||||
let bytes = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
xml
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
|
||||
String::from_utf8(z.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> {
|
||||
fn set_code(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let code = p::req_str(v, "code")?.trim().to_string();
|
||||
if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) {
|
||||
return Err(CmdError::Params("bad field code".into()));
|
||||
return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into()));
|
||||
}
|
||||
let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) };
|
||||
with_field(s, &f.at, |o| match o {
|
||||
@@ -441,7 +441,10 @@ mod tests {
|
||||
s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap();
|
||||
let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default();
|
||||
assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report"));
|
||||
assert!(s.run("fields.setCode", &json!({"code": ""})).is_err());
|
||||
assert!(matches!(
|
||||
s.run("fields.setCode", &json!({"code": ""})),
|
||||
Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers"
|
||||
));
|
||||
|
||||
// A locked field keeps its result.
|
||||
s.run("fields.lock", &json!({})).unwrap();
|
||||
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(),
|
||||
CommandSpec::new("file.open", "Open", "File", open)
|
||||
.key("Mod+O / Mod+F12 / Mod+Alt+F2")
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#)
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
// to undo; it marks the document as changed itself.
|
||||
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
|
||||
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
|
||||
// No path (the command search, say): the app asks where to save, as File › Export
|
||||
@@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()}))
|
||||
}
|
||||
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved
|
||||
/// with from now on, or none.
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word packages and
|
||||
/// OpenDocument text files (.odt, .ott) are saved with from now on, or none.
|
||||
fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let password = match v.get("password") {
|
||||
Some(Value::Null) => None,
|
||||
@@ -651,6 +651,77 @@ fn info(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Most fields [`story_fields`] lists for one story, and how deep it goes into nested tables.
|
||||
const MAX_STORY_FIELDS: usize = 200;
|
||||
const MAX_STORY_DEPTH: usize = 8;
|
||||
|
||||
/// The fields of a story's paragraphs, tables included: the code, the result stored with it, and
|
||||
/// whether the page shows a value of its own (#4467). A header or footer's text carries the
|
||||
/// stored result of a page field (`1` for a PAGE, the page count when it was inserted for a
|
||||
/// NUMPAGES); each page shows its own, as the layout draws it. A STYLEREF counts too: the layout
|
||||
/// looks its text up from the page it lands on. False when a limit cut the list short.
|
||||
fn story_fields(blocks: &wordcraft_doc::Blocks, depth: usize, out: &mut Vec<Value>) -> bool {
|
||||
if depth > MAX_STORY_DEPTH {
|
||||
return false;
|
||||
}
|
||||
for b in blocks {
|
||||
match &**b {
|
||||
Block::Para(p) => {
|
||||
for o in &p.objects {
|
||||
if let wordcraft_doc::para::InlineObject::Field { instr, result, .. } = o {
|
||||
if out.len() >= MAX_STORY_FIELDS {
|
||||
return false;
|
||||
}
|
||||
out.push(field_json(instr, result));
|
||||
}
|
||||
}
|
||||
}
|
||||
Block::Table(t) => {
|
||||
for cell in t.rows.iter().flat_map(|r| &r.cells) {
|
||||
if !story_fields(&cell.blocks, depth + 1, out) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The range fields of `story` (a `FieldStart` … `FieldEnd` pair: what the DOCX reader makes of a
|
||||
/// field whose result has tracked changes of its own or spans paragraphs, and of every TOC),
|
||||
/// listed as [`story_fields`] lists inline ones, after them; the result is the text between the
|
||||
/// markers as it is, at most [`MAX_RANGE_RESULT`] characters of it (`resultTruncated` when it is
|
||||
/// cut: a bibliography or a long TOC). False when a limit cut the list short.
|
||||
fn range_fields(doc: &Document, story: StoryRef, out: &mut Vec<Value>) -> bool {
|
||||
for r in doc.field_ranges(story) {
|
||||
if out.len() >= MAX_STORY_FIELDS {
|
||||
return false;
|
||||
}
|
||||
let from = wordcraft_doc::Pos { off: r.start.off.saturating_add(wordcraft_doc::para::OBJ.len_utf8()), ..r.start.clone() };
|
||||
let text = doc.copy_range(&from, &r.end).plain_text();
|
||||
let mut chars = text.chars().filter(|c| *c != wordcraft_doc::para::OBJ);
|
||||
let result: String = chars.by_ref().take(MAX_RANGE_RESULT).collect();
|
||||
let mut field = field_json(&r.instr, &result);
|
||||
if chars.next().is_some() {
|
||||
field["resultTruncated"] = json!(true);
|
||||
}
|
||||
out.push(field);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Longest result `document.inspect` gives a range field, in characters.
|
||||
const MAX_RANGE_RESULT: usize = 2000;
|
||||
|
||||
/// A field as `document.inspect` lists it: its code, its stored result, and whether each page
|
||||
/// shows a value of its own.
|
||||
fn field_json(instr: &str, result: &str) -> Value {
|
||||
let name = wordcraft_layout::fields::field_name(instr);
|
||||
let per_page = matches!(name.as_str(), "PAGE" | "NUMPAGES" | "SECTIONPAGES" | "SECTION" | "PAGEREF" | "STYLEREF");
|
||||
json!({"code": instr.trim(), "result": result, "perPage": per_page})
|
||||
}
|
||||
|
||||
/// Structure for agents: blocks with text and formatting summary, selection, stats.
|
||||
fn inspect(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let with_text = p::bool(v, "text").unwrap_or(true);
|
||||
@@ -702,8 +773,23 @@ fn inspect(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
let l = s.layout();
|
||||
let parts: Vec<Value> =
|
||||
s.doc.parts.iter().map(|(id, p)| json!({"id": id, "kind": p.kind, "text": s.doc.plain_text(StoryRef::Part(*id))})).collect();
|
||||
let parts: Vec<Value> = s
|
||||
.doc
|
||||
.parts
|
||||
.iter()
|
||||
.map(|(id, p)| {
|
||||
let mut o = json!({"id": id, "kind": p.kind, "text": s.doc.plain_text(StoryRef::Part(*id))});
|
||||
let mut fields = Vec::new();
|
||||
let complete = story_fields(&p.blocks, 0, &mut fields) && range_fields(&s.doc, StoryRef::Part(*id), &mut fields);
|
||||
if !fields.is_empty() {
|
||||
o["fields"] = json!(fields);
|
||||
}
|
||||
if !complete {
|
||||
o["fieldsTruncated"] = json!(true);
|
||||
}
|
||||
o
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"blocks": blocks,
|
||||
"parts": parts,
|
||||
|
||||
@@ -198,9 +198,14 @@ fn special(query: &str, o: &Opts) -> (String, bool) {
|
||||
if (o.ignore_punct && is_punct(c)) || (o.ignore_space && is_space(c)) {
|
||||
continue;
|
||||
}
|
||||
// A keyboard apostrophe also finds text produced by smart quotes. Explicit character
|
||||
// codes above, and literal/regex/wildcard searches, keep exact character matching.
|
||||
atoms.push(if c == '\'' { "['‘’]".into() } else { lit(c) });
|
||||
// A keyboard apostrophe or double quote also finds text produced by smart quotes.
|
||||
// Explicit character codes above, and literal/regex/wildcard searches, keep exact
|
||||
// character matching.
|
||||
atoms.push(match c {
|
||||
'\'' => "['‘’]".into(),
|
||||
'"' => "[\"“”]".into(),
|
||||
_ => lit(c),
|
||||
});
|
||||
}
|
||||
let filler = match (o.ignore_punct, o.ignore_space) {
|
||||
(true, true) => r"[\p{P} \t\x{A0}]*",
|
||||
|
||||
@@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let Some(n) = v.get(k) else { return Ok(None) };
|
||||
let n = n.as_str().map(str::trim).unwrap_or("");
|
||||
if n.is_empty() || n.len() > 128 {
|
||||
return Err(CmdError::Params(format!("bad font name `{k}`")));
|
||||
return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes")));
|
||||
}
|
||||
Ok(Some(n.to_string()))
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user