diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dfd9910eba..b0959ec140 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ on: default: "" permissions: - contents: write + contents: read concurrency: group: release-${{ github.ref }} @@ -19,6 +19,10 @@ concurrency: jobs: release: + # Only this job publishes the GitHub release, so only it gets write access. + permissions: + contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 85a3f19518..a7b3e0d2f6 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -26,8 +26,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main with: app-name: wordcraft app-dir: WordCraft diff --git a/AGENTS.md b/AGENTS.md index 44ec9f17be..f52cb94d7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,13 +1,13 @@ # WordCraft — instructions for agents -WordCraft is a clean-room, open-source, Rust-native word processor targeting Microsoft Word parity — and going further on speed, openness and agent control. It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). Shared rules and learnings: [`storytold/craftrules`](https://github.com/storytold/craftrules) (`../../craftrules`) — read its `AGENTS.md`. +WordCraft is a clean-room, open-source, Rust-native word processor targeting Microsoft Word parity — and going further on speed, openness and agent control. It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. `plan/` is gitignored (local only); if it's missing, start from `ROADMAP.md`, `docs/gaps.md` and `docs/roadmap.md` (Current focus). 2. Follow the autonomous operation protocol (`plan/execution-plan.md` §5). Don't stop to ask unless a decision is genuinely the owner's (licensing, publishing, pushing to new remotes, secrets). ## Never crash -People trust WordCraft with their writing; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust WordCraft with their writing; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). - **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or is disabled; it never panics. - **Input-derived numbers are hostile** (files, commands, MCP/control params): `get()` instead of `[i]`, slice strings only at char boundaries, checked/saturating arithmetic, clamp sizes, cap allocations, bound recursion. @@ -63,22 +63,24 @@ Typing, Enter, Backspace, Tab, lists, AutoCorrect and AutoFormat follow Word's o - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -Progress docs follow [`craftrules/standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md): `ROADMAP.md` (stage, headline numbers, progress log), `docs/target-app-parity.md` (the assessment), `docs/gaps.md` (ranked work list), `docs/roadmap.md` (milestones, Current focus), `docs/architecture.md`, and the parity checklists `docs/file-format-parity.md`, `docs/layout-parity.md`, `docs/typing-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the gap, the parity doc and the progress log, and bump each touched doc's status line and revision history. +Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/target-app-parity.md` (the assessment), `docs/gaps.md` (ranked work list), `docs/roadmap.md` (milestones, Current focus), `docs/architecture.md`, and the parity checklists `docs/file-format-parity.md`, `docs/layout-parity.md`, `docs/typing-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the gap, the parity doc and the progress log, and bump each touched doc's status line and revision history. ## Contributor credits (About window) - About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` - (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for + (commit stats; never hand-edit) and `contributors/people.toml` (names people chose for themselves). See `docs/contributors.md`. - **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once whether they want to be credited by more than their username: a real name, a display name, and/or their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file, or run - `python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`) + (copy the template at the top of the file) and include it in their PR, committed as them. If no, change nothing: they are credited as `@username` anyway. - Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or GitHub profiles). Never hand-edit `contributors.json`. -- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also - re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- 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. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5f1eba265b..23d8cbd219 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -59,14 +59,14 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `docs/images/dark.png` | WordCraft contributors | screenshot of WordCraft itself (sample document written for WordCraft, rendered by `ui_shot`) | MIT OR Apache-2.0 | Original; no Microsoft UI or assets | | `docs/images/backstage.png` | WordCraft contributors | screenshot of WordCraft itself (sample document written for WordCraft, rendered by `ui_shot`) | MIT OR Apache-2.0 | Original; no Microsoft UI or assets | | `docs/images/layout.png` | WordCraft contributors | screenshot of WordCraft itself (sample document written for WordCraft, rendered by `ui_shot`) | MIT OR Apache-2.0 | Original; no Microsoft UI or assets | -| `docs/brand/LICENSE-brand.txt` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-logo.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-logo.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-mark.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | -| `docs/brand/artcraft-mark.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/LICENSE-brand.txt` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | +| `docs/brand/artcraft-mark.svg` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only | | craft-fonts (optional build input, not files in this repo): BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic | see https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | embedded only when built with `CRAFT_FONTS_DIR` (all official releases) | OFL-1.1 | Japanese and Chinese UI, Japanese document fallback | | craft-i18n (optional build input, not files in this repo): the interface translations | see https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md, which credits every translator of WordCraft's former in-repo catalogs (`crates/ui-egui/src/i18n/*.tsv`, migrated at `wordcraft@806a945`) | embedded only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | MIT OR Apache-2.0 | Interface languages other than English; clean-room translations from the English interface labels | diff --git a/CLAUDE.md b/CLAUDE.md index 55b2767729..35024b74d0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,13 +1,13 @@ # WordCraft — instructions for agents -WordCraft is a clean-room, open-source, Rust-native word processor targeting Microsoft Word parity — and going further on speed, openness and agent control. It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). Shared rules and learnings: [`storytold/craftrules`](https://github.com/storytold/craftrules) (`../../craftrules`) — read its `AGENTS.md`. +WordCraft is a clean-room, open-source, Rust-native word processor targeting Microsoft Word parity — and going further on speed, openness and agent control. It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. `plan/` is gitignored (local only); if it's missing, start from `ROADMAP.md`, `docs/gaps.md` and `docs/roadmap.md` (Current focus). 2. Follow the autonomous operation protocol (`plan/execution-plan.md` §5). Don't stop to ask unless a decision is genuinely the owner's (licensing, publishing, pushing to new remotes, secrets). ## Never crash -People trust WordCraft with their writing; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust WordCraft with their writing; a crash loses their work. **This outranks feature work**: never ship a feature through a panic path, and fix a crash before building on top of it. - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). - **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or is disabled; it never panics. - **Input-derived numbers are hostile** (files, commands, MCP/control params): `get()` instead of `[i]`, slice strings only at char boundaries, checked/saturating arithmetic, clamp sizes, cap allocations, bound recursion. @@ -62,4 +62,9 @@ Typing, Enter, Backspace, Tab, lists, AutoCorrect and AutoFormat follow Word's o - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -Progress docs follow [`craftrules/standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md): `ROADMAP.md` (stage, headline numbers, progress log), `docs/target-app-parity.md` (the assessment), `docs/gaps.md` (ranked work list), `docs/roadmap.md` (milestones, Current focus), `docs/architecture.md`, and the parity checklists `docs/file-format-parity.md`, `docs/layout-parity.md`, `docs/typing-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the gap, the parity doc and the progress log, and bump each touched doc's status line and revision history. +Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/target-app-parity.md` (the assessment), `docs/gaps.md` (ranked work list), `docs/roadmap.md` (milestones, Current focus), `docs/architecture.md`, and the parity checklists `docs/file-format-parity.md`, `docs/layout-parity.md`, `docs/typing-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the gap, the parity doc and the progress log, and bump each touched doc's status line and revision history. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- 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. diff --git a/Cargo.lock b/Cargo.lock index 901e13678b..0500086433 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -809,9 +809,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -1084,13 +1084,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", @@ -1207,9 +1208,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a" dependencies = [ "cmov", ] @@ -6647,7 +6648,7 @@ dependencies = [ [[package]] name = "wordcraft" -version = "0.12.0" +version = "0.13.2" dependencies = [ "arboard", "chrono", @@ -6682,7 +6683,7 @@ dependencies = [ [[package]] name = "wordcraft-cli" -version = "0.12.0" +version = "0.13.2" dependencies = [ "serde_json", "sys-locale", @@ -6695,11 +6696,11 @@ dependencies = [ [[package]] name = "wordcraft-control-key" -version = "0.12.0" +version = "0.13.2" [[package]] name = "wordcraft-doc" -version = "0.12.0" +version = "0.13.2" dependencies = [ "base64 0.23.1", "log", @@ -6713,7 +6714,7 @@ dependencies = [ [[package]] name = "wordcraft-docbin" -version = "0.12.0" +version = "0.13.2" dependencies = [ "cfb", "chrono", @@ -6730,7 +6731,7 @@ dependencies = [ [[package]] name = "wordcraft-docx" -version = "0.12.0" +version = "0.13.2" dependencies = [ "aes", "base64 0.23.1", @@ -6754,7 +6755,7 @@ dependencies = [ [[package]] name = "wordcraft-engine" -version = "0.12.0" +version = "0.13.2" dependencies = [ "cfb", "chrono", @@ -6785,7 +6786,7 @@ dependencies = [ [[package]] name = "wordcraft-fonts" -version = "0.12.0" +version = "0.13.2" dependencies = [ "brotli-decompressor", "harfrust 0.13.3", @@ -6799,7 +6800,7 @@ dependencies = [ [[package]] name = "wordcraft-formats" -version = "0.12.0" +version = "0.13.2" dependencies = [ "cfb", "chardetng", @@ -6812,12 +6813,13 @@ dependencies = [ "quick-xml 0.41.0", "wordcraft-doc", "wordcraft-geom", + "wordcraft-metafile", "zip 3.0.0", ] [[package]] name = "wordcraft-geom" -version = "0.12.0" +version = "0.13.2" dependencies = [ "image", "serde", @@ -6825,7 +6827,7 @@ dependencies = [ [[package]] name = "wordcraft-layout" -version = "0.12.0" +version = "0.13.2" dependencies = [ "image", "js-sys", @@ -6845,7 +6847,7 @@ dependencies = [ [[package]] name = "wordcraft-mcp" -version = "0.12.0" +version = "0.13.2" dependencies = [ "log", "serde_json", @@ -6857,7 +6859,7 @@ dependencies = [ [[package]] name = "wordcraft-metafile" -version = "0.12.0" +version = "0.13.2" dependencies = [ "kurbo", "thiserror 2.0.21", @@ -6865,7 +6867,7 @@ dependencies = [ [[package]] name = "wordcraft-pdf" -version = "0.12.0" +version = "0.13.2" dependencies = [ "chrono", "craft-pdf", @@ -6886,7 +6888,7 @@ dependencies = [ [[package]] name = "wordcraft-proof" -version = "0.12.0" +version = "0.13.2" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -6896,7 +6898,7 @@ dependencies = [ [[package]] name = "wordcraft-render" -version = "0.12.0" +version = "0.13.2" dependencies = [ "image", "log", @@ -6910,7 +6912,7 @@ dependencies = [ [[package]] name = "wordcraft-ui-egui" -version = "0.12.0" +version = "0.13.2" dependencies = [ "cfb", "chrono", @@ -6941,7 +6943,7 @@ dependencies = [ [[package]] name = "wordcraft-web" -version = "0.12.0" +version = "0.13.2" dependencies = [ "eframe", "egui", @@ -6960,7 +6962,7 @@ dependencies = [ [[package]] name = "wordcraft-zotero" -version = "0.12.0" +version = "0.13.2" dependencies = [ "log", "proptest", @@ -7123,7 +7125,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.12.0" +version = "0.13.2" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index eca974d33b..ecf431a0fa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/wordcraft", "apps/wordcraft-cli", "xtask"] [workspace.package] -version = "0.12.0" +version = "0.13.2" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -59,7 +59,8 @@ 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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", default-features = false, features = ["write"] } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +# 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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } # zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates. diff --git a/ROADMAP.md b/ROADMAP.md index 02b23eab2f..78d27c7307 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,8 +4,8 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. WordCraft aims for complete parity with Microsoft Word, then goes further on speed, openness and @@ -140,7 +140,28 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log +- 2026-10-31: DOCX: a paragraph naming a style the file doesn't define is formatted as Normal, as in Word, not with the document defaults alone, so a Pandoc footer naming an undefined `Footer` style is as tall as Word's and no longer pushes the last paragraph to the next page (#5077). Readiness unchanged. +- 2026-10-31: A table of contents writes its page numbers as `PAGEREF` fields to the headings' bookmarks, as Word does, so updating the fields in Word moves the numbers with the headings; they were plain text (#5097). +- 2026-10-31: Keytips reach the Backstage: Alt, F badges its pages with Word's letters, and Alt, F, P (or V) opens Print (#4960). +- 2026-10-29: Documents with hyperlinks or a table of contents print again on the desktop (#4734). The print job scales each page to the paper, and the spooler refused a page with link annotations ("flatten page annotations before using shrink-to-fit"); the PDF sent to the printer now omits link annotations, which print nothing; the link and table-of-contents text stays on the page. Exported PDFs and Save these pages as PDF (`file.printPdf`) keep the annotations. +- 2026-10-28: Word count counts each Chinese and Japanese character as a word, as Word does, in the status bar, the Word Count dialog and NUMWORDS fields. Unspaced Chinese text used to count as one word per run of text; Korean, which is written with spaces, still counts by words. (#4547) +- 2026-10-28: Aligned-copy review fixes keep the document axis locked through middle-button scrolling and let Ctrl/Command+Shift start on a secondary selected object. Plain Ctrl and Shift clicks keep their existing behavior (#4764). + +- 2026-10-28: Ctrl/Command+Shift copies a selected floating picture, shape or text box along its dominant axis (#4764); inline copies keep the text cursor. Guides on the free axis, original/clipboard/selection, cancel, protection and history are covered by synthetic Linux tests. Native desktop and Word untested; readiness unchanged. + +- 2026-10-28: Charts and SmartArt draw text their font lacks in a fallback face, as body text does: Chinese titles, axis labels and legends no longer show boxes (#4720). A run of such characters takes one face that covers it all, so a label doesn't mix serif and sans glyphs; bold labels stay bold. +- 2026-10-28: Custom document properties retain their bookmark link targets through DOCX saves, native JSON reopens, value edits and dialog renames (#4767). Linked values are not evaluated; the existing dialog and field-update behavior are unchanged. Original fixtures cover ordinary and raw property values; broader corpus qualification and readiness estimates remain unchanged. + +- 2026-10-29: Increase/Decrease Font Size and the one-point shortcuts change each selected run from its own resolved size, retaining mixed-size formatting, inherited styles and one-step Undo (#4903). Existing size steps and limits stay unchanged. + +- 2026-10-28: Convert Notes walks reference offsets and formatting runs together instead of rescanning all references for every run (#4750). Note text, IDs, custom marks, styles, history and saved content retain their behavior. Synthetic scaling, CLI/MCP and native/DOCX reopen coverage; readiness estimates unchanged. + +- 2026-10-29: Saving a DOCX with many comments no longer searches all comment paragraph IDs and all reserved durable IDs for each comment. Paragraph IDs use their existing sorted order; durable-ID reservations are indexed once. Parent links, resolved flags, authored text and existing ID rules are unchanged. + +- 2026-10-28: RTF import keeps pictures stored as Windows Metafiles (`\wmetafile8`, as Word writes a pasted or floating picture) and Enhanced Metafiles (`\emfblip`); they were dropped, so such a document opened without its pictures. They are drawn by the metafile renderer, saved to .docx as `.wmf`/`.emf` media, and saved to .rtf as metafiles again (RTF export dropped them too). (#4259) +- 2026-10-27: File › Options › Proofing › AutoCorrect Options opens with no document open (#4585). On the Start screen, or after closing the last document, the button did nothing: AutoCorrect wasn't among the commands allowed without a document. Its options are user preferences, so changes made there are kept for the next document. - 2026-10-29: Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Labels → New Document with one label per recipient includes every selected address, with unused labels blank on the final sheet. Fixed-text and single-label output remain one sheet. Finish & Merge template expansion is separate. +- 2026-10-29: HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged. - 2026-10-22: View › Window › New Window opens a second window on the document (desktop). The windows are titled `Name:1` and `Name:2` and each keeps its own caret, scroll position, zoom and view; edits and Undo are the document's and show in both. Closing one of them asks nothing; the last one asks about unsaved changes, and quitting asks once per document. - 2026-10-22: One native window per open document on the desktop. File › New and Open (from the ribbon, File, shortcuts, the file manager, the command line or the control channel) open the document in a window of its own, focused and placed a step below and right of the last one; opening a file replaces a blank document nobody has used in its own window, and a file that is already open brings its window to the front. Each window keeps its own ribbon tab, File page, dialogs, panes, scroll position and composition. View › Window › Switch Windows lists the windows and brings the chosen one forward. File › Close and a window's close button close that window, asking about unsaved changes first; the last window stays open with no document. Quitting asks about each document with unsaved changes in its own window, and Cancel keeps everything open. The control channel's input and screenshots go to the window focused last. The web app keeps one window. - 2026-10-22: Recovery covers every open document. Each dirty document keeps its own copy, written on the same ten-second cadence whether it is shown or not; closing a document without saving deletes its copy, as saving does, and a clean exit deletes the copies of every document saved or closed since its last copy. File › Recover lists only copies no open document keeps, and Restore opens a copy as another document (or in place of an untouched blank one), so it never replaces work. After a crash with several unsaved documents, the next start lists all of them. @@ -202,7 +223,15 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target - 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096). | Date | What landed | +| 2026-10-28 | **Arabic diacritic editing (#4757):** Backspace removes the last stored Arabic combining mark, so its base letter can stay while the mark is replaced. Caret movement and forward Delete keep their cluster rules. Synthetic command, history, protection and native/DOCX fresh-reopen checks; no native Word comparison or readiness change. | +| 2026-10-29 | Insert › Shapes shows the basic shapes as a grid of code-drawn icon tiles, each with an accessible name and tooltip, instead of a text list (#4349) | +| 2026-10-29 | Window sizing falls back to the screen rectangle when the reported inner size is invalid, and an Equation symbol tooltip no longer repeats a missing glyph's name or code point | +| 2026-10-29 | A NUL in a document title no longer reaches the native window title, which panicked on X11 (#3634): displayed titles and suggested file names drop NUL characters and fall back to the untitled name when empty; the stored title is unchanged | +| 2026-10-28 | The Traditional Chinese interface draws hanzi to the Taiwan standard: on the desktop an installed Traditional Chinese font (PingFang TC on macOS, Microsoft JhengHei on Windows, Noto Sans CJK TC on Linux) comes before the embedded Noto Sans CJK SC, which drew 說, 這, 為, 戶 in mainland shapes; without one, and on the web, nothing changes. | +| 2026-10-17 | macOS launch arguments (`-psn_*`, `-NS*`, `-Apple*`) are no longer opened as files, and a file that fails to open names the file and the real cause on the status bar and in the log (#1103). The reported "corrupt" error could not be reproduced. | | 2026-10-17 | Password-protected Word files from Word 2007 (Standard encryption: AES-128/192/256, SHA-1) open with their password, also when named `.doc` or `.dot`; a wrong or missing password is reported as for newer files. Word 97-2003 files with an AES header, which the public spec doesn't define, are refused with a clear message (gap 9) | +| 2026-10-27 | Connector rerouting indexes laid-out object positions once per batch, preserving page hints, first-match order and same-page glue; synthetic equivalence, geometry and scaling regressions (#3631); routing policy and readiness estimates unchanged | +| 2026-10-28 | Markdown import bounds nested undefined reference-label work within the existing link allowance; literal source and normal reference matching are preserved (#4658). | | 2026-10-23 | A command that changes nothing is not an edit: it adds no undo step, marks no unsaved changes and forces no relayout, so the redo stack survives it and five hundred of them can no longer push the user's own edits out of the undo history. | | 2026-10-23 | Interface translations come from storytold/craft-i18n, shared with the other Crafting Apps: the catalogs are embedded at build time from the commit in `craft-i18n.rev` and looked up through craft-libs' `craft-i18n` crate; `crates/ui-egui/src/i18n/*.tsv` are gone (translations now go to craft-i18n). Strings other apps already translate show translated; a build without `CRAFT_I18N_DIR` is English only | | 2026-10-25 | #4085 mark review: whole-cell and ordinary highlight targets include their selected paragraph marks; empty, inherited and partial-column controls added. | @@ -256,6 +285,8 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-16 | DOCX: a `HYPERLINK` field (complex or simple) reads as a link, as a `w:hyperlink` does: its result stays ordinary text carrying the link (`url`, `url#bookmark` or `#bookmark`), so a tab in it reaches its tab stop and a `PAGEREF` in it stays a field (#2174). A table of contents from Word for the web, whose entries are such fields, showed a box for each tab and no dot leaders; the entries now open as in Word and their links work | | 2026-10-17 | The document's right-click menu offers the ribbon's Paste menu, item for item (#2583): Paste (the clipboard's formatting kept, Word's Keep Source Formatting), Keep Text Only, Merge Formatting and Paste Special…, where it had a single Paste. Same commands and shortcuts, with the system clipboard | | 2026-10-17 | SmartArt Text Pane: Tab demotes and Shift+Tab promotes the focused item, as Word's pane does (#2701). The row keeps its focus, so a second Tab acts on the same item; an item that can't go down a level is left alone | +| 2026-10-15 | Selected table rows and cells copy as a table (#1744): Copy of whole rows, of cells in a row, or of a block of cells over several rows, then Paste outside the table, inserts a table of just those cells; Cut of rows or cells clears their text and leaves the rows and cells in place (the clipboard still gets the table), as Word does. Copy used to take only the cells' paragraphs | +| 2026-10-14 | Tables can be copied and cut (#1744): with the whole table selected (Select Table, or a drag over all of it), Copy puts the table itself on the clipboard, so Paste outside it inserts a copy of the table with its formatting (the plain text is tab and newline separated); Cut removes the table in one undo step, as in Word. Copy used to keep only the cells' paragraphs and Cut left the table in place | | 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. | | 2026-10-19 | Typing no longer starts render threads on every repaint (#3027): page, area and icon renders share one kept vello_cpu context, reset to each size, instead of building a multi-threaded one (and its thread pool) per render. Typing about 150 characters in 15 s created 295–388 threads before and none now; CPU time while typing fell by about a third (Windows, debug build). | | 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture | @@ -625,7 +656,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-10 | Draw tab: pen, pencil and highlighter ink, stroke eraser, Select, Review › Hide Ink; ink saved to DOCX as DrawingML freeforms (#307); catalog 399/431 (92.6%) | | 2026-10-10 | Draw Table and Eraser (#303): a pen draws one-cell tables and splits cells along drawn lines; the eraser merges the cells beside a border. Catalog 393/431 (91.2%) | | 2026-10-10 | DOCX charts, SmartArt and OLE objects survive open and save with their parts (#319) | -| 2026-10-10 | Full re-measure against Word for Mac 16.113.4 and progress docs to the craftrules standard (this page, `docs/target-app-parity.md`, `gaps.md`, `roadmap.md`, `architecture.md`, format/layout/UI/hardware/localization parity; `docs/parity.md` → `docs/parity-checklist.md`). Landed the same day (~80 PRs): equations with OMML and an Equation tab (#191); Word 97-2003 `.doc` import (#145); right-to-left and Persian text (#207); Zotero integration (#189); Read Aloud player (#190); text boxes and floating objects editable (#46) and placed like Word (#136); floating tables (#137); track-changes fixes (#125, #244); typing parity with Word (#204); hidden text (#173); save prompts and AutoSave rules (#151); LaTeX import/export (#11); keytips and mini-toolbar (#43); Spanish, Ukrainian and Brazilian Portuguese interfaces; system theme (#249); Linux file dialogs no longer freeze (#246); Chinese UI font on Windows (#248); every installed font weight (#239); cell text direction (#245); Paste Special (#235), Advanced Find (#234), Column Selection (#237), Style Inspector (#236), custom table styles (#256), View gridlines (#243), zoom buttons (#232), inertial touchpad scrolling (#252), File Info fields kept (#268), ¶ in mixed-direction paragraphs (#278), Serbian interface (#250), table Height/Width boxes, AutoFit Contents and Table Properties (#44), AutoSave switch greyed out with the reason where it can't save (.md/.txt/.html, unsaved, browser) (#196, #176), OpenGL fallback on Windows PCs without a DirectX 12 driver (#316), Columns, Symbol and Field dialogs (#321), Tabs and Borders and Shading dialogs (#320); free rotation and flips for pictures, shapes and text boxes with a rotation handle (#332); v0.4.0 released; file associations on Windows and Linux with a Make-default button in Options (#295) | +| 2026-10-10 | Full re-measure against Word for Mac 16.113.4 and progress docs restructured (this page, `docs/target-app-parity.md`, `gaps.md`, `roadmap.md`, `architecture.md`, format/layout/UI/hardware/localization parity; `docs/parity.md` → `docs/parity-checklist.md`). Landed the same day (~80 PRs): equations with OMML and an Equation tab (#191); Word 97-2003 `.doc` import (#145); right-to-left and Persian text (#207); Zotero integration (#189); Read Aloud player (#190); text boxes and floating objects editable (#46) and placed like Word (#136); floating tables (#137); track-changes fixes (#125, #244); typing parity with Word (#204); hidden text (#173); save prompts and AutoSave rules (#151); LaTeX import/export (#11); keytips and mini-toolbar (#43); Spanish, Ukrainian and Brazilian Portuguese interfaces; system theme (#249); Linux file dialogs no longer freeze (#246); Chinese UI font on Windows (#248); every installed font weight (#239); cell text direction (#245); Paste Special (#235), Advanced Find (#234), Column Selection (#237), Style Inspector (#236), custom table styles (#256), View gridlines (#243), zoom buttons (#232), inertial touchpad scrolling (#252), File Info fields kept (#268), ¶ in mixed-direction paragraphs (#278), Serbian interface (#250), table Height/Width boxes, AutoFit Contents and Table Properties (#44), AutoSave switch greyed out with the reason where it can't save (.md/.txt/.html, unsaved, browser) (#196, #176), OpenGL fallback on Windows PCs without a DirectX 12 driver (#316), Columns, Symbol and Field dialogs (#321), Tabs and Borders and Shading dialogs (#320); free rotation and flips for pictures, shapes and text boxes with a rotation handle (#332); v0.4.0 released; file associations on Windows and Linux with a Make-default button in Options (#295) | | 2026-10-09 | Interface languages follow the system or Options (#12; zh-hans, zh-hant, ja); TOC page numbers as an updatable field (#52); rotating log file (#17); window geometry remembered (#38) | | 2026-10-08 | v0.2.0 and v0.3.0 released; Flatpak and AppImage auto-update (#22) | | 2026-10-07 | v0.1.0 released; contributor credits in About (#6) | @@ -637,15 +668,38 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-15 | The web app keeps its preferences between visits (#2132): theme (dark mode), interface size, editing options and the rest of what the desktop app saves in `ui.json` are kept in the browser's `localStorage`, written as soon as they change | | 2026-10-17 | Saving into a folder that refuses a temporary file (macOS privacy protection, read-only folders, #2138) never overwrites an existing document in place: it is left untouched and the error says to use Save As to another folder or allow WordCraft access to the folder (System Settings › Privacy & Security › Files and Folders on macOS). A new file is created directly. Unit tests on Linux; not yet confirmed on a Mac | | 2026-10-20 | Saving to a NAS share mounted by GVFS (`smb://` in the Linux file manager, #3003) works: the share refuses every Unix mode change with "Operation not supported", which used to fail the whole save, so the close prompt's Save never closed. The save now goes on without copying a mode the folder doesn't keep; any other failure still keeps the original. Unit tests; not yet confirmed on a real share | +| 2026-10-29 | Corporate authors in bibliographies (#4848): a source whose author is an organisation (Word's Corporate Author, `b:Corporate`) keeps it when a Word document opens, instead of losing the author. Citations and bibliography entries write the name as it is in every style ("(World Health Organization, 2021)", never "Organization, W. H."); it gives the source's tag and its place in an author-sorted list, and it saves back as `b:Corporate`. Create Source has a Corporate Author box under Author. | +| 2026-10-29 | Table Properties follows the selection (#4857): with the whole table (or several rows, columns or cells) selected, the Row, Column and Cell settings apply to every selected row, column and cell, as in Word. Before, they changed the caret's row alone, so unticking Allow row to break across pages with the table selected left the other rows breaking. Allow row to break and Repeat as header row show as mixed when the selected rows differ and change nothing unless clicked. | Footer page-table height and body wrapping are corrected. Other pagination gaps remain open. ## Revision history +> 2026-10-28 · Markdown import bounds reference-label scans and normalization within the existing link-work allowance. Nested undefined labels preserve literal text instead of causing quadratic work (#4658). +> > 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged. | Date | Change | Summary | |---|---|---| +| 2026-10-31 | trivial | Progress log: a paragraph naming an undefined DOCX style is formatted as Normal (#5077) | +| 2026-10-31 | trivial | Progress log: TOC page numbers are PAGEREF fields (#5097) | +| 2026-10-31 | trivial | Progress log: Backstage keytips, Alt, F, P prints (#4960) | +| 2026-10-30 | trivial | Progress log: only the PDF sent to the printer leaves out link annotations; Save these pages as PDF keeps them (#4734) | +| 2026-10-29 | trivial | Progress log: documents with links print (#4734) | +| 2026-10-28 | trivial | Aligned copies retain their locked document coordinate during middle-button scrolling and can start on secondary selected objects; existing Ctrl and Shift selection behavior stays (#4764) | +| 2026-10-28 | trivial | Ctrl/Command+Shift drags a selected floating object into an axis-aligned copy (#4764); synthetic Linux interaction and persistence controls, native desktop and Word untested; gap/readiness estimates unchanged | +| 2026-10-28 | trivial | Connector object lookups retain the typed column-selection inputs on current main (#3631); readiness estimates unchanged | +| 2026-10-27 | trivial | Connector rerouting indexes laid-out object positions once per batch, preserving page hints, first-match order and same-page glue; synthetic equivalence, geometry and scaling regressions (#3631); routing policy and readiness estimates unchanged | +| 2026-10-28 | trivial | Preserve custom-property bookmark link targets through saves, value edits and dialog renames (#4767); no linked-value evaluation or readiness change | +| 2026-10-29 | trivial | Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged | +| 2026-10-28 | trivial | Arabic Backspace removes one combining mark and keeps its base letter (#4757); stored mark order, caret/forward-Delete and other-script behavior retained; original synthetic command/history/protection/save-reopen checks, no native Word comparison; readiness estimates unchanged | +| 2026-10-28 | trivial | Note conversion walks reference offsets and formatting runs together, #4750; readiness estimates unchanged. | +| 2026-10-29 | trivial | DOCX comment IDs use ordered paragraph lookup and one durable-ID reservation set; threading and ID rules unchanged | +| 2026-10-28 | trivial | #4658: bound Markdown reference-label rejection work, preserving literal source and ordinary link matching | +| 2026-10-29 | trivial | Progress log: Insert › Shapes icon grid (#4349) | +| 2026-10-29 | trivial | HTML import keeps preformatted lines with CR, CRLF or LF input newlines (#4810); numeric character references retain their separate meaning; readiness estimates unchanged. | +| 2026-10-29 | trivial | Progress log: window fallback geometry and equation symbol tooltips | +| 2026-10-29 | trivial | Progress log: window titles omit NUL characters (#3634) | | 2026-10-29 | trivial | Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880). Filtered/sorted order, product geometry and single-label mode retained; readiness estimates unchanged. | | 2026-10-22 | trivial | Progress log: one native window per open document | | 2026-10-22 | trivial | Progress log: every open document keeps its own recovery copy | @@ -751,6 +805,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-18 | trivial | Progress log: header-cell picture watermarks drawn behind the text (#1775); readiness estimates unchanged | | 2026-10-14 | trivial | Progress log: comment drafts kept and written before saving or closing (#1348) | | 2026-10-17 | trivial | Language dialog keeps inherited proofing language and no-proof choices (#2717); readiness estimates unchanged | +| 2026-10-17 | trivial | Progress log: macOS launch arguments and open failures (#1103) | | 2026-10-14 | trivial | Progress log: ASK and SET fields show nothing (#1765) | | 2026-10-15 | trivial | Progress log: at-least table rows start the next page whole (#1742) | | 2026-10-14 | trivial | Progress log: ODT sections on export (gap 19) | @@ -804,6 +859,8 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-16 | trivial | Progress log: a text frame in the paragraph defaults frames nothing (#2360) | | 2026-10-16 | trivial | Progress log: a text file saved over itself closes without asking (#2376) | | 2026-10-15 | trivial | Progress log: recovery copies and .json files store pictures as base64 (#586 follow-up) | +| 2026-10-15 | trivial | Progress log: selected table rows and cells copy as a table; Cut clears their text (#1744) | +| 2026-10-14 | trivial | Progress log: Select Table copies and cuts the whole table (#1744) | | 2026-10-17 | trivial | Progress log: Scale Font Sizes command (#1475) | | 2026-10-14 | trivial | Progress log: row table border exceptions | | 2026-10-12 | minor | Czech proofing review: short-word splits rank after deletion, NOSUGGEST excludes suggestions while accepting typed forms, affix comments apply only to headers, ratios keep spaces and repeated-word messages use Czech quotes; synthetic engine end-to-end and latency checks | @@ -992,10 +1049,10 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-10 | minor | Relanded clipboard pane, table styles editor, Manage Styles, Asian typography (kinsoku), Group/Ungroup and Shape Effects (#264 #263 #270 #271 #267 #280): catalog 390/431 (90.5%) | | 2026-10-10 | minor | Polish interface and proofing landed: Localization 25% → 27%, Proofing 35% → 40% | | 2026-10-10 | minor | Merged main: catalog 384/430 (89.3%), 431 commands; Paste Special, Advanced Find, Column Selection, Style Inspector, custom table styles, gridlines, zoom buttons, touchpad scrolling, File Info, Serbian landed; mainstream 54→55% | -| 2026-10-10 | minor | Readiness table with hours per audience; full number restored to the additive weighted sum (~47% → ~60%): method aligned with the standard, no new evidence; beta distance back to ~15 points and ~150–230 h | -| 2026-10-10 | minor | Mainstream practitioner (~54%) and essentials user (~63%) numbers added; full number recomputed 60% → ~47% with the standard's discounts; beta distance now ~28 points and ~450–700 h; stage stays alpha | +| 2026-10-10 | minor | Readiness table with hours per audience; full number restored to the additive weighted sum (~47% → ~60%): no new evidence; beta distance back to ~15 points and ~150–230 h | +| 2026-10-10 | minor | Mainstream practitioner (~54%) and essentials user (~63%) numbers added; full number recomputed 60% → ~47% with the discounts; beta distance now ~28 points and ~450–700 h; stage stays alpha | | 2026-10-10 | minor | Alpha gate checked (six core workflows pass); stage stays alpha | -| 2026-10-10 | major | Full re-measure; restructured to the progress-docs standard (stage banner, two numbers, dimensions, languages, upcoming, progress log); parity tables moved to `docs/target-app-parity.md`, milestones to `docs/roadmap.md` | +| 2026-10-10 | major | Full re-measure; progress docs restructured (stage banner, two numbers, dimensions, languages, upcoming, progress log); parity tables moved to `docs/target-app-parity.md`, milestones to `docs/roadmap.md` | | 2026-10-09 | minor | Recently landed: RTL, Ukrainian and Brazilian Portuguese | | 2026-10-06 | major | First honest estimate: 88% catalog, ~62% real parity, alpha ~85% of the way | | 2026-10-12 | trivial | Progress log: recipient filter and sort, .xls and legacy-encoding recipient lists (#778) | @@ -1009,3 +1066,9 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | 2026-10-23 | trivial | Progress log: justified lines ending in a manual line break reach the margin (#3924) | | 2026-10-23 | trivial | Progress log: "NaN" in the Font dialog's Size box no longer closes the app (#3663) | | 2026-10-23 | trivial | Progress log: a table cell span from a `.json` file no longer overflows (#3637) | +| 2026-10-28 | trivial | Progress log: chart and SmartArt text the font lacks is drawn in a fallback face (#4720) | +| 2026-10-29 | trivial | Progress log: corporate authors in bibliographies (#4848) | +| 2026-10-29 | trivial | Progress log: Table Properties follows the selection (#4857) | +| 2026-10-27 | trivial | Progress log: AutoCorrect Options with no document open (#4585) | +| 2026-10-28 | trivial | Progress log: RTF metafile pictures are imported (#4259) | +| 2026-10-28 | trivial | Progress log: Chinese and Japanese text counts a word per character (#4547) | diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..f539bf60cd --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,26 @@ +# Security policy + +## Reporting a vulnerability + +Please report security problems privately through GitHub: +**[Report a vulnerability](https://github.com/storytold/wordcraft/security/advisories/new)** +(Security tab › Advisories › Report a vulnerability). + +Don't open a public issue or pull request for a vulnerability until a fix is released. + +Useful to include: +- the WordCraft version or commit, and the platform (macOS, Windows, Linux, BSD, web); +- what an attacker can do, and what they need (a crafted document, MCP or control-channel access, a local account…); +- steps or a sample file that reproduce it. + +We'll acknowledge the report, keep you updated while we work on a fix, and credit you in the advisory unless you'd rather not be named. + +## Supported versions + +Fixes go into `main` and ship in the next release. Older releases don't get backported fixes. + +## Scope + +In scope: anything that lets a document, file, command, MCP or control-channel request, or network response read or write files it shouldn't, run code, leak data, or crash WordCraft and lose the user's work. + +Crashes from hostile input count, because WordCraft treats every panic as a bug (see [Never crash](AGENTS.md)). diff --git a/apps/wordcraft-web/src/prefs.rs b/apps/wordcraft-web/src/prefs.rs index 1131a7551b..5b3f9a99b6 100644 --- a/apps/wordcraft-web/src/prefs.rs +++ b/apps/wordcraft-web/src/prefs.rs @@ -49,9 +49,9 @@ impl PrefsSync { pub fn changed(&mut self, app: &WordApp) -> Option { let mut prefs = app.prefs(); if let Some((host, own)) = &self.host_author - && prefs.author == *host + && prefs.author.as_deref() == Some(host.as_str()) { - prefs.author = own.clone(); + prefs.author = Some(own.clone()); } let json = match serde_json::to_string(&prefs) { Ok(j) => j, diff --git a/apps/wordcraft/src/apple_events.rs b/apps/wordcraft/src/apple_events.rs index 0eae596a9d..e79d923a9a 100644 --- a/apps/wordcraft/src/apple_events.rs +++ b/apps/wordcraft/src/apple_events.rs @@ -47,10 +47,9 @@ pub fn poll(inbox: &Inbox, app: &mut WordApp, ctx: &egui::Context) { // Leave Backstage, as opening from the Open dialog does. Ok(_) => app.ui.backstage = false, Err(e) => { - log::warn!("{p}: {e}"); - let e = e.to_string(); - let msg = wordcraft_ui_egui::tl!("Couldn't open {path}: {error}"); - app.status(wordcraft_ui_egui::i18n::fmt(msg, &[("path", p), ("error", &e)])); + app.report_open_failure(p, &e); + // Backstage hides the status bar, so leave it to show the error. + app.ui.backstage = false; } } } diff --git a/apps/wordcraft/src/main.rs b/apps/wordcraft/src/main.rs index bc66c94115..1a9f25d9d8 100644 --- a/apps/wordcraft/src/main.rs +++ b/apps/wordcraft/src/main.rs @@ -329,6 +329,26 @@ fn text_args() -> (Vec, Vec) { (args, files) } +/// The arguments without the ones macOS adds when it launches an app (#1103): `-psn_0_12345`, and +/// the `-NS…` / `-Apple…` options (`-AppleLanguages (en)`, `-NSDocumentRevisionsDebugMode YES`) with +/// the value after each. They are not files, and opening them as files fails. +fn without_launch_args(args: Vec) -> Vec { + let mut kept = Vec::with_capacity(args.len()); + let mut args = args.into_iter().peekable(); + while let Some(a) = args.next() { + if a.starts_with("-psn_") { + continue; + } + if a.starts_with("-NS") || a.starts_with("-Apple") { + // Its value, unless the next argument is another flag. + args.next_if(|v| !v.starts_with('-')); + continue; + } + kept.push(a); + } + kept +} + /// Open a file whose name isn't valid Unicode (#1440). `file.open` takes its path as text, so it /// gets the file's bytes under the lossy name, and the document then keeps the real path to save to. /// The bytes are read as `file.open` reads a path: only a regular file, and at most 2 GB. @@ -340,7 +360,9 @@ fn open_non_unicode(app: &mut WordApp, path: &std::path::Path) { // Not when it waits for a password: that open names the document itself. Ok(r) if r.get("pending").is_none() => app.session.path = Some(path.into()), Ok(_) => {} - Err(e) => log::warn!("{name}: {e}"), + Err(e) => { + app.report_open_failure(&name, &e); + } } } @@ -350,7 +372,7 @@ fn open_non_unicode(app: &mut WordApp, path: &std::path::Path) { fn main() -> eframe::Result { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&craft_update::suite::WORDCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft_update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // First, so the panic hook and every start-up warning are recorded (`logging`). @@ -360,6 +382,8 @@ fn main() -> eframe::Result { let mut files = Vec::new(); let mut sample = false; let (args, other_files) = text_args(); + // Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name. + let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args }; let mut bad_control: Option> = None; let mut args = args.into_iter().peekable(); while let Some(a) = args.next() { @@ -504,7 +528,7 @@ fn main() -> eframe::Result { } for f in files { if let Err(e) = app.run("file.open", serde_json::json!({"path": f})) { - log::warn!("{f}: {e}"); + app.report_open_failure(&f, &e); } } for f in other_files { @@ -590,6 +614,33 @@ mod tests { } } +#[cfg(test)] +mod launch_arg_tests { + use super::without_launch_args; + + fn strip(args: &[&str]) -> Vec { + without_launch_args(args.iter().map(|a| a.to_string()).collect()) + } + + #[test] + fn macos_launch_arguments_are_not_files() { + assert_eq!(strip(&["-psn_0_12345", "a.docx"]), ["a.docx"]); + assert_eq!(strip(&["-AppleLanguages", "(en)", "a.docx"]), ["a.docx"]); + assert_eq!(strip(&["a.docx", "-NSDocumentRevisionsDebugMode", "YES", "b.docx"]), ["a.docx", "b.docx"]); + // A flag with no value after it, or followed by another flag, takes nothing with it. + assert_eq!(strip(&["a.docx", "-AppleLocale"]), ["a.docx"]); + assert_eq!(strip(&["-NSFoo", "--sample", "a.docx"]), ["--sample", "a.docx"]); + } + + #[test] + fn real_arguments_are_kept() { + assert_eq!(strip(&["--control", "7981", "--sample", "-h"]), ["--control", "7981", "--sample", "-h"]); + // Files whose names merely start like a launch argument keep their place when they are paths. + assert_eq!(strip(&["./-psn_x.docx", "Apple.docx", "-", "-nsfoo"]), ["./-psn_x.docx", "Apple.docx", "-", "-nsfoo"]); + assert!(strip(&[]).is_empty()); + } +} + #[cfg(test)] mod prefs_tests { use super::write_prefs; diff --git a/contributors/people.toml b/contributors/people.toml index ea73277286..b95d43ea85 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -1,13 +1,10 @@ -# Contributor names for the About window (craftrules standards/contributors.md). +# Contributor names for the About window. # # Everyone who contributes is credited by GitHub username automatically. Anything more is up to # you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a # maintainer may add a person only when that person asked, recording where in consent_source. # -# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \ -# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name] -# -# Or copy this block, replacing your-github-username (every field is optional): +# Copy this block, replacing your-github-username (every field is optional): # # [people.your-github-username] # real_name = "Your Name" # shown when the viewer picks "Real name" @@ -181,3 +178,12 @@ sync_github_name = true [people.pakiat] display_name = "OtorO" + +[people.TobyWu666] +display_name = "tobywu" + +[people.Bra1nZ] +sync_github_name = true + +[people.dylanmtaylor] +sync_github_name = true diff --git a/crates/doc/src/cluster.rs b/crates/doc/src/cluster.rs index 186b79f9d6..4b4db881f9 100644 --- a/crates/doc/src/cluster.rs +++ b/crates/doc/src/cluster.rs @@ -115,12 +115,22 @@ pub fn next_cluster(text: &str, off: usize) -> usize { } } -/// Scripts whose Backspace removes one character at a time (a vowel sign, a medial, a stacked -/// consonant) rather than the whole cluster, as on Windows and macOS: the Brahmic scripts of -/// South and South-East Asia. +/// Characters Backspace removes individually rather than with their whole cluster: Arabic +/// combining marks and characters of the Brahmic scripts of South and South-East Asia. pub fn backspaces_by_char(c: char) -> bool { matches!(u32::from(c), - 0x0900..=0x0DFF // Devanagari … Sinhala + 0x0610..=0x061A // Arabic nonspacing marks (Unicode 17.0) + | 0x064B..=0x065F + | 0x0670 + | 0x06D6..=0x06DC + | 0x06DF..=0x06E4 + | 0x06E7..=0x06E8 + | 0x06EA..=0x06ED + | 0x0897..=0x089F + | 0x08CA..=0x08E1 + | 0x08E3..=0x08FF + | 0x10EFA..=0x10EFF + | 0x0900..=0x0DFF // Devanagari … Sinhala | 0x0E00..=0x0EFF // Thai, Lao | 0x0F00..=0x0FFF // Tibetan | 0x1000..=0x109F // Myanmar @@ -250,8 +260,10 @@ mod tests { } #[test] - fn backspace_by_character_in_brahmic_scripts_only() { + fn backspace_by_character_in_brahmic_scripts_and_arabic_marks() { assert!(backspaces_by_char('ေ') && backspaces_by_char('ि') && backspaces_by_char('្')); + assert!(backspaces_by_char('\u{064E}') && backspaces_by_char('\u{06E7}') && backspaces_by_char('\u{10EFF}')); assert!(!backspaces_by_char('\u{301}') && !backspaces_by_char('a') && !backspaces_by_char('語')); + assert!(!backspaces_by_char('ب') && !backspaces_by_char('\u{06E5}') && !backspaces_by_char('\u{08E2}')); } } diff --git a/crates/doc/src/control.rs b/crates/doc/src/control.rs index 31ff6814af..4647706892 100644 --- a/crates/doc/src/control.rs +++ b/crates/doc/src/control.rs @@ -14,7 +14,7 @@ //! outside what's deleted (so deleting across a control's edge empties it rather than breaking //! it); writers call [`Document::balance_controls`] so a saved file always has whole controls. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use serde::{Deserialize, Serialize}; @@ -422,24 +422,37 @@ fn scan(story: StoryRef, bl: &Blocks, prefix: &mut Vec, depth: usize, out: } /// Positions of the markers without a partner in a block list and the cells inside it. -fn orphans(bl: &Blocks, prefix: &mut Vec, depth: usize, out: &mut Vec<(Path, usize)>, tables: &mut Vec<(Path, usize, bool)>) { +pub(crate) fn orphans(bl: &Blocks, prefix: &mut Vec, depth: usize, out: &mut Vec<(Path, usize)>, tables: &mut Vec<(Path, usize, bool)>) { if depth > MAX_DEPTH { return; } let events = control_events(bl); let (_, lone) = pair_events(&events); - for k in lone { - let Some(e) = events.get(k) else { continue }; - let mut path = prefix.clone(); - path.push(u32::try_from(e.block()).unwrap_or(u32::MAX)); - match (e, e.off()) { - (_, Some(off)) => out.push((Path(path), off)), - (ControlEvent::Open { .. }, None) => { - // Which of the table's opens: count those before it on the same table. - let nth = events.iter().take(k).filter(|x| matches!(x, ControlEvent::Open { block, off: None, .. } if *block == e.block())).count(); - tables.push((Path(path), nth, true)); + if !lone.is_empty() { + let mut table_counts: HashMap = HashMap::new(); + let mut open_nth = Vec::with_capacity(events.len()); + for e in &events { + if let ControlEvent::Open { block, off: None, .. } = e { + let count = table_counts.entry(*block).or_insert(0); + open_nth.push(*count); + *count += 1; + } else { + open_nth.push(0); + } + } + for k in lone { + let Some(e) = events.get(k) else { continue }; + let mut path = prefix.clone(); + path.push(u32::try_from(e.block()).unwrap_or(u32::MAX)); + match (e, e.off()) { + (_, Some(off)) => out.push((Path(path), off)), + (ControlEvent::Open { .. }, None) => { + // Which of the table's opens: index among table opens on the same table. + let nth = open_nth.get(k).copied().unwrap_or(0); + tables.push((Path(path), nth, true)); + } + (ControlEvent::Close { .. }, None) => tables.push((Path(path), 0, false)), } - (ControlEvent::Close { .. }, None) => tables.push((Path(path), 0, false)), } } for (i, b) in bl.iter().enumerate() { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 7d116858c2..a1df2b1618 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -443,8 +443,7 @@ impl Document { Ok(id) } - /// Count words like Word's status bar (whitespace-separated tokens containing a letter or digit, - /// including generated numbered-list labels). + /// Count words like Word's status bar ([`crate::count_words`], plus generated numbered-list labels). pub fn word_count(&self) -> usize { self.story_word_count(StoryRef::Body) } @@ -795,7 +794,9 @@ impl Document { p.kind = "lpwstr".into(); p.value = value.to_string(); } - None => self.custom_props.push(CustomProp { name: name.to_string(), kind: "lpwstr".into(), value: value.to_string() }), + None => { + self.custom_props.push(CustomProp { name: name.to_string(), kind: "lpwstr".into(), value: value.to_string(), ..Default::default() }) + } } } diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index b823d892dc..66d483e81e 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -434,10 +434,16 @@ impl Document { at.extend(offs.get(k).copied()); } } + // Reference offsets and run boundaries are ordered; do not restart at the first + // reference for every run, including runs after the last reference. + let mut at = at.into_iter().peekable(); let mut start = 0usize; for r in &mut p.runs { let end = start.saturating_add(r.len); - if at.iter().any(|&o| o >= start && o < end) { + while at.peek().is_some_and(|&o| o < start) { + at.next(); + } + if at.peek().is_some_and(|&o| o < end) { swap(&mut r.props.style); } start = end; @@ -792,6 +798,63 @@ impl Document { Fragment { blocks, parts } } + /// A copy of the block at `path` (a whole table, say) as a fragment, with its text boxes. + pub fn copy_block(&self, story: crate::StoryRef, path: &Path) -> Option { + Some(self.fragment_of(vec![self.block(story, path)?.clone()])) + } + + /// A copy of rows `rows` of the table at `tp`, with the cells of each that reach into grid + /// columns `cols` (see [`crate::Table::slice`]), as a fragment holding that table. + pub fn copy_table_cells(&self, story: crate::StoryRef, tp: &Path, rows: (usize, usize), cols: (usize, usize)) -> Option { + let t = self.table(story, tp)?.slice(rows, cols); + if t.rows.is_empty() { + return None; + } + Some(self.fragment_of(vec![Block::Table(t)])) + } + + /// `blocks` as a fragment: half content controls dropped, text boxes copied along. + fn fragment_of(&self, mut blocks: Vec) -> Fragment { + crate::control::balance_blocks(&mut blocks); + let parts = self.text_box_parts(&blocks); + Fragment { blocks, parts } + } + + /// The table whose whole text `a..b` covers when the range runs across its cells: from the + /// start of its first paragraph to the end of its last. Of the tables holding both ends, the + /// outermost one covered whole (a table nested in a cell when the range covers just it). + /// `None` for a range inside one cell, or one that doesn't cover a whole table. + pub fn whole_table(&self, a: &Pos, b: &Pos) -> Option { + let (a, b) = order(a, b); + if a.story != b.story || a.off != 0 || a.path.parent() == b.path.parent() { + return None; + } + let mut paths: Option> = None; + // Table block paths are the prefixes of a cell paragraph's path one block deep, then + // every three steps (block, row, cell) deeper. + let mut n = 1usize; + while n.saturating_add(3) <= a.path.0.len() { + let pre = a.path.0.get(..n)?; + if !b.path.0.starts_with(pre) { + return None; + } + let tp = Path(pre.to_vec()); + if self.table(a.story, &tp).is_some() { + let paths = paths.get_or_insert_with(|| self.para_paths(a.story)); + let mut inside = paths.iter().filter(|p| p.0.starts_with(pre)); + if let Some(first) = inside.next() { + let last = inside.next_back().unwrap_or(first); + let end = self.para(a.story, last).map_or(0, Paragraph::len); + if *first == a.path && *last == b.path && b.off >= end { + return Some(tp); + } + } + } + n = n.saturating_add(3); + } + None + } + /// The whole body as a fragment (with its text boxes), to insert into another document. pub fn body_fragment(&self) -> Fragment { let blocks: Vec = self.body.iter().map(|b| (**b).clone()).collect(); @@ -846,6 +909,13 @@ impl Document { } return out; } + // Across the cells of a whole table: the table itself, not its cells' paragraphs (#1744). + if let Some(tp) = self.whole_table(&a, &b) + && let Some(blk) = self.block(a.story, &tp) + { + out.push(blk.clone()); + return out; + } for p in self.paths_between(&a, &b) { if let Some(para) = self.para(a.story, &p) { let mut q = para.clone(); diff --git a/crates/doc/src/para.rs b/crates/doc/src/para.rs index 193dc55892..3959bad1d1 100644 --- a/crates/doc/src/para.rs +++ b/crates/doc/src/para.rs @@ -501,9 +501,8 @@ impl Paragraph { pub fn next_boundary(&self, off: usize) -> usize { crate::cluster::next_cluster(&self.text, self.clamp(off)) } - /// Where Backspace at `off` deletes from: the previous character in the Brahmic scripts - /// (Myanmar, Khmer, Devanagari, Thai…), where it removes one vowel sign or stacked consonant - /// at a time, otherwise the previous caret stop. + /// Where Backspace at `off` deletes from: one Arabic combining mark or one character in the + /// Brahmic scripts (Myanmar, Khmer, Devanagari, Thai…), otherwise the previous caret stop. pub fn backspace_from(&self, off: usize) -> usize { let off = self.clamp(off); match self.text.get(..off).and_then(|t| t.char_indices().next_back()) { diff --git a/crates/doc/src/props/char_props.rs b/crates/doc/src/props/char_props.rs index b8ef433c52..32757edc89 100644 --- a/crates/doc/src/props/char_props.rs +++ b/crates/doc/src/props/char_props.rs @@ -273,6 +273,12 @@ pub struct CharProps { pub small_caps: Option, #[serde(skip_serializing_if = "Option::is_none")] pub hidden: Option, + /// Hidden in Web Layout (`w:webHidden`); distinct from `w:vanish` (`hidden`). + #[serde(skip_serializing_if = "Option::is_none")] + pub web_hidden: Option, + /// Snap characters to the document grid (`w:snapToGrid`). Unset inherits; Word's default is on. + #[serde(skip_serializing_if = "Option::is_none")] + pub snap_to_grid: Option, /// Character spacing (expanded/condensed), points. #[serde(skip_serializing_if = "Option::is_none")] pub spacing: Option, @@ -448,6 +454,7 @@ impl CharProps { /// overlaid on `base`. pub fn minus(mut self, base: &CharProps) -> CharProps { self.minus_text_style(base); + self.minus_run_visibility(base); self.minus_script_style(base); self.minus_document_marks(base); self @@ -458,6 +465,10 @@ impl CharProps { shading, border, vert_align, caps, small_caps, hidden, spacing, scale, position, kern, outline, shadow, emboss, engrave, lang, no_proof, rtl); } + fn minus_run_visibility(&mut self, base: &CharProps) { + drop_same_fields!(self, base; web_hidden, snap_to_grid); + } + fn minus_script_style(&mut self, base: &CharProps) { drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout); } @@ -472,6 +483,7 @@ impl CharProps { /// format both scripts must set both values explicitly. pub fn overlay(&mut self, patch: &CharProps) { self.overlay_text_style(patch); + self.overlay_run_visibility(patch); self.overlay_script_style(patch); self.overlay_document_marks(patch); if let Some(p) = &patch.text_effects { @@ -484,6 +496,10 @@ impl CharProps { shading, border, vert_align, caps, small_caps, hidden, spacing, scale, position, kern, outline, shadow, emboss, engrave, lang, no_proof, rtl); } + fn overlay_run_visibility(&mut self, patch: &CharProps) { + overlay_fields!(self, patch; web_hidden, snap_to_grid); + } + fn overlay_script_style(&mut self, patch: &CharProps) { overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout); } diff --git a/crates/doc/src/resolve.rs b/crates/doc/src/resolve.rs index 49b6904822..0192713d02 100644 --- a/crates/doc/src/resolve.rs +++ b/crates/doc/src/resolve.rs @@ -270,7 +270,12 @@ impl ResolvedPara { drop_cap_margin: p.drop_cap_margin.unwrap_or(false), drop_cap_distance: p.drop_cap_distance.filter(|d| d.is_finite()).unwrap_or(0.0).clamp(0.0, MAX_DROP_CAP_DISTANCE), drop_cap_font: p.drop_cap_font.clone().filter(|f| !f.trim().is_empty()), - frame: p.frame.clone().filter(|_| p.drop_cap.unwrap_or(0) == 0), + // Explicit zero dimensions cancel a frame; omitted dimensions still fit its text. + frame: p.frame.clone().filter(|f| p.drop_cap.unwrap_or(0) == 0 && (f.w != Some(0.0) || f.h != Some(0.0))).map(|mut f| { + f.w = f.w.filter(|v| *v != 0.0); + f.h = f.h.filter(|v| *v != 0.0); + f + }), suppress_hyphens: p.suppress_hyphens.unwrap_or(false), suppress_line_numbers: p.suppress_line_numbers.unwrap_or(false), kinsoku: p.kinsoku.unwrap_or(true), @@ -295,8 +300,12 @@ impl StyleSheet { self.para_style_props_over(style, self.default_para.clone(), self.default_chr.clone()) } - /// The paragraph style chain of `style` applied over `pp` / `cp`. + /// The paragraph style chain of `style` applied over `pp` / `cp`. A style the document doesn't + /// define is the default paragraph style, Normal, as in Word: a footer naming a `Footer` style + /// that `styles.xml` leaves out is formatted as Normal, not with the document defaults alone + /// (#5077). fn para_style_props_over(&self, style: &str, mut pp: ParaProps, mut cp: CharProps) -> (ParaProps, CharProps) { + let style = if self.get(style).is_some() { style } else { "Normal" }; for s in self.chain(style) { if s.kind == StyleKind::Paragraph { let mut sp = s.para.clone(); @@ -395,6 +404,31 @@ mod tests { assert_eq!(s.resolve_char(None, &direct).font, "Wingdings"); } + /// #5077: a paragraph naming a style the document doesn't define is formatted as Normal, + /// paragraph and run alike, not with the document defaults alone. + #[test] + fn an_undefined_paragraph_style_is_normal() { + let mut s = StyleSheet::builtin(); + s.default_para.space_after = Some(10.0); + if let Some(n) = s.get_mut("Normal") { + n.para.space_after = Some(2.0); + n.chr.size = Some(13.0); + } + let undefined = ParaProps { style: Some("NoSuchStyle".into()), ..Default::default() }; + let normal = s.resolve_para(&ParaProps::default()); + let p = s.resolve_para(&undefined); + assert_eq!(p.space_after, 2.0); + assert_eq!(p.space_after, normal.space_after); + assert_eq!(p.line_spacing, normal.line_spacing); + assert_eq!(s.resolve_char(Some("NoSuchStyle"), &CharProps::default()).size, 13.0); + // The paragraph keeps the style it names; direct formatting still wins. + assert_eq!(p.style, "NoSuchStyle"); + let direct = ParaProps { space_after: Some(7.0), ..undefined }; + assert_eq!(s.resolve_para(&direct).space_after, 7.0); + // A defined style is unchanged. + assert_eq!(s.resolve_para(&ParaProps { style: Some("Heading1".into()), ..Default::default() }).space_after, 4.0); + } + #[test] fn heading_resolves() { let s = StyleSheet::builtin(); diff --git a/crates/doc/src/settings.rs b/crates/doc/src/settings.rs index aec1bd70f8..3d8c341cea 100644 --- a/crates/doc/src/settings.rs +++ b/crates/doc/src/settings.rs @@ -10,6 +10,10 @@ pub struct Source { pub kind: String, /// "Last, First; Last, First" pub author: String, + /// A corporate author ("World Health Organization"): written as it is, never split into + /// names, and in place of `author` when set (Create Source › Corporate Author, `b:Corporate`, + /// #4848). + pub corporate: String, pub title: String, pub year: String, pub publisher: String, @@ -39,6 +43,9 @@ pub struct CustomProp { /// the property's XML content kept verbatim (vectors, blobs). pub kind: String, pub value: String, + /// Bookmark associated with this property (`linkTarget`), retained without evaluating it. + #[serde(skip_serializing_if = "Option::is_none")] + pub link_target: Option, } /// Document properties (File › Info). diff --git a/crates/doc/src/table.rs b/crates/doc/src/table.rs index 76911dd4f8..abdda89241 100644 --- a/crates/doc/src/table.rs +++ b/crates/doc/src/table.rs @@ -77,6 +77,80 @@ pub const MAX_COLS: usize = 63; pub const MAX_TABLE_DEPTH: usize = 24; impl Table { + /// Grid columns `lo..hi` that [`Table::slice`] copies for `rows`/`cols` (widened over merged cells), + /// and whether any cell touches them (Cut clears the same cells it copies). + pub fn slice_bounds(&self, rows: (usize, usize), cols: (usize, usize)) -> (usize, usize, bool) { + let ((r0, r1), (g0, g1)) = (rows, cols); + let kept = || self.rows.iter().take(r1.saturating_add(1)).skip(r0); + // Grid columns `lo..hi` the cells touching them cover: a cell merged across that is partly + // in them widens them, for every row, so the copy isn't ragged. Each round only widens + // (at most once per grid column), so a bound of the grid's width plus one round is enough. + let (mut lo, mut hi) = (g0, g1.saturating_add(1)); + let mut any = false; + for _ in 0..=MAX_COLS.saturating_add(1) { + let (mut nlo, mut nhi, mut found) = (lo, hi, false); + for row in kept() { + let mut g = 0usize; + for cell in &row.cells { + let end = g.saturating_add(cell.span()); + if g < hi && end > lo { + (nlo, nhi, found) = (nlo.min(g), nhi.max(end), true); + } + g = end; + } + } + any = found; + if (nlo, nhi) == (lo, hi) { + break; + } + (lo, hi) = (nlo, nhi); + } + (lo, hi, any) + } + + /// A copy of rows `rows` of this table holding, of each row, the cells that reach into grid + /// columns `cols` (both inclusive): what Copy takes from selected rows or cells. Content + /// controls around rows and the table aren't copied (they'd lose their other end); a cell + /// that continues a vertical merge from a row left out starts the merge instead. + pub fn slice(&self, rows: (usize, usize), cols: (usize, usize)) -> Table { + let (r0, r1) = rows; + let kept = || self.rows.iter().take(r1.saturating_add(1)).skip(r0); + let (lo, hi, any) = self.slice_bounds(rows, cols); + let mut out_rows = Vec::new(); + for row in kept() { + let mut g = 0usize; + let mut cells = Vec::new(); + for cell in &row.cells { + let end = g.saturating_add(cell.span()); + if any && g < hi && end > lo { + cells.push(cell.clone()); + } + g = end; + } + if !cells.is_empty() { + out_rows.push(Row { props: row.props.clone(), cells, controls: ControlWrap::default() }); + } + } + if let Some(first) = out_rows.first_mut() { + for c in &mut first.cells { + if c.props.vmerge == VMerge::Continue { + c.props.vmerge = VMerge::Restart; + } + } + } + let whole = lo == 0 && hi >= self.grid.len(); + let grid = if whole { self.grid.clone() } else { self.grid.get(lo..hi.min(self.grid.len())).map(<[f32]>::to_vec).unwrap_or_default() }; + let mut props = self.props.clone(); + if !whole { + // Part of the columns: as wide as they are, not the whole table's width. + if props.width.is_some() || props.width_pct.is_some() { + props.width = Some(grid.iter().sum()); + } + props.width_pct = None; + } + Table { props, grid, rows: out_rows, controls: ControlWrap::default() } + } + /// A `rows × cols` table spanning `width` points, "Table Grid" style. pub fn new(rows: usize, cols: usize, width: f32) -> Table { let rows = rows.clamp(1, MAX_ROWS); @@ -566,6 +640,69 @@ impl Table { mod tests { use super::*; + /// A 3×3 table, 100 pt columns: (0,0)–(0,1) merged across, (1,2)–(2,2) merged down. + fn merged() -> Table { + let mut t = Table::new(3, 3, 300.0); + t.merge(0, 0, 0, 1); + t.merge(1, 2, 2, 2); + assert_eq!(t.rows[0].cells.iter().map(Cell::span).collect::>(), [2, 1]); + assert_eq!((t.rows[1].cells[2].props.vmerge, t.rows[2].cells[2].props.vmerge), (VMerge::Restart, VMerge::Continue)); + t + } + + fn spans(t: &Table) -> Vec> { + t.rows.iter().map(|r| r.cells.iter().map(Cell::span).collect()).collect() + } + + /// #1744 review: a cell merged across that is partly selected takes its whole width, and the + /// other rows widen with it, so the copy isn't ragged. + #[test] + fn slice_widens_to_a_merged_cell_in_every_row() { + let t = merged().slice((0, 1), (1, 2)); + assert_eq!(t.grid, [100.0, 100.0, 100.0]); + assert_eq!(spans(&t), [vec![2, 1], vec![1, 1, 1]]); + // Rows without the merged cell: just the selected columns. + let t = merged().slice((1, 2), (1, 2)); + assert_eq!(t.grid, [100.0, 100.0]); + assert_eq!(spans(&t), [vec![1, 1], vec![1, 1]]); + } + + /// #1744 review: a cell continuing a vertical merge from a row left out starts it instead. + #[test] + fn slice_starts_a_vertical_merge_whose_first_row_is_left_out() { + let t = merged().slice((2, 2), (0, 2)); + assert_eq!(t.rows.len(), 1); + assert_eq!(t.rows[0].cells[2].props.vmerge, VMerge::Restart); + // Both rows kept: the merge is kept as it is. + let t = merged().slice((1, 2), (2, 2)); + assert_eq!((t.rows[0].cells[0].props.vmerge, t.rows[1].cells[0].props.vmerge), (VMerge::Restart, VMerge::Continue)); + } + + /// #1744 review: part of the columns is as wide as they are; content controls around rows + /// and the table aren't copied. + #[test] + fn slice_width_and_controls() { + let mut t = Table::new(3, 3, 300.0); + (t.props.width, t.props.width_pct) = (Some(300.0), Some(50.0)); + let wrap = ControlWrap { open: vec![crate::control::ContentControl::default()], close: 1 }; + t.controls = wrap.clone(); + t.rows[1].controls = wrap; + let part = t.slice((0, 2), (2, 2)); + assert_eq!((part.grid.len(), part.props.width, part.props.width_pct), (1, Some(100.0), None)); + let whole = t.slice((0, 2), (0, 2)); + assert_eq!((whole.props.width, whole.props.width_pct), (Some(300.0), Some(50.0)), "all columns keep the table's width"); + let row = t.slice((1, 1), (0, 2)); + assert!(row.controls.is_empty() && row.rows[0].controls.is_empty()); + // A table sized only by a percentage keeps a width for the part. + let mut pct = Table::new(3, 3, 300.0); + (pct.props.width, pct.props.width_pct) = (None, Some(50.0)); + let part = pct.slice((0, 2), (2, 2)); + assert_eq!((part.props.width, part.props.width_pct), (Some(100.0), None)); + // Nothing in range: no rows. + assert!(t.slice((5, 6), (0, 2)).rows.is_empty()); + assert!(t.slice((0, 2), (9, 9)).rows.is_empty()); + } + #[test] fn grid_before_shifts_the_row() { let mut t = Table::new(2, 3, 300.0); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 67256fd78c..4ae157deb0 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -1,5 +1,7 @@ use super::*; +mod note_conversion; + #[test] fn new_document_is_valid() { let d = Document::new(); @@ -16,6 +18,20 @@ fn word_count() { assert_eq!(count_words(" -- "), 0); } +/// #4547: each Han ideograph and kana counts as a word; punctuation and Hangul spacing don't change. +#[test] +fn word_count_counts_each_chinese_and_japanese_character() { + // #4547: unspaced Chinese counted as one word per run. + assert_eq!(count_words("我们今天去公园。"), 7); + assert_eq!(count_words("WordCraft是一个文字处理器,很好用!"), 1 + 11); + assert_eq!(count_words("ひらがなとカタカナ"), 9); + assert_eq!(count_words("カタカナ"), 4); + assert_eq!(count_words("ガギ"), 2, "voiced sound marks belong to their kana"); + assert_eq!(count_words("。、・「」"), 0); + // Korean is spaced: Hangul counts by tokens. + assert_eq!(count_words("안녕하세요 세계"), 2); +} + #[test] fn word_count_includes_numbered_list_labels_but_not_bullets() { let mut d = Document::new(); @@ -61,6 +77,23 @@ fn word_count_includes_numbered_labels_with_nothing_suffix() { assert_eq!(d.word_count(), 5); } +/// #4547: a generated CJK list label such as 第十二章 still counts as one word. +#[test] +fn word_count_keeps_a_cjk_list_label_one_word() { + let mut d = Document::new(); + let num_id = d.numbering.add_list(ListKind::Numbered); + let aid = d.numbering.num(num_id).expect("list num exists").abstract_id; + let a = d.numbering.abstracts.iter_mut().find(|a| a.id == aid).expect("abstract num exists"); + a.levels[0].format = section::NumFormat::ChineseCounting; + a.levels[0].text = "第%1章".into(); + a.levels[0].start = 12; + let mut p = Paragraph::with_text("总结", CharProps::default()); + p.props.numbering = Some(props::NumRef { num: num_id, level: 0 }); + d.body = vec![Arc::new(Block::Para(p))]; + // The label 第十二章 stays one word (#4547 changed only document text); 总结 is two. + assert_eq!(d.word_count(), 1 + 2); +} + #[test] fn sections_and_section_mut() { let mut d = Document::from_text("a\nb\nc"); @@ -651,3 +684,66 @@ fn control_markers_kept_are_sorted() { assert!(kept.windows(2).all(|p| p[0] < p[1]), "sorted, no repeats: {kept:?}"); } } + +#[test] +fn lone_table_open_markers_linear_time() { + let mut d = Document::new(); + let mut t = Table::new(1, 1, 100.0); + const COUNT: usize = 2_000; + t.controls.open = (0..COUNT).map(|i| ContentControl { tag: format!("ctrl_{i}"), ..Default::default() }).collect(); + d.body.insert(0, Arc::new(Block::Table(t))); + + let mut paras = Vec::new(); + let mut tables = Vec::new(); + let timer = std::time::Instant::now(); + crate::control::orphans(&d.body, &mut Vec::new(), 0, &mut paras, &mut tables); + + assert_eq!(paras.len(), 0); + assert_eq!(tables.len(), COUNT); + for (i, (path, nth, is_open)) in tables.iter().enumerate() { + assert_eq!(*path, Path::top(0)); + assert_eq!(*nth, i); + assert!(*is_open); + } + + assert!(d.has_unbalanced_controls()); + let removed = d.balance_controls(); + assert_eq!(removed, COUNT); + assert!(!d.has_unbalanced_controls()); + assert!(timer.elapsed().as_secs_f32() < 10.0, "{:?}", timer.elapsed()); + let Block::Table(tbl) = &*d.body[0] else { panic!("expected table") }; + assert!(tbl.controls.open.is_empty()); +} + +#[test] +fn lone_table_open_markers_mixed_tables_and_paired() { + let mut d = Document::new(); + let mut t0 = Table::new(1, 1, 100.0); + t0.controls.open = (0..3).map(|i| ContentControl { tag: format!("t0_{i}"), ..Default::default() }).collect(); + t0.controls.close = 1; + + let mut t1 = Table::new(1, 1, 100.0); + t1.controls.open = (0..2).map(|i| ContentControl { tag: format!("t1_{i}"), ..Default::default() }).collect(); + + d.body = vec![Arc::new(Block::Table(t0)), Arc::new(Block::Table(t1))]; + + let mut paras = Vec::new(); + let mut tables = Vec::new(); + crate::control::orphans(&d.body, &mut Vec::new(), 0, &mut paras, &mut tables); + + assert_eq!(paras.len(), 0); + assert_eq!(tables, vec![(Path::top(0), 0, true), (Path::top(0), 1, true), (Path::top(1), 0, true), (Path::top(1), 1, true),]); + + let removed = d.balance_controls(); + assert_eq!(removed, 4); + assert!(!d.has_unbalanced_controls()); + + let Block::Table(res0) = &*d.body[0] else { panic!("expected table") }; + assert_eq!(res0.controls.open.len(), 1); + assert_eq!(res0.controls.open[0].tag, "t0_2"); + assert_eq!(res0.controls.close, 1); + + let Block::Table(res1) = &*d.body[1] else { panic!("expected table") }; + assert!(res1.controls.open.is_empty()); + assert_eq!(res1.controls.close, 0); +} diff --git a/crates/doc/src/tests/note_conversion.rs b/crates/doc/src/tests/note_conversion.rs new file mode 100644 index 0000000000..3c9a5e2b43 --- /dev/null +++ b/crates/doc/src/tests/note_conversion.rs @@ -0,0 +1,145 @@ +use super::*; +use crate::para::{InlineObject, NoteKind, OBJ}; + +fn reference(id: u32, kind: NoteKind) -> InlineObject { + InlineObject::NoteRef { kind, id, custom: "*".into() } +} + +fn styled(len: usize, style: &str) -> Run { + Run { len, props: CharProps { style: Some(style.into()), italic: Some(true), ..Default::default() } } +} + +#[test] +fn conversion_preserves_reference_run_boundaries_and_unmatched_storage() { + for (foot, end, expected) in [ + (true, false, ["FootnoteReference", "EndnoteReference", "FootnoteReference", "EndnoteReference", "EndnoteReference", "FootnoteReference"]), + (false, true, ["FootnoteReference", "FootnoteReference", "FootnoteReference", "EndnoteReference", "FootnoteReference", "FootnoteReference"]), + (true, true, ["FootnoteReference", "EndnoteReference", "FootnoteReference", "EndnoteReference", "FootnoteReference", "FootnoteReference"]), + ] { + let mut d = Document::new(); + let note = |style: &str| { + let mut p = Paragraph::with_text("Original note 漢", CharProps::default()); + p.props.style = Some(style.into()); + p.mark.style = Some(style.into()); + vec![para_block(p)] + }; + let f = d.add_part(PartKind::Footnote, note("FootnoteText")); + let e = d.add_part(PartKind::Endnote, note("EndnoteText")); + let p = Paragraph { + text: format!("é{OBJ}{OBJ}漢{OBJ}{OBJ}"), + objects: vec![ + reference(f, NoteKind::Footnote), + InlineObject::BookmarkStart { name: "kept".into() }, + reference(e, NoteKind::Endnote), + reference(999, NoteKind::Footnote), + reference(f, NoteKind::Footnote), + ], + runs: vec![ + styled(2, "FootnoteReference"), + styled(3, "FootnoteReference"), + styled(3, "FootnoteReference"), + styled(3, "EndnoteReference"), + styled(3, "EndnoteReference"), + styled(3, "FootnoteReference"), + ], + ..Paragraph::new() + }; + let mut table = Table::new(1, 1, 200.0); + table.rows[0].cells[0].blocks = vec![para_block(p.clone())]; + d.body = vec![para_block(p.clone()), Arc::new(Block::Table(table))]; + let h = d.add_part(PartKind::Header, vec![para_block(p.clone())]); + let t = d.add_part(PartKind::TextBox, vec![para_block(p.clone())]); + let before = d.clone(); + assert_eq!(d.convert_notes(foot, end), usize::from(foot) + usize::from(end)); + for (story, path) in [ + (StoryRef::Body, Path::top(0)), + (StoryRef::Body, Path(vec![1, 0, 0, 0])), + (StoryRef::Part(h), Path::top(0)), + (StoryRef::Part(t), Path::top(0)), + ] { + let got = d.para(story, &path).unwrap(); + assert_eq!(got.text, p.text); + assert_eq!(got.runs.iter().map(|r| r.props.style.as_deref().unwrap()).collect::>(), expected); + assert!(got.runs.iter().all(|r| r.props.italic == Some(true))); + assert_eq!(got.objects[1], p.objects[1]); + assert_eq!(got.objects[3], p.objects[3], "a missing note stays unchanged"); + assert_eq!(got.objects[0], reference(f, if foot { NoteKind::Endnote } else { NoteKind::Footnote })); + assert_eq!(got.objects[2], reference(e, if end { NoteKind::Footnote } else { NoteKind::Endnote })); + assert_eq!(got.objects[4], got.objects[0], "surplus object storage retains the existing conversion"); + } + for (id, flipped, from, to) in [(f, foot, "FootnoteText", "EndnoteText"), (e, end, "EndnoteText", "FootnoteText")] { + let got = d.para(StoryRef::Part(id), &Path::top(0)).unwrap(); + assert_eq!(got.text, before.plain_text(StoryRef::Part(id))); + assert_eq!(got.props.style.as_deref(), Some(if flipped { to } else { from })); + assert_eq!(got.mark.style, got.props.style); + } + let mut missing = Paragraph { + text: format!("{OBJ}{OBJ}"), + objects: vec![reference(f, if foot { NoteKind::Endnote } else { NoteKind::Footnote })], + runs: vec![styled(0, "FootnoteReference"), styled(3, "FootnoteReference"), styled(3, "FootnoteReference")], + ..Paragraph::new() + }; + missing.runs.push(styled(usize::MAX, "FootnoteReference")); + d.body = vec![para_block(missing)]; + d.convert_notes(true, true); + let got = d.para(StoryRef::Body, &Path::top(0)).unwrap(); + assert_eq!( + got.runs.iter().map(|r| r.props.style.as_deref().unwrap()).collect::>(), + ["FootnoteReference", "EndnoteReference", "FootnoteReference", "FootnoteReference"] + ); + } +} + +fn dense(n: usize) -> Document { + let mut d = Document::new(); + let id = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Shared original note", CharProps::default()))]); + d.body = vec![para_block(Paragraph { + text: format!("{}{}", OBJ.to_string().repeat(n), "x".repeat(n)), + objects: (0..n).map(|_| reference(id, NoteKind::Footnote)).collect(), + runs: (0..n).map(|_| styled(OBJ.len_utf8(), "FootnoteReference")).chain((0..n).map(|_| styled(1, "FootnoteReference"))).collect(), + ..Paragraph::new() + })]; + d +} + +// Thread CPU excludes scheduler delays. Missing or nonadvancing counters provide no timing +// evidence; the semantic assertions still run on those platforms. +fn cpu_cost(f: impl FnOnce()) -> Option { + let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::().ok(); + let before = ran(); + f(); + match (before, ran()) { + (Some(a), Some(b)) if b > a => Some((b - a) as f64 * 1e-9), + _ => None, + } +} + +#[test] +fn conversion_work_scales_with_reference_and_formatting_runs() { + let (small, big) = (dense(2_000), dense(16_000)); + let convert = |input: &Document| { + let mut d = input.clone(); + assert_eq!(d.convert_notes(true, false), 1); + let p = d.para(StoryRef::Body, &Path::top(0)).unwrap(); + let n = p.objects.len(); + assert!(p.runs[..n].iter().all(|r| r.props.style.as_deref() == Some("EndnoteReference"))); + assert!(p.runs[n..].iter().all(|r| r.props.style.as_deref() == Some("FootnoteReference"))); + std::hint::black_box(d); + }; + convert(&small); + convert(&big); + let (mut t1, mut t8) = (f64::INFINITY, f64::INFINITY); + for _ in 0..3 { + let a = cpu_cost(|| (0..8).for_each(|_| convert(&small))); + let b = cpu_cost(|| convert(&big)); + if let (Some(a), Some(b)) = (a, b) { + t1 = t1.min(a / 8.0); + t8 = t8.min(b); + } + } + if t1.is_finite() && t8.is_finite() { + let ratio = t8 / t1; + eprintln!("note conversion CPU: small={t1:.6}s big={t8:.6}s ratio={ratio:.2}"); + assert!(ratio < 24.0, "8x the references and runs cost {ratio:.2}x CPU"); + } +} diff --git a/crates/doc/src/text_walk.rs b/crates/doc/src/text_walk.rs index d7a681a5f8..6a554f8131 100644 --- a/crates/doc/src/text_walk.rs +++ b/crates/doc/src/text_walk.rs @@ -3,9 +3,36 @@ use super::parts::PartKind; use super::position::Path; use super::{InlineObject, Numbering, numbering, para, section, styles}; -/// Words in `s` (tokens separated by whitespace that contain at least one alphanumeric char). +/// Words in `s`, as Word counts them: tokens separated by whitespace that contain at least one +/// alphanumeric char, plus each Han ideograph and kana as a word of its own (Chinese and Japanese +/// are written without spaces, #4547; Korean is spaced, so Hangul counts by tokens). pub fn count_words(s: &str) -> usize { - s.split(|c: char| c.is_whitespace() || c == para::OBJ).filter(|w| w.chars().any(char::is_alphanumeric)).count() + // The half-width voiced sound marks belong to the kana before them, not a word of their own. + let word_char = |c: char| c.is_alphanumeric() && !matches!(c, '\u{FF9E}' | '\u{FF9F}'); + let tokens = s.split(|c: char| c.is_whitespace() || c == para::OBJ || is_cjk_word(c)).filter(|w| w.chars().any(word_char)).count(); + tokens.saturating_add(s.chars().filter(|c| is_cjk_word(*c)).count()) +} + +/// Words in a generated list label: whitespace-separated tokens holding a letter or digit, so a +/// CJK label such as 第十二章 stays one word (how Word counts those is unverified). +fn count_label_words(s: &str) -> usize { + s.split(char::is_whitespace).filter(|w| w.chars().any(char::is_alphanumeric)).count() +} + +/// A Han ideograph or kana letter (not CJK punctuation), which Word counts as one word. +fn is_cjk_word(c: char) -> bool { + matches!(c, + '\u{3005}'..='\u{3007}' // 々 〆 〇 + | '\u{3031}'..='\u{3035}' | '\u{303B}' // vertical kana repeat marks, 〻 + | '\u{3040}'..='\u{30FF}' // hiragana, katakana + | '\u{31F0}'..='\u{31FF}' // katakana phonetic extensions + | '\u{3400}'..='\u{4DBF}' // extension A + | '\u{4E00}'..='\u{9FFF}' // unified ideographs + | '\u{F900}'..='\u{FAFF}' // compatibility ideographs + | '\u{FF66}'..='\u{FF9D}' // half-width katakana + | '\u{1B000}'..='\u{1B16F}' // kana supplement and extended + | '\u{20000}'..='\u{3FFFF}' // extensions B and later + ) && c.is_alphanumeric() } /// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped. @@ -146,7 +173,7 @@ pub(crate) fn story_word_count_of( && let Some((label, def)) = counters.next_label(numbering, n.num, n.level) && !matches!(def.format, section::NumFormat::Bullet | section::NumFormat::None) { - total = total.saturating_add(count_words(&label)); + total = total.saturating_add(count_label_words(&label)); } total = total.saturating_add(count_words(&p.plain_text())); } diff --git a/crates/docx/src/bibliography.rs b/crates/docx/src/bibliography.rs index 0b6776825b..495c21e50d 100644 --- a/crates/docx/src/bibliography.rs +++ b/crates/docx/src/bibliography.rs @@ -90,13 +90,16 @@ pub(crate) fn parse(root: &El, seen: &mut Seen, room: usize) -> Sources { let tag = child_text(src_el, "Tag"); let raw_kind = child_text(src_el, "SourceType"); let kind = crate::write::from_source_type(&raw_kind); - let (author, editor) = match src_el.els().find(|e| e.local() == "Author") { + let (author, corporate, editor) = match src_el.els().find(|e| e.local() == "Author") { Some(a) => { - let auth = a.els().find(|e| e.local() == "Author").map(parse_persons).filter(|s| !s.is_empty()).unwrap_or_else(|| parse_persons(a)); + let role = a.els().find(|e| e.local() == "Author"); + let auth = role.map(parse_persons).filter(|s| !s.is_empty()).unwrap_or_else(|| parse_persons(a)); + // Word's Corporate Author: one name, kept whole (`b:Corporate`, #4848). + let corporate = role.map(|r| child_text(r, "Corporate").trim().to_string()).unwrap_or_default(); let ed = a.els().find(|e| e.local() == "Editor").map(parse_persons).unwrap_or_default(); - (auth, ed) + (auth, corporate, ed) } - None => (String::new(), String::new()), + None => (String::new(), String::new(), String::new()), }; let editor = if editor.is_empty() { src_el.els().find(|e| e.local() == "Editor").map(parse_persons).unwrap_or_default() } else { editor }; let title = child_text(src_el, "Title"); @@ -132,11 +135,12 @@ pub(crate) fn parse(root: &El, seen: &mut Seen, room: usize) -> Sources { }; // Keep sources with some content, once each (by tag, or title and author untagged). - if tag.is_empty() && title.is_empty() && author.is_empty() && editor.is_empty() { + if tag.is_empty() && title.is_empty() && author.is_empty() && corporate.is_empty() && editor.is_empty() { continue; } let fresh = if tag.is_empty() { - seen.untagged.insert((title.clone(), if author.is_empty() { editor.clone() } else { author.clone() })) + let who = [&author, &corporate, &editor].into_iter().find(|w| !w.is_empty()).cloned().unwrap_or_default(); + seen.untagged.insert((title.clone(), who)) } else { seen.tags.insert(tag.clone()) }; @@ -147,6 +151,7 @@ pub(crate) fn parse(root: &El, seen: &mut Seen, room: usize) -> Sources { tag, kind, author, + corporate, title, year, city, @@ -265,6 +270,25 @@ mod tests { assert!(read_sources(br#""#).is_err(), "an unrelated namespace"); } + /// #4848: a corporate author (Word's Corporate Author box, `b:Corporate`) is read whole, and + /// an untagged source with only a corporate author is still kept, once. + #[test] + fn a_corporate_author_is_read_whole() { + let xml = br#" + Wor20Report + World Health Organization + World report on hearing2020 + Book + Harbor Guild, Inc. + Book + Harbor Guild, Inc. +"#; + let f = read_sources(xml).unwrap(); + assert_eq!(f.sources.len(), 2, "{:?}", f.sources); + assert_eq!((f.sources[0].corporate.as_str(), f.sources[0].author.as_str()), ("World Health Organization", "")); + assert_eq!(f.sources[1].corporate, "Harbor Guild, Inc.", "a comma doesn't split a corporate name"); + } + /// Word's own 2004/10 bibliography namespace (`Sources.xml` written by scripts and older /// builds, the VBA `Source.XML` format) reads as well as OOXML's. #[test] diff --git a/crates/docx/src/crypt/tests.rs b/crates/docx/src/crypt/tests.rs index 44421be745..0b316061bd 100644 --- a/crates/docx/src/crypt/tests.rs +++ b/crates/docx/src/crypt/tests.rs @@ -193,6 +193,25 @@ fn hostile_encryption_info_errors_without_panicking() { assert!(decrypt(&fake, Some("pw")).is_err()); } +/// The key a real-world Standard-encrypted package derives: Apache POI's test file +/// `protected_passtika.xlsx` (Apache-2.0 test data), password "tika", written by Excel +/// itself. The value was computed from [MS-OFFCRYPTO] §2.3.4.7 independently of this code — +/// the file decrypts to a valid package under it and nothing else opens that file — so real +/// Word 2007 documents stay pinned, not just spec-derived ones. +#[test] +fn standard_key_matches_a_real_world_package() { + let salt: [u8; 16] = [0x19, 0xd0, 0xc7, 0xf3, 0x95, 0x28, 0x78, 0x43, 0x6a, 0x49, 0x49, 0xd7, 0xf0, 0xa2, 0xcf, 0x1e]; + const KEY: &str = "8d4d00143a5f2e4918af7e6e7410d46c"; + let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); + assert_eq!(hex(&standard_key(&salt, "tika", 16)), KEY); + // A different password or salt gives a different key; the key is exactly the length + // asked for, for each AES width. + assert_ne!(hex(&standard_key(&salt, "tika2", 16)), KEY); + assert_ne!(hex(&standard_key(&[0; 16], "tika", 16)), KEY); + assert_eq!(standard_key(&salt, "tika", 24).len(), 24); + assert_eq!(standard_key(&salt, "tika", 32).len(), 32); +} + /// Standard encryption's key derivation (§2.3.4.7) for the password "Password1234_" and the /// salt 00 01 … 0F. The expected keys were computed outside WordCraft (Python's hashlib) /// following the specification's steps, so the encryptor and decryptor can't share a mistake. diff --git a/crates/docx/src/custom.rs b/crates/docx/src/custom.rs index a208441b5a..aa49c45879 100644 --- a/crates/docx/src/custom.rs +++ b/crates/docx/src/custom.rs @@ -25,11 +25,11 @@ pub fn read(root: &El) -> Vec { let Some(v) = p.els().next() else { continue }; let kind = v.local(); let prop = if SIMPLE.contains(&kind) { - CustomProp { name: name.to_string(), kind: kind.to_string(), value: v.text() } + CustomProp { name: name.to_string(), kind: kind.to_string(), value: v.text(), link_target: p.attr("linkTarget").map(str::to_string) } } else { let mut xml = String::new(); el_xml(v, &mut xml, 0); - CustomProp { name: name.to_string(), kind: "raw".into(), value: xml } + CustomProp { name: name.to_string(), kind: "raw".into(), value: xml, link_target: p.attr("linkTarget").map(str::to_string) } }; out.push(prop); } @@ -51,7 +51,12 @@ pub fn write(props: &[CustomProp]) -> Vec { if p.kind == "raw" && !raw_is_wellformed(&p.value) { continue; } - w.open("property", &[("fmtid", FMTID), ("pid", &pid.to_string()), ("name", &p.name)]); + let pid = pid.to_string(); + let mut attrs = vec![("fmtid", FMTID), ("pid", &pid), ("name", &p.name)]; + if let Some(target) = &p.link_target { + attrs.push(("linkTarget", target)); + } + w.open("property", &attrs); if p.kind == "raw" { w.raw(&p.value); } else { diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 878dd487dd..8f77ec63c5 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -210,18 +210,20 @@ pub(crate) fn read_opened(pkg: &Package) -> Result { if let Some(p) = part(rt::SETTINGS) { lenient("settings", r.read_settings(&p)); } - if let Some(p) = part(rt::FOOTNOTES) { - lenient("footnotes", r.read_notes(&p, true)); - } - if let Some(p) = part(rt::ENDNOTES) { - lenient("endnotes", r.read_notes(&p, false)); - } + // Comments before notes: a comment range inside a footnote or endnote resolves its id against + // the comments already read, and was dropped when the notes came first. if let Some(p) = part(rt::COMMENTS) { let ex = part(rt::COMMENTS_EX); let ids = part(rt::COMMENTS_IDS); let cex = part(rt::COMMENTS_EXTENSIBLE); lenient("comments", r.read_comments(&p, ex.as_deref(), ids.as_deref(), cex.as_deref())); } + if let Some(p) = part(rt::FOOTNOTES) { + lenient("footnotes", r.read_notes(&p, true)); + } + if let Some(p) = part(rt::ENDNOTES) { + lenient("endnotes", r.read_notes(&p, false)); + } // Bibliography sources live in a custom XML data store (`b:Sources`), related from the // package root or the main part; Word's own files sometimes leave the relationship out, so // the conventional `customXml/itemN.xml` names are tried too. Each part is read at most once. diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index acd56b2ef4..ed5ccf0d03 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -23,8 +23,8 @@ fn text_frame(k: &El) -> wordcraft_doc::props::TextFrame { let word = |name: &str, allowed: &[&str], default: &str| k.attr(name).filter(|v| allowed.contains(v)).unwrap_or(default).to_string(); let align = |name: &str, allowed: &[&str]| k.attr(name).filter(|v| allowed.contains(v)).map(str::to_string); wordcraft_doc::props::TextFrame { - w: len("w:w").filter(|v| *v > 0.0), - h: len("w:h").map(f32::abs).filter(|v| *v > 0.0), + w: len("w:w").filter(|v| *v >= 0.0), + h: len("w:h").map(f32::abs), h_exact: k.attr("w:hRule") == Some("exact"), x: len("w:x").unwrap_or(0.0), y: len("w:y").unwrap_or(0.0), @@ -258,6 +258,8 @@ impl PropCtx { "w:imprint" => c.engrave = Some(on_off(k)), "w:noProof" => c.no_proof = Some(on_off(k)), "w:vanish" => c.hidden = Some(on_off(k)), + "w:webHidden" => c.web_hidden = Some(on_off(k)), + "w:snapToGrid" => c.snap_to_grid = Some(on_off(k)), "w:rtl" => c.rtl = Some(on_off(k)), "w:color" => { c.color = match (self.theme_color(k, "w:themeColor", "w:themeTint", "w:themeShade"), k.attr("w:val")) { diff --git a/crates/docx/src/read/styles.rs b/crates/docx/src/read/styles.rs index 55d01e8a49..cf9bccf51b 100644 --- a/crates/docx/src/read/styles.rs +++ b/crates/docx/src/read/styles.rs @@ -42,6 +42,13 @@ pub(crate) fn ui_style_name(n: &str) -> String { n.to_string() } +/// The outline level (0 for Heading 1) of Word's built-in style named `heading 1` … `heading 9`. +fn builtin_heading_level(name: &str) -> Option { + let name = name.trim(); + let digit = name.get(..8).filter(|p| p.eq_ignore_ascii_case("heading ")).and(name.get(8..))?; + digit.parse::().ok().filter(|d| digit.len() == 1 && (1..=9).contains(d)).map(|d| d - 1) +} + impl Reader<'_> { pub(super) fn read_styles(&mut self, path: &str) -> Result<(), DocxError> { /// Largest `w:latentStyles` kept (Word's has ~380 exceptions, ~40 KB). @@ -115,7 +122,7 @@ impl Reader<'_> { priority: s.child_val("w:uiPriority").and_then(u32_of), quick: flag(s, "w:qFormat").unwrap_or(false), hidden: flag(s, "w:semiHidden").unwrap_or(false) || flag(s, "w:hidden").unwrap_or(false), - builtin: !s.attr("w:customStyle").is_some_and(|v| v == "1" || v == "true"), + builtin: !s.attr("w:customStyle").is_some_and(|v| matches!(v.trim(), "1" | "true" | "on")), locked: flag(s, "w:locked").unwrap_or(false), // Only where the writer couldn't tell from the id (it flags the English ids). default: s.attr("w:default").is_some_and(|v| v == "1" || v == "true") @@ -131,6 +138,16 @@ impl Reader<'_> { if let Some(p) = s.child("w:pPr") { st.para = self.pc.ppr(p).0; } + // Word gives its built-in heading styles their outline level whether or not the file + // writes `w:outlineLvl` (some producers leave it out): "heading 2" is level 2 in the + // Navigation pane and the table of contents, whatever its id (#4696). + if kind == StyleKind::Paragraph + && st.builtin + && st.para.outline_level.is_none() + && let Some(level) = s.child_val("w:name").and_then(builtin_heading_level) + { + st.para.outline_level = Some(level); + } if let Some(rp) = s.child("w:rPr") { st.chr = self.pc.rpr(rp); } diff --git a/crates/docx/src/write/bibliography.rs b/crates/docx/src/write/bibliography.rs index ee343c8662..91dfb23f57 100644 --- a/crates/docx/src/write/bibliography.rs +++ b/crates/docx/src/write/bibliography.rs @@ -121,10 +121,16 @@ pub(super) fn bibliography_xml(doc: &Document) -> Vec { w.open("b:Source", &[]); w.leaf("b:Tag", &[], &src.tag); w.leaf("b:SourceType", &[], to_source_type(&src.kind)); - // Author & Editor - if !src.author.is_empty() || !src.editor.is_empty() { + // Author & Editor. A role holds a name list or a corporate name, not both (ECMA-376 + // `CT_NameOrCorporateType`), so a corporate author takes the author's place (#4848). + let corporate = src.corporate.trim(); + if !src.author.is_empty() || !corporate.is_empty() || !src.editor.is_empty() { w.open("b:Author", &[]); - if !src.author.is_empty() { + if !corporate.is_empty() { + w.open("b:Author", &[]); + w.leaf("b:Corporate", &[], corporate); + w.close("b:Author"); + } else if !src.author.is_empty() { w.open("b:Author", &[]); write_name_list(&mut w, &src.author); w.close("b:Author"); diff --git a/crates/docx/src/write/parts.rs b/crates/docx/src/write/parts.rs index 7cea957d46..39c2e58d24 100644 --- a/crates/docx/src/write/parts.rs +++ b/crates/docx/src/write/parts.rs @@ -429,13 +429,15 @@ fn write_comments( ("xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"), ], ); - let pid_of = |cid: u32| comment_paras.iter().find(|(c, _)| *c == cid).map(|(_, p)| p.clone()); + // Assigned in BTreeMap comment-ID order above, including gaps for missing parts. + let pid_of = + |cid: u32| comment_paras.binary_search_by_key(&cid, |(c, _)| *c).ok().and_then(|i| comment_paras.get(i)).map(|(_, p)| p.as_str()); for (cid, c) in &doc.comments { let Some(pid) = pid_of(*cid) else { continue }; let done = if c.resolved { "1" } else { "0" }; match c.parent.and_then(pid_of) { - Some(parent) => w.empty("w15:commentEx", &[("w15:paraId", &pid), ("w15:paraIdParent", &parent), ("w15:done", done)]), - None => w.empty("w15:commentEx", &[("w15:paraId", &pid), ("w15:done", done)]), + Some(parent) => w.empty("w15:commentEx", &[("w15:paraId", pid), ("w15:paraIdParent", parent), ("w15:done", done)]), + None => w.empty("w15:commentEx", &[("w15:paraId", pid), ("w15:done", done)]), } } w.close("w15:commentsEx"); diff --git a/crates/docx/src/write/props.rs b/crates/docx/src/write/props.rs index b67ee6b076..57400cd059 100644 --- a/crates/docx/src/write/props.rs +++ b/crates/docx/src/write/props.rs @@ -53,7 +53,9 @@ pub fn rpr_inner(w: &mut W, c: &CharProps) { toggle(w, "w:emboss", c.emboss); toggle(w, "w:imprint", c.engrave); toggle(w, "w:noProof", c.no_proof); + toggle(w, "w:snapToGrid", c.snap_to_grid); toggle(w, "w:vanish", c.hidden); + toggle(w, "w:webHidden", c.web_hidden); match c.color { Some(TextColor::Auto) => w.val("w:color", "auto"), Some(TextColor::Rgb(rgb)) => w.val("w:color", &rgb.hex()), diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index df4e77fa64..1c7d20e53b 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -172,6 +172,8 @@ pub(super) fn write_comment_ids( if comment_paras.is_empty() { return; } + // Keep the existing exact-string reservation rule, including comments without a written part. + let reserved: std::collections::HashSet<&str> = doc.comments.values().filter_map(|c| c.durable_id.as_deref()).collect(); let mut used: std::collections::HashSet = std::collections::HashSet::new(); let mut next = 0x1000_0000u32; let mut rows: Vec<(String, String, Option)> = Vec::new(); @@ -183,7 +185,7 @@ pub(super) fn write_comment_ids( None => loop { next = next.saturating_add(1); let d = format!("{next:08X}"); - if !used.contains(&d) && !doc.comments.values().any(|o| o.durable_id.as_deref() == Some(d.as_str())) { + if !used.contains(&d) && !reserved.contains(d.as_str()) { break d; } }, diff --git a/crates/docx/tests/it/citations.rs b/crates/docx/tests/it/citations.rs index 344ad9f67b..0c5fadd923 100644 --- a/crates/docx/tests/it/citations.rs +++ b/crates/docx/tests/it/citations.rs @@ -155,6 +155,38 @@ fn zotero_fields_and_prefs_round_trip() { assert_eq!(read(&write(&d2).unwrap()).unwrap().custom_props, d.custom_props); } +#[test] +fn custom_property_bookmark_links_survive_saves_and_value_edits() { + let props = r#" +Original value +Ω +17 +"#; + let doc = format!( + r#"{}{}"#, + t("Original value"), + t("Ω") + ); + let bytes = zip(&[("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", doc.as_bytes()), ("docProps/custom.xml", props.as_bytes())]); + let mut d = read(&bytes).unwrap(); + for value in ["Original value", "Edited value"] { + d.set_custom_prop("linked", value); + 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(); + 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"); + d = read(&out).unwrap(); + assert_eq!(d.custom_props, before); + assert_eq!(d.custom_prop("Linked"), Some(value)); + } + } +} + #[test] fn unterminated_and_resultless_addin_fields() { // A field left open at the end of the document, and one with no result at all. diff --git a/crates/docx/tests/it/comment_save_cost.rs b/crates/docx/tests/it/comment_save_cost.rs new file mode 100644 index 0000000000..2716578b29 --- /dev/null +++ b/crates/docx/tests/it/comment_save_cost.rs @@ -0,0 +1,55 @@ +//! Saving large comment threads must not search all comments for each emitted ID. + +use wordcraft_doc::{Comment, Document, Paragraph, Part, PartKind, para_block}; + +fn comments(n: u32, imported: bool) -> Document { + let mut d = Document::from_text("Original comment save fixture."); + for i in 0..n { + // Sparse IDs and replies to a later comment also exercise paragraph-ID lookup order. + let id = i * 3 + 7; + d.parts.insert(id, Part { kind: PartKind::Comment, blocks: vec![para_block(Paragraph::new())], ..Default::default() }); + d.comments.insert( + id, + Comment { part: id, parent: (i + 1 < n).then_some(id + 3), durable_id: imported.then(|| format!("{:08X}", i + 1)), ..Default::default() }, + ); + } + d +} + +fn cpu_cost(mut f: impl FnMut()) -> f64 { + let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::().ok(); + let (wall, before) = (std::time::Instant::now(), ran()); + f(); + match (before, ran()) { + (Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9, + _ => wall.elapsed().as_secs_f64(), + } +} + +#[test] +fn many_comments_save_without_quadratic_id_searches() { + for imported in [true, false] { + let small = comments(4_000, imported); + let big = comments(32_000, imported); + let save = |d: &Document| drop(std::hint::black_box(wordcraft_docx::write(d).unwrap())); + save(&small); + save(&big); + let mut ratios = Vec::new(); + // Alternating inputs and thread CPU time leave scheduler delays out on Linux. Elsewhere + // use elapsed time; retry ratios far from linear before declaring a regression. + for _ in 0..3 { + let (mut s, mut b) = (f64::INFINITY, f64::INFINITY); + for _ in 0..3 { + s = s.min(cpu_cost(|| (0..8).for_each(|_| save(&small))) / 8.0); + b = b.min(cpu_cost(|| save(&big))); + } + let ratio = b / s.max(1e-9); + eprintln!("comments imported={imported}: {s:.4}s -> {b:.4}s, ratio {ratio:.2}"); + if ratio < 24.0 { + break; + } + ratios.push(ratio); + } + assert!(ratios.len() < 3, "8x comments took {ratios:?}x CPU: repeated ID searches"); + } +} diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 5d9e128fba..34b3bd0746 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -114,6 +114,68 @@ fn paragraph_default_presence_survives_repeated_saves() { } } +#[test] +fn zero_frame_keeps_normal_flow() { + const ROUND_TRIPS: usize = 2; + let zero = r#""#; + let sized = r#""#; + for frame in [zero, sized] { + let styles = format!( + r#"{frame} + {sized}"# + ); + let header = format!(r#"Header alphaHeader beta"#); + let footer = format!(r#"Footer delta"#); + let body = format!( + r#"Body one + {sized}Direct frame + Styled frame + {zero}Frame reset + "# + ); + let mut document = wordcraft_docx::read(&docx( + &body, + &[("styles", "styles", "styles.xml"), ("header", "header", "header1.xml"), ("footer", "footer", "footer1.xml")], + &[("word/styles.xml", &styles), ("word/header1.xml", &header), ("word/footer1.xml", &footer)], + )) + .unwrap(); + for pass in 0..=ROUND_TRIPS { + let body = paras(&document); + let resolved = document.styles.resolve_para(&body[0].props); + assert!(resolved.frame.is_none(), "document defaults never create a frame"); + assert!(document.styles.default_para.frame.is_none()); + let reset = body[3].props.frame.as_ref().unwrap(); + assert_eq!((reset.w, reset.h), (Some(0.0), Some(0.0)), "the direct reset survives saving"); + assert_eq!(resolved.space_after, 8.0); + assert!(document.styles.resolve_para(&body[1].props).frame.is_some()); + assert!(document.styles.resolve_para(&body[2].props).frame.is_some()); + assert!(document.styles.resolve_para(&body[3].props).frame.is_none()); + for id in [document.last_section.headers.default, document.last_section.footers.default] { + for block in &document.parts.get(&id.unwrap()).unwrap().blocks { + let paragraph = block.as_para().unwrap(); + assert!(document.styles.resolve_para(¶graph.props).frame.is_none(), "defaults do not frame headers or footers"); + } + } + if pass == ROUND_TRIPS { + break; + } + document = wordcraft_docx::read(&wordcraft_docx::write(&document).unwrap()).unwrap(); + } + } +} + +#[test] +fn frame_zero_side_is_automatic() { + for (attrs, width, height) in + [(r#"w:w="0" w:h="1200""#, None, Some(60.0)), (r#"w:w="2400" w:h="0" w:hRule="exact""#, Some(120.0), None), ("", None, None)] + { + let document = read_body(&format!(r#"Original automatic frame"#)); + let paragraph = paras(&document)[0]; + let frame = document.styles.resolve_para(¶graph.props).frame.unwrap(); + assert_eq!((frame.w, frame.h), (width, height)); + } +} + #[test] fn omitted_paragraph_defaults_can_be_edited() { let styles = diff --git a/crates/docx/tests/it/heading_levels.rs b/crates/docx/tests/it/heading_levels.rs new file mode 100644 index 0000000000..e32059dce8 --- /dev/null +++ b/crates/docx/tests/it/heading_levels.rs @@ -0,0 +1,57 @@ +//! #4696: Word's built-in heading styles have their outline level even when the file's +//! `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"; + +fn package(styles: &str, body: &str) -> Vec { + let root = r#""#; + let rels = r#""#; + let doc = format!(r#"{body}"#); + let styles = format!(r#"{styles}"#); + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::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.finish().unwrap().into_inner() +} + +fn para(style: &str, text: &str) -> String { + format!(r#"{text}"#) +} + +fn levels(d: &wordcraft_doc::Document) -> Vec> { + d.body.iter().filter_map(|b| b.as_para()).map(|p: &Paragraph| d.styles.resolve_para(&p.props).outline_level).collect() +} + +#[test] +fn built_in_heading_styles_have_their_outline_level_without_outline_lvl() { + let styles = r#" + + + + + + + + "#; + let body = ["Heading1", "Titolo2", "Heading9", "Below", "MyHead", "Heading10", "Fake4", "Heading3", "Normal"] + .iter() + .map(|s| para(s, "x")) + .collect::(); + let d = wordcraft_docx::read(&package(styles, &body)).unwrap(); + // Heading 1, 2 and 9 by name; a style based on a heading inherits its level; a custom style, + // "heading 10", a custom style named "heading 4" (`w:customStyle="on"`) and Normal have none; a + // level the file gives is kept. + let want = vec![Some(0), Some(1), Some(8), Some(1), None, None, None, Some(5), None]; + assert_eq!(levels(&d), want); + // The level survives a save and reopen. + let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(levels(&again), want); +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index c3661f2c31..e7134e11d0 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -3,6 +3,7 @@ mod bidi_runs; mod cell_margin_inheritance; mod char_units; mod citations; +mod comment_save_cost; mod complex_script_inheritance; mod content_control_save_cost; mod content_controls; @@ -13,14 +14,17 @@ mod east_asian_lang; mod east_asian_layout; mod fixtures; mod glossary; +mod heading_levels; mod legacy_forms; mod ligatures; mod malformed; +mod note_comments; mod passthrough; mod positional_tabs; mod privacy; mod roundtrip; mod row_property_exceptions; +mod run_props; mod section_form_protection; mod section_page_number_type; mod section_text_direction; @@ -28,6 +32,7 @@ mod section_valign; mod settings_merge; mod text_boxes; mod toc_ranges; +mod undefined_style; mod vml_shapes; mod word_xml; mod wordml2003_write; diff --git a/crates/docx/tests/it/note_comments.rs b/crates/docx/tests/it/note_comments.rs new file mode 100644 index 0000000000..d9dfba865d --- /dev/null +++ b/crates/docx/tests/it/note_comments.rs @@ -0,0 +1,68 @@ +//! Comments anchored inside footnotes and endnotes keep their ranges on read. All markup here is +//! synthetic, written from ECMA-376 §17.13.4 and §17.11. + +use wordcraft_doc::para::{NoteKind, OBJ}; +use wordcraft_doc::{Document, InlineObject}; + +use crate::fixtures::zip; + +const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#; +const ROOT_RELS: &str = r#""#; +const DOC_RELS: &str = r#""#; + +fn note(tag: &str, mark: &str, comment: u32, text: &str) -> String { + format!( + r#" {text}"# + ) +} + +fn read_doc() -> Document { + let doc = format!( + r#"Body"# + ); + let footnotes = format!(r#"{}"#, note("footnote", "footnoteRef", 7, "Foot.")); + let endnotes = format!(r#"{}"#, note("endnote", "endnoteRef", 8, "End.")); + let comments = format!( + r#"On the footnoteOn the endnote"# + ); + let bytes = zip(&[ + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/_rels/document.xml.rels", DOC_RELS.as_bytes()), + ("word/footnotes.xml", footnotes.as_bytes()), + ("word/endnotes.xml", endnotes.as_bytes()), + ("word/comments.xml", comments.as_bytes()), + ]); + wordcraft_docx::read(&bytes).unwrap() +} + +/// comments.xml has to be read before the notes: a note's `w:commentRangeStart` resolves its id +/// against the comments already read, and was dropped when the notes came first. +#[test] +fn comment_ranges_inside_notes_are_kept() { + let d = read_doc(); + let body = d.body[0].as_para().unwrap(); + let refs: Vec<(NoteKind, u32)> = body + .objects + .iter() + .filter_map(|o| match o { + InlineObject::NoteRef { kind, id, .. } => Some((*kind, *id)), + _ => None, + }) + .collect(); + assert_eq!(refs.len(), 2, "{:?}", body.objects); + for ((kind, id), (author, text)) in refs.into_iter().zip([("Ann", " Foot."), ("Bob", " End.")]) { + let p = d.parts.get(&id).unwrap().blocks[0].as_para().unwrap(); + let comment = match &p.objects[..] { + [InlineObject::NoteRef { kind: k, id: n, .. }, InlineObject::CommentStart { id: c }, InlineObject::CommentEnd { id: e }] + if *k == kind && *n == id && c == e => + { + *c + } + o => panic!("{kind:?} {id}: {o:?}"), + }; + assert_eq!(d.comments.get(&comment).unwrap().author, author); + assert_eq!(p.text.chars().filter(|c| *c == OBJ).count(), 3); + assert_eq!(p.plain_text(), text); + } +} diff --git a/crates/docx/tests/it/passthrough.rs b/crates/docx/tests/it/passthrough.rs index d5182922b2..cedb8d12ac 100644 --- a/crates/docx/tests/it/passthrough.rs +++ b/crates/docx/tests/it/passthrough.rs @@ -443,3 +443,51 @@ fn embedded_fonts_load_and_save_when_the_package_spells_the_font_table_in_capita assert_eq!(fonts.len(), 1, "the font survives a save: {:?}", files.keys()); assert_eq!(fonts[0].data, font_bytes); } + +#[test] +fn comment_ids_keep_sparse_threads_reservations_and_missing_parts() { + use wordcraft_doc::{Comment, Document, Paragraph, Part, PartKind, para_block}; + let mut doc = Document::from_text("Original thread fixture."); + // New IDs must skip the exact durable ID reserved by a later comment, even one whose + // missing part keeps it out of commentsIds.xml. Duplicate imported IDs are reassigned. + let rows = [ + (3, None, Some(90), false, true), + (11, Some("5a1b2c3d"), Some(90), true, true), + (25, Some("5A1B2C3D"), Some(999), false, true), + (90, Some("10000001"), None, true, true), + (999, Some("10000002"), None, false, false), + (u32::MAX, Some("not-hex"), Some(3), false, true), + ]; + for (id, durable, parent, resolved, has_part) in rows { + let part = id; + if has_part { + doc.parts.insert( + part, + Part { + kind: PartKind::Comment, + blocks: vec![para_block(Paragraph::with_text(&format!("Comment {id} β"), Default::default()))], + ..Default::default() + }, + ); + } + doc.comments.insert(id, Comment { part, parent, resolved, durable_id: durable.map(str::to_string), ..Default::default() }); + } + let files = save(&doc); + let (ids, _) = written_ids(&files); + assert_eq!(ids.iter().map(|(_, id)| id.as_str()).collect::>(), ["10000003", "5A1B2C3D", "10000004", "10000001", "10000005"]); + let ex = text(&files, "word/commentsExtended.xml"); + assert_eq!(ex.matches("World Health Organization"), "{item_xml}"); + assert!(item_xml.contains("Harbor Guild, Inc."), "{item_xml}"); + assert!(!item_xml.contains("Rivera"), "the corporate author takes the person authors' place: {item_xml}"); + let back = wordcraft_docx::read(&bytes).expect("read"); + let got: Vec<(&str, &str, &str)> = back.sources.iter().map(|s| (s.corporate.as_str(), s.author.as_str(), s.editor.as_str())).collect(); + assert_eq!(got, [("World Health Organization", "", "Chadha, Shelly"), ("Harbor Guild, Inc.", "", "")]); +} + 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()); diff --git a/crates/docx/tests/it/run_props.rs b/crates/docx/tests/it/run_props.rs new file mode 100644 index 0000000000..c203b26a05 --- /dev/null +++ b/crates/docx/tests/it/run_props.rs @@ -0,0 +1,74 @@ +//! Run and style properties that must survive repeated DOCX saves. + +use std::io::{Read, Write}; + +fn docx(body: &str, styles: &str) -> Vec { + let root = r#""#; + let rels = r#""#; + let document = format!( + r#"{body}"# + ); + let styles = format!(r#"{styles}"#); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::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.finish().unwrap().into_inner() +} + +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 +} + +#[test] +fn run_and_style_snap_to_grid_and_web_hidden_survive_two_saves() { + let styles = r#" + + + "#; + let body = r#" + + inherit + direct true + override + visible in print + absent + + "#; + let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap(); + let p = doc.body.iter().find_map(|b| b.as_para()).unwrap(); + assert_eq!(p.runs[0].props.snap_to_grid, None); + assert_eq!(p.runs[0].props.web_hidden, None); + assert_eq!(p.runs[1].props.snap_to_grid, Some(true)); + assert_eq!(p.runs[1].props.web_hidden, Some(true)); + assert_eq!(p.runs[2].props.snap_to_grid, Some(false)); + assert_eq!(p.runs[2].props.web_hidden, Some(false)); + assert_eq!(p.runs[3].props.hidden, Some(true)); + assert_eq!(p.runs[3].props.web_hidden, None); + assert_eq!(p.runs[4].props.snap_to_grid, None); + assert_eq!(p.runs[4].props.web_hidden, None); + assert!(!doc.styles.resolve_char(None, &p.runs[0].props).hidden, "w:webHidden does not hide Print Layout text"); + assert!(doc.styles.resolve_char(None, &p.runs[3].props).hidden, "w:vanish still controls hidden text"); + for pass in 0..2 { + let out = wordcraft_docx::write(&doc).unwrap(); + let style_xml = part(&out, "word/styles.xml"); + assert!(style_xml.contains(r#""#), "pass {pass}: {style_xml}"); + assert!(style_xml.contains(r#""#), "pass {pass}: {style_xml}"); + let document_xml = part(&out, "word/document.xml"); + assert!(document_xml.contains(r#""#), "pass {pass}: {document_xml}"); + assert!(document_xml.contains(r#""#), "pass {pass}: {document_xml}"); + assert!(document_xml.contains(""), "pass {pass}: {document_xml}"); + assert!(document_xml.contains(""), "pass {pass}: {document_xml}"); + assert!(document_xml.contains("visible in print")); + doc = wordcraft_docx::read(&out).unwrap(); + } +} diff --git a/crates/docx/tests/it/undefined_style.rs b/crates/docx/tests/it/undefined_style.rs new file mode 100644 index 0000000000..86cd795812 --- /dev/null +++ b/crates/docx/tests/it/undefined_style.rs @@ -0,0 +1,71 @@ +//! 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 +//! `` without defining Footer. +use std::io::Write; +use wordcraft_doc::props::LineSpacing; +use wordcraft_doc::{Block, Document, PartKind}; + +const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; +const R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + +fn package(normal_id: &str) -> Vec { + let root = r#""#; + let doc = format!( + r#"bodynormal"# + ); + let footer = format!( + r#"1"# + ); + let styles = format!( + r#""# + ); + let rels = r#""#; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::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()), + ("word/footer1.xml", footer.as_str()), + ] { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(body.as_bytes()).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +fn footer_para(d: &Document) -> &wordcraft_doc::Paragraph { + let part = d.parts.values().find(|p| p.kind == PartKind::Footer).expect("a footer"); + match part.blocks.first().map(|b| &**b) { + Some(Block::Para(p)) => p, + _ => panic!("the footer starts with a paragraph"), + } +} + +#[test] +fn a_paragraph_naming_an_undefined_style_is_formatted_as_normal() { + // Also when the file's default paragraph style has another id (read as Normal). + for normal_id in ["Normal", "a"] { + let d = wordcraft_docx::read(&package(normal_id)).unwrap(); + let Some(Block::Para(body)) = d.body.first().map(|b| &**b) else { panic!("a body paragraph") }; + let Some(Block::Para(normal)) = d.body.get(1).map(|b| &**b) else { panic!("a second body paragraph") }; + let normal_rp = d.styles.resolve_para(&normal.props); + assert_eq!((normal_rp.space_before, normal_rp.space_after), (1.0, 2.0), "{normal_id}"); + for p in [body, footer_para(&d)] { + // The paragraph keeps the style it names, for the round trip. + assert_eq!(p.props.style.as_deref(), Some("Footer")); + let rp = d.styles.resolve_para(&p.props); + assert_eq!((rp.space_before, rp.space_after), (1.0, 2.0), "{normal_id}: Normal's spacing, not the defaults' 10 pt after"); + assert_eq!(rp.line_spacing, LineSpacing::Multiple(259.0 / 240.0), "{normal_id}"); + assert_eq!(d.styles.resolve_char(Some("Footer"), &Default::default()).size, 13.0, "{normal_id}"); + } + } +} + +#[test] +fn an_undefined_style_is_written_back_as_it_was_named() { + let d = wordcraft_docx::read(&package("Normal")).unwrap(); + let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(footer_para(&again).props.style.as_deref(), Some("Footer")); + assert_eq!(again.styles.resolve_para(&footer_para(&again).props).space_after, 2.0); +} diff --git a/crates/engine/src/cmd/caret.rs b/crates/engine/src/cmd/caret.rs index 12a65494f1..b305a06e38 100644 --- a/crates/engine/src/cmd/caret.rs +++ b/crates/engine/src/cmd/caret.rs @@ -273,8 +273,9 @@ fn set(s: &mut Session, v: &Value) -> CmdResult { } else if let (Some(pg), Some(x), Some(y)) = (p::u64(v, "page"), p::f32(v, "x"), p::f32(v, "y")) { let story = super::story_param(s, v); let l = s.layout(); - s.page_hint = pg as usize; - l.hit(pg as usize, x, y, story).ok_or_else(|| CmdError::Params("no text on that page".into()))? + let page = usize::try_from(pg).unwrap_or(usize::MAX); + s.page_hint = page; + l.hit(page, x, y, story).ok_or_else(|| CmdError::Params("no text on that page".into()))? } else { return Err(CmdError::Params("`pos` or `page`/`x`/`y` required".into())); }; diff --git a/crates/engine/src/cmd/citations/cross_refs.rs b/crates/engine/src/cmd/citations/cross_refs.rs index 64967f0bd7..265a73fabc 100644 --- a/crates/engine/src/cmd/citations/cross_refs.rs +++ b/crates/engine/src/cmd/citations/cross_refs.rs @@ -1,5 +1,5 @@ use super::generated::page_of; -use super::{CharProps, CmdError, CmdResult, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p}; +use super::{CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p}; pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult { let to = p::str(v, "to").unwrap_or("heading"); @@ -77,13 +77,19 @@ pub(super) fn caption_label(p: &Paragraph, text: &str) -> Option { (!label.is_empty() && label.chars().count() <= 40).then_some(label) } +/// Whether `p` is a caption: its style is Caption or one based on it, as a caption restyled with a +/// style of its own (a `Table Caption` based on Caption) still is (#4411). +pub(super) fn is_caption(doc: &Document, p: &Paragraph) -> bool { + p.props.style.as_deref().is_some_and(|id| id == "Caption" || doc.styles.chain(id).iter().any(|s| s.id == "Caption")) +} + /// The caption paragraphs of the body: (text, position, label). fn captions(s: &Session) -> Vec<(String, Pos, Option)> { s.doc .para_paths(StoryRef::Body) .into_iter() .filter_map(|path| { - let p = s.doc.para(StoryRef::Body, &path).filter(|p| p.props.style.as_deref() == Some("Caption"))?; + let p = s.doc.para(StoryRef::Body, &path).filter(|p| is_caption(&s.doc, p))?; let text = p.plain_text(); let label = caption_label(p, &text); Some((text, Pos { story: StoryRef::Body, path, off: 0 }, label)) @@ -125,7 +131,7 @@ pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> { }; for path in s.doc.para_paths(StoryRef::Body) { if let Some(p) = s.doc.para(StoryRef::Body, &path) - && p.props.style.as_deref() == Some("Caption") + && is_caption(&s.doc, p) && p.plain_text().starts_with(label) { targets.push((p.plain_text(), Pos { story: StoryRef::Body, path: path.clone(), off: 0 })); diff --git a/crates/engine/src/cmd/citations/generated.rs b/crates/engine/src/cmd/citations/generated.rs index f0946e10b2..364a6223be 100644 --- a/crates/engine/src/cmd/citations/generated.rs +++ b/crates/engine/src/cmd/citations/generated.rs @@ -1,10 +1,10 @@ -use super::cross_refs::caption_label; +use super::cross_refs::{caption_label, is_caption}; use super::render::entry; use super::sources::bib_order; use super::styles::style; use super::{ - Block, CharProps, CmdError, CmdResult, FieldCode, InlineObject, Paragraph, Path, Pos, Session, SortKey, StoryRef, TabAlign, TabLeader, TabStop, - Value, delete_selection, heading_letter, p, sel_result, sort_key, + 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, }; /// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "