mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-28 08:45:52 -06:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5796c665b9 | ||
|
|
e74e627a38 | ||
|
|
e9286c9487 | ||
|
|
b7057e56f6 | ||
|
|
784e4c3c35 | ||
|
|
188be727b7 | ||
|
|
05dc3214ea | ||
|
|
72ca96a27c | ||
|
|
f83d554322 | ||
|
|
0f4e80aedd | ||
|
|
bab08b77e1 | ||
|
|
2b407facd0 | ||
|
|
b7819874c8 | ||
|
|
9cf6a33374 | ||
|
|
29bb5a4f44 | ||
|
|
aae46e1274 | ||
|
|
b322c3d816 | ||
|
|
64e297ca57 | ||
|
|
ca8feb71aa | ||
|
|
73f42fd607 | ||
|
|
ff11882e9d | ||
|
|
9d78c95517 | ||
|
|
6ea92c6b93 | ||
|
|
7905692c1f | ||
|
|
7416d36aeb | ||
|
|
9e68fdb76a | ||
|
|
d63de66920 | ||
|
|
bee50afd8f | ||
|
|
a1a3b53f74 | ||
|
|
8ff9bdb1a1 | ||
|
|
694ac7810d | ||
|
|
1441c64970 | ||
|
|
3b94750945 | ||
|
|
376411a22b | ||
|
|
932f5b4748 | ||
|
|
011a46c677 | ||
|
|
4239458948 | ||
|
|
b4219f9745 | ||
|
|
37e5849e58 |
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -74,5 +74,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
|
||||
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
|
||||
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
|
||||
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
|
||||
Generated
+9
-152
@@ -235,56 +235,12 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
@@ -316,7 +272,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -1001,65 +957,6 @@ dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_complete"
|
||||
version = "4.6.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
|
||||
dependencies = [
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
|
||||
|
||||
[[package]]
|
||||
name = "clap_mangen"
|
||||
version = "0.2.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"roff",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.3"
|
||||
@@ -1143,12 +1040,6 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "colored"
|
||||
version = "2.2.0"
|
||||
@@ -2786,7 +2677,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3194,7 +3085,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4532,12 +4423,6 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
@@ -5662,12 +5547,6 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "open"
|
||||
version = "5.4.5"
|
||||
@@ -5735,7 +5614,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6290,7 +6169,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6636,12 +6515,6 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roff"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.2"
|
||||
@@ -6695,7 +6568,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6764,7 +6637,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7454,12 +7327,6 @@ dependencies = [
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.28.0"
|
||||
@@ -7640,7 +7507,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8193,12 +8060,6 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.27.0"
|
||||
@@ -8790,7 +8651,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9176,14 +9037,10 @@ dependencies = [
|
||||
name = "wordcraft-cli"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"clap_mangen",
|
||||
"craft-zip",
|
||||
"image",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"thiserror 2.0.21",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-engine",
|
||||
"wordcraft-fonts",
|
||||
|
||||
@@ -56,10 +56,6 @@ craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0b8bb
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
thiserror = "2"
|
||||
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4"
|
||||
clap_mangen = "0.2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
quick-xml = "0.41"
|
||||
|
||||
@@ -157,7 +157,7 @@ Command line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert report.docx report.pdf # docx, pdf, odt, rtf, html, md, tex, txt, png
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 1, no file, if a character or picture would be left out
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 3, no file, if a character or picture would be left out
|
||||
wordcraft-cli text report.docx # plain text
|
||||
wordcraft-cli inspect report.docx # structure as JSON
|
||||
wordcraft-cli run --template sample \
|
||||
@@ -165,27 +165,16 @@ wordcraft-cli run --template sample \
|
||||
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
|
||||
```
|
||||
|
||||
`wordcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
|
||||
(command-line conventions); `wordcraft-cli --help` and `<subcommand> --help` are the reference for every flag. Exit status:
|
||||
0 success, 1 the command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that conflict or that a
|
||||
subcommand doesn't take, all checked before any file is opened), and 128 plus the signal number when a signal ends the
|
||||
process. Errors are `error: <message>` on stderr; results are on stdout. `--version`/`-V` work on every subcommand and there
|
||||
is no `version` subcommand. `WORDCRAFT_PASSWORD` is read by `--password` (a flag wins, an empty variable counts as unset,
|
||||
and `--help` never shows its value); `WORDCRAFT_REGION` sets the paper. The Linux packages (deb, rpm and tar.gz) and the
|
||||
FreeBSD package install the man pages and the bash, zsh and fish completions.
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 1
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 3
|
||||
and write nothing if the output would draw a character no font has (an empty box) or leave out a
|
||||
picture. Exit codes are 0 (written) and 1 (unreadable input or a strict refusal); `--strict` with another
|
||||
output type is a usage error (2), checked before the input is read. On a strict refusal, stderr has one
|
||||
`error: strict: …` line per kind, then one JSON line. (Before RFC-0018 a strict refusal exited 3; RFC-0018 has no code 3.)
|
||||
`validate` exits 0 for PASS and 1 for FAIL, INCOMPLETE or a file it can't read: the verdict is the first line of the report
|
||||
(`verdict` with `--json`).
|
||||
picture. Exit codes are 0 (written), 1 (unreadable input, usage error, or `--strict` with another
|
||||
output type, checked before the input is read) and 3 (strict refusal). On exit 3, stderr has one
|
||||
`wordcraft-cli: strict: …` line per kind, then one JSON line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert in.docx out.pdf --strict
|
||||
# error: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# error: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# wordcraft-cli: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# wordcraft-cli: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# {"schema":1,"strict":"failed","missing_glyphs":[{"cp":"U+2D30","count":3}],"missing_pictures":[{"part":"word/media/image2.bin","source_part":"word/header2.xml","reason":"unsupported_format"}],"truncated":false,"total_missing_glyphs":1,"total_missing_pictures":1,"glyphs_truncated":false,"pictures_truncated":false}
|
||||
```
|
||||
|
||||
|
||||
@@ -172,6 +172,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
|
||||
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
|
||||
- 2026-11-03: A picture inserted or pasted in a table cell fits the cell, as in Word, instead of running out of it; in text columns it fits the column, in a section with other margins that section's width (#5428).
|
||||
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
|
||||
|
||||
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
|
||||
@@ -202,6 +203,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
- 2026-11-08: Layout: a turned inline picture whose file keeps no room for the turn (no or a zero `wp:effectExtent`, as other tools write) keeps its line to its frame and overhangs it, cut at the line's top and bottom, as Word does: the frame as it is in Word 2007 layout, with width and height exchanged from 45° to 135° and 225° to 315° in Word 2013+ layout. Such a file saves the same way. Pictures with the room recorded (Word's own files) still take their rotated bounds. Readiness unchanged.
|
||||
- 2026-11-08: XML text and CDATA read with their line ends normalised (XML 1.0 §2.11): CR LF and a lone CR are one line feed, ` ` stays a CR, so a line break inside `w:t` in a file saved with Windows line ends is one space, not two (#5897); readiness estimates unchanged.
|
||||
- 2026-11-08: Layout: contextual spacing drops the space after a table cell's last paragraph when that paragraph is in the Normal style, the end-of-cell mark counting as a Normal paragraph next to it; a last paragraph in another style keeps its space after. The rule is inferred from docxide-pdf's notes and its `cell-end-*` fixtures (`cell-end-text-context`, `cell-end-empty-context`); a Word comparison that tells it apart from the neighbouring paragraph's style is still open. Readiness unchanged.
|
||||
- 2026-11-07: Justified paragraphs that start with a tab or contain tabs shrink the spaces after their last tab in Word 2013+ compatibility mode (mode 15), matching Word (#5847). Spaces before the line's last tab remain at their natural width.
|
||||
- 2026-11-07: An in-line picture lowered past its own height (`w:position`) lowers its line as far, as in Word; all 156 synthetic lines measured for #3984 match Word (#5796). Exact spacing keeps the line's baseline.
|
||||
- 2026-11-07: DOCX: a VML text box keeps its text direction: `mso-layout-flow-alt:bottom-to-top` reads as Rotate all text 270° whatever `layout-flow` says, and otherwise `layout-flow:vertical` (or `vertical-ideographic`) as 90°, so the turned text box in a compatibility-mode document's header is drawn turned, as in Word. (#5193)
|
||||
- 2026-11-07: Newly opened secondary windows constrain their initial viewport dimensions to the monitor's usable area with margins for system panels, preventing new windows from exceeding screen width on high-DPI scaled displays (#5871).
|
||||
@@ -993,6 +995,7 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
| 2026-11-12 | trivial | Validator: exclude every glossary-typed part from main traversal and fallback assignment; multiple content-type fallback candidates are ambiguous, with no selected anchor (#5875). Synthetic controls; no parity estimate changed. |
|
||||
| 2026-11-12 | trivial | Validator: mixed Transitional/Strict entry points to the same target skip document checks with coverage in either order (#5875); distinct competing roots retain ambiguity treatment without evaluating the profile gate. No parity estimate changed. |
|
||||
| 2026-11-12 | trivial | Validator: competing official role targets produce coverage and suppress dependent findings; both-order, repeated-target, malformed-source and owner-isolation controls (#5875). No parity estimate changed. |
|
||||
| 2026-11-03 | trivial | Progress log: a picture inserted or pasted in a table cell fits the cell (#5428) |
|
||||
| 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) |
|
||||
| 2026-11-08 | trivial | Progress log: freestanding custom.dic dictionary file support in File › Options › Proofing (#5840) |
|
||||
| 2026-11-08 | trivial | Progress log: XML line ends in text normalised (#5897) |
|
||||
@@ -1528,6 +1531,7 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
| 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-11-07 | trivial | Progress log: a justified line with a tab shrinks the spaces after it (#5847) |
|
||||
> 2026-10-27 · Technical synchronization: existing Proofing pane hooks and regression tests follow the extracted engine/UI modules on main `436d444`; compact context menus remain upstream. New-SHA validation is pending; readiness unchanged.
|
||||
|
||||
> 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.
|
||||
|
||||
@@ -6,9 +6,6 @@ license.workspace = true
|
||||
publish = false
|
||||
description = "WordCraft command line: convert, inspect, render, run commands, MCP server"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "wordcraft-cli"
|
||||
path = "src/main.rs"
|
||||
@@ -25,14 +22,9 @@ wordcraft-zotero = { workspace = true }
|
||||
wordcraft-validate = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
thiserror = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
|
||||
clap_complete = { workspace = true }
|
||||
clap_mangen = { workspace = true }
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
//! Writes wordcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `wordcraft-cli.1` and one per subcommand, such as
|
||||
//! `wordcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (see `packaging/`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p wordcraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Also run by the tests.
|
||||
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = wordcraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "wordcraft-cli", dir)?;
|
||||
}
|
||||
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
|
||||
// which `clap_mangen` would otherwise give pages of its own (`wordcraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(wordcraft_cli::command(), dir)
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string; what
|
||||
//! clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The end of every subcommand's `--help`.
|
||||
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// The top-level `--help` ends with the environment and the exit status.
|
||||
const TOP_NOTES: &str = "A password-protected Word file is opened with --password PASS, --password-file PATH or the WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by every other process, so the other two are better. A file opened with a password is written with it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.\n\nPaper: documents created here, and HTML, Markdown and text files (which give no page size), use the system region's paper (A4, or Letter in the US and other Letter regions), read from LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the same output on every machine.\n\nEnvironment:\n WORDCRAFT_PASSWORD the password of a protected Word file, when neither --password nor --password-file is given\n WORDCRAFT_REGION the paper and region to use instead of the system's (a tag such as en-US)\n\nExit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// WordCraft from the command line: convert, inspect, render, run commands, validate, serve MCP
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "wordcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum Command {
|
||||
/// Convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png, xml)
|
||||
///
|
||||
/// `--update-fields` refreshes unlocked fields before saving (if protection blocks updates, they are skipped with a
|
||||
/// warning). An .xml file is a Word XML Document (Flat OPC), or with `--format wordml2003` a Word 2003 XML Document.
|
||||
/// `--markup` (Print Markup) puts comments beside each page and tracked changes in pdf/png, and a comment list in
|
||||
/// html/md/txt. `--strict` (pdf or png output only) writes nothing and exits 1 if a character can't be drawn or a
|
||||
/// picture is missing or undecodable; the report is on stderr, with one JSON line.
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Convert(ConvertArgs),
|
||||
/// Pages, words, paragraphs and properties (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Info(FileArgs),
|
||||
/// The plain text
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Text(FileArgs),
|
||||
/// The document structure (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Inspect(FileArgs),
|
||||
/// Render one page to a PNG
|
||||
///
|
||||
/// `--strict` writes nothing and exits 1 if a character on the page can't be drawn or a picture is missing or
|
||||
/// undecodable (the report is on stderr, as for `convert --strict`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Render(RenderArgs),
|
||||
/// Run commands headlessly, then save
|
||||
///
|
||||
/// `--script` runs a JSON file (`-` is stdin) first: {"file"?, "template"?, "commands": [{"command": id, "params"?:
|
||||
/// {…}} | id, …], "save"?: [OUT, …]}; save formats follow the extension (docx and pdf in one run); relative paths
|
||||
/// resolve against the script's folder. `file.new` and `file.open` open another document and make it active; later
|
||||
/// commands and the saves work on the active one; `view.switchWindows` lists the open documents and with {"id": N}
|
||||
/// makes one active. PNG saves use `--page` (1-based, default 1) and `--scale` (default 2).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Run(RunArgs),
|
||||
/// List every command
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Commands(JsonArgs),
|
||||
/// Feature-catalog parity
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Parity(ParityArgs),
|
||||
/// Structural integrity check
|
||||
///
|
||||
/// Exit 0 for PASS; 1 for FAIL, INCOMPLETE or a file that can't be read (the verdict is the first line of the report,
|
||||
/// and `verdict` in `--json`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Validate(ValidateArgs),
|
||||
/// MCP server on stdio, with a headless session
|
||||
///
|
||||
/// Both roots are required: the agent's commands read files (open, insert text or picture, mail-merge data,
|
||||
/// templates…) only inside the read root and write them (save, export, merge output…) only inside the write root,
|
||||
/// links followed; the same folder may be both. `--connect` (bridge to the running app) is refused until the app
|
||||
/// confines its control channel (#3695, #5819).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Mcp(McpArgs),
|
||||
/// Run a Zotero command on a document (Zotero must be running)
|
||||
///
|
||||
/// The commands are addEditCitation, addEditBibliography, addNote, refresh, removeCodes and setDocPrefs; `--cmd`
|
||||
/// runs first (for example `--cmd caret.docEnd`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Zotero(ZoteroArgs),
|
||||
}
|
||||
|
||||
/// How a password-protected Word file is opened.
|
||||
#[derive(Args, Debug, Default)]
|
||||
pub(crate) struct Password {
|
||||
/// The password (readable by every other process on the machine; prefer --password-file)
|
||||
#[arg(long, value_name = "PASS", env = "WORDCRAFT_PASSWORD", hide_env_values = true)]
|
||||
pub(crate) password: Option<String>,
|
||||
/// Read the password from this file (a trailing newline is dropped)
|
||||
#[arg(long = "password-file", value_name = "PATH")]
|
||||
pub(crate) password_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct FileArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
pub(crate) enum XmlFormat {
|
||||
/// A Word 2003 XML Document
|
||||
Wordml2003,
|
||||
/// A Word XML Document (Flat OPC), the default
|
||||
Flatopc,
|
||||
}
|
||||
|
||||
impl XmlFormat {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
XmlFormat::Wordml2003 => "wordml2003",
|
||||
XmlFormat::Flatopc => "flatopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ConvertArgs {
|
||||
/// The document to read
|
||||
pub(crate) input: PathBuf,
|
||||
/// The file to write; its extension names the format
|
||||
pub(crate) output: PathBuf,
|
||||
/// Print Markup: comments beside each page and tracked changes
|
||||
#[arg(long)]
|
||||
pub(crate) markup: bool,
|
||||
/// Refresh unlocked fields before saving
|
||||
#[arg(long = "update-fields")]
|
||||
pub(crate) update_fields: bool,
|
||||
/// For pdf or png output: write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
/// The kind of .xml file to write
|
||||
#[arg(long, value_enum, value_name = "KIND")]
|
||||
pub(crate) format: Option<XmlFormat>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RenderArgs {
|
||||
/// The document
|
||||
pub(crate) input: PathBuf,
|
||||
/// The PNG to write
|
||||
pub(crate) output: PathBuf,
|
||||
/// The page, from 1
|
||||
#[arg(long, value_name = "N", value_parser = page, default_value = "1")]
|
||||
pub(crate) page: u64,
|
||||
/// Device pixels per point
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale, default_value = "2")]
|
||||
pub(crate) scale: f64,
|
||||
/// Write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
/// One `--cmd ID[=JSON]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Cmd {
|
||||
pub(crate) id: String,
|
||||
pub(crate) params: Value,
|
||||
}
|
||||
|
||||
fn cmd(text: &str) -> Result<Cmd, UsageError> {
|
||||
match text.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
let params = serde_json::from_str(p).map_err(|e| UsageError::CmdJson { id: id.to_owned(), why: e.to_string() })?;
|
||||
Ok(Cmd { id: id.to_owned(), params })
|
||||
}
|
||||
None => Ok(Cmd { id: text.to_owned(), params: json!({}) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn page(text: &str) -> Result<u64, UsageError> {
|
||||
match text.parse::<u64>() {
|
||||
Ok(0) => Err(UsageError::Page("invalid --page `0`: page numbers start at 1".to_owned())),
|
||||
Ok(n) => Ok(n),
|
||||
Err(_) => Err(UsageError::Page(format!("invalid --page `{text}`: not a valid integer"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(text: &str) -> Result<f64, UsageError> {
|
||||
let n = text.parse::<f64>().map_err(|_| UsageError::Scale(format!("invalid --scale `{text}`: not a number")))?;
|
||||
if n.is_finite() && n > 0.0 { Ok(n) } else { Err(UsageError::Scale(format!("invalid --scale `{text}`: scale must be a finite positive number"))) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RunArgs {
|
||||
/// Open this document first
|
||||
#[arg(long, value_name = "F", conflicts_with = "template")]
|
||||
pub(crate) file: Option<PathBuf>,
|
||||
/// Start from this template
|
||||
#[arg(long, value_name = "T")]
|
||||
pub(crate) template: Option<String>,
|
||||
/// A script to run first (`-` is stdin)
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) script: Option<PathBuf>,
|
||||
/// Run one command, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the result here (the extension names the format)
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// The page of a PNG save, from 1 (default 1)
|
||||
#[arg(long, value_name = "N", value_parser = page)]
|
||||
pub(crate) page: Option<u64>,
|
||||
/// The scale of a PNG save (default 2)
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale)]
|
||||
pub(crate) scale: Option<f64>,
|
||||
/// Print each command's result
|
||||
#[arg(long)]
|
||||
pub(crate) print: bool,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct JsonArgs {
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ParityArgs {
|
||||
/// Markdown instead of JSON
|
||||
#[arg(long)]
|
||||
pub(crate) markdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ValidateArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// The folder the agent may read in (links followed); the same folder may be the write root
|
||||
#[arg(long = "automation-read-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) read_root: Option<PathBuf>,
|
||||
/// The folder the agent may write in (links followed)
|
||||
#[arg(long = "automation-write-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) write_root: Option<PathBuf>,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
/// Refused for now: the desktop app does not confine its control channel to automation roots yet
|
||||
#[arg(long, value_name = "HOST:PORT")]
|
||||
pub(crate) connect: Option<String>,
|
||||
}
|
||||
|
||||
fn folder(text: &str) -> Result<PathBuf, UsageError> {
|
||||
if text.is_empty() { Err(UsageError::EmptyFolder) } else { Ok(PathBuf::from(text)) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ZoteroArgs {
|
||||
/// The Zotero command (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)
|
||||
#[arg(value_parser = zotero_command)]
|
||||
pub(crate) command: String,
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// Run one command first, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the document here afterwards
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// Show the calls to and from Zotero on stderr
|
||||
#[arg(long)]
|
||||
pub(crate) trace: bool,
|
||||
/// Zotero's port
|
||||
#[arg(long, value_name = "P")]
|
||||
pub(crate) port: Option<u16>,
|
||||
}
|
||||
|
||||
fn zotero_command(text: &str) -> Result<String, UsageError> {
|
||||
if wordcraft_zotero::Command::from_name(text).is_some() { Ok(text.to_owned()) } else { Err(UsageError::Zotero(text.to_owned())) }
|
||||
}
|
||||
|
||||
/// A mistake in the command line that clap can't see by itself.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub(crate) enum UsageError {
|
||||
#[error("{0}")]
|
||||
Page(String),
|
||||
#[error("{0}")]
|
||||
Scale(String),
|
||||
#[error("--cmd {id}: bad JSON params: {why}")]
|
||||
CmdJson { id: String, why: String },
|
||||
#[error("a folder is needed, not an empty name")]
|
||||
EmptyFolder,
|
||||
#[error("unknown Zotero command `{0}` (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)")]
|
||||
Zotero(String),
|
||||
}
|
||||
|
||||
/// The clap definition of the whole command line (completions and man pages are generated from it).
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
}
|
||||
|
||||
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("wordcraft-cli")).chain(args.iter().cloned()))?;
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
if let Some((name, sub)) = matches.subcommand() {
|
||||
password_precedence(&mut cli.command, sub, name);
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// `--password`, `--password-file`, then `WORDCRAFT_PASSWORD`: a password file named on the command line beats the
|
||||
/// variable, which clap would otherwise read into `--password`.
|
||||
fn password_precedence(command: &mut Command, sub: &ArgMatches, _name: &str) {
|
||||
let open = match command {
|
||||
Command::Convert(a) => &mut a.open,
|
||||
Command::Info(a) | Command::Text(a) | Command::Inspect(a) => &mut a.open,
|
||||
Command::Render(a) => &mut a.open,
|
||||
Command::Run(a) => &mut a.open,
|
||||
_ => return,
|
||||
};
|
||||
let from_env = sub.value_source("password") == Some(clap::parser::ValueSource::EnvVariable);
|
||||
if from_env && open.password_file.is_some() {
|
||||
open.password = None;
|
||||
}
|
||||
// A blank variable counts as unset.
|
||||
if from_env && open.password.as_deref() == Some("") {
|
||||
open.password = None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
|
||||
//! flag must not silently remove a root and leave the server unconfined.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct AutomationArgs {
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
read_given: bool,
|
||||
write_given: bool,
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
|
||||
Self { read_root, write_root, read_given: false, write_given: false }
|
||||
}
|
||||
|
||||
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
|
||||
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
|
||||
let (root, given) = match flag {
|
||||
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
|
||||
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if *given {
|
||||
return Err(format!("{flag} given twice"));
|
||||
}
|
||||
let value = match inline {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if value.starts_with('-') {
|
||||
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
|
||||
}
|
||||
value
|
||||
}
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!("{flag} needs a non-empty folder"));
|
||||
}
|
||||
*root = Some(value.into());
|
||||
*given = true;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roots_are_taken_once_and_other_arguments_are_left() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
let mut args = ["a folder".to_owned(), "report.docx".to_owned()].into_iter();
|
||||
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
|
||||
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
|
||||
assert!(!roots.consume("--author", &mut args).unwrap());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
assert_eq!(roots.write_root, Some("out".into()));
|
||||
assert_eq!(args.next().as_deref(), Some("report.docx"));
|
||||
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_operands_leave_roots_unchanged() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
|
||||
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
|
||||
let mut args = operand.map(str::to_owned).into_iter();
|
||||
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
|
||||
assert_eq!(roots.read_root, Some("read".into()));
|
||||
assert_eq!(roots.write_root, Some("write".into()));
|
||||
}
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
|
||||
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
|
||||
assert_eq!(roots.read_root, Some("-folder".into()));
|
||||
assert_eq!(roots.write_root, Some("./-folder".into()));
|
||||
}
|
||||
}
|
||||
@@ -1,609 +0,0 @@
|
||||
//! The subcommands: each takes its parsed arguments and the output streams, and returns the exit status.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::{CmdError, Session};
|
||||
|
||||
use crate::args::{self, Command, ConvertArgs, FileArgs, JsonArgs, McpArgs, ParityArgs, Password, RenderArgs, RunArgs, ValidateArgs, ZoteroArgs};
|
||||
use crate::error::CliError;
|
||||
use crate::script;
|
||||
use crate::{Io, errln};
|
||||
|
||||
type Result<T> = std::result::Result<T, CliError>;
|
||||
|
||||
fn engine_error(e: impl std::fmt::Display) -> CliError {
|
||||
CliError::Failed(escape_text(&e.to_string(), false))
|
||||
}
|
||||
|
||||
/// Open a document for a subcommand. A password-protected Word file needs its password
|
||||
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
|
||||
/// `convert` does not quietly write a copy the password no longer protects.
|
||||
fn open(path: &Path, password: Option<&str>) -> Result<Session> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, ®ion).map_err(engine_error)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The password for a protected Word file: `--password`, `--password-file` or `WORDCRAFT_PASSWORD` (clap reads the
|
||||
/// variable into `--password`; a blank one counts as unset). The file form exists because a password on a command line
|
||||
/// is readable by every other process on the machine; a trailing newline is dropped so a file written by `echo` works.
|
||||
/// Never logged, and never named in an error.
|
||||
pub(crate) fn password_from(open: &Password) -> Result<Option<String>> {
|
||||
if let Some(password) = &open.password {
|
||||
return Ok(Some(password.clone()));
|
||||
}
|
||||
if let Some(path) = &open.password_file {
|
||||
let raw =
|
||||
std::fs::read_to_string(path).map_err(|e| CliError::Failed(escape_text(&format!("--password-file {}: {e}", path.display()), false)))?;
|
||||
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A path the engine takes as text: output paths must be valid Unicode (only the opened file may not be, #1440).
|
||||
fn unicode(path: &Path) -> Result<&str> {
|
||||
path.to_str().ok_or_else(|| CliError::Failed(format!("{}: the file name is not valid Unicode", path.display().to_string().escape_debug())))
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
let mut s = Session::new(doc);
|
||||
s.system_region = system_region();
|
||||
s
|
||||
}
|
||||
|
||||
/// The system region, read as the app reads it (locale variables, else the platform's locale).
|
||||
fn system_region() -> wordcraft_engine::Region {
|
||||
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
|
||||
fn listed_text(doc: &wordcraft_doc::Document) -> std::result::Result<String, String> {
|
||||
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
|
||||
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
|
||||
}
|
||||
|
||||
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
|
||||
/// The command also checks whether the open document is protected: this name determines which
|
||||
/// named editing exceptions the session can use, so the flag must not bypass that check.
|
||||
fn set_author(s: &mut Session, name: &str) -> std::result::Result<(), String> {
|
||||
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
|
||||
}
|
||||
|
||||
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
|
||||
/// process to the same roots first (`confine_process`), which a test must not do.
|
||||
fn headless_mcp(
|
||||
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
|
||||
author: Option<&str>,
|
||||
) -> std::result::Result<wordcraft_mcp::Headless, String> {
|
||||
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
|
||||
if let Some(name) = author {
|
||||
set_author(&mut headless.session, name)?;
|
||||
}
|
||||
Ok(headless)
|
||||
}
|
||||
|
||||
/// A failed `--strict` export: a strict refusal becomes [`CliError::Strict`] carrying what stderr
|
||||
/// shows (each line of the report as `error: …`, then its JSON on one line, from
|
||||
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
|
||||
/// failure.
|
||||
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> CliError {
|
||||
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
|
||||
return engine_error(e);
|
||||
}
|
||||
let mut params = json!({"markup": markup});
|
||||
if let Some(page) = page {
|
||||
params["page"] = json!(page);
|
||||
}
|
||||
CliError::Strict(match s.run("file.strictReport", ¶ms).map_err(|e| e.to_string()) {
|
||||
Ok(json) => {
|
||||
let mut text = String::new();
|
||||
for line in report_lines(&json) {
|
||||
text += &format!("error: {}\n", escape_peer(&line));
|
||||
}
|
||||
text + &json_line_safe(&json.to_string())
|
||||
}
|
||||
Err(e) => format!("error: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
|
||||
fn report_lines(json: &Value) -> Vec<String> {
|
||||
wordcraft_engine::strict::lines_from_json(json)
|
||||
}
|
||||
|
||||
/// Explicitly update unlocked fields in a session before saving the document.
|
||||
///
|
||||
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
|
||||
/// stderr and continues conversion rather than aborting. Other command failures are converted to
|
||||
/// [`CliError`] via [`engine_error`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Err(CliError)` if the command fails with an error other than `CmdError::Disabled`.
|
||||
fn update_fields(s: &mut Session, io: &mut Io) -> Result<()> {
|
||||
if let Err(e) = s.run("references.updateFields", &json!({})) {
|
||||
if matches!(e, CmdError::Disabled(_)) {
|
||||
errln!(io, "warning: {e}");
|
||||
} else {
|
||||
return Err(engine_error(e));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
|
||||
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
|
||||
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
|
||||
/// terminal or pass for other output.
|
||||
fn escape_peer(s: &str) -> String {
|
||||
escape_text(s, true)
|
||||
}
|
||||
|
||||
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
|
||||
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
|
||||
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
|
||||
fn is_unsafe_char(c: char) -> bool {
|
||||
c.is_control()
|
||||
|| matches!(
|
||||
c,
|
||||
'\u{00ad}'
|
||||
| '\u{061c}'
|
||||
| '\u{200b}'..='\u{200f}'
|
||||
| '\u{2028}'..='\u{202e}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{feff}'
|
||||
| '\u{e0000}'..='\u{e007f}'
|
||||
)
|
||||
}
|
||||
|
||||
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
|
||||
/// paths, and a backslash can't forge or hide anything).
|
||||
fn escape_text(s: &str, backslash: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' if backslash => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
|
||||
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
|
||||
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
|
||||
/// can't drive or spoof a terminal.
|
||||
fn json_line_safe(json: &str) -> String {
|
||||
let mut out = String::with_capacity(json.len());
|
||||
for c in json.chars() {
|
||||
if is_unsafe_char(c) {
|
||||
for unit in c.encode_utf16(&mut [0u16; 2]) {
|
||||
out.push_str(&format!("\\u{unit:04x}"));
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parity_markdown(p: &Value) -> String {
|
||||
let mut s = String::from(
|
||||
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
|
||||
);
|
||||
s += &format!(
|
||||
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
|
||||
p["live"], p["total"], p["percent"]
|
||||
);
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
s += "\n## Missing\n\n";
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
let m = t["missing"].as_array().cloned().unwrap_or_default();
|
||||
if m.is_empty() {
|
||||
continue;
|
||||
}
|
||||
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
|
||||
for x in m {
|
||||
s += &format!("- {}\n", x.as_str().unwrap_or(""));
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Write a `validate` report for people: the verdict, then one line per finding
|
||||
/// (`SEVERITY RULE [part] message`), then the coverage notes.
|
||||
fn write_validate_report(o: &mut dyn Write, report: &wordcraft_validate::Report) -> std::io::Result<()> {
|
||||
o.write_all(render_validate_report(report).as_bytes())
|
||||
}
|
||||
|
||||
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
|
||||
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
|
||||
/// terminal; printable text, including Unicode, is left as written.
|
||||
///
|
||||
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
|
||||
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
|
||||
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
|
||||
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
|
||||
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
|
||||
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
|
||||
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
|
||||
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
|
||||
/// why its escaping is left to `serde_json`.
|
||||
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
|
||||
let mut out = format!("{}\n", verdict_label(report.verdict));
|
||||
for f in &report.findings {
|
||||
let severity = severity_label(f.severity);
|
||||
match &f.part {
|
||||
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
|
||||
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
|
||||
}
|
||||
}
|
||||
for note in &report.coverage_notes {
|
||||
out.push_str(&format!("note: {}\n", escape_report_text(note)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
|
||||
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
|
||||
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
|
||||
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
|
||||
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
|
||||
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
|
||||
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
|
||||
/// injective.
|
||||
fn escape_report_text(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if c.is_control() || is_invisible_format(c) {
|
||||
out.extend(c.escape_debug());
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
|
||||
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
|
||||
fn is_invisible_format(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Map a validation verdict enum to its human-readable uppercase display label.
|
||||
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
|
||||
match v {
|
||||
wordcraft_validate::Verdict::Pass => "PASS",
|
||||
wordcraft_validate::Verdict::Fail => "FAIL",
|
||||
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a validation severity enum to its human-readable uppercase display label.
|
||||
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
|
||||
match s {
|
||||
wordcraft_validate::Severity::Corrupt => "CORRUPT",
|
||||
wordcraft_validate::Severity::Error => "ERROR",
|
||||
wordcraft_validate::Severity::Warning => "WARNING",
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
|
||||
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
|
||||
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
|
||||
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
|
||||
--automation-read-root DIR --automation-write-root DIR";
|
||||
|
||||
/// Run one parsed subcommand; the result is the exit status.
|
||||
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<u8> {
|
||||
match command {
|
||||
Command::Convert(a) => convert(a, io).map(|()| 0),
|
||||
Command::Info(a) => info(a, io).map(|()| 0),
|
||||
Command::Text(a) => text(a, io).map(|()| 0),
|
||||
Command::Inspect(a) => inspect(a, io).map(|()| 0),
|
||||
Command::Render(a) => render(a, io).map(|()| 0),
|
||||
Command::Run(a) => run_script(a, io).map(|()| 0),
|
||||
Command::Commands(a) => commands(a, io).map(|()| 0),
|
||||
Command::Parity(a) => parity(a, io).map(|()| 0),
|
||||
Command::Validate(a) => validate(a, io),
|
||||
Command::Mcp(a) => mcp(a, io).map(|()| 0),
|
||||
Command::Zotero(a) => zotero(a, io).map(|()| 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to stdout and flush. A closed stdout comes back as [`CliError::StdoutClosed`] instead of a panic.
|
||||
fn write_stdout(io: &mut Io, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write(&mut *io.out)?;
|
||||
io.out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert(a: ConvertArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
// Before the input is opened: a wrong output type is a usage error, not a file error.
|
||||
let to_png = o.to_ascii_lowercase().ends_with(".png");
|
||||
if a.strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
return Err(CliError::Usage("convert: --strict needs a .pdf or .png output".into()));
|
||||
}
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
if a.update_fields {
|
||||
update_fields(&mut s, io)?;
|
||||
}
|
||||
let r = if to_png {
|
||||
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": a.markup, "strict": a.strict}))
|
||||
} else {
|
||||
let mut params = json!({"path": o, "markup": a.markup, "strict": a.strict});
|
||||
if let Some(f) = a.format {
|
||||
params["format"] = json!(f.name());
|
||||
}
|
||||
s.run("file.save", ¶ms)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
return Err(if a.strict { refusal(&mut s, e, a.markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
errln!(io, "wrote {o}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_file(a: &FileArgs) -> Result<Session> {
|
||||
let password = password_from(&a.open)?;
|
||||
open(&a.file, password.as_deref())
|
||||
}
|
||||
|
||||
fn info(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{info}"))
|
||||
}
|
||||
|
||||
fn text(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let s = open_file(&a)?;
|
||||
let text = listed_text(&s.doc)?;
|
||||
write_stdout(io, |o| writeln!(o, "{text}"))
|
||||
}
|
||||
|
||||
fn inspect(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{tree}"))
|
||||
}
|
||||
|
||||
fn render(a: RenderArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
let mut params = json!({"path": o, "page": a.page, "scale": a.scale, "strict": a.strict});
|
||||
if a.strict {
|
||||
// The check and its report must see the page as it is written.
|
||||
params["markup"] = json!(false);
|
||||
}
|
||||
let r = match s.run("file.exportPng", ¶ms) {
|
||||
Ok(r) => r,
|
||||
Err(e) if a.strict => return Err(refusal(&mut s, e, false, Some(a.page))),
|
||||
Err(e) => return Err(engine_error(e)),
|
||||
};
|
||||
write_stdout(io, |o| writeln!(o, "{r}"))
|
||||
}
|
||||
|
||||
fn load_run_script(path: Option<&Path>) -> Result<Option<script::Script>> {
|
||||
path.map(|p| script::load(p).map_err(engine_error)).transpose()
|
||||
}
|
||||
|
||||
fn run_script(a: RunArgs, io: &mut Io) -> Result<()> {
|
||||
let password = password_from(&a.open)?;
|
||||
let script = load_run_script(a.script.as_deref())?;
|
||||
// A source named on the command line wins over both of the script's.
|
||||
let (mut from_file, mut from_template) = (a.file.clone(), a.template.clone());
|
||||
if from_file.is_none() && from_template.is_none() {
|
||||
from_file = script.as_ref().and_then(|loaded| loaded.file.as_deref().map(std::path::PathBuf::from));
|
||||
from_template = script.as_ref().and_then(|loaded| loaded.template.clone());
|
||||
}
|
||||
let mut s = match (from_file, from_template) {
|
||||
(Some(f), _) => open(&f, password.as_deref())?,
|
||||
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
|
||||
// `file.new` opens beside the session's first document, which is then closed: the
|
||||
// run starts with one open document.
|
||||
(None, t) => {
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
let first = s.document_id();
|
||||
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
|
||||
s.run("file.new", ¶ms).map_err(engine_error)?;
|
||||
s.close_document(first).map_err(engine_error)?;
|
||||
s
|
||||
}
|
||||
};
|
||||
if let Some(name) = &a.author {
|
||||
set_author(&mut s, name).map_err(CliError::Failed)?;
|
||||
}
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
let mut outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).collect();
|
||||
if let Some(save) = &a.save {
|
||||
outputs.push(unicode(save)?.to_owned());
|
||||
}
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
if let Some(p) = parent.filter(|p| !p.is_dir()) {
|
||||
return Err(format!("{out}: folder {} does not exist", p.display()).into());
|
||||
}
|
||||
if Path::new(out).is_dir() {
|
||||
return Err(format!("{out}: is a folder, not a file").into());
|
||||
}
|
||||
if !out.to_ascii_lowercase().ends_with(".png") {
|
||||
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
|
||||
}
|
||||
}
|
||||
for out in outputs {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = a.page {
|
||||
v["page"] = json!(n);
|
||||
}
|
||||
if let Some(k) = a.scale {
|
||||
v["scale"] = json!(k);
|
||||
}
|
||||
s.run("file.exportPng", &v)
|
||||
} else {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commands(a: JsonArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
if a.json {
|
||||
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{list}"))
|
||||
} else {
|
||||
write_stdout(io, |o| {
|
||||
for c in s.registry.all() {
|
||||
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
|
||||
}
|
||||
writeln!(o, "{:<32} Structural integrity check", "validate")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parity(a: ParityArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
let p = wordcraft_engine::catalog::parity(&s.registry);
|
||||
if a.markdown {
|
||||
write_stdout(io, |o| write!(o, "{}", parity_markdown(&p)))
|
||||
} else {
|
||||
write_stdout(io, |o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(a: McpArgs, io: &mut Io) -> Result<()> {
|
||||
if a.connect.is_some() {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. clap requires both roots.
|
||||
let roots = wordcraft_engine::file_access::AutomationRoots::new(a.read_root.as_deref(), a.write_root.as_deref())
|
||||
.map_err(|e| CliError::Failed(format!("mcp: {e}")))?;
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(CliError::Usage("mcp: give both --automation-read-root DIR and --automation-write-root DIR".into()));
|
||||
};
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
errln!(io, "files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, a.author.as_deref()).map_err(CliError::Failed)?);
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), &mut *io.out)?)
|
||||
}
|
||||
|
||||
fn zotero(a: ZoteroArgs, io: &mut Io) -> Result<()> {
|
||||
let command =
|
||||
wordcraft_zotero::Command::from_name(&a.command).ok_or_else(|| CliError::Usage(format!("unknown Zotero command `{}`", a.command)))?;
|
||||
let mut s = open(&a.file, None)?;
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
}
|
||||
let mut opts = wordcraft_zotero::client::Options::default();
|
||||
if let Some(p) = a.port {
|
||||
opts.addr.set_port(p);
|
||||
}
|
||||
let mut bridge = wordcraft_zotero::Bridge::new();
|
||||
let mut host = wordcraft_zotero::Headless::default();
|
||||
let mut trace = Vec::new();
|
||||
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
|
||||
let r = bridge.handle(&mut s, &mut host, call);
|
||||
if a.trace {
|
||||
trace.push(format!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string()))));
|
||||
trace.push(format!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r))))));
|
||||
}
|
||||
r
|
||||
})
|
||||
.map_err(engine_error)?;
|
||||
for line in &trace {
|
||||
errln!(io, "{line}");
|
||||
}
|
||||
for alert in &host.alerts {
|
||||
errln!(io, "Zotero: {}", escape_peer(alert));
|
||||
}
|
||||
errln!(io, "{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = &a.save {
|
||||
let o = unicode(o)?;
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
errln!(io, "wrote {o}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `validate`: 0 for PASS, 1 for any other verdict or a file that can't be read (RFC-0018 rule 1.2 has no other code;
|
||||
/// the verdict is in the report).
|
||||
fn validate(a: ValidateArgs, io: &mut Io) -> Result<u8> {
|
||||
let report =
|
||||
wordcraft_validate::validate_path(&a.file).map_err(|e| CliError::Failed(escape_text(&format!("{}: {e}", a.file.display()), false)))?;
|
||||
let written = if a.json {
|
||||
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{json}"))
|
||||
} else {
|
||||
write_stdout(io, |o| write_validate_report(o, &report))
|
||||
};
|
||||
match written {
|
||||
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
|
||||
Ok(()) | Err(CliError::StdoutClosed) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
Ok(match report.verdict {
|
||||
wordcraft_validate::Verdict::Pass => 0,
|
||||
wordcraft_validate::Verdict::Fail | wordcraft_validate::Verdict::Incomplete => 1,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,37 +0,0 @@
|
||||
//! What stops a command, and how each case exits.
|
||||
|
||||
/// Why a CLI run stopped early.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub enum CliError {
|
||||
/// The command failed (exit 1); the text is already safe to print.
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
/// A mistake in the command line found after parsing (exit 2).
|
||||
#[error("{0}")]
|
||||
Usage(String),
|
||||
/// A strict export refused (exit 1): the report's lines, then its JSON line, ready for stderr.
|
||||
#[error("{0}")]
|
||||
Strict(String),
|
||||
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): nobody is left to write to, so a quiet
|
||||
/// exit 0 (`validate` keeps its verdict's status).
|
||||
#[error("stdout closed")]
|
||||
StdoutClosed,
|
||||
}
|
||||
|
||||
impl From<String> for CliError {
|
||||
fn from(e: String) -> Self {
|
||||
CliError::Failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CliError {
|
||||
fn from(e: &str) -> Self {
|
||||
CliError::Failed(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for CliError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
if e.kind() == std::io::ErrorKind::BrokenPipe { CliError::StdoutClosed } else { CliError::Failed(e.to_string()) }
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//! Headless WordCraft (`wordcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
|
||||
//! through the binary; `wordcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
|
||||
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
|
||||
|
||||
mod args;
|
||||
mod commands;
|
||||
mod error;
|
||||
mod script;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
|
||||
use error::CliError;
|
||||
|
||||
pub use args::command;
|
||||
|
||||
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
|
||||
pub(crate) struct Io<'a> {
|
||||
pub(crate) out: &'a mut dyn Write,
|
||||
pub(crate) err: &'a mut dyn Write,
|
||||
}
|
||||
|
||||
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
|
||||
macro_rules! errln {
|
||||
($io:expr, $($arg:tt)*) => {
|
||||
drop(writeln!($io.err, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use errln;
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
let arg = arg.to_string_lossy();
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
|
||||
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
|
||||
/// to `out`, exit 0.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
let _ = writeln!(err, "error: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match args::parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
let _ = write!(to, "{}", e.render());
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
let mut io = Io { out, err };
|
||||
// Language packs installed in the suite's font store are used; `proof.installPack` installs
|
||||
// only while the person has turned downloading on in the app.
|
||||
wordcraft_engine::packs::use_font_store(false);
|
||||
if let Some(source) = wordcraft_engine::packs::index_override() {
|
||||
errln!(io, "Language packs come from a test source: {source}");
|
||||
}
|
||||
match commands::dispatch(cli.command, &mut io) {
|
||||
Ok(code) => i32::from(code),
|
||||
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
|
||||
Err(CliError::StdoutClosed) => 0,
|
||||
Err(CliError::Usage(e)) => {
|
||||
errln!(io, "error: {e}");
|
||||
2
|
||||
}
|
||||
// The report's lines already start with `error:`.
|
||||
Err(CliError::Strict(report)) => {
|
||||
errln!(io, "{report}");
|
||||
1
|
||||
}
|
||||
Err(e) => {
|
||||
errln!(io, "error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
+1073
-5
File diff suppressed because it is too large
Load Diff
+448
-280
@@ -1,285 +1,5 @@
|
||||
use super::*;
|
||||
use crate::launcher_profile_flag;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A failed in-process run: the exit code and what stderr said (without its `error: ` prefix).
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Fail {
|
||||
code: i32,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Fail {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the whole CLI in this process, as the binary does.
|
||||
fn exec<S: AsRef<OsStr>>(args: &[S]) -> (i32, String, String) {
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = crate::run(args.iter().map(|a| a.as_ref().to_owned()), &mut out, &mut err);
|
||||
(code, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned())
|
||||
}
|
||||
|
||||
/// `Ok` for exit 0, else the exit code and message.
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> std::result::Result<(), Fail> {
|
||||
let (code, _, err) = exec(args);
|
||||
if code == 0 { Ok(()) } else { Err(Fail { code, text: err.trim_end().strip_prefix("error: ").unwrap_or(err.trim_end()).to_owned() }) }
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
/// A usage error: exit 2, the message on stderr, nothing on stdout, and no work done.
|
||||
fn usage(argv: &[&str]) -> String {
|
||||
let (code, out, err) = exec(argv);
|
||||
assert_eq!((code, out.as_str()), (2, ""), "{argv:?}: {err}");
|
||||
err
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_and_scale_are_checked_before_any_file_is_opened() {
|
||||
for sub in [vec!["render", "missing.docx", "out.png"], vec!["run", "--template", "sample", "--save", "out.png"]] {
|
||||
let with = |extra: &[&str]| usage(&[&sub[..], extra].concat());
|
||||
for missing in [&["--page"][..], &["--scale"], &["--page", "--scale", "2"], &["--scale", "--page", "1"]] {
|
||||
with(missing);
|
||||
}
|
||||
assert!(with(&["--page", "banana"]).contains("invalid --page `banana`: not a valid integer"));
|
||||
assert!(with(&["--page", "0"]).contains("invalid --page `0`: page numbers start at 1"));
|
||||
with(&["--page", "-1"]);
|
||||
assert!(with(&["--scale", "banana"]).contains("invalid --scale `banana`: not a number"));
|
||||
for bad in ["0", "-2", "NaN", "inf"] {
|
||||
assert!(with(&["--scale", bad]).contains(&format!("invalid --scale `{bad}`: scale must be a finite positive number")));
|
||||
}
|
||||
with(&["--page", "1", "--page", "2"]);
|
||||
with(&["--scale", "1", "--scale", "2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_repeated_and_conflicting_options_are_usage_errors_before_file_access() {
|
||||
assert!(usage(&["info", "missing.docx", "--passwrod", "x"]).contains("--passwrod"));
|
||||
assert!(usage(&["render", "missing.docx", "out.png", "--sclae", "2"]).contains("--sclae"));
|
||||
assert!(usage(&["zotero", "refresh", "missing.docx", "--prot", "1"]).contains("--prot"));
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "--markup"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "flatopc", "--format", "wordml2003"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.xml", "--format", "docx"]).contains("wordml2003"));
|
||||
usage(&["convert", "missing.docx"]);
|
||||
usage(&["convert", "a.docx", "b.docx", "c.docx"]);
|
||||
usage(&["run", "--file", "a.docx", "--template", "blank"]);
|
||||
usage(&["info"]);
|
||||
usage(&["frobnicate"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.docx", "--strict"]).contains("--strict needs a .pdf or .png output"));
|
||||
// A valid single value reaches file access, rather than an option error.
|
||||
let (code, _, err) = exec(&["convert", "missing.docx", "out.xml", "--format", "flatopc"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: missing.docx:"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_and_script_values_are_checked_by_the_parser() {
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--script", "--cmd", "caret.docEnd"],
|
||||
] {
|
||||
usage(&argv);
|
||||
}
|
||||
assert!(usage(&["run", "--cmd", "text.insert={nope"]).contains("bad JSON params"));
|
||||
assert_eq!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_author_flag_names_the_headless_session() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert_eq!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])), Ok(()));
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_or_a_file_and_never_shows_in_an_error() {
|
||||
let open = |password: Option<&str>, file: Option<&str>| Password { password: password.map(Into::into), password_file: file.map(PathBuf::from) };
|
||||
assert_eq!(password_from(&open(None, None)), Ok(None));
|
||||
assert_eq!(password_from(&open(Some("s3cret"), None)), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the file.
|
||||
assert_eq!(password_from(&open(Some("a"), Some("/nonexistent"))), Ok(Some("a".into())));
|
||||
let path = std::env::temp_dir().join(format!("wordcraft-cli-password-test-{}.txt", std::process::id()));
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&open(None, path.to_str()));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())), "only the trailing newline is lost");
|
||||
let err = password_from(&open(None, Some("/nonexistent/secret.txt"))).unwrap_err().to_string();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
/// A password file on the command line beats the variable, a blank variable is unset, and `--help` shows neither value.
|
||||
#[test]
|
||||
fn the_password_variable_is_read_by_the_flag_and_hidden() {
|
||||
let parse = |argv: &[&str]| crate::args::parse(&argv.iter().map(OsString::from).collect::<Vec<_>>());
|
||||
let help = parse(&["info", "--help"]).unwrap_err().render().to_string();
|
||||
assert!(help.contains("WORDCRAFT_PASSWORD") || help.contains("--password"), "{help}");
|
||||
let Err(e) = parse(&["info", "--password"]) else { panic!("a missing value must not parse") };
|
||||
assert_eq!(e.exit_code(), 2);
|
||||
let top = parse(&["--help"]).unwrap_err().render().to_string();
|
||||
assert!(top.contains("WORDCRAFT_PASSWORD") && top.contains("WORDCRAFT_REGION") && top.contains("Exit status"), "{top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_needs_both_roots_and_refuses_connect() {
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec!["mcp".to_string()], given].concat();
|
||||
let err = usage(&line.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
assert!(err.contains("--automation-read-root") || err.contains("--automation-write-root"), "{line:?}: {err}");
|
||||
}
|
||||
let missing = usage(&["mcp", "--automation-read-root", "a", "--automation-read-root=b", "--automation-write-root", "c"]);
|
||||
assert!(missing.contains("--automation-read-root"), "{missing}");
|
||||
usage(&["mcp", "--automation-read-root=", "--automation-write-root=x"]);
|
||||
// A folder that does not exist is an error, not a server that quietly runs unconfined.
|
||||
let (code, _, err) = exec(&["mcp", "--automation-read-root", "/definitely/not/a/folder", "--automation-write-root", "/definitely/not/a/folder"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: mcp: cannot open the automation read root"), "{err}");
|
||||
// `--connect` is refused whether or not it has roots, before anything connects (#3695, #5819).
|
||||
let dir = base.to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect=127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let (code, _, err) = exec(&line);
|
||||
assert_eq!(code, 1, "{line:?}");
|
||||
assert!(err.contains("--connect") && err.contains("#3695") && err.contains("#5819"), "{line:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_opening_subcommand_reaches_the_open_with_a_non_unicode_name_but_not_an_output() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
for argv in [
|
||||
vec![OsString::from("convert"), latin1(), "out.pdf".into()],
|
||||
vec!["info".into(), latin1()],
|
||||
vec!["text".into(), latin1()],
|
||||
vec!["inspect".into(), latin1()],
|
||||
vec!["render".into(), latin1(), "out.png".into()],
|
||||
vec!["run".into(), "--file".into(), latin1()],
|
||||
vec!["zotero".into(), "refresh".into(), latin1()],
|
||||
] {
|
||||
let (code, _, err) = exec(&argv);
|
||||
assert_eq!(code, 1, "{argv:?}: {err}");
|
||||
assert!(err.contains("No such file"), "{argv:?}: {err}");
|
||||
}
|
||||
// An output the engine takes as text must be Unicode: a failure, and nothing opened.
|
||||
let out = OsString::from_vec(b"caf\xe9.png".to_vec());
|
||||
let (code, _, err) = exec(&["render".into(), OsString::from("in.docx"), out]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.contains("not valid Unicode"), "{err}");
|
||||
// Elsewhere clap refuses it as usage.
|
||||
assert_eq!(exec(&["run".into(), OsString::from("--template"), OsString::from_vec(b"caf\xe9".to_vec())]).0, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// `validate`: PASS is 0; FAIL, INCOMPLETE and a file that can't be read are 1 (RFC-0018 rule 1.2); usage is 2.
|
||||
#[test]
|
||||
fn validate_exits_0_for_pass_1_for_anything_else_and_2_for_usage() {
|
||||
let dir = script_dir("validate-exit");
|
||||
let good = dir.join("good.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &good.to_string_lossy()])).unwrap();
|
||||
let good = good.to_string_lossy().into_owned();
|
||||
let (code, out, _) = exec(&["validate", &good]);
|
||||
assert_eq!((code, out.lines().next()), (0, Some("PASS")));
|
||||
let (code, out, _) = exec(&["validate", "--json", &good]);
|
||||
assert_eq!(code, 0);
|
||||
assert!(out.contains("\"verdict\""), "{out}");
|
||||
let broken = dir.join("broken.docx");
|
||||
std::fs::write(&broken, b"not a zip").unwrap();
|
||||
let (code, out, _) = exec(&["validate".to_string(), broken.to_string_lossy().into_owned()]);
|
||||
assert_eq!(code, 1, "{out}");
|
||||
assert!(out.starts_with("FAIL") || out.starts_with("INCOMPLETE"), "{out}");
|
||||
let (code, _, err) = exec(&["validate", "/definitely/not/there.docx"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: /definitely/not/there.docx:"), "{err}");
|
||||
usage(&["validate"]);
|
||||
usage(&["validate", &good, &good]);
|
||||
usage(&["validate", &good, "--bogus"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_go_to_stdout_with_exit_0() {
|
||||
for argv in [vec!["--version"], vec!["-V"], vec!["--help"], vec!["-h"], vec!["help"], vec!["convert", "--help"], vec!["help", "validate"]] {
|
||||
let (code, out, err) = exec(&argv);
|
||||
assert_eq!((code, err.as_str()), (0, ""), "{argv:?}");
|
||||
assert!(out.contains("wordcraft-cli"), "{argv:?}: {out}");
|
||||
}
|
||||
let (_, out, _) = exec(&["--version"]);
|
||||
assert_eq!(out.trim(), format!("wordcraft-cli {}", env!("CARGO_PKG_VERSION")));
|
||||
// The version is not a subcommand; with no arguments the help is shown as an error, exit 2.
|
||||
usage(&["version"]);
|
||||
assert_eq!(exec::<&str>(&[]).0, 2);
|
||||
// Every subcommand's help ends with the exit status.
|
||||
for sub in crate::command().get_subcommands().map(|c| c.get_name().to_owned()).filter(|n| n != "help") {
|
||||
let (code, out, _) = exec(&[sub.as_str(), "--help"]);
|
||||
assert_eq!(code, 0, "{sub}");
|
||||
assert!(out.contains("Exit status"), "{sub}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_bootstrap_exits_2_before_anything_runs() {
|
||||
let err = usage(&["--launch-profile=nightly-v1", "info", "x.docx"]);
|
||||
assert!(err.starts_with("error: --launch-profile and --profile-root"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_stdout_ends_quietly_and_other_write_errors_fail() {
|
||||
struct Closed(std::io::ErrorKind);
|
||||
impl Write for Closed {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::BrokenPipe), &mut err), 0);
|
||||
assert!(err.is_empty());
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::PermissionDenied), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_strict_and_render_strict_refusals_exit_1() {
|
||||
// A document whose text can't be drawn is a refusal: exit 1 with the report on stderr and no file.
|
||||
let dir = script_dir("strict-exit");
|
||||
let out = dir.join("out.pdf");
|
||||
let (code, _, err) = exec(&["convert", "/definitely/not/there.docx", &out.to_string_lossy(), "--strict"]);
|
||||
assert_eq!(code, 1, "{err}");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
|
||||
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
|
||||
#[test]
|
||||
@@ -298,6 +18,10 @@ fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_text_stays_on_one_visible_line() {
|
||||
let alert = "Done.\nwrote /etc/passwd\r\u{1b}[2J\u{9b}31m\u{202e}txt.exe\\n\tok é";
|
||||
@@ -307,12 +31,127 @@ fn peer_text_stays_on_one_visible_line() {
|
||||
assert_eq!(escape_peer("Citation (Doe, 2020) — “ok”"), "Citation (Doe, 2020) — “ok”");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
"zotero",
|
||||
&args(&["refresh", "in.docx", "--cmd", "caret.docEnd", "--save", "out.docx", "--trace", "--port", "23119"]),
|
||||
ZOTERO_OPTIONS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_value_is_never_read_as_a_path() {
|
||||
// `--password`'s value sits between the paths and would be taken for one without
|
||||
// `positionals`, so `render` would write its picture over a file called after the password.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
// A bare flag takes no value, so the next argument stays a path.
|
||||
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
|
||||
// `convert` is the one with a value-taking flag between the two paths.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_a_file_or_the_environment() {
|
||||
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
|
||||
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the other two sources.
|
||||
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_file_loses_only_its_trailing_newline() {
|
||||
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_password_file_is_named_without_the_password() {
|
||||
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_are_rejected_before_file_access() {
|
||||
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--sclae", "2"])), Err("render: unknown option --sclae".into()));
|
||||
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_rejects_malformed_format_options_before_file_access() {
|
||||
for (options, error) in [
|
||||
(vec!["--format"], "convert: --format requires a value"),
|
||||
(vec!["--format", "--markup"], "convert: --format requires a value"),
|
||||
(vec!["--format", "flatopc", "--format", "wordml2003"], "convert: duplicate --format option"),
|
||||
] {
|
||||
let mut argv = args(&["convert", "missing.docx", "out.xml"]);
|
||||
argv.extend(args(&options));
|
||||
assert_eq!(run(&argv), Err(error.into()), "{options:?}");
|
||||
}
|
||||
// A valid single value reaches file access, rather than a format-option error.
|
||||
let error = run(&args(&["convert", "missing.docx", "out.xml", "--format", "flatopc"])).unwrap_err().to_string();
|
||||
assert!(error.starts_with("missing.docx:"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
|
||||
for cmd in SUBCOMMANDS {
|
||||
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
|
||||
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
|
||||
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
|
||||
}
|
||||
assert!(!wants_help("frobnicate", &args(&["--help"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_exactly_the_subcommands() {
|
||||
let listed: Vec<&str> = USAGE
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
|
||||
.filter(|word| !word.starts_with(['-', '[']))
|
||||
.collect();
|
||||
assert_eq!(listed, SUBCOMMANDS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_keeps_bullet_and_number_labels() {
|
||||
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
|
||||
assert_eq!(listed_text(&doc).unwrap(), "\u{2022}\talpha\n\u{2022}\tbeta\n1.\tfirst\n2.\tsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_names_the_headless_session() {
|
||||
assert!(validate_options("run", &args(&["--author", "Claude (copyedit)", "--cmd", "edit.undo"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--author", "Claude"]), MCP_OPTIONS).is_ok());
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
use wordcraft_doc::{CharProps, InlineObject, StoryRef};
|
||||
@@ -331,6 +170,91 @@ fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
assert!(s.run("text.insert", &json!({"text": "Changed"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_are_taken_out_of_the_mcp_arguments() {
|
||||
let base = std::env::temp_dir().join(format!("wc-cli-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let (read, write) = (base.join("in").to_string_lossy().into_owned(), base.join("out").to_string_lossy().into_owned());
|
||||
|
||||
let (roots, left) =
|
||||
automation_roots("mcp", &args(&["--automation-read-root", &read, "--author", "Claude", &format!("--automation-write-root={write}")]))
|
||||
.unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert_eq!(left, args(&["--author", "Claude"]));
|
||||
assert!(roots.read_root().is_some() && roots.write_root().is_some());
|
||||
assert!(validate_options("mcp", &left, MCP_OPTIONS).is_ok());
|
||||
|
||||
// A root left out grants none of its access.
|
||||
let (roots, _) = automation_roots("mcp", &args(&["--automation-read-root", &read])).unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert!(roots.write_root().is_none());
|
||||
assert!(roots.check(&format!("{write}/x.docx"), wordcraft_engine::file_access::Access::Write).unwrap_err().contains("write authority is absent"));
|
||||
|
||||
// No flags: nothing is confined and the arguments pass through.
|
||||
let (roots, left) = automation_roots("mcp", &args(&["--connect", "127.0.0.1:9"])).unwrap();
|
||||
assert!(roots.is_none());
|
||||
assert_eq!(left, args(&["--connect", "127.0.0.1:9"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_reject_bad_operands_and_missing_folders() {
|
||||
for bad in [
|
||||
args(&["--automation-read-root"]),
|
||||
args(&["--automation-read-root", "--author"]),
|
||||
args(&["--automation-write-root="]),
|
||||
args(&["--automation-read-root", "a", "--automation-read-root=b"]),
|
||||
] {
|
||||
assert!(automation_roots("mcp", &bad).is_err(), "{bad:?}");
|
||||
}
|
||||
let e = automation_roots("mcp", &args(&["--automation-read-root", "/definitely/not/a/folder"])).err().unwrap();
|
||||
assert!(e.starts_with("mcp: cannot open the automation read root"), "{e}");
|
||||
// Through the command line: an error, not a server that quietly runs unconfined.
|
||||
assert!(run(&args(&["mcp", "--automation-write-root", "/definitely/not/a/folder"])).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"caf\xe9.docx".to_vec());
|
||||
let ok = |raw: Vec<OsString>| text_args(&raw).unwrap().1;
|
||||
assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), "--page".into(), "2".into(), latin1(), "out.png".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["convert".into(), "--format".into(), "flatopc".into(), latin1(), "out.xml".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "--password".into(), "secret".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["zotero".into(), "--port".into(), "23119".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
|
||||
// Every command that opens a file reaches the open with it (no such file here), so
|
||||
// `OPENS_FILE` and the commands' own arguments agree. `validate` takes exactly one path, so it
|
||||
// is checked separately below, together with its exit-3 usage status.
|
||||
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
|
||||
.iter()
|
||||
.filter(|(cmd, _)| *cmd != "validate")
|
||||
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
|
||||
.collect();
|
||||
opening.push(vec!["run".into(), "--file".into(), missing()]);
|
||||
for raw in opening {
|
||||
let e = run(&raw).unwrap_err().to_string();
|
||||
assert!(e.contains("No such file"), "{raw:?}: {e}");
|
||||
}
|
||||
assert!(matches!(run(&["validate".into(), missing()]), Err(Failure::Status(3))));
|
||||
for (raw, n) in [
|
||||
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
|
||||
(vec!["render".into(), "in.docx".into(), latin1()], 3),
|
||||
(vec!["render".into(), "--page".into(), latin1(), "in.docx".into(), "out.png".into()], 3),
|
||||
(vec!["run".into(), "--save".into(), latin1()], 3),
|
||||
(vec!["commands".into(), latin1()], 2),
|
||||
] {
|
||||
assert_eq!(text_args(&raw).unwrap_err(), format!("argument {n} is not valid Unicode: caf\u{FFFD}.docx"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
@@ -357,6 +281,66 @@ impl Drop for Scratch {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests
|
||||
/// rather than running what the person typed and exiting, refuses to start without both
|
||||
/// automation roots. Each subcommand has a row, so a new one fails here until it is classified,
|
||||
/// and a new agent entry point fails until it refuses.
|
||||
#[test]
|
||||
fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
enum Kind {
|
||||
Agent,
|
||||
NotAgent(&'static str),
|
||||
}
|
||||
use Kind::{Agent, NotAgent};
|
||||
let table = [
|
||||
("convert", NotAgent("converts the files named on its command line, then exits")),
|
||||
("info", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("text", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("inspect", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("render", NotAgent("renders the file named on its command line, then exits")),
|
||||
("run", NotAgent("runs the commands and script named on its command line, then exits")),
|
||||
("commands", NotAgent("lists the commands; touches no file")),
|
||||
("parity", NotAgent("prints the feature catalog; touches no file")),
|
||||
("validate", NotAgent("validates the one file named on its command line, then exits")),
|
||||
("mcp", Agent),
|
||||
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
|
||||
];
|
||||
assert_eq!(table.iter().map(|(name, _)| *name).collect::<Vec<_>>(), SUBCOMMANDS);
|
||||
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for (name, kind) in table {
|
||||
if let NotAgent(why) = kind {
|
||||
assert!(!why.is_empty(), "{name}: say why it is not an agent entry point");
|
||||
continue;
|
||||
}
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec![name.to_string()], given].concat();
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
|
||||
/// to it is refused, with roots or without, before anything connects.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
|
||||
#[test]
|
||||
fn mcp_headless_session_takes_the_author_flag() {
|
||||
@@ -368,6 +352,120 @@ fn mcp_headless_session_takes_the_author_flag() {
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_without_a_value_too() {
|
||||
let scratch = Scratch::new("connect-bare");
|
||||
let dir = scratch.0.to_string_lossy().into_owned();
|
||||
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
|
||||
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
|
||||
let line = args(&[&["mcp"][..], &roots, &tail].concat());
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale"])), Err("render: --scale requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "--scale", "2"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "--page", "1"])), Err("render: --scale requires a value".into()));
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "banana"])),
|
||||
Err("render: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "banana"])), Err("render: invalid --scale `banana`: not a number".into()));
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "0"])), Err("render: invalid --page `0`: page numbers start at 1".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
|
||||
Err("render: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
|
||||
Err("render: invalid --scale `-2`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
|
||||
Err("render: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
|
||||
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "1", "--page", "2"])), Err("render: duplicate --page option".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "1", "--scale", "2"])), Err("render: duplicate --scale option".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--page"])), Err("run: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale"])), Err("run: --scale requires a value".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "--scale", "2"])),
|
||||
Err("run: --page requires a value".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "--page", "1"])),
|
||||
Err("run: --scale requires a value".into())
|
||||
);
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "banana"])),
|
||||
Err("run: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "banana"])),
|
||||
Err("run: invalid --scale `banana`: not a number".into())
|
||||
);
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "0"])),
|
||||
Err("run: invalid --page `0`: page numbers start at 1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "-1"])),
|
||||
Err("run: invalid --page `-1`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
|
||||
Err("run: invalid --scale `-1`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
|
||||
Err("run: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
|
||||
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "1", "--page", "2"])),
|
||||
Err("run: duplicate --page option".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "1", "--scale", "2"])),
|
||||
Err("run: duplicate --scale option".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_and_run_valid_options_and_defaults_produce_files() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-render-{}", std::process::id()));
|
||||
@@ -517,6 +615,33 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
assert!(e.contains("--script requires a value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
|
||||
@@ -579,6 +704,34 @@ fn script_parse_resolves_paths_against_the_base() {
|
||||
assert_eq!(s.commands.len(), 1);
|
||||
}
|
||||
|
||||
/// Finding 3: a surplus operand is a usage error (exit 3) rejected in the operand check, before any
|
||||
/// file is validated, so a valid first path can no longer make `validate a.docx b.docx` print PASS.
|
||||
/// The two paths are DIFFERENT files and validating either one would return `Ok`; the code path
|
||||
/// returns `Status(3)` from the `paths.len() != 1` check before `validate_path` runs, so no file was
|
||||
/// validated to produce it. (A `Status(3)` on its own does not prove that — `validate` also returns
|
||||
/// it for an I/O error after a single valid operand reaches the validator — which is why the
|
||||
/// operand check, not the status, is what establishes the rejection happened first.)
|
||||
#[test]
|
||||
fn validate_rejects_missing_or_surplus_operands_without_validating() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-validate-args-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = dir.join("first.docx");
|
||||
let second = dir.join("second.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &first.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--template", "sample", "--save", &second.to_string_lossy()])).unwrap();
|
||||
let (first, second) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned());
|
||||
assert_ne!(first, second, "the two operands must be different files");
|
||||
assert_eq!(run(&args(&["validate", &first])), Ok(()), "one valid path reports PASS");
|
||||
assert_eq!(
|
||||
run(&args(&["validate", &first, &second])),
|
||||
Err(Failure::Status(3)),
|
||||
"two different paths are a usage error; validating either would return Ok, so it validated neither"
|
||||
);
|
||||
assert_eq!(run(&args(&["validate"])), Err(Failure::Status(3)), "no path is a usage error");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
|
||||
/// validator by its preserved path rather than being rejected as a bad argument.
|
||||
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
|
||||
@@ -674,3 +827,18 @@ fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
|
||||
assert!(line.contains("\\ud800") || line.contains("\\udb40"), "{line}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), value);
|
||||
}
|
||||
|
||||
/// Native non-Unicode paths survive argument parsing and reach the validator's I/O error path.
|
||||
/// No file is created: APFS refuses invalid UTF-8 names. The original bytes, rather than their
|
||||
/// lossy display spelling, must be retained even when options precede the operand.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn validate_preserves_a_non_unicode_path_without_creating_a_file() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let raw_path = OsString::from_vec(b"wordcraft-nonexistent-caf\xe9.docx".to_vec());
|
||||
let raw = vec![OsString::from("validate"), OsString::from("--json"), raw_path.clone()];
|
||||
let (_, parsed) = text_args(&raw).unwrap();
|
||||
assert_eq!(parsed.as_deref(), Some(Path::new(&raw_path)));
|
||||
assert!(parsed.as_deref().unwrap().to_str().is_none());
|
||||
assert_eq!(run(&raw), Err(Failure::Status(3)), "native path reaches I/O handling");
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
|
||||
std::fs::write(&pass, bytes).unwrap();
|
||||
let mut results = Vec::new();
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 1)] {
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 2)] {
|
||||
for json in [false, true] {
|
||||
let mut open = cli();
|
||||
open.arg("validate").arg(&fixture);
|
||||
@@ -87,7 +87,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other report-write failures are status 1 (RFC-0018: there is no 3); a child-only file-size limit forces EFBIG on stdout.
|
||||
/// Other report-write failures are I/O status 3; a child-only file-size limit forces EFBIG on stdout.
|
||||
#[test]
|
||||
fn validate_stdout_write_error_is_io_status() {
|
||||
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration/14-comment-dup.docx");
|
||||
@@ -105,7 +105,7 @@ fn validate_stdout_write_error_is_io_status() {
|
||||
}
|
||||
std::fs::remove_file(stdout).unwrap();
|
||||
for (json, output) in results {
|
||||
assert_eq!(output.status.code(), Some(1), "json={json}: {output:?}");
|
||||
assert_eq!(output.status.code(), Some(3), "json={json}: {output:?}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const SUBCOMMANDS: [&str; 11] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
|
||||
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
|
||||
@@ -14,7 +14,7 @@ fn assert_prints_usage(args: &[&str]) {
|
||||
let out = cli(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("wordcraft-cli"), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
|
||||
@@ -39,9 +39,9 @@ fn help_comes_before_opening_files_and_folders() {
|
||||
#[test]
|
||||
fn misspelled_options_and_unknown_commands_still_fail() {
|
||||
let out = cli(&["info", "--hepl"]);
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--hepl"));
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
|
||||
let out = cli(&["frobnicate", "--help"]);
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("frobnicate"));
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod help;
|
||||
mod man_and_completions;
|
||||
mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
//! The clap definition is consistent, and every shell's completions and every man page
|
||||
//! (`examples/man-and-completions.rs`) can be generated from it.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
// The example itself, so the test writes the files exactly as the packages get them.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../examples/man-and-completions.rs"]
|
||||
mod example;
|
||||
|
||||
#[test]
|
||||
fn command_is_consistent() {
|
||||
wordcraft_cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completions_generate_for_every_shell() {
|
||||
for &shell in Shell::value_variants() {
|
||||
let mut out = Vec::new();
|
||||
clap_complete::generate(shell, &mut wordcraft_cli::command(), "wordcraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = wordcraft_cli::command();
|
||||
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
|
||||
let mut out = Vec::new();
|
||||
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
|
||||
assert!(!out.is_empty(), "{}", page.get_name());
|
||||
}
|
||||
}
|
||||
|
||||
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
|
||||
/// `packaging/freebsd/package.sh` install, `wordcraft-cli.1` and a page per subcommand, and no
|
||||
/// pages for the `help` subcommand.
|
||||
#[test]
|
||||
fn the_example_writes_the_files_the_packages_install() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
example::generate(&dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["wordcraft-cli.bash", "_wordcraft-cli", "wordcraft-cli.fish", "wordcraft-cli.elv", "_wordcraft-cli.ps1"];
|
||||
let subcommands = ["commands", "convert", "info", "inspect", "mcp", "parity", "render", "run", "text", "validate", "zotero"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("wordcraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("wordcraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -67,19 +67,17 @@ fn any_other_such_argument_is_an_error_naming_it() {
|
||||
let (dir, file) = folder("error");
|
||||
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
|
||||
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
|
||||
// An output the engine takes as text: a failure (1), naming it; the other arguments are usage errors (2).
|
||||
for (args, code, shown) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 1, out_name.clone()),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd.clone()], 2, cmd),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 2, OsString::from_vec(b"t\xe9xt".to_vec())),
|
||||
for (args, n) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
|
||||
] {
|
||||
let out = cli(&args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let shown = shown.to_string_lossy();
|
||||
let shown = args[n - 1].to_string_lossy();
|
||||
assert!(shown.contains('\u{FFFD}'));
|
||||
assert_eq!(out.status.code(), Some(code), "{args:?}: stderr: {stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("not valid Unicode") || stderr.contains("invalid UTF-8") || stderr.contains(&*shown), "{args:?}: {stderr}");
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out_name).exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `convert --strict` (#6005): exit 1 and a report when a PDF or PNG would silently lack a
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
@@ -145,9 +145,9 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
@@ -186,7 +186,7 @@ fn a_corrupt_header_picture_fails_strict_naming_the_part_and_the_header() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("word/media/image2.bin (header2.xml): unsupported format"), "{text}");
|
||||
let json = report_json(&r);
|
||||
@@ -218,7 +218,7 @@ fn an_external_picture_target_is_never_fetched_and_is_reported_under_strict() {
|
||||
assert_eq!(lenient.status.code(), Some(0), "{}", stderr(&lenient));
|
||||
let out = d.join("strict.pdf");
|
||||
let strict = convert(&input, &out, true);
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(strict.status.code(), Some(3), "{}", stderr(&strict));
|
||||
let json = report_json(&strict);
|
||||
assert_eq!(json["missing_pictures"][0]["reason"], "external_target");
|
||||
assert!(stderr(&strict).contains("external target"));
|
||||
@@ -246,19 +246,19 @@ fn bad_input_exits_1_with_the_usual_message_with_and_without_strict() {
|
||||
assert_eq!(plain.status.code(), Some(1), "{}", stderr(&plain));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(stderr(&plain), stderr(&strict));
|
||||
assert!(stderr(&plain).starts_with("error: "), "{}", stderr(&plain));
|
||||
assert!(stderr(&plain).starts_with("wordcraft-cli: "), "{}", stderr(&plain));
|
||||
assert!(!d.join("a.pdf").exists() && !d.join("b.pdf").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_with_another_output_type_exits_2_before_the_input_is_read() {
|
||||
fn strict_with_another_output_type_exits_1_before_the_input_is_read() {
|
||||
let d = dir("wrong-output");
|
||||
let missing = d.join("does-not-exist.docx");
|
||||
for out in ["out.docx", "out.txt", "out.odt"] {
|
||||
let r = convert(&missing, &d.join(out), true);
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("--strict needs a .pdf or .png output"), "{text}");
|
||||
assert!(!d.join(out).exists());
|
||||
@@ -291,11 +291,11 @@ fn render_strict_refuses_an_uncovered_character_on_the_page_with_no_stdout_or_fi
|
||||
let input = two_page_input(&d, &format!("a{c}b"));
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
assert!(!out.exists());
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
eprintln!("{text}");
|
||||
|
||||
@@ -323,7 +323,7 @@ fn render_strict_refuses_a_corrupt_header_picture_and_bad_input_still_exits_1()
|
||||
std::fs::write(&input, docx_with_header_picture(b"corrupt bytes, not a picture")).unwrap();
|
||||
let out = d.join("out.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty());
|
||||
assert!(stderr(&r).contains("word/media/image2.bin (header2.xml)"), "{}", stderr(&r));
|
||||
assert!(!out.exists());
|
||||
@@ -341,16 +341,16 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
let d = dir("escape");
|
||||
let input = d.join("in.docx");
|
||||
// XML character references put a newline and U+202E in the target.
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
// One human line for the picture, then the JSON line.
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].starts_with("error: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nerror: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(lines[0].starts_with("wordcraft-cli: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nwordcraft-cli: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(!text.contains('\u{202e}'), "the raw bidi override reached the terminal");
|
||||
// The JSON keeps the raw value, escaped by the JSON encoder.
|
||||
let json = report_json(&r);
|
||||
@@ -363,14 +363,14 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
let d = dir("run-escape");
|
||||
let input = d.join("in.docx");
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged[2J‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged[2J‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let cmd = format!("file.exportPdf={}", serde_json::json!({"path": out, "strict": true}));
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("run").arg("--file").arg(&input).arg("--cmd").arg(cmd).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains("\\nerror: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
|
||||
assert!(!out.exists());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
@@ -378,20 +378,19 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
|
||||
#[test]
|
||||
fn usage_errors_keep_their_line_breaks() {
|
||||
// Errors go to stderr (clap's message, then its usage), exit 2.
|
||||
// Errors go to stderr with the usage after a blank line (`missing argument`, `unknown command`).
|
||||
for args in [&["frobnicate"][..], &["convert"][..]] {
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
let text = stderr(&r);
|
||||
assert_eq!(r.status.code(), Some(2), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 2, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l.starts_with("Usage:")), "{args:?}: {text}");
|
||||
assert_eq!(r.status.code(), Some(1), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 3, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l == "USAGE:"), "{args:?}: {text}");
|
||||
assert!(!text.contains("\\n"), "{args:?}: {text}");
|
||||
}
|
||||
// No arguments at all prints the help (on stderr, as clap does for a missing subcommand), exit 2.
|
||||
// No arguments at all prints the usage as help, on stdout.
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let all = format!("{}{}", String::from_utf8_lossy(&r.stdout), stderr(&r));
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l.starts_with("Usage:")), "{all}");
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l == "USAGE:"), "{all}");
|
||||
}
|
||||
|
||||
/// A minimal EMF (88-byte header, 100 mm square frame) with one EMR_EXTTEXTOUTW record showing
|
||||
@@ -445,7 +444,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str(), "{}", stderr(&r));
|
||||
assert!(!out.exists(), "{} was written", out.display());
|
||||
// Without --strict it converts, the character a hollow box.
|
||||
@@ -455,7 +454,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
}
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty() && !out.exists());
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
// Text the faces cover passes.
|
||||
@@ -480,7 +479,7 @@ fn a_metafile_page_background_fails_strict_for_png_but_not_for_pdf() {
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let png = d.join("out.png");
|
||||
let r = convert(&input, &png, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["missing_pictures"][0]["part"], "bg.emf", "{}", stderr(&r));
|
||||
assert_eq!(json["missing_pictures"][0]["source_part"], "background");
|
||||
|
||||
@@ -57,7 +57,7 @@ winresource = "0.1"
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Finder double-click, Open With, Dock drops and `open -a WordCraft letter.docx` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
|
||||
craft = { workspace = true, features = ["platform-apple-events"] }
|
||||
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
@@ -20,6 +20,8 @@ mod build_flavor;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod launch_profile;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod prefs;
|
||||
mod process_identity;
|
||||
@@ -54,6 +56,8 @@ use wordcraft_ui_egui::{Services, WordApp, prefs::Prefs};
|
||||
/// exit, the print spool it waits for at exit and the control server it stops at exit.
|
||||
struct App {
|
||||
app: WordApp,
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: Option<craft::menu::NativeMenu>,
|
||||
/// The native panels behind the file service the app reaches through `Host::files`.
|
||||
panels: FilePanels,
|
||||
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
|
||||
@@ -71,10 +75,22 @@ struct App {
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn before_input(&mut self, ctx: &egui::Context) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(menu) = &mut self.native_menu {
|
||||
menu.poll(ctx);
|
||||
}
|
||||
embed::before_input(ctx, |out| self.app.frame_input(out));
|
||||
}
|
||||
|
||||
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
|
||||
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
|
||||
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
|
||||
self.app.logic(ctx);
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(menu) = &mut self.native_menu {
|
||||
native_menu::update(menu, &mut self.app, ctx);
|
||||
}
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
// A quit that waits for nothing (the documents are answered for) closes the root window.
|
||||
if self.app.quit_requested && !self.app.printing.busy() {
|
||||
@@ -123,7 +139,7 @@ impl eframe::App for App {
|
||||
if !files.is_empty() {
|
||||
self.drops.dropped(files);
|
||||
}
|
||||
embed::before_input(ctx, |out| self.app.frame_input(out));
|
||||
self.before_input(ctx);
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
self.logic_pass(ctx, Some(frame));
|
||||
@@ -798,6 +814,8 @@ fn main() -> eframe::Result {
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
@@ -1014,14 +1032,29 @@ mod smoke {
|
||||
let drops = intake.sender();
|
||||
let session = Session::new(wordcraft_doc::Document::new());
|
||||
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
|
||||
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
|
||||
Run {
|
||||
app: App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: None,
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: None,
|
||||
exit: None,
|
||||
},
|
||||
frames,
|
||||
ctx,
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
|
||||
/// Returns whether the frame sent a close command.
|
||||
fn step(&mut self, events: Vec<egui::Event>) -> bool {
|
||||
let Run { app, frames, ctx, .. } = self;
|
||||
embed::before_input(ctx, |out| app.app.frame_input(out));
|
||||
app.before_input(ctx);
|
||||
let mut first = true;
|
||||
frames.frame_without_input(events, |ui| {
|
||||
if std::mem::take(&mut first) {
|
||||
@@ -1044,7 +1077,7 @@ mod smoke {
|
||||
/// cancelling the close.
|
||||
fn close_request_is_let_through(&mut self) -> bool {
|
||||
let Run { app, ctx, .. } = self;
|
||||
embed::before_input(ctx, |out| app.app.frame_input(out));
|
||||
app.before_input(ctx);
|
||||
let mut input =
|
||||
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 920.0))), ..Default::default() };
|
||||
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { events: vec![egui::ViewportEvent::Close], ..Default::default() });
|
||||
@@ -1118,6 +1151,47 @@ mod smoke {
|
||||
assert!(closed, "Don't Save lets the close through");
|
||||
}
|
||||
}
|
||||
|
||||
/// A native menu selection reaches the hosted About dialog, including its credits, and Escape
|
||||
/// dismisses it without changing the document. The fake backend supplies the OS selection.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn native_about_shows_credits_and_closes_with_escape() {
|
||||
use craft::menu::{Backend, Dispatch, Event, ItemRole, MenuBar, NativeMenu};
|
||||
|
||||
struct Selection(Vec<Event>);
|
||||
impl Backend for Selection {
|
||||
fn sync(&mut self, _: &MenuBar) {}
|
||||
fn attach(&mut self, _: Dispatch) {}
|
||||
fn drain(&mut self) -> Vec<Event> {
|
||||
std::mem::take(&mut self.0)
|
||||
}
|
||||
}
|
||||
|
||||
let mut run = Run::new();
|
||||
run.app.app.start_screen();
|
||||
run.settle();
|
||||
let before = run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
let layout = native_menu::layout(&str::to_owned);
|
||||
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().command.clone();
|
||||
run.app.native_menu = Some(NativeMenu::new(Box::new(Selection(vec![Event::Click(about)]))));
|
||||
run.settle();
|
||||
assert!(run.app.app.dialog_host_mut().shows_modal());
|
||||
let tree = run.frames.tree();
|
||||
for label in ["WordCraft", "Contributors", "Models", "Language data"] {
|
||||
assert!(tree.keys().into_iter().any(|key| craft::ui::testing::access::name(&tree, key) == Some(label)), "About exposes {label}");
|
||||
}
|
||||
run.step(vec![egui::Event::Key {
|
||||
key: egui::Key::Escape,
|
||||
physical_key: None,
|
||||
pressed: true,
|
||||
repeat: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
}]);
|
||||
run.settle();
|
||||
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
|
||||
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The macOS application menu uses the same About dialog as File › About.
|
||||
|
||||
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
|
||||
use serde_json::json;
|
||||
use wordcraft_ui_egui::{WordApp, i18n};
|
||||
|
||||
const APP_NAME: &str = "WordCraft";
|
||||
const ABOUT: &str = "About WordCraft";
|
||||
|
||||
/// The application menu, with `tr` the translation of an English string.
|
||||
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
|
||||
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
|
||||
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
|
||||
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
|
||||
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
|
||||
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
|
||||
// WordCraft's document menus live in its ribbon; keep only the application menu.
|
||||
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
|
||||
layout
|
||||
}
|
||||
|
||||
fn lang(app: &WordApp) -> i18n::Lang {
|
||||
i18n::Lang::from_pref(&app.ui.language)
|
||||
}
|
||||
|
||||
fn layout_in(lang: i18n::Lang) -> Layout {
|
||||
layout(&|s| i18n::tr(lang, s).to_owned())
|
||||
}
|
||||
|
||||
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
|
||||
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
|
||||
if menu.is_none() {
|
||||
log::warn!("the WordCraft application menu could not be installed");
|
||||
}
|
||||
menu
|
||||
}
|
||||
|
||||
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
|
||||
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
|
||||
for command in menu.take_clicks(ctx) {
|
||||
if let Err(error) = app.run(&command.id, command.params) {
|
||||
log::warn!("application menu: {error}");
|
||||
}
|
||||
}
|
||||
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
|
||||
let lang = lang(app);
|
||||
for clash in menu.sync_with(lang.code(), || layout_in(lang)) {
|
||||
log::warn!("application menu: {clash:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The catalogs translate "About WordCraft" and have no "About {app}" row.
|
||||
#[test]
|
||||
fn about_shows_the_catalogs_translation() {
|
||||
let translate = |s: &'static str| if s == "About WordCraft" { "Über WordCraft".to_owned() } else { s.to_owned() };
|
||||
let layout = layout(&translate);
|
||||
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
|
||||
assert_eq!(about.label, "Über WordCraft");
|
||||
}
|
||||
}
|
||||
+48
-27
@@ -647,6 +647,20 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Remaps media references across `blocks` and any text box stories in `parts`.
|
||||
fn remap_media_in(blocks: &mut [Block], parts: &mut BTreeMap<u32, Part>, map: &BTreeMap<String, String>) {
|
||||
if map.is_empty() {
|
||||
return;
|
||||
}
|
||||
for b in blocks {
|
||||
remap_media_block(b, map);
|
||||
}
|
||||
for part in parts.values_mut() {
|
||||
for b in &mut part.blocks {
|
||||
remap_media_block(Arc::make_mut(b), map);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Visit `(index, item)` in forward (`!last`) or reverse (`last`) order, returning the first `Some`.
|
||||
fn find_in_slice<T>(slice: &[T], last: bool, mut f: impl FnMut(usize, &T) -> Option<Path>) -> Option<Path> {
|
||||
if last { slice.iter().enumerate().rev().find_map(|(i, x)| f(i, x)) } else { slice.iter().enumerate().find_map(|(i, x)| f(i, x)) }
|
||||
@@ -688,7 +702,6 @@ fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> P
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Convert notes between footnotes and endnotes: footnotes (`foot`) become endnotes and
|
||||
/// endnotes (`end`) footnotes, both at once to swap them. Each note's kind changes, as do its
|
||||
@@ -1643,13 +1656,41 @@ impl Document {
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// The blocks of `frag`, a fragment of another document, with every text box given a new
|
||||
/// story of its own here copied from the fragment's parts (as a paste does), to place them
|
||||
/// in this document; a box the fragment has no story for keeps none.
|
||||
/// Copies `media` into `self.media`, returning a remap for keys whose bytes differ from an
|
||||
/// existing entry under the same key.
|
||||
fn adopt_media(&mut self, media: &BTreeMap<String, Arc<Vec<u8>>>) -> BTreeMap<String, String> {
|
||||
let mut media_remap = BTreeMap::new();
|
||||
for (k, v) in media {
|
||||
if let Some(existing) = self.media.get(k) {
|
||||
if existing.as_slice() != v.as_slice() {
|
||||
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
|
||||
let new_key = self.add_media((**v).clone(), ext);
|
||||
media_remap.insert(k.clone(), new_key);
|
||||
}
|
||||
} else {
|
||||
self.media.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
media_remap
|
||||
}
|
||||
|
||||
/// The blocks of `frag`, a fragment of another document, with its media copied (remapping
|
||||
/// conflicting keys) and every text box given a new story of its own here copied from the
|
||||
/// fragment's parts (as a paste does), to place them in this document; a box the fragment
|
||||
/// has no story for keeps none.
|
||||
pub fn adopt_fragment(&mut self, frag: &Fragment) -> Vec<Block> {
|
||||
let media_remap = self.adopt_media(&frag.media);
|
||||
let mut blocks = frag.blocks.clone();
|
||||
let mut remapped_parts;
|
||||
let parts = if media_remap.is_empty() {
|
||||
&frag.parts
|
||||
} else {
|
||||
remapped_parts = frag.parts.clone();
|
||||
remap_media_in(&mut blocks, &mut remapped_parts, &media_remap);
|
||||
&remapped_parts
|
||||
};
|
||||
let mut budget = BoxBudget { local: false, ..BoxBudget::new() };
|
||||
self.adopt_text_boxes(&mut blocks, &frag.parts, 0, &mut budget);
|
||||
self.adopt_text_boxes(&mut blocks, parts, 0, &mut budget);
|
||||
if budget.skipped > 0 {
|
||||
log::warn!(
|
||||
"{} text boxes are left empty; their stories are past what one copy brings ({MAX_PASTED_BOXES} stories, {MAX_PASTED_BOX_BYTES} bytes)",
|
||||
@@ -1661,18 +1702,7 @@ impl Document {
|
||||
|
||||
/// Insert a fragment at `pos`; returns the position after the pasted content.
|
||||
pub fn insert_fragment(&mut self, pos: &Pos, frag: &Fragment) -> Result<Pos> {
|
||||
let mut media_remap = BTreeMap::new();
|
||||
for (k, v) in &frag.media {
|
||||
if let Some(existing) = self.media.get(k) {
|
||||
if existing.as_slice() != v.as_slice() {
|
||||
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
|
||||
let new_key = self.add_media((**v).clone(), ext);
|
||||
media_remap.insert(k.clone(), new_key);
|
||||
}
|
||||
} else {
|
||||
self.media.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let media_remap = self.adopt_media(&frag.media);
|
||||
// Tables that would nest deeper than the limit here become their paragraphs (#1596).
|
||||
let room = MAX_TABLE_DEPTH.saturating_sub(pos.path.depth());
|
||||
let mut blocks = Vec::with_capacity(frag.blocks.len());
|
||||
@@ -1689,16 +1719,7 @@ impl Document {
|
||||
let table_para = table_style_para(self, pos);
|
||||
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
|
||||
let mut parts = frag.parts.clone();
|
||||
if !media_remap.is_empty() {
|
||||
for b in &mut blocks {
|
||||
remap_media_block(b, &media_remap);
|
||||
}
|
||||
for part in parts.values_mut() {
|
||||
for b in &mut part.blocks {
|
||||
remap_media_block(Arc::make_mut(b), &media_remap);
|
||||
}
|
||||
}
|
||||
}
|
||||
remap_media_in(&mut blocks, &mut parts, &media_remap);
|
||||
// Pasted text boxes get stories of their own (never shared with the copy's source).
|
||||
let mut budget = BoxBudget::new();
|
||||
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
|
||||
|
||||
@@ -1192,6 +1192,61 @@ fn insert_fragment_remaps_conflicting_media_keys() {
|
||||
assert_eq!(remapped, other_key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adopt_fragment_copies_and_remaps_conflicting_media_in_blocks_and_text_boxes() {
|
||||
let mut d = doc(&["destination"]);
|
||||
d.media.insert("image1.png".into(), Arc::new(vec![1, 1, 1]));
|
||||
|
||||
let mut frag_media = std::collections::BTreeMap::new();
|
||||
frag_media.insert("image1.png".into(), Arc::new(vec![2, 2, 2]));
|
||||
frag_media.insert("missing.png".into(), Arc::new(vec![3, 3, 3]));
|
||||
|
||||
let img = |key: &str| InlineObject::Image {
|
||||
media: key.into(),
|
||||
w: 10.0,
|
||||
h: 10.0,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
|
||||
let mut tb_para = Paragraph::with_text(&crate::para::OBJ.to_string(), CharProps::default());
|
||||
tb_para.objects.push(img("image1.png"));
|
||||
let mut parts = std::collections::BTreeMap::new();
|
||||
parts.insert(7, Part { kind: PartKind::TextBox, blocks: vec![para_block(tb_para)], body: Default::default() });
|
||||
|
||||
let mut top_para = Paragraph::with_text(&format!("{}{}", crate::para::OBJ, crate::para::OBJ), CharProps::default());
|
||||
top_para.objects.push(img("missing.png"));
|
||||
top_para.objects.push(InlineObject::Shape {
|
||||
kind: crate::para::ShapeKind::TextBox,
|
||||
w: 40.0,
|
||||
h: 40.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: Default::default(),
|
||||
story: Some(7),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
});
|
||||
let frag = Fragment { blocks: vec![Block::Para(top_para)], parts, media: frag_media };
|
||||
|
||||
let adopted = d.adopt_fragment(&frag);
|
||||
assert_eq!(d.media["image1.png"].as_slice(), &[1, 1, 1]);
|
||||
assert_eq!(d.media["missing.png"].as_slice(), &[3, 3, 3]);
|
||||
let remapped_key = d.media.keys().find(|k| k.as_str() != "image1.png" && k.as_str() != "missing.png").unwrap();
|
||||
assert_eq!(d.media[remapped_key].as_slice(), &[2, 2, 2]);
|
||||
|
||||
let adopted_para = adopted[0].as_para().unwrap();
|
||||
assert!(matches!(&adopted_para.objects[0], InlineObject::Image { media, .. } if media == "missing.png"));
|
||||
let adopted_tb_id = adopted_para.objects[1].text_box().unwrap();
|
||||
let adopted_tb_para = d.parts[&adopted_tb_id].blocks[0].as_para().unwrap();
|
||||
assert!(matches!(&adopted_tb_para.objects[0], InlineObject::Image { media, .. } if media == remapped_key));
|
||||
}
|
||||
|
||||
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
|
||||
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
|
||||
#[test]
|
||||
|
||||
@@ -532,6 +532,98 @@ Tools|Templates|Templates and Add-ins|tools.templates
|
||||
Tools|Views|Full Screen View|view.fullScreenView
|
||||
";
|
||||
|
||||
/// RFC-0052 hand marks for catalog features with no engine command: `id|headless|reach|why`.
|
||||
///
|
||||
/// `headless` is `no` or `partial`, `reach` is `window` (needs a desktop window, dialog or
|
||||
/// pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could
|
||||
/// be an engine command, isn't one yet). `yes` is never written here: a feature is `yes` only when
|
||||
/// its id is in the engine registry that `wordcraft-cli` and the MCP server load, and a mark on such
|
||||
/// an id is stale (`headless_errors`). A missing feature with no mark is `unknown`.
|
||||
pub const HEADLESS: &str = "\
|
||||
tools.dictate|no|os|speech recognition service
|
||||
insert.onlinePicture|no|os|online image search service
|
||||
insert.model3d|no|engine-gap|3-D model files could be inserted by a command
|
||||
insert.screenshot|no|os|screen capture of other windows
|
||||
addins.get|no|os|add-in store service
|
||||
insert.video|no|os|online video service
|
||||
insert.inkEquation|no|window|drawn with a pen or pointer
|
||||
draw.inkToMath|no|os|handwriting recognition service
|
||||
review.translate|no|os|online translation service
|
||||
review.blockAuthors|no|os|co-authoring service
|
||||
view.readLayout|no|window|Read Mode window layout
|
||||
";
|
||||
|
||||
/// One feature's RFC-0052 `headless:` value and, for `no`/`partial`, its `reach:` and reason.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Headless {
|
||||
pub value: &'static str,
|
||||
pub reach: Option<&'static str>,
|
||||
pub why: &'static str,
|
||||
}
|
||||
|
||||
const REACHES: [&str; 3] = ["window", "os", "engine-gap"];
|
||||
|
||||
/// Parsed `HEADLESS`-format marks: (id, value, reach, why). A malformed line is an error.
|
||||
pub fn headless_marks(src: &'static str) -> Result<Vec<(&'static str, Headless)>, String> {
|
||||
let mut out = Vec::new();
|
||||
for line in src.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let f: Vec<&'static str> = line.splitn(4, '|').collect();
|
||||
let [id, value, reach, why] = f[..] else {
|
||||
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
|
||||
};
|
||||
if !matches!(value, "no" | "partial") {
|
||||
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !REACHES.contains(&reach) {
|
||||
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if out.iter().any(|(m, _)| *m == id) {
|
||||
return Err(format!("headless mark `{id}` is written twice"));
|
||||
}
|
||||
out.push((id, Headless { value, reach: Some(reach), why }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `headless:` value of a catalog feature: `yes` when the engine registry has its id, else its
|
||||
/// hand mark, else `unknown`.
|
||||
pub fn headless_of(id: &str, live: bool, marks: &[(&'static str, Headless)]) -> Headless {
|
||||
if live {
|
||||
return Headless { value: "yes", reach: None, why: "" };
|
||||
}
|
||||
marks.iter().find(|(m, _)| *m == id).map(|(_, h)| *h).unwrap_or(Headless { value: "unknown", reach: None, why: "" })
|
||||
}
|
||||
|
||||
/// Problems with the marks against the catalog and the registry's ids: unknown ids, and marks on
|
||||
/// ids the engine registry has (they would hide a `yes`).
|
||||
pub fn headless_errors(src: &'static str, catalog: &[(&str, &str, &str, &str)], live: impl Fn(&str) -> bool) -> Vec<String> {
|
||||
let marks = match headless_marks(src) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return vec![e],
|
||||
};
|
||||
let mut errs = Vec::new();
|
||||
for (id, _) in &marks {
|
||||
if !catalog.iter().any(|e| e.3 == *id) {
|
||||
errs.push(format!("headless mark `{id}` is not a catalog id"));
|
||||
} else if live(id) {
|
||||
errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`"));
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
/// Headless counts in the RFC-0052 summary shape.
|
||||
fn headless_summary(values: &[Headless]) -> Value {
|
||||
let count = |v: &str| values.iter().filter(|h| h.value == v).count();
|
||||
let no = |r: &str| values.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
|
||||
json!({
|
||||
"yes": count("yes"),
|
||||
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
|
||||
"partial": count("partial"),
|
||||
"unknown": count("unknown"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Catalog entries: (tab, group, feature, id).
|
||||
pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)> {
|
||||
CATALOG
|
||||
@@ -546,9 +638,13 @@ pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)
|
||||
/// Parity summary: per tab and overall, with the missing features.
|
||||
pub fn parity(reg: &Registry) -> Value {
|
||||
let e = entries();
|
||||
let marks = headless_marks(HEADLESS).unwrap_or_default();
|
||||
let mut values = Vec::with_capacity(e.len());
|
||||
let mut tabs: Vec<(&str, usize, usize, Vec<String>)> = Vec::new();
|
||||
for (tab, group, label, id) in &e {
|
||||
let have = reg.get(id).is_some();
|
||||
let h = headless_of(id, have, &marks);
|
||||
values.push(h);
|
||||
let t = match tabs.iter_mut().find(|t| t.0 == *tab) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
@@ -564,7 +660,8 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
if have {
|
||||
t.1 += 1;
|
||||
} else {
|
||||
t.3.push(format!("{group} › {label} (`{id}`)"));
|
||||
let reach = h.reach.map(|r| format!(", reach: {r} ({})", h.why)).unwrap_or_default();
|
||||
t.3.push(format!("{group} › {label} (`{id}`): headless: {}{reach}", h.value));
|
||||
}
|
||||
}
|
||||
let live = tabs.iter().map(|t| t.1).sum::<usize>();
|
||||
@@ -573,6 +670,7 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
"live": live,
|
||||
"total": total,
|
||||
"percent": if total == 0 { 0.0 } else { (live as f64 * 1000.0 / total as f64).round() / 10.0 },
|
||||
"headless": headless_summary(&values),
|
||||
"tabs": tabs.iter().map(|t| json!({"tab": t.0, "live": t.1, "total": t.2, "missing": t.3})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -597,6 +695,44 @@ mod tests {
|
||||
assert!(pct >= 90.4, "parity {pct}%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_are_current() {
|
||||
let reg = crate::cmd::registry();
|
||||
let errs = headless_errors(HEADLESS, &entries(), |id| reg.get(id).is_some());
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_yes_comes_only_from_the_registry() {
|
||||
let marks = headless_marks("a.b|no|window|pointer\n").unwrap();
|
||||
assert_eq!(headless_of("a.b", true, &marks).value, "yes", "a live id is yes whatever the mark says");
|
||||
assert_eq!(headless_of("a.b", false, &marks).reach, Some("window"));
|
||||
assert_eq!(headless_of("c.d", false, &marks).value, "unknown");
|
||||
assert!(headless_marks("a.b|yes|window|x\n").is_err(), "a hand-written yes is refused");
|
||||
assert!(headless_marks("a.b|no|desk|x\n").is_err(), "reach must be window, os or engine-gap");
|
||||
assert!(headless_marks("a.b|no\n").is_err());
|
||||
assert!(headless_marks("a.b|no|os|x\na.b|partial|os|y\n").is_err(), "one mark per id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_errors_flag_stale_and_unknown_marks() {
|
||||
let cat = [("T", "G", "F", "a.b"), ("T", "G", "H", "c.d")];
|
||||
let errs = headless_errors("a.b|no|os|x\nz.z|no|os|y\n", &cat, |id| id == "a.b");
|
||||
assert!(errs.iter().any(|e| e.contains("`a.b` is stale")), "{errs:?}");
|
||||
assert!(errs.iter().any(|e| e.contains("`z.z` is not a catalog id")), "{errs:?}");
|
||||
assert!(headless_errors("bad\n", &cat, |_| false).len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parity_counts_every_feature_once_in_the_headless_summary() {
|
||||
let p = parity(&crate::cmd::registry());
|
||||
let h = &p["headless"];
|
||||
let n = |v: &Value| v.as_u64().unwrap_or(0);
|
||||
let no = n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]);
|
||||
assert_eq!(n(&h["yes"]) + no + n(&h["partial"]) + n(&h["unknown"]), n(&p["total"]));
|
||||
assert_eq!(n(&h["yes"]), n(&p["live"]), "every live feature is an engine command here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_mode_view_menu_is_catalogued() {
|
||||
let e = entries();
|
||||
|
||||
@@ -117,9 +117,9 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
|
||||
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
|
||||
},
|
||||
};
|
||||
// Fitted to the room where it goes: the table cell, the column, its own section (#5428).
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
let key = s.doc.add_media(bytes, ext);
|
||||
// Fitted to the text width.
|
||||
let max_w = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
|
||||
let (mut w, mut h) = (natural_w, natural_h);
|
||||
if let Some(want) = width {
|
||||
// At most 22 inches, as for icons: a huge width made the height of a tall picture infinite.
|
||||
|
||||
@@ -499,10 +499,23 @@ pub(crate) fn unlink_sections(blocks: &mut [Block]) {
|
||||
/// lists and styles it refers to (renumbered so they can't collide with ours).
|
||||
fn adopt(s: &mut Session, src: Document) -> Fragment {
|
||||
let mut frag = s.doc.adopt(src);
|
||||
// Pasted pictures fit our text width, like Insert › Pictures (layout keeps their size).
|
||||
let max_w = crate::io::text_width(&s.doc);
|
||||
// Pasted pictures fit the room where they go, like Insert › Pictures: the table cell, the
|
||||
// column, its own section (#5428; layout keeps their size). Measured (a layout) only when
|
||||
// the fragment holds an inline picture.
|
||||
let mut has_picture = false;
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
each_para(b, 0, &mut |p| {
|
||||
has_picture |= p
|
||||
.objects
|
||||
.iter()
|
||||
.any(|o| matches!(o, wordcraft_doc::InlineObject::Image { float, .. } if float.wrap == wordcraft_doc::para::Wrap::Inline));
|
||||
});
|
||||
}
|
||||
if has_picture {
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
}
|
||||
}
|
||||
unlink_sections(&mut frag.blocks);
|
||||
frag
|
||||
|
||||
@@ -21,7 +21,7 @@ mod typing;
|
||||
|
||||
pub use autocorrect::{AUTOCORRECT, AutoCap, AutoCorrectPrefs, lenient_autocorrect};
|
||||
#[cfg(test)]
|
||||
use compare::{Op, collapse_noise_matches, lcs_ops};
|
||||
use compare::{Op, collapse_noise_matches, lcs_len, lcs_ops};
|
||||
pub use specs::specs;
|
||||
pub use typing::{INITIAL_CAPS_EXCEPTIONS, autocorrect, autocorrect_word, emphasis_autoformat, has_emphasis};
|
||||
pub(crate) use typing::{is_turkic, lower_char, upper_char};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -204,6 +204,43 @@ impl Session {
|
||||
Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts))
|
||||
}
|
||||
|
||||
/// How wide a picture put in at `pos` may be, as Word fits an inserted or pasted picture
|
||||
/// (#5428): the room its paragraph's lines have (the width available to its widest laid-out line,
|
||||
/// so the paragraph's indents are already taken out; inside a table cell, the innermost cell's
|
||||
/// text area, nested tables included; a turned cell isn't measured and falls back to the
|
||||
/// column width), never wider than the column it is in, of its own section. The narrowest
|
||||
/// section's text width ([`crate::io::text_width`]) when `pos` isn't laid out. It is measured on the pages, whatever the view: Web Layout and Read Mode reflow the
|
||||
/// text to the window, and a picture put in there keeps the size it gets in the document.
|
||||
pub(crate) fn room_at(&mut self, pos: &wordcraft_doc::Pos) -> f32 {
|
||||
let first = crate::io::text_width(&self.doc);
|
||||
let l =
|
||||
if !self.view.read_mode && self.view.mode == ViewMode::Print { self.layout() } else { self.output_layout_of(&self.doc, false, false) };
|
||||
let Some((caret, page)) = l.caret_on(pos, self.page_hint).and_then(|c| Some((c, l.pages.get(c.page)?))) else { return first };
|
||||
// A page can hold several continuous sections: the body's own comes from the position.
|
||||
let at = match (pos.story, pos.path.0.first()) {
|
||||
(StoryRef::Body, Some(b)) => self.doc.section_index_of(*b as usize),
|
||||
_ => page.section,
|
||||
};
|
||||
let section = self.doc.sections().get(at).map(|(_, sp)| (*sp).clone());
|
||||
let column = match (§ion, pos.story) {
|
||||
(Some(sp), StoryRef::Body) => {
|
||||
let boxes = sp.column_boxes();
|
||||
let x = caret.x - page.body.x;
|
||||
boxes.iter().find(|(cx, w)| x >= cx - 0.5 && x <= cx + w + 0.5).map_or_else(|| sp.text_width(), |(_, w)| *w)
|
||||
}
|
||||
(Some(sp), StoryRef::Part(_)) => sp.text_width(),
|
||||
(None, _) => first,
|
||||
};
|
||||
let lines = wordcraft_layout::hit::page_lines(page, pos.story)
|
||||
.iter()
|
||||
.filter(|h| *h.path == pos.path)
|
||||
.map(|h| h.right - h.left)
|
||||
.filter(|w| w.is_finite())
|
||||
.fold(0.0f32, f32::max);
|
||||
let room = if lines >= 1.0 { lines.min(column) } else { column };
|
||||
if room.is_finite() && room >= 1.0 { room } else { first }
|
||||
}
|
||||
|
||||
/// Invalidate the cached layout (fonts changed etc.).
|
||||
pub fn relayout(&mut self) {
|
||||
self.layout = Default::default();
|
||||
|
||||
+141
-4
@@ -6281,8 +6281,8 @@ fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_none());
|
||||
|
||||
let copy_res = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(copy_res["text"], "", "copy on bare caret returns empty text");
|
||||
let copy_res = s.run("edit.copy", &json!({}));
|
||||
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
|
||||
assert!(s.clipboard.is_none(), "clipboard remains unset");
|
||||
|
||||
let cut_res = s.run("edit.cut", &json!({}));
|
||||
@@ -6297,8 +6297,8 @@ fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_none());
|
||||
|
||||
let copy_res = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(copy_res["text"], "", "copy on bare caret returns empty text");
|
||||
let copy_res = s.run("edit.copy", &json!({}));
|
||||
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
|
||||
assert!(s.clipboard.is_none(), "clipboard remains unset");
|
||||
|
||||
let cut_res = s.run("edit.cut", &json!({}));
|
||||
@@ -14943,6 +14943,143 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_inserted_or_pasted_picture_fits_where_it_goes() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let widths = |s: &Session| {
|
||||
let mut v = Vec::new();
|
||||
for b in s.doc.body.iter() {
|
||||
let mut b = (**b).clone();
|
||||
cmd::paste::each_para(&mut b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
if let wordcraft_doc::InlineObject::Image { w, h, .. } = o {
|
||||
v.push((*w, *h));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let in_cell = |cols: u32| {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": cols}));
|
||||
assert!(s.sel.focus.path.depth() > 0, "the caret is in the first cell");
|
||||
s
|
||||
};
|
||||
// Insert › Pictures and Paste in a cell of a three-column table.
|
||||
let cell = text_w / 3.0;
|
||||
let mut s = in_cell(3);
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = in_cell(3);
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let got = widths(s);
|
||||
let [(w, h)] = got.as_slice() else { panic!("{how}: {got:?}") };
|
||||
assert!(*w <= cell && *w > cell - 20.0, "{how}: {w} fits the cell's text area ({cell} less its margins)");
|
||||
assert!((h * 5.0 - w).abs() < 0.1, "{how}: proportions kept: {w} × {h}");
|
||||
}
|
||||
// A table in that cell: its own narrower cell.
|
||||
let mut s = in_cell(2);
|
||||
let outer = s.room_at(&s.sel.focus.clone());
|
||||
// (A table inserted in a cell takes the page's text width for its columns, so four columns
|
||||
// make its cells narrower than the outer one.)
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": 4}));
|
||||
assert!(s.sel.focus.path.depth() > 1, "the caret is in the nested cell");
|
||||
let nested = s.room_at(&s.sel.focus.clone());
|
||||
assert!(nested < outer - 50.0, "the nested cell ({nested}) is narrower than the outer one ({outer})");
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - nested).abs() < 0.5 && w <= text_w / 4.0, "{w} fits the nested cell ({nested})");
|
||||
// Two text columns: one column's width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "layout.columns", json!({"count": 2}));
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - column).abs() < 0.5, "{w} fits the column ({column})");
|
||||
// Body text keeps the full text width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
assert!((widths(&s)[0].0 - text_w).abs() < 0.5);
|
||||
}
|
||||
|
||||
/// #5428 review: a page can hold several continuous sections; a picture goes by the section of the
|
||||
/// position, not of the page's first one (two columns, then a continuous single-column section).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_after_a_continuous_break_fits_its_own_section() {
|
||||
let sect = |cols: &str, kind: &str| format!(r#"<w:sectPr>{kind}<w:pgSz w:w="11906" w:h="16838"/><w:cols {cols} w:space="708"/></w:sectPr>"#);
|
||||
let body = [
|
||||
"<w:p><w:r><w:t>one</w:t></w:r></w:p>".to_string(),
|
||||
format!("<w:p><w:pPr>{}</w:pPr></w:p>", sect(r#"w:num="2""#, "")),
|
||||
"<w:p><w:r><w:t>two</w:t></w:r></w:p>".to_string(),
|
||||
sect("", r#"<w:type w:val="continuous"/>"#),
|
||||
]
|
||||
.concat();
|
||||
let mut s = Session::new(wordcraft_docx::read(&docx_with_styles(&body, "")).unwrap());
|
||||
let last = s.doc.body.len() - 1;
|
||||
s.sel = crate::Selection::caret(Pos::body(last, 0));
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
assert!(room > column + 50.0, "{room} is the single column's width, not the earlier two columns' ({column})");
|
||||
}
|
||||
|
||||
/// #5428 review: Web Layout and Read Mode reflow the text to the window, but a picture put in
|
||||
/// there is fitted to the page's text width, as in Print Layout: the size stays in the document.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_put_in_in_web_layout_fits_the_page_not_the_window() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let width = |s: &Session| {
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
|
||||
wordcraft_doc::InlineObject::Image { w, .. } => Some(*w),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let web = || {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "view.webLayout", json!({}));
|
||||
// A narrow window, or a high zoom.
|
||||
s.view.web_width = 350.0;
|
||||
assert!(s.layout().pages[0].w < text_w, "the window is narrower than the page's text");
|
||||
s
|
||||
};
|
||||
let mut s = web();
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = web();
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let w = width(s).unwrap();
|
||||
assert!((w - text_w).abs() < 0.5, "{how}: {w} fits the page's text width ({text_w})");
|
||||
}
|
||||
// Read Mode's narrow pages don't set it either.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "Read"}));
|
||||
run(&mut s, "view.readMode", json!({}));
|
||||
s.view.read_width = 240.0;
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
assert!((room - text_w).abs() < 0.5, "Read Mode: {room} is the page's text width ({text_w})");
|
||||
}
|
||||
|
||||
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
|
||||
/// formats' are; one with a stated size keeps it, in line too.
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::options::DisplayOptions;
|
||||
use super::paint::{Paint, paint_for};
|
||||
use super::{BezPath, Document, Draw, FaceRef, Graphic, GraphicItem, GraphicKind, InlineObject, PathSeg, Rect, Rgb, ShapeKind, Spin, TextAlign};
|
||||
use wordcraft_doc::connector::ArrowStyle;
|
||||
use wordcraft_doc::connector::{ArrowStyle, LineCap};
|
||||
|
||||
/// The draws of a chart or diagram's items inside `rect` (page coordinates). The items were built
|
||||
/// for the size `g.w` × `g.h` (0: `rect`'s own size), so they are scaled to `rect`; strokes and text
|
||||
@@ -294,9 +294,14 @@ fn line_draws(
|
||||
out: &mut Vec<Draw>,
|
||||
) {
|
||||
use wordcraft_doc::connector::{connector_segs, end_direction};
|
||||
let start_dir = end_direction(kind, rect.w, rect.h, false);
|
||||
let end_dir = end_direction(kind, rect.w, rect.h, true);
|
||||
// An arrowed end stops inside its head, which the stroke would otherwise stick out of.
|
||||
let inset = |on: bool, style| if on && stroke.is_some() { arrow_inset(stroke_width, style, extra.cap) } else { 0.0 };
|
||||
let ends = [(inset(extra.arrow_start, extra.start_style), start_dir), (inset(extra.arrow_end, extra.end_style), end_dir)];
|
||||
match connector_segs(kind, rect.w, rect.h) {
|
||||
Some(segs) => {
|
||||
let segs = segs
|
||||
let mut segs: Vec<PathSeg> = segs
|
||||
.into_iter()
|
||||
.map(|s| match s {
|
||||
PathSeg::Move(x, y) => PathSeg::Move(rect.x + x, rect.y + y),
|
||||
@@ -305,32 +310,92 @@ fn line_draws(
|
||||
PathSeg::Close => PathSeg::Close,
|
||||
})
|
||||
.collect();
|
||||
shorten_ends(&mut segs, ends);
|
||||
let width = path_stroke_width(stroke_width);
|
||||
out.push(Draw::Path { segs, fill: None, stroke, stroke_width: width, dash: extra.dash.pattern(width), cap: extra.cap });
|
||||
}
|
||||
None => out.push(Draw::Shape {
|
||||
rect,
|
||||
kind,
|
||||
fill: None,
|
||||
stroke,
|
||||
stroke_width,
|
||||
effects,
|
||||
corner: None,
|
||||
dash: extra.dash.pattern(stroke_width),
|
||||
cap: extra.cap,
|
||||
}),
|
||||
None => {
|
||||
// A line's frame is its diagonal, top left to bottom right: shortened, it stays one.
|
||||
let mut segs = [PathSeg::Move(rect.x, rect.y), PathSeg::Line(rect.right(), rect.bottom())];
|
||||
shorten_ends(&mut segs, ends);
|
||||
let line = match segs {
|
||||
[PathSeg::Move(x0, y0), PathSeg::Line(x1, y1)] => Rect::new(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()),
|
||||
_ => rect,
|
||||
};
|
||||
out.push(Draw::Shape {
|
||||
rect: line,
|
||||
kind,
|
||||
fill: None,
|
||||
stroke,
|
||||
stroke_width,
|
||||
effects,
|
||||
corner: None,
|
||||
dash: extra.dash.pattern(stroke_width),
|
||||
cap: extra.cap,
|
||||
});
|
||||
}
|
||||
}
|
||||
let Some(color) = stroke else { return };
|
||||
// A line runs from the top-left corner to the bottom-right, as it is drawn (DrawingML's
|
||||
// `line`), and so do connectors; flips are the frame's turn.
|
||||
let (start, end) = ((rect.x, rect.y), (rect.right(), rect.bottom()));
|
||||
for (on, tip, at_end, style) in [(extra.arrow_start, start, false, extra.start_style), (extra.arrow_end, end, true, extra.end_style)] {
|
||||
for (on, tip, dir, style) in [(extra.arrow_start, start, start_dir, extra.start_style), (extra.arrow_end, end, end_dir, extra.end_style)] {
|
||||
if on {
|
||||
out.push(arrowhead(tip, end_direction(kind, rect.w, rect.h, at_end), stroke_width, style, color));
|
||||
out.push(arrowhead(tip, dir, stroke_width, style, color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far short of an arrowhead's tip a line `stroke_width` wide with `cap` ends stops, so that
|
||||
/// none of its stroke shows outside the head (#6767): where the head is as wide as the stroke,
|
||||
/// plus what the cap reaches past the end. A head is at least twice as wide as its line, so this
|
||||
/// is inside the head; never past its base.
|
||||
fn arrow_inset(stroke_width: f32, style: ArrowStyle, cap: LineCap) -> f32 {
|
||||
let width = path_stroke_width(stroke_width);
|
||||
let (len, wide) = style.dims(stroke_width);
|
||||
let reach = if cap == LineCap::Flat { 0.0 } else { width / 2.0 };
|
||||
(len * width / wide.max(f32::EPSILON) + reach).clamp(0.0, len)
|
||||
}
|
||||
|
||||
/// Draw the path `segs` (a line's or connector's, from its start to its end) short of its ends:
|
||||
/// each end by its distance, back against its unit direction (where its arrowhead points). An end
|
||||
/// moves at most half way to its neighbouring point, so the path keeps its shape, and a curve its
|
||||
/// direction at the end. The two ends of a single straight segment share its length in proportion
|
||||
/// to their distances instead, so an end without an arrowhead leaves its share to the other.
|
||||
fn shorten_ends(segs: &mut [PathSeg], [(start, start_dir), (end, end_dir)]: [(f32, (f32, f32)); 2]) {
|
||||
let distance = |by: f32| if by.is_finite() { by.max(0.0) } else { 0.0 };
|
||||
let (start, end) = (distance(start), distance(end));
|
||||
let share = |by: f32| match segs {
|
||||
[PathSeg::Move(..), PathSeg::Line(..)] => by / (start + end).max(f32::EPSILON),
|
||||
_ => 0.5,
|
||||
};
|
||||
let (start_share, end_share) = (share(start), share(end));
|
||||
let pull = |(x, y): (f32, f32), toward: Option<(f32, f32)>, by: f32, share: f32, (dx, dy): (f32, f32)| {
|
||||
let room = toward.map_or(0.0, |(tx, ty)| (tx - x).hypot(ty - y) * share);
|
||||
let by = if room.is_finite() { by.min(room) } else { 0.0 };
|
||||
(x - dx * by, y - dy * by)
|
||||
};
|
||||
// The points next to each end, before either moves.
|
||||
let after_first = match segs.get(1) {
|
||||
Some(PathSeg::Line(x, y) | PathSeg::Cubic(x, y, ..)) => Some((*x, *y)),
|
||||
_ => None,
|
||||
};
|
||||
let before_last = match segs.len().checked_sub(1).map(|i| segs.split_at(i)) {
|
||||
Some((_, [PathSeg::Cubic(_, _, x, y, ..)])) => Some((*x, *y)),
|
||||
Some((head, [PathSeg::Line(..)])) => match head.last() {
|
||||
Some(PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) => Some((*x, *y)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
if let Some(PathSeg::Move(x, y)) = segs.first_mut() {
|
||||
(*x, *y) = pull((*x, *y), after_first, start, start_share, start_dir);
|
||||
}
|
||||
if let Some(PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) = segs.last_mut() {
|
||||
(*x, *y) = pull((*x, *y), before_last, end, end_share, end_dir);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn seg_path(segs: &[PathSeg]) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
for s in segs {
|
||||
|
||||
@@ -488,4 +488,60 @@ mod tests {
|
||||
}
|
||||
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
|
||||
}
|
||||
|
||||
/// #5847: shrink_line_spaces is a no-op when there are no spaces after the line's last tab,
|
||||
/// guarding against division by zero, negative room, or shifting pre-tab clusters.
|
||||
#[test]
|
||||
fn shrink_line_spaces_with_no_spaces_after_last_tab_is_noop() {
|
||||
crate::test_fonts();
|
||||
let chr = CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let fields = FieldCtx::default();
|
||||
let env = ParaEnv {
|
||||
doc: &d,
|
||||
fields: &fields,
|
||||
width: 468.0,
|
||||
label: None,
|
||||
show_hidden: false,
|
||||
hide_deleted: Default::default(),
|
||||
table: None,
|
||||
proofing: None,
|
||||
typing_word: None,
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
eq_number: 0,
|
||||
numeral: Default::default(),
|
||||
read_line_spacing: None,
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
let mut p = Paragraph::with_text("n n n n\tWordWithoutSpaces", chr);
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
tabs: Some(vec![TabStop { pos: 150.0, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
let mut pl = layout_para(&p, &env);
|
||||
let mark_style = pl.clusters[0].style;
|
||||
break_lines(&mut pl, &env, mark_style, None);
|
||||
let c0 = pl.lines[0].c0;
|
||||
let c1 = pl.lines[0].c1;
|
||||
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab)).unwrap();
|
||||
let from = last_tab + 1;
|
||||
|
||||
let spaces_after = (from..c1).filter(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Space)).count();
|
||||
assert_eq!(spaces_after, 0);
|
||||
|
||||
let orig_xs = pl.lines[0].xs.clone();
|
||||
let content_end = *orig_xs.last().unwrap();
|
||||
|
||||
for slack in [-20.0, 0.0, f32::NEG_INFINITY] {
|
||||
let mut xs = orig_xs.clone();
|
||||
justify::shrink_line_spaces(&pl, &mut xs, (c0, from), c1, content_end, slack);
|
||||
assert_eq!(xs, orig_xs, "slack {slack} with 0 post-tab spaces must not shift any cluster");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,23 +22,29 @@ pub(super) fn space_room(spaces: f32, word: f32) -> f32 {
|
||||
(spaces * MAX_SPACE_SHRINK).min(word.max(0.0) * MAX_WORD_OVERRUN)
|
||||
}
|
||||
|
||||
/// Take `-slack` (an overflow) out of the line's inner spaces, in proportion to their widths and
|
||||
/// never more than [`MAX_SPACE_SHRINK`] of them. Trailing spaces hang and are left alone.
|
||||
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], c0: usize, c1: usize, content_end: f32, slack: f32) {
|
||||
let spaces: Vec<(usize, f32)> = (c0..c1)
|
||||
/// Take `-slack` (an overflow) out of the line's inner spaces from `from` on (after the line's last
|
||||
/// left/default tab), in proportion to their widths and never more than [`MAX_SPACE_SHRINK`] of them.
|
||||
/// Trailing spaces hang and are left alone.
|
||||
///
|
||||
/// `c0` is the first cluster on the line, and `from` is where space shrinking begins (the cluster
|
||||
/// following the line's last tab, or `c0` when there are no tabs on the line). `c1` is the end of
|
||||
/// the line's cluster range.
|
||||
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], (c0, from): (usize, usize), c1: usize, content_end: f32, slack: f32) {
|
||||
let from = from.max(c0);
|
||||
let spaces: Vec<(usize, f32)> = (from..c1)
|
||||
.filter_map(|k| {
|
||||
let c = pl.clusters.get(k).filter(|c| c.kind == ClKind::Space)?;
|
||||
(xs.get(k - c0).copied().unwrap_or(f32::MAX) < content_end - 0.01).then_some((k, c.adv))
|
||||
})
|
||||
.collect();
|
||||
let total: f32 = spaces.iter().map(|s| s.1).sum();
|
||||
if total <= 0.0 || !slack.is_finite() {
|
||||
if !total.is_finite() || total <= 0.0 || !slack.is_finite() {
|
||||
return;
|
||||
}
|
||||
let ratio = (-slack / total).clamp(0.0, MAX_SPACE_SHRINK);
|
||||
let mut take = 0.0;
|
||||
let mut next = spaces.iter().peekable();
|
||||
for k in c0..c1 {
|
||||
for k in from..c1 {
|
||||
if let Some(v) = xs.get_mut(k - c0) {
|
||||
*v -= take;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ struct Breaker<'e> {
|
||||
/// Where default tab stops are counted from (see [`next_tab`]).
|
||||
tab_origin: f32,
|
||||
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
|
||||
/// spaces (`space_room`); never on lines with tabs.
|
||||
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
|
||||
shrink_spaces: bool,
|
||||
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
|
||||
/// unnumbered paragraph: a row starts right after a floating object before the indent.
|
||||
@@ -100,9 +100,13 @@ struct Scan {
|
||||
pending_tab: Option<(usize, TabStop, f32)>,
|
||||
/// The text after a pending decimal tab looked at so far for its '.'.
|
||||
decimal: Option<DecimalScan>,
|
||||
/// The width of the spaces so far on this line.
|
||||
/// The width of the spaces so far on this line, after its last tab.
|
||||
space_w: f32,
|
||||
has_tab: bool,
|
||||
/// Whether spaces after the last tab so far may shrink (true initially and after left/default
|
||||
/// tabs; false after right, center, or decimal tabs whose anchors use unshrunk widths).
|
||||
shrink_tab: bool,
|
||||
/// Tab cluster indices on this line whose alignment is not `TabAlign::Left`.
|
||||
non_left_tabs: Vec<usize>,
|
||||
/// The first word doesn't fit a span narrowed by a floating object: it moves on whole.
|
||||
skip: bool,
|
||||
}
|
||||
@@ -306,7 +310,8 @@ impl<'e> Breaker<'e> {
|
||||
pending_tab: None,
|
||||
decimal: None,
|
||||
space_w: 0.0,
|
||||
has_tab: false,
|
||||
shrink_tab: true,
|
||||
non_left_tabs: Vec::new(),
|
||||
skip: false,
|
||||
}
|
||||
}
|
||||
@@ -603,10 +608,12 @@ impl<'e> Breaker<'e> {
|
||||
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
|
||||
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
|
||||
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
|
||||
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
|
||||
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
|
||||
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too,
|
||||
// unless its last tab is a non-left tab whose anchor was resolved with unshrunk widths.
|
||||
let can_shrink_tab = last_tab.is_none_or(|k| !sc.non_left_tabs.contains(&k));
|
||||
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && can_shrink_tab;
|
||||
if shrink {
|
||||
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
|
||||
shrink_line_spaces(pl, &mut sc.xs, (c0, align_from), c1, content_end, slack);
|
||||
} else if justify && slack > 0.0 {
|
||||
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
|
||||
}
|
||||
@@ -834,7 +841,8 @@ impl Scan {
|
||||
/// A tab: its stop, and the room to it. True when the line ends before it.
|
||||
fn tab(&mut self, bk: &mut Breaker, pl: &mut ParaLayout) -> bool {
|
||||
let j = self.j;
|
||||
self.has_tab = true;
|
||||
// Only the spaces after a line's last tab shrink (measured in Word for Mac).
|
||||
self.space_w = 0.0;
|
||||
resolve_tab(pl, &mut self.pending_tab, &mut self.xs, self.c0, self.x, &mut self.x);
|
||||
let rp = &bk.rp;
|
||||
let ptab = pl.ptabs.iter().find(|t| t.0 == j).map(|&(_, a, b, l)| ptab_stop(a, b, l, bk.width, (rp.indent_left, rp.indent_right)));
|
||||
@@ -877,6 +885,10 @@ impl Scan {
|
||||
/// decimal tab).
|
||||
fn place_tab(&mut self, pl: &mut ParaLayout, stop: TabStop) {
|
||||
let j = self.j;
|
||||
self.shrink_tab = stop.align == TabAlign::Left;
|
||||
if !self.shrink_tab {
|
||||
self.non_left_tabs.push(j);
|
||||
}
|
||||
match stop.align {
|
||||
TabAlign::Left | TabAlign::Bar | TabAlign::Clear => {
|
||||
let w = (stop.pos - self.x).max(0.0);
|
||||
@@ -917,7 +929,7 @@ impl Scan {
|
||||
// each segment's font, glyphs and position for painting.
|
||||
let advance = pl.atomic_advance(j);
|
||||
let absorbs = self.absorbs(pl, advance);
|
||||
let shrink = if bk.shrink_spaces && !self.has_tab {
|
||||
let shrink = if bk.shrink_spaces && self.shrink_tab {
|
||||
space_room(self.space_w, self.x + advance - pl.auto_space_after(j) - self.word_from)
|
||||
} else {
|
||||
0.0
|
||||
@@ -1057,6 +1069,7 @@ impl Scan {
|
||||
self.last_break = Some(tj - 1);
|
||||
self.pending_tab = None;
|
||||
self.leaders.retain(|(k, _)| *k < tj);
|
||||
self.non_left_tabs.retain(|&k| k < tj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+560
-1
@@ -4738,7 +4738,147 @@ fn a_lines_arrowheads_sit_at_its_ends() {
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(tips, [(rect.x, rect.y), (rect.right(), rect.bottom())]);
|
||||
let [(x0, y0), (x1, y1)] = tips[..] else { panic!("two arrowheads: {tips:?}") };
|
||||
assert!((x1 - x0 - 60.0).abs() < 0.01 && (y1 - y0 - 40.0).abs() < 0.01, "tips at the frame's corners: {tips:?}");
|
||||
// The line, drawn short of its arrowed ends (#6767), runs along the same diagonal.
|
||||
assert!(rect.x > x0 && rect.y > y0 && rect.right() < x1 && rect.bottom() < y1, "{rect:?} between {tips:?}");
|
||||
assert!(((rect.x - x0) / 60.0 - (rect.y - y0) / 40.0).abs() < 0.001, "{rect:?} on the diagonal from {tips:?}");
|
||||
assert!(((x1 - rect.right()) / 60.0 - (y1 - rect.bottom()) / 40.0).abs() < 0.001, "{rect:?} on the diagonal to {tips:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thick_lines_stroke_ends_inside_its_arrowheads() {
|
||||
// #6767: the stroke stopped at each arrowhead's tip, so a thick line's body and cap stuck out
|
||||
// of the narrow head. Each arrowed end now stops where the head is as wide as the stroke (and
|
||||
// its cap's reach before that), for lines and every connector.
|
||||
use wordcraft_doc::connector::{LineCap, ShapeExtra};
|
||||
use wordcraft_doc::para::{Float, ShapeKind};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
|
||||
let width = 6.0;
|
||||
let kinds = [ShapeKind::Line, ShapeKind::StraightConnector, ShapeKind::ElbowConnector, ShapeKind::CurvedConnector];
|
||||
for kind in kinds {
|
||||
for cap in [LineCap::Flat, LineCap::Square, LineCap::Round] {
|
||||
let shape = InlineObject::Shape {
|
||||
kind,
|
||||
w: 120.0,
|
||||
h: 60.0,
|
||||
fill: None,
|
||||
stroke: Some(Rgb::BLACK),
|
||||
stroke_width: width,
|
||||
float: Float::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: ShapeExtra { arrow_start: true, arrow_end: true, cap, ..Default::default() },
|
||||
};
|
||||
let (ends, heads, draws) = line_ends_and_heads(shape);
|
||||
assert_eq!((ends.len(), heads.len()), (2, 2), "{kind:?} {cap:?}: {draws:?}");
|
||||
for (end, head) in ends.iter().zip(&heads) {
|
||||
for corner in stroke_end_corners(*end, *head, width, cap) {
|
||||
assert!(in_triangle(corner, *head), "{kind:?} {cap:?}: stroke corner {corner:?} outside the head {head:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_lines_lone_arrowhead_takes_the_room_its_other_end_does_not_need() {
|
||||
// #6767: an arrowed end moved at most half way along a straight line, even when the other end
|
||||
// had no arrowhead and stayed put, so a short thick line's stroke still stuck out of its head.
|
||||
use wordcraft_doc::connector::{LineCap, ShapeExtra};
|
||||
use wordcraft_doc::para::{Float, ShapeKind};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
|
||||
let width = 6.0;
|
||||
// Each is shorter than twice its inset (6 pt flat, 9 pt with the cap's reach) but no shorter
|
||||
// than one inset, so the head can cover the stroke: 8 pt and 10 pt diagonals.
|
||||
for (cap, (w, h)) in [(LineCap::Flat, (6.4, 4.8)), (LineCap::Square, (8.0, 6.0)), (LineCap::Round, (8.0, 6.0))] {
|
||||
for kind in [ShapeKind::Line, ShapeKind::StraightConnector] {
|
||||
for at_start in [true, false] {
|
||||
let shape = InlineObject::Shape {
|
||||
kind,
|
||||
w,
|
||||
h,
|
||||
fill: None,
|
||||
stroke: Some(Rgb::BLACK),
|
||||
stroke_width: width,
|
||||
float: Float::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: ShapeExtra { arrow_start: at_start, arrow_end: !at_start, cap, ..Default::default() },
|
||||
};
|
||||
let (ends, heads, draws) = line_ends_and_heads(shape);
|
||||
let (&[start, end], &[head]) = (&ends[..], &heads[..]) else { panic!("{kind:?} {cap:?}: {draws:?}") };
|
||||
let tip = head[0];
|
||||
let (near, far) = if at_start { (start, end) } else { (end, start) };
|
||||
// The end without an arrowhead stays where it was.
|
||||
let other = if at_start { (tip.0 + w, tip.1 + h) } else { (tip.0 - w, tip.1 - h) };
|
||||
assert!((far.0 - other.0).abs() < 0.01 && (far.1 - other.1).abs() < 0.01, "{kind:?} {cap:?}: {far:?} moved from {other:?}");
|
||||
for corner in stroke_end_corners(near, head, width, cap) {
|
||||
assert!(in_triangle(corner, head), "{kind:?} {cap:?} start={at_start}: stroke corner {corner:?} outside the head {head:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ends of the stroked line or connector `shape` draws, from its start to its end, its
|
||||
/// arrowheads (each tip first), and all its draws.
|
||||
fn line_ends_and_heads(shape: InlineObject) -> (Vec<(f32, f32)>, Vec<[(f32, f32); 3]>, Vec<display::Draw>) {
|
||||
use wordcraft_doc::graphic::PathSeg;
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
|
||||
let mut doc = Document::from_text("Scan");
|
||||
doc.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
|
||||
let draws = flat(display::page_display(&doc, &lay(&doc).pages[0], &Default::default()));
|
||||
let mut ends = Vec::new();
|
||||
let mut heads = Vec::new();
|
||||
for d in &draws {
|
||||
match d {
|
||||
display::Draw::Shape { rect, kind: ShapeKind::Line, .. } => ends.extend([(rect.x, rect.y), (rect.right(), rect.bottom())]),
|
||||
display::Draw::Path { fill: None, stroke: Some(_), segs, .. } => {
|
||||
let point = |s: &PathSeg| match *s {
|
||||
PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y) => Some((x, y)),
|
||||
PathSeg::Close => None,
|
||||
};
|
||||
ends.extend(segs.first().and_then(point));
|
||||
ends.extend(segs.last().and_then(point));
|
||||
}
|
||||
display::Draw::Path { fill: Some(_), segs, .. } => {
|
||||
if let [PathSeg::Move(tx, ty), PathSeg::Line(ax, ay), PathSeg::Line(bx, by), PathSeg::Close] = segs[..] {
|
||||
heads.push([(tx, ty), (ax, ay), (bx, by)]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(ends, heads, draws)
|
||||
}
|
||||
|
||||
/// The corners of a `width` stroke's `end` under arrowhead `head`, its `cap` included (a round
|
||||
/// cap lies inside them).
|
||||
fn stroke_end_corners(end: (f32, f32), head: [(f32, f32); 3], width: f32, cap: wordcraft_doc::connector::LineCap) -> [(f32, f32); 2] {
|
||||
let [tip, a, b] = head;
|
||||
let base = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
|
||||
let len = (tip.0 - base.0).hypot(tip.1 - base.1);
|
||||
// The head's direction, and across it.
|
||||
let (dx, dy) = ((tip.0 - base.0) / len, (tip.1 - base.1) / len);
|
||||
let (nx, ny) = (-dy, dx);
|
||||
let reach = if cap == wordcraft_doc::connector::LineCap::Flat { 0.0 } else { width / 2.0 };
|
||||
[-1.0, 1.0].map(|side| (end.0 + dx * reach + nx * side * width / 2.0, end.1 + dy * reach + ny * side * width / 2.0))
|
||||
}
|
||||
|
||||
/// Whether `p` lies inside (or within 0.01 pt of) triangle `t`.
|
||||
fn in_triangle(p: (f32, f32), t: [(f32, f32); 3]) -> bool {
|
||||
let edge = |(ax, ay): (f32, f32), (bx, by): (f32, f32)| {
|
||||
let len = (bx - ax).hypot(by - ay);
|
||||
((bx - ax) * (p.1 - ay) - (by - ay) * (p.0 - ax)) / len
|
||||
};
|
||||
let sides = [edge(t[0], t[1]), edge(t[1], t[2]), edge(t[2], t[0])];
|
||||
sides.iter().all(|s| *s >= -0.01) || sides.iter().all(|s| *s <= 0.01)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -7385,6 +7525,425 @@ fn justified_spaces_shrink_a_quarter_at_most_and_by_the_word() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Measured in Word for Mac (compatibility mode 15, synthetic justified paragraphs that start
|
||||
/// with a label and a tab, or with words and then a left tab): a line with a tab shrinks its
|
||||
/// spaces too, but only those after its last tab. WordCraft never shrank a line with a tab, so a
|
||||
/// numbered paragraph's first line wrapped a word earlier than Word's (#4845, #5847).
|
||||
#[test]
|
||||
fn justified_line_with_a_tab_shrinks_only_the_spaces_after_it() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let (lead, n) = ("n n n n n n n n n n n n", 12);
|
||||
let tab_at = 200.0;
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
indent_right: Some(right),
|
||||
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
// Words after the tab on the first line.
|
||||
let after_tab = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
// Room from the n spaces after the tab alone; the eleven before it would allow more.
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let all_room = (0.25 * (n + 11) as f32 * sw).min(0.355 * (w + sw));
|
||||
assert!(all_room > room + 0.5, "the test needs the spaces before the tab to matter: {room} vs {all_room}");
|
||||
let text = format!("{lead}\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
|
||||
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
|
||||
let d = para(&text, full - width(overrun));
|
||||
assert_eq!(after_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
|
||||
}
|
||||
|
||||
// Verify rendered positions: spaces after the tab shrink in the allowed-overrun case,
|
||||
// while positions before the tab remain unchanged.
|
||||
let shrunk_doc = para(&text, full - width(room - 0.1));
|
||||
let unconstrained_doc = para(&text, 0.0);
|
||||
let l_shrunk = lay(&shrunk_doc);
|
||||
let l_unconstrained = lay(&unconstrained_doc);
|
||||
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let pl_unconstrained =
|
||||
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
|
||||
// Characters in `lead` and the tab's start position must have identical positions.
|
||||
for k in 0..=lead.len() {
|
||||
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before tab must not move when spaces after tab shrink");
|
||||
}
|
||||
// Text after the tab starts at tab_at.
|
||||
assert!((pl_shrunk.x_of(0, lead.len() + 1).unwrap() - tab_at).abs() < 0.01, "tab position");
|
||||
// Text after the tab is shifted left compared to its natural (un-shrunk) positions:
|
||||
// for each word k after the tab on line 0, natural position is tab_at + k * (w + sw).
|
||||
let natural_x = |k: usize| tab_at + k as f32 * (w + sw);
|
||||
for k in 1..=n {
|
||||
let char_pos = lead.len() + 1 + k * (word.len() + 1);
|
||||
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
|
||||
assert!(x < natural_x(k), "word {k} after tab at {x} must be shifted left from natural {}", natural_x(k));
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: a justified line with multiple tabs shrinks spaces only after its last tab.
|
||||
/// Spaces before the first tab and between tabs retain their natural width and positions,
|
||||
/// and only spaces after the last tab count toward space_room.
|
||||
#[test]
|
||||
fn justified_line_with_multiple_tabs_shrinks_only_spaces_after_last_tab() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let (lead1, lead2, n) = ("n n n n n n", "n n n n n n", 12);
|
||||
let tab1_at = 120.0;
|
||||
let tab2_at = 240.0;
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
indent_right: Some(right),
|
||||
tabs: Some(vec![
|
||||
TabStop { pos: tab1_at, align: TabAlign::Left, leader: Default::default() },
|
||||
TabStop { pos: tab2_at, align: TabAlign::Left, leader: Default::default() },
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
// Words after the second tab on the first line.
|
||||
let after_second_tab = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(2).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
// Room from the n spaces after the second tab alone; spaces before tab 1 or between tabs would allow more.
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let all_room = (0.25 * (n + 10) as f32 * sw).min(0.355 * (w + sw));
|
||||
assert!(all_room > room + 0.5, "the test needs the spaces before the last tab to matter: {room} vs {all_room}");
|
||||
let text = format!("{lead1}\t{lead2}\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = |overrun: f32| tab2_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
|
||||
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
|
||||
let d = para(&text, full - width(overrun));
|
||||
assert_eq!(after_second_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
|
||||
}
|
||||
|
||||
// Verify rendered positions: spaces after the last tab shrink in the allowed-overrun case,
|
||||
// while positions before tab 1 and between tabs remain completely unchanged.
|
||||
let shrunk_doc = para(&text, full - width(room - 0.1));
|
||||
let unconstrained_doc = para(&text, 0.0);
|
||||
let l_shrunk = lay(&shrunk_doc);
|
||||
let l_unconstrained = lay(&unconstrained_doc);
|
||||
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let pl_unconstrained =
|
||||
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
|
||||
// Characters in `lead1`, tab 1, and `lead2` up to the second tab must have identical positions.
|
||||
let pre_last_tab_len = lead1.len() + 1 + lead2.len();
|
||||
for k in 0..=pre_last_tab_len {
|
||||
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before last tab must not move when spaces after last tab shrink");
|
||||
}
|
||||
// Text after the second tab starts at tab2_at.
|
||||
assert!((pl_shrunk.x_of(0, pre_last_tab_len + 1).unwrap() - tab2_at).abs() < 0.01, "second tab position");
|
||||
// Text after the second tab is shifted left compared to its natural (un-shrunk) positions:
|
||||
let natural_x = |k: usize| tab2_at + k as f32 * (w + sw);
|
||||
for k in 1..=n {
|
||||
let char_pos = pre_last_tab_len + 1 + k * (word.len() + 1);
|
||||
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
|
||||
assert!(x < natural_x(k), "word {k} after last tab at {x} must be shifted left from natural {}", natural_x(k));
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: a tabbed line with no spaces after its last tab has zero shrink room.
|
||||
/// Space shrinking is a no-op, guarding against division by zero, negative room,
|
||||
/// or shifting pre-tab clusters when there are no spaces to shrink after the tab.
|
||||
#[test]
|
||||
fn justified_line_with_tab_and_no_spaces_after_it_does_not_shrink() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let lead = "n n n n n n n n";
|
||||
let word = "OverlongWordWithoutAnySpace";
|
||||
let tab_at = 200.0;
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
indent_right: Some(right),
|
||||
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
|
||||
let probe = para(word, 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let word_w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
|
||||
let text = format!("{lead}\t{word}");
|
||||
let full = probe.last_section.text_width();
|
||||
// Constrain the line so that `word` overruns the right edge by 2.0 pt.
|
||||
// Because there are no spaces after the tab, shrink room is 0 and the word
|
||||
// must wrap to line 1 rather than shrinking onto line 0.
|
||||
let tight_doc = para(&text, full - (tab_at + word_w - 2.0));
|
||||
let l_tight = lay(&tight_doc);
|
||||
let pl_tight = l_tight.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
assert_eq!(pl_tight.lines.len(), 2, "word with no spaces after tab must wrap when it overruns the line");
|
||||
|
||||
// When the word fits within the line, characters before the tab and the word after the tab
|
||||
// remain at their exact natural positions (no pre-tab shift, no shrink).
|
||||
let fit_doc = para(&text, full - (tab_at + word_w + 50.0));
|
||||
let unconstrained_doc = para(&text, 0.0);
|
||||
let l_fit = lay(&fit_doc);
|
||||
let l_unconstrained = lay(&unconstrained_doc);
|
||||
let pl_fit = l_fit.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let pl_unconstrained =
|
||||
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
|
||||
for k in 0..=text.len() {
|
||||
assert_eq!(
|
||||
pl_fit.x_of(0, k),
|
||||
pl_unconstrained.x_of(0, k),
|
||||
"char {k} position must be unchanged when there are no spaces to shrink after the tab"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: justified paragraphs starting with a tab shrink spaces on the first line in Word 2013+
|
||||
/// mode, fitting more text than legacy mode 14 just as non-tab lines do.
|
||||
#[test]
|
||||
fn justified_lines_with_tab_shrink_spaces_in_word_2013_mode() {
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let n = 12;
|
||||
let tab_at = 36.0; // default 0.5" tab stop
|
||||
let para = |text: &str, right: f32, mode: u32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = mode;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
let first = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0, 15);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let text = format!("\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = tab_at + (n + 1) as f32 * w + n as f32 * sw - (room - 0.1);
|
||||
|
||||
// Verify on the tabbed first line that mode 15 fits the extra word via space shrinking
|
||||
// while legacy mode 14 does not shrink spaces, wrapping the extra word to the next line.
|
||||
let modern_doc = para(&text, full - width, 15);
|
||||
let legacy_doc = para(&text, full - width, 14);
|
||||
assert_eq!(first(&modern_doc), n + 1, "mode 15 with leading tab fits extra word within allowable overrun");
|
||||
assert_eq!(first(&legacy_doc), n, "mode 14 with leading tab does not shrink spaces and wraps extra word");
|
||||
|
||||
// Multi-line justified paragraph with leading tab also fits more lines overall in mode 15.
|
||||
let text_full = format!("\t{}", "We tie the spend to a pipe and to the books, so it is in an ad hoc view of all of it. ".repeat(40));
|
||||
let (modern, ends) = justified_lines(&text_full, 15, Align::Justify);
|
||||
let (legacy, legacy_ends) = justified_lines(&text_full, 14, Align::Justify);
|
||||
assert!(modern < legacy, "mode 15 with leading tab fits more per line: {modern} vs {legacy} lines");
|
||||
for e in ends.iter().chain(&legacy_ends) {
|
||||
assert!(*e <= 540.0 + 0.05, "line ends past the right margin: {e}");
|
||||
}
|
||||
for e in &ends[..ends.len() - 1] {
|
||||
assert!((*e - 540.0).abs() < 0.05, "justified line ends at {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: leading tab on a justified line shrinks spaces after the tab when fitting words.
|
||||
#[test]
|
||||
fn justified_line_with_leading_tab_shrinks_spaces() {
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let n = 12;
|
||||
let tab_at = 36.0; // default 0.5" tab stop
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
let first = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let text = format!("\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
|
||||
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
|
||||
let d = para(&text, full - width(overrun));
|
||||
assert_eq!(first(&d), words, "leading tab overrun {overrun:.2} of {room:.2} allowed");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: fit-time and final space compression apply only after left/default tabs, not after
|
||||
/// right, center, or decimal tabs whose anchors are resolved with unshrunk widths.
|
||||
#[test]
|
||||
fn justified_line_with_non_left_tab_preserves_anchor_and_does_not_shrink() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let para = |text: &str, right: f32, tabs: Vec<TabStop>| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), tabs: Some(tabs), ..Default::default() };
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
let first_pl = |d: &Document| {
|
||||
let l = lay(d);
|
||||
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap()
|
||||
};
|
||||
|
||||
// 1. Right tab past the usable right edge: multiword run is absorbed against the stop and
|
||||
// must keep its final edge at the stop rather than shrinking left of it.
|
||||
let right_text = "lead\tnnnn nnnn nnnn";
|
||||
let right_stop = 280.0;
|
||||
let right_edge = 240.0;
|
||||
let right_tabs = vec![TabStop { pos: right_stop, align: TabAlign::Right, leader: Default::default() }];
|
||||
let right_unconstrained = para(right_text, 0.0, right_tabs.clone());
|
||||
let full = right_unconstrained.last_section.text_width();
|
||||
let pl_right_unconstrained = first_pl(&right_unconstrained);
|
||||
let pl_right = first_pl(¶(right_text, full - right_edge, right_tabs));
|
||||
assert_eq!(pl_right.lines.len(), 1, "absorbed multiword run after right tab stays on line 0");
|
||||
assert!(
|
||||
(pl_right.x_of(0, right_text.len()).unwrap() - right_stop).abs() < 0.01,
|
||||
"right-tabbed multiword run must remain aligned to stop {right_stop}, got {:?}",
|
||||
pl_right.x_of(0, right_text.len())
|
||||
);
|
||||
for k in 0..=right_text.len() {
|
||||
assert_eq!(pl_right.x_of(0, k), pl_right_unconstrained.x_of(0, k), "char {k} after right tab must not shrink");
|
||||
}
|
||||
|
||||
// 2. Decimal tab on an overfull line: spaces before the decimal point must not shrink and
|
||||
// pull the decimal point left of its stop.
|
||||
let dec_text = "\t12 34.56789";
|
||||
let dec_stop = 200.0;
|
||||
let dec_tabs = vec![TabStop { pos: dec_stop, align: TabAlign::Decimal, leader: Default::default() }];
|
||||
let dec_unconstrained = para(dec_text, 0.0, dec_tabs.clone());
|
||||
let pl_dec_unconstrained = first_pl(&dec_unconstrained);
|
||||
let dot_idx = dec_text.find('.').unwrap();
|
||||
let dec_end = pl_dec_unconstrained.x_of(0, dec_text.len()).unwrap();
|
||||
let pl_dec = first_pl(¶(dec_text, full - (dec_end - 5.0), dec_tabs));
|
||||
assert_eq!(pl_dec.lines.len(), 1, "decimal-tabbed run stays on line 0");
|
||||
assert_eq!(
|
||||
pl_dec.x_of(0, dot_idx),
|
||||
pl_dec_unconstrained.x_of(0, dot_idx),
|
||||
"decimal point must keep its unconstrained anchor on an overfull line"
|
||||
);
|
||||
for k in 0..=dec_text.len() {
|
||||
assert_eq!(pl_dec.x_of(0, k), pl_dec_unconstrained.x_of(0, k), "char {k} after decimal tab must not shrink");
|
||||
}
|
||||
|
||||
// 3. Center tab:
|
||||
// (a) Overfull center-tabbed line must not run final compression and shift off its stop.
|
||||
let center_overfull_text = "\taaaaaaaaaa bbbbbbbbbb";
|
||||
let center_overfull_stop = 250.0;
|
||||
let center_overfull_tabs = vec![TabStop { pos: center_overfull_stop, align: TabAlign::Center, leader: Default::default() }];
|
||||
let center_unconstrained = para(center_overfull_text, 0.0, center_overfull_tabs.clone());
|
||||
let pl_center_unconstrained = first_pl(¢er_unconstrained);
|
||||
let pl_center_overfull = first_pl(¶(center_overfull_text, full - 260.0, center_overfull_tabs));
|
||||
assert_eq!(pl_center_overfull.lines.len(), 1, "overfull center-tabbed line stays on line 0");
|
||||
let mid = (pl_center_overfull.x_of(0, 1).unwrap() + pl_center_overfull.x_of(0, center_overfull_text.len()).unwrap()) / 2.0;
|
||||
assert!((mid - center_overfull_stop).abs() < 0.01, "centered midpoint {mid} must stay at {center_overfull_stop}");
|
||||
for k in 0..=center_overfull_text.len() {
|
||||
assert_eq!(pl_center_overfull.x_of(0, k), pl_center_unconstrained.x_of(0, k), "char {k} after center tab must not shrink");
|
||||
}
|
||||
|
||||
// (b) Fit-time compression must not pull an overflowing trailing word onto a non-left-tabbed line.
|
||||
let probe = para("n n i", 0.0, Vec::new());
|
||||
let pl_probe = first_pl(&probe);
|
||||
let sw = pl_probe.x_of(0, 2).unwrap() - pl_probe.x_of(0, 1).unwrap();
|
||||
let w_i = pl_probe.x_of(0, 5).unwrap() - pl_probe.x_of(0, 4).unwrap();
|
||||
let prefix = "n ".repeat(12);
|
||||
let fit_text = format!("\t{prefix}i");
|
||||
let pl_prefix = first_pl(¶(&prefix, 0.0, Vec::new()));
|
||||
let w_pre = pl_prefix.x_of(0, prefix.len()).unwrap();
|
||||
let room = (0.25 * 12.0 * sw).min(0.355 * (sw + w_i));
|
||||
let fit_edge = w_pre + w_i - (room - 0.1);
|
||||
for align in [TabAlign::Right, TabAlign::Center, TabAlign::Decimal] {
|
||||
let pl_fit = first_pl(¶(&fit_text, full - fit_edge, vec![TabStop { pos: 3.0, align, leader: Default::default() }]));
|
||||
assert_eq!(pl_fit.lines.len(), 2, "{align:?} tab must not use fit-time space shrinking to accept 'i'");
|
||||
}
|
||||
|
||||
// 4. Right tab followed by a left tab: spaces after the final left tab still shrink while the
|
||||
// earlier right tab keeps its anchor.
|
||||
let word = "nnnn";
|
||||
let n = 12;
|
||||
let right_seg = "aa bb";
|
||||
let pl_w = first_pl(¶(&format!("{word} {word}"), 0.0, Vec::new()));
|
||||
let w = pl_w.x_of(0, word.len()).unwrap();
|
||||
let left_room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let mixed_text = format!("\t{right_seg}\t{}", vec![word; 3 * n].join(" "));
|
||||
let mixed_right_stop = 120.0;
|
||||
let mixed_left_stop = 160.0;
|
||||
let mixed_width = mixed_left_stop + (n + 1) as f32 * w + n as f32 * sw - (left_room - 0.1);
|
||||
let pl_mixed = first_pl(¶(
|
||||
&mixed_text,
|
||||
full - mixed_width,
|
||||
vec![
|
||||
TabStop { pos: mixed_right_stop, align: TabAlign::Right, leader: Default::default() },
|
||||
TabStop { pos: mixed_left_stop, align: TabAlign::Left, leader: Default::default() },
|
||||
],
|
||||
));
|
||||
assert!(
|
||||
(pl_mixed.x_of(0, 1 + right_seg.len()).unwrap() - mixed_right_stop).abs() < 0.01,
|
||||
"earlier right tab must keep its stop {mixed_right_stop}"
|
||||
);
|
||||
let first_line_words = mixed_text[pl_mixed.lines[0].start..pl_mixed.lines[0].stop].split('\t').nth(2).unwrap_or("").split_whitespace().count();
|
||||
assert_eq!(first_line_words, n + 1, "spaces after final left tab still shrink");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_shrinking_is_only_for_justified_text() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -319,6 +319,7 @@ impl WordApp {
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
if self.ctx.is_none() {
|
||||
theme::set_dark_text_curve(ctx);
|
||||
self.ctx = Some(ctx.clone());
|
||||
}
|
||||
updates_ui::tick(self, ctx);
|
||||
|
||||
@@ -330,6 +330,25 @@ fn a_desktop_paste_after_mod_shift_v_is_not_swallowed() {
|
||||
assert_eq!(body(h.state()), "source later");
|
||||
}
|
||||
|
||||
/// #5616: Mod+Shift+C (Copy Formatting), Shift released, Mod still held or released: Mod+C's
|
||||
/// chord isn't the paste's modifiers, so a subsequent Mod+V paste keeps HTML's formatting (bold).
|
||||
#[test]
|
||||
fn an_unrelated_keys_modifiers_do_not_steer_a_later_paste() {
|
||||
for mod_still_held in [false, true] {
|
||||
let mut h = alt_frame_app();
|
||||
offer(&h, bold_flavours("external"));
|
||||
let chord = Modifiers { shift: true, ..mod_held() };
|
||||
mods_frame(&mut h, chord, vec![key_event(Key::C, true, chord)]);
|
||||
let after = if mod_still_held { mod_held() } else { Modifiers::NONE };
|
||||
mods_frame(&mut h, after, vec![key_event(Key::C, false, after)]);
|
||||
let ctrl = mod_held();
|
||||
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
|
||||
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
|
||||
assert_eq!(body(h.state()), "external");
|
||||
assert!(is_bold(&mut h), "held={mod_still_held}: Mod+V keeps the HTML's bold");
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste Formatting on a chord the user bound pastes the copied formatting once.
|
||||
#[test]
|
||||
fn paste_formatting_on_another_key_pastes_the_copied_formatting() {
|
||||
@@ -422,6 +441,36 @@ fn mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing() {
|
||||
assert_eq!(body(h.state()), "", "picture file paste does not fall back to HTML text");
|
||||
}
|
||||
|
||||
/// #819: Alt+Q reaches Search/commands even when the canvas does not hold focus.
|
||||
#[test]
|
||||
fn alt_shortcuts_work_without_the_canvas_focused() {
|
||||
if cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Text")), Default::default());
|
||||
app.run("view.focus", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
if let Some(focused_id) = h.ctx.memory(|m| m.focused()) {
|
||||
h.ctx.memory_mut(|m| m.surrender_focus(focused_id));
|
||||
}
|
||||
crate::test_harness::frames(&mut h, 1);
|
||||
assert!(!h.state().canvas.focused(&h.ctx.clone()), "canvas is unfocused");
|
||||
|
||||
let alt = egui::Modifiers { alt: true, ..Default::default() };
|
||||
mods_frame(&mut h, alt, vec![key_event(Key::Q, true, alt)]);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
assert!(h.query_by_role(egui::accesskit::Role::Dialog).is_some(), "Alt+Q opens Search/commands with canvas unfocused");
|
||||
}
|
||||
|
||||
/// Alt held, keypad 0 2 3 3, Alt released: é (й on a Russian system) is typed, the digits
|
||||
/// aren't, and keytips stay off (#961). Linux sends each digit's text too; Windows may send the
|
||||
/// composed character.
|
||||
|
||||
@@ -155,13 +155,14 @@ fn markup_key(app: &WordApp) -> MarkupKey {
|
||||
|
||||
/// What the preview's layout is made from besides the document's text: the document id, the
|
||||
/// revision, Print Markup and Track Changes Options, the file name and path FILENAME fields show
|
||||
/// (#6282: Save As and Rename change them without an edit), and the font database generation the
|
||||
/// app has seen (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
|
||||
type LayoutKey = (u64, u64, MarkupKey, (String, String), u64);
|
||||
/// (#6282: Save As and Rename change them without an edit), the numeral mode (#6265: it changes
|
||||
/// the display without an edit or a revision), and the font database generation the app has seen
|
||||
/// (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
|
||||
type LayoutKey = (u64, u64, MarkupKey, wordcraft_layout::NumeralMode, (String, String), u64);
|
||||
|
||||
/// The [`LayoutKey`] now.
|
||||
fn layout_key(app: &WordApp) -> LayoutKey {
|
||||
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.resolved_filenames(), app.font_generation)
|
||||
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.view.numeral, app.session.resolved_filenames(), app.font_generation)
|
||||
}
|
||||
|
||||
/// The output layout, kept in `cache` while what it is made from ([`LayoutKey`]) is unchanged.
|
||||
@@ -496,6 +497,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Numeral display changes layout and pixels without changing the document revision
|
||||
/// (#6265): the preview must not reuse either cache.
|
||||
#[test]
|
||||
fn preview_refreshes_layout_and_texture_when_the_numeral_mode_changes() {
|
||||
let session = Session::new(wordcraft_doc::Document::from_text("2026 Report"));
|
||||
let mut app = WordApp::new(session, Services::default());
|
||||
let mut cache = None;
|
||||
let rev = app.session.rev();
|
||||
let mut previous = None;
|
||||
for mode in ["arabic", "hindi", "arabic"] {
|
||||
app.session.run("view.numeral", &json!({ "value": mode })).unwrap();
|
||||
let layout = layout_of(&app, &mut cache);
|
||||
assert!(Arc::ptr_eq(&layout, &layout_of(&app, &mut cache)), "unchanged layout is reused");
|
||||
let revision = preview::inputs(&app);
|
||||
assert_eq!(revision, preview::inputs(&app));
|
||||
if let Some((old_layout, old_revision)) = previous.take() {
|
||||
assert!(!Arc::ptr_eq(&layout, &old_layout));
|
||||
assert_ne!(revision, old_revision, "the sheet is drawn again");
|
||||
}
|
||||
previous = Some((layout, revision));
|
||||
assert_eq!(app.session.rev(), rev);
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-page synthetic document in a fresh preview.
|
||||
fn synthetic_app() -> (WordApp, egui::Context) {
|
||||
let session = Session::new(wordcraft_doc::Document::from_text("Synthetic print preview"));
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::ui::buttons::{Arrangement, Button, IconButton};
|
||||
use craft::ui::contract::{ActivateOn, BodyCx, CollectionEvent, Gap, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::primitives::{HAlign, TextRun};
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
@@ -286,17 +286,69 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The recent and common characters as a grid of six per row; a click inserts the character, remembers it and closes
|
||||
/// The characters the grid offers after the recent ones, with their Unicode names (UnicodeData.txt). No Unicode-names
|
||||
/// crate is installed, and the one on crates.io is under Unicode-DFS-2016, which the licence allowlist lacks.
|
||||
const DEFAULT_SYMBOLS: &[(char, &str)] = &[
|
||||
('\u{A9}', "COPYRIGHT SIGN"),
|
||||
('\u{AE}', "REGISTERED SIGN"),
|
||||
('\u{2122}', "TRADE MARK SIGN"),
|
||||
('\u{A7}', "SECTION SIGN"),
|
||||
('\u{B6}', "PILCROW SIGN"),
|
||||
('\u{20AC}', "EURO SIGN"),
|
||||
('\u{A3}', "POUND SIGN"),
|
||||
('\u{A5}', "YEN SIGN"),
|
||||
('\u{B0}', "DEGREE SIGN"),
|
||||
('\u{B1}', "PLUS-MINUS SIGN"),
|
||||
('\u{2260}', "NOT EQUAL TO"),
|
||||
('\u{2264}', "LESS-THAN OR EQUAL TO"),
|
||||
('\u{2265}', "GREATER-THAN OR EQUAL TO"),
|
||||
('\u{F7}', "DIVISION SIGN"),
|
||||
('\u{D7}', "MULTIPLICATION SIGN"),
|
||||
('\u{221E}', "INFINITY"),
|
||||
('\u{B5}', "MICRO SIGN"),
|
||||
('\u{3B1}', "GREEK SMALL LETTER ALPHA"),
|
||||
('\u{3B2}', "GREEK SMALL LETTER BETA"),
|
||||
('\u{3C0}', "GREEK SMALL LETTER PI"),
|
||||
('\u{3A9}', "GREEK CAPITAL LETTER OMEGA"),
|
||||
('\u{2211}', "N-ARY SUMMATION"),
|
||||
('\u{221A}', "SQUARE ROOT"),
|
||||
('\u{2192}', "RIGHTWARDS ARROW"),
|
||||
('\u{2190}', "LEFTWARDS ARROW"),
|
||||
('\u{2713}', "CHECK MARK"),
|
||||
('\u{2605}', "BLACK STAR"),
|
||||
('\u{2665}', "BLACK HEART SUIT"),
|
||||
('\u{2014}', "EM DASH"),
|
||||
('\u{2026}', "HORIZONTAL ELLIPSIS"),
|
||||
];
|
||||
|
||||
/// A symbol's hover text: its Unicode name and code point (the code point alone, with its block, for a character
|
||||
/// not named above), then its font when it has one.
|
||||
pub(super) fn symbol_tip(glyph: &str, font: &str) -> String {
|
||||
let mut chars = glyph.chars();
|
||||
let tip = match (chars.next(), chars.next()) {
|
||||
(Some(c), None) => {
|
||||
let name = DEFAULT_SYMBOLS.iter().find(|(n, _)| *n == c).map(|(_, name)| *name);
|
||||
let block = crate::dialogs_insert::subset_of(c);
|
||||
match (name, block) {
|
||||
(Some(name), _) => format!("{name} (U+{:04X})", c as u32),
|
||||
(None, Some(block)) => format!("U+{:04X} ({block})", c as u32),
|
||||
(None, None) => format!("U+{:04X}", c as u32),
|
||||
}
|
||||
}
|
||||
_ => glyph.to_string(),
|
||||
};
|
||||
if font.is_empty() { tip } else { format!("{tip}, {font}") }
|
||||
}
|
||||
|
||||
/// The recent and common characters as a compact grid; a click inserts the character, remembers it and closes
|
||||
/// the menu.
|
||||
fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
// Recently used symbols first (their font on hover), then common ones.
|
||||
let mut items: Vec<(String, String)> = app.ui.recent_symbols.iter().map(|r| (r.ch.clone(), r.font.clone())).collect();
|
||||
for c in [
|
||||
"©", "®", "™", "§", "¶", "€", "£", "¥", "°", "±", "≠", "≤", "≥", "÷", "×", "∞", "µ", "α", "β", "π", "Ω", "∑", "√", "→", "←", "✓", "★", "♥",
|
||||
"—", "…",
|
||||
] {
|
||||
if !items.iter().any(|(ch, f)| ch == c && f.is_empty()) {
|
||||
items.push((c.to_string(), String::new()));
|
||||
for (c, _) in DEFAULT_SYMBOLS {
|
||||
let c = c.to_string();
|
||||
if !items.iter().any(|(ch, f)| *ch == c && f.is_empty()) {
|
||||
items.push((c, String::new()));
|
||||
}
|
||||
}
|
||||
items.truncate(30);
|
||||
@@ -304,20 +356,20 @@ fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.caption(CaptionPlace::None)
|
||||
.card_columns(6)
|
||||
.content_cells()
|
||||
// Small cells (#7165): a glyph needs no more room than the small thumbnail step.
|
||||
.thumb_size(ThumbSize::Small)
|
||||
// At most thirty symbols, all shown; the menu's body is the one scroll.
|
||||
.natural_height(true)
|
||||
.show_items(ui, &SymbolCells(items.len()), &mut |key, _| {
|
||||
let (c, font) = items.get(*key).cloned().unwrap_or_default();
|
||||
let glyph = c.clone();
|
||||
let (glyph, tip) = (c.clone(), symbol_tip(&c, &font));
|
||||
let tile = Tile::new(c).thumb(ThumbAspect::SQUARE, move |cx, rect| {
|
||||
let run = TextRun::new(glyph.as_str()).align(HAlign::Center);
|
||||
cx.with_draw(|d| {
|
||||
d.text_on_centre_line(rect, &run);
|
||||
});
|
||||
});
|
||||
if font.is_empty() { tile } else { tile.tooltip(font) }
|
||||
tile.tooltip(tip)
|
||||
});
|
||||
for event in &out.response.events {
|
||||
if let CollectionEvent::Activate(key) = event
|
||||
|
||||
@@ -959,92 +959,109 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #7324, #7457: Table ribbon menu buttons (Styles, Borders, Select, Delete, AutoFit) bind their command IDs
|
||||
/// so they disable when editing is protected or when no table is active.
|
||||
#[test]
|
||||
fn table_ribbon_menu_buttons_disable_when_unselected_or_protected() {
|
||||
/// Is the ribbon button `name` disabled? (helpers for the table ribbon gate tests below.)
|
||||
fn table_button_disabled(h: &Harness, name: &str) -> bool {
|
||||
use egui::accesskit::Role;
|
||||
h.query_all(By::new().role(Role::Button).label(name)).next().unwrap_or_else(|| panic!("button {name} not found")).accesskit_node().is_disabled()
|
||||
}
|
||||
|
||||
let is_disabled = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.is_disabled()
|
||||
};
|
||||
fn table_button_hint(h: &Harness, name: &str) -> String {
|
||||
use egui::accesskit::Role;
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.description()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
let description = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.description()
|
||||
.map(|s| s.to_string())
|
||||
};
|
||||
/// A 2x2 table app on `tab`; `protected` sets read-only protection.
|
||||
fn table_tab_harness(tab: &str, protected: bool) -> Harness {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
if protected {
|
||||
app.session.doc.settings.protection = Some("readOnly".into());
|
||||
}
|
||||
tab_harness(app, tab)
|
||||
}
|
||||
|
||||
// Configure Table Design & Table Layout as explicit ribbon tabs so they can be
|
||||
// displayed even when the cursor is outside a table.
|
||||
let make_table_tabs_app = |mut app: WordApp| {
|
||||
/// #7324, #7457: without an active table the Table ribbon menu buttons disable. The Table tabs are
|
||||
/// configured explicitly so they show with the cursor outside a table.
|
||||
#[test]
|
||||
fn table_ribbon_menu_buttons_disable_when_unselected() {
|
||||
for tab in ["Table Design", "Table Layout"] {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default());
|
||||
app.session.ribbon.tabs = vec![
|
||||
wordcraft_engine::ribbon::TabEntry { name: "Table Design".to_string(), custom: false, hidden: false, groups: Vec::new() },
|
||||
wordcraft_engine::ribbon::TabEntry { name: "Table Layout".to_string(), custom: false, hidden: false, groups: Vec::new() },
|
||||
];
|
||||
app
|
||||
};
|
||||
let h = tab_harness(app, tab);
|
||||
if tab == "Table Design" {
|
||||
assert!(table_button_disabled(&h, "Styles"), "Styles button should be disabled when not in table");
|
||||
assert!(table_button_disabled(&h, "Borders"), "Borders button should be disabled when not in table");
|
||||
} else {
|
||||
assert!(table_button_disabled(&h, "Select"), "Select button should be disabled when not in table");
|
||||
assert!(table_button_disabled(&h, "Delete"), "Delete button should be disabled when not in table");
|
||||
assert!(table_button_disabled(&h, "AutoFit"), "AutoFit button should be disabled when not in table");
|
||||
assert!(
|
||||
table_button_hint(&h, "Select").to_ascii_lowercase().contains("the cursor isn't in a table"),
|
||||
"Select should indicate outside table in disabled hint"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Without a table active:
|
||||
let app_no_table = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
|
||||
let h_design_empty = tab_harness(app_no_table, "Table Design");
|
||||
assert!(is_disabled(&h_design_empty, "Styles"), "Styles button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_design_empty, "Borders"), "Borders button should be disabled when not in table");
|
||||
/// With an active, unprotected table the Table Design buttons are enabled.
|
||||
#[test]
|
||||
fn table_design_menu_buttons_enabled_in_table() {
|
||||
let h = table_tab_harness("Table Design", false);
|
||||
assert!(!table_button_disabled(&h, "Styles"), "Styles button should be enabled in table");
|
||||
assert!(!table_button_disabled(&h, "Borders"), "Borders button should be enabled in table");
|
||||
}
|
||||
|
||||
let app_no_table2 = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
|
||||
let h_layout_empty = tab_harness(app_no_table2, "Table Layout");
|
||||
assert!(is_disabled(&h_layout_empty, "Select"), "Select button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_layout_empty, "Delete"), "Delete button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_layout_empty, "AutoFit"), "AutoFit button should be disabled when not in table");
|
||||
assert!(
|
||||
description(&h_layout_empty, "Select").as_deref().unwrap_or("").to_ascii_lowercase().contains("the cursor isn't in a table"),
|
||||
"Select should indicate outside table in disabled hint"
|
||||
);
|
||||
/// With an active, unprotected table the Table Layout buttons are enabled and open their menus
|
||||
/// (the controls for the shut-menu checks under protection).
|
||||
#[test]
|
||||
fn table_layout_menu_buttons_enabled_in_table() {
|
||||
let mut h = table_tab_harness("Table Layout", false);
|
||||
assert!(!table_button_disabled(&h, "Select"), "Select button should be enabled in table");
|
||||
assert!(!table_button_disabled(&h, "Delete"), "Delete button should be enabled in table");
|
||||
assert!(!table_button_disabled(&h, "AutoFit"), "AutoFit button should be enabled in table");
|
||||
click_button(&mut h, "Delete");
|
||||
assert!(h.query_all(menu_row("Delete Rows")).next().is_some(), "an enabled Delete opens its menu");
|
||||
}
|
||||
|
||||
// 2. With an active table and no protection: buttons are enabled:
|
||||
let mut app_table = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_table.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let h_design = tab_harness(app_table, "Table Design");
|
||||
assert!(!is_disabled(&h_design, "Styles"), "Styles button should be enabled in table");
|
||||
assert!(!is_disabled(&h_design, "Borders"), "Borders button should be enabled in table");
|
||||
/// Positive control for the AutoFit shut-menu check under protection: an enabled AutoFit opens its menu.
|
||||
#[test]
|
||||
fn table_layout_autofit_opens_menu_in_table() {
|
||||
let mut h = table_tab_harness("Table Layout", false);
|
||||
click_button(&mut h, "AutoFit");
|
||||
assert!(h.query_all(menu_row("AutoFit Window")).next().is_some(), "an enabled AutoFit opens its menu");
|
||||
}
|
||||
|
||||
let mut app_table2 = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_table2.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let h_layout = tab_harness(app_table2, "Table Layout");
|
||||
assert!(!is_disabled(&h_layout, "Select"), "Select button should be enabled in table");
|
||||
assert!(!is_disabled(&h_layout, "Delete"), "Delete button should be enabled in table");
|
||||
assert!(!is_disabled(&h_layout, "AutoFit"), "AutoFit button should be enabled in table");
|
||||
/// Under read-only protection the Table Design buttons disable and say why.
|
||||
#[test]
|
||||
fn table_design_menu_buttons_disable_when_protected() {
|
||||
let h = table_tab_harness("Table Design", true);
|
||||
assert!(table_button_disabled(&h, "Styles"), "Styles button should be disabled under protection");
|
||||
assert!(table_button_disabled(&h, "Borders"), "Borders button should be disabled under protection");
|
||||
assert!(table_button_hint(&h, "Styles").contains("protected"), "Styles should indicate protection in disabled hint");
|
||||
}
|
||||
|
||||
// 3. With an active table under document protection (read-only): mutating buttons are disabled:
|
||||
let mut app_protected_design = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_protected_design.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app_protected_design.session.doc.settings.protection = Some("readOnly".into());
|
||||
let h_prot_design = tab_harness(app_protected_design, "Table Design");
|
||||
assert!(is_disabled(&h_prot_design, "Styles"), "Styles button should be disabled under protection");
|
||||
assert!(is_disabled(&h_prot_design, "Borders"), "Borders button should be disabled under protection");
|
||||
assert!(
|
||||
description(&h_prot_design, "Styles").as_deref().unwrap_or("").contains("protected"),
|
||||
"Styles should indicate protection in disabled hint"
|
||||
);
|
||||
|
||||
let mut app_protected_layout = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_protected_layout.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app_protected_layout.session.doc.settings.protection = Some("readOnly".into());
|
||||
let h_prot_layout = tab_harness(app_protected_layout, "Table Layout");
|
||||
assert!(!is_disabled(&h_prot_layout, "Select"), "Select button should remain enabled under protection");
|
||||
assert!(is_disabled(&h_prot_layout, "Delete"), "Delete button should be disabled under protection");
|
||||
assert!(is_disabled(&h_prot_layout, "AutoFit"), "AutoFit button should be disabled under protection");
|
||||
assert!(
|
||||
description(&h_prot_layout, "Delete").as_deref().unwrap_or("").contains("protected"),
|
||||
"Delete should indicate protection in disabled hint"
|
||||
);
|
||||
/// Under read-only protection the mutating Table Layout buttons disable, say why, and stay shut
|
||||
/// when clicked (C2-5, #7824).
|
||||
#[test]
|
||||
fn table_layout_menu_buttons_disable_when_protected() {
|
||||
let mut h = table_tab_harness("Table Layout", true);
|
||||
assert!(!table_button_disabled(&h, "Select"), "Select button should remain enabled under protection");
|
||||
assert!(table_button_disabled(&h, "Delete"), "Delete button should be disabled under protection");
|
||||
assert!(table_button_disabled(&h, "AutoFit"), "AutoFit button should be disabled under protection");
|
||||
assert!(table_button_hint(&h, "Delete").contains("protected"), "Delete should indicate protection in disabled hint");
|
||||
click_button(&mut h, "Delete");
|
||||
assert!(h.query_all(menu_row("Delete Rows")).next().is_none(), "a disabled Delete opens no menu");
|
||||
click_button(&mut h, "AutoFit");
|
||||
assert!(h.query_all(menu_row("AutoFit Window")).next().is_none(), "a disabled AutoFit opens no menu");
|
||||
}
|
||||
|
||||
/// #7374: the Decorative Text / WordArt Styles dropdown menu renders compact tiles (~40×36 pt)
|
||||
@@ -1322,3 +1339,37 @@ fn a_combo_field_reached_with_tab_shows_its_hint_after_a_delay() {
|
||||
}
|
||||
assert!(h.query_all_by_label("Font Size").count() >= 2, "hint must show after tooltip delay");
|
||||
}
|
||||
|
||||
/// #7165: the Symbol drop-down's cells are compact (a thumbnail-small step, not a card) and the hover text names
|
||||
/// the character, not just the glyph.
|
||||
#[test]
|
||||
fn symbol_menu_cells_are_compact_and_the_tooltip_names_the_character() {
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
|
||||
let mut h = tab_harness(app, "Insert");
|
||||
click_button(&mut h, "Symbol");
|
||||
let cell_y = |h: &Harness| h.get_by_label("\u{A9}").rect().min.y;
|
||||
let cell = h.get_by_label("\u{A9}").rect();
|
||||
assert!(cell.width() <= 80.0 && cell.height() <= 80.0, "a symbol cell is compact, got {:?}", cell.size());
|
||||
// Eight symbols fit one row, so the menu does not cover the page.
|
||||
assert_eq!(h.get_by_label("\u{A5}").rect().min.y, cell_y(&h), "the eighth symbol is on the first row");
|
||||
h.get_by_label("\u{A9}").hover();
|
||||
crate::test_harness::frames(&mut h, 40);
|
||||
assert!(h.query_by_label_contains("COPYRIGHT SIGN (U+00A9)").is_some(), "the tooltip names the character");
|
||||
// A screen reader gets the name without hovering: the tile's label is the glyph, its description the name.
|
||||
let desc = h.get_by_label("\u{A9}").accesskit_node().description().map(|d| d.to_string()).unwrap_or_default();
|
||||
assert!(desc.contains("COPYRIGHT SIGN"), "the tile's accessible description names the character, got {desc:?}");
|
||||
}
|
||||
|
||||
/// Characters outside the common list still say what they are: code point and block.
|
||||
#[test]
|
||||
fn symbol_tip_names_known_characters_and_falls_back_to_the_code_point() {
|
||||
use super::insert::symbol_tip;
|
||||
let named = symbol_tip("\u{A9}", "");
|
||||
assert!(named.contains("COPYRIGHT SIGN") && named.contains("00A9"), "named character: {named}");
|
||||
let with_font = symbol_tip("\u{3B1}", "Symbol");
|
||||
assert!(with_font.contains("GREEK SMALL LETTER ALPHA") && with_font.contains("03B1") && with_font.contains("Symbol"), "{with_font}");
|
||||
assert!(!named.contains("Symbol"), "no font, none named");
|
||||
let unnamed = symbol_tip("\u{2602}", "");
|
||||
assert!(unnamed.contains("2602") && unnamed.contains("Miscellaneous Symbols"), "unnamed character: {unnamed}");
|
||||
assert_eq!(symbol_tip("", ""), "");
|
||||
}
|
||||
|
||||
@@ -2080,6 +2080,57 @@ fn title_and_account_buttons_work() {
|
||||
assert!(h.query_by_label("User name:").is_some());
|
||||
}
|
||||
|
||||
/// A pointer drag on a pane's resize edge leaves no keyboard focus behind, so Ctrl and
|
||||
/// F-key shortcuts run right after it, docked or floating (#1756).
|
||||
#[test]
|
||||
fn shortcuts_run_after_a_pane_resize() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{By, Queryable};
|
||||
type H = egui_kittest::Harness<'static, WordApp>;
|
||||
fn key(h: &mut H, key: egui::Key, modifiers: egui::Modifiers) {
|
||||
h.key_press_modifiers(modifiers, key);
|
||||
h.step();
|
||||
}
|
||||
fn drag(h: &mut H, from: egui::Pos2, by: egui::Vec2) {
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
h.event(egui::Event::PointerMoved(from));
|
||||
h.event(button(from, true));
|
||||
h.step();
|
||||
h.event(egui::Event::PointerMoved(from + by));
|
||||
h.step();
|
||||
h.event(button(from + by, false));
|
||||
h.step();
|
||||
}
|
||||
let find_open = |h: &H| h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("find"));
|
||||
let styles_pane =
|
||||
|h: &H| h.query_all(By::new().role(Role::Group).label("Styles")).map(|n| n.rect()).find(|r| r.height() > 300.0).expect("Styles pane frame");
|
||||
|
||||
let mut a = app();
|
||||
a.run("view.stylesPane", json!({"value": true})).unwrap();
|
||||
let mut h = harness(a);
|
||||
h.step();
|
||||
|
||||
let pane = styles_pane(&h);
|
||||
// On the pane's inner edge: drag left by 40 px to widen it.
|
||||
drag(&mut h, egui::pos2(pane.left() + 1.0, pane.center().y), egui::vec2(-40.0, 0.0));
|
||||
let width = h.state().ui.styles_pane_width.unwrap_or_default();
|
||||
assert!((width - 290.0).abs() <= 2.0, "the drag widened the docked pane: {width}");
|
||||
key(&mut h, egui::Key::H, egui::Modifiers::COMMAND);
|
||||
assert!(find_open(&h), "Ctrl+H runs after the docked drag");
|
||||
key(&mut h, egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert!(h.state().dialog_host.open_dialogs().is_empty(), "Escape closes Replace");
|
||||
|
||||
h.state_mut().run("view.stylesPaneDock", json!({"dock": "float"})).unwrap();
|
||||
h.step();
|
||||
let float_pane = styles_pane(&h);
|
||||
let before = h.state().ui.styles_pane_float;
|
||||
// Drag the bottom-right corner.
|
||||
drag(&mut h, float_pane.max - egui::vec2(2.0, 2.0), egui::vec2(30.0, 30.0));
|
||||
assert_ne!(h.state().ui.styles_pane_float, before, "the drag resized the floating pane");
|
||||
key(&mut h, egui::Key::H, egui::Modifiers::COMMAND);
|
||||
assert!(find_open(&h), "Ctrl+H runs after the floating pane's resize");
|
||||
}
|
||||
|
||||
/// #3172: the Paste button is named "Paste": its tooltip adds the key as the platform writes it,
|
||||
/// so its name no longer carries macOS's "⌘V", which screen readers read on Windows as "Paste (⌘V)".
|
||||
#[test]
|
||||
@@ -3342,6 +3393,28 @@ fn check_spelling_off_in_a_second_window_stays_off_in_every_window() {
|
||||
assert!(!b.session.view.proofing && !b.session.prefs.check_spelling, "saved off, whichever window was drawn");
|
||||
}
|
||||
|
||||
/// #7841: in dark mode the app draws its interface text with its own lighter curve, not egui's dark default, and
|
||||
/// light mode keeps egui's light one.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn dark_interface_text_uses_the_app_s_lighter_curve() {
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut a = app();
|
||||
let curve = |a: &mut WordApp, theme: theme::Appearance| {
|
||||
a.ui.theme = theme;
|
||||
for _ in 0..2 {
|
||||
crate::test_harness::pass(&ctx, a, egui::RawInput::default());
|
||||
}
|
||||
ctx.global_style().visuals.text_options.color_transfer_function
|
||||
};
|
||||
let dark = curve(&mut a, theme::Appearance::Dark);
|
||||
let light = curve(&mut a, theme::Appearance::Light);
|
||||
let lighter = egui::epaint::FontColorTransferFunction::Gamma(0.8);
|
||||
assert_eq!(dark, lighter, "dark mode draws with the app's curve");
|
||||
assert_eq!(light, egui::Visuals::light().text_options.color_transfer_function, "light mode keeps egui's");
|
||||
assert_eq!(curve(&mut a, theme::Appearance::Dark), lighter, "back to dark gets the app's curve again");
|
||||
}
|
||||
|
||||
/// #1861: the registered Interface Theme command drives the same setting as Options:
|
||||
/// searchable in the registry, settable, toggling without a value, and surviving a restart.
|
||||
#[test]
|
||||
|
||||
@@ -712,6 +712,16 @@ pub fn apply_animations(ctx: &egui::Context, on: bool) {
|
||||
/// Coverage exponent for light-on-dark interface text on Linux and the BSDs (see [`visuals`]).
|
||||
const DARK_TEXT_GAMMA: f32 = 0.8;
|
||||
|
||||
/// Gives egui's dark style our lighter light-on-dark text curve on Linux and the BSDs (see [`visuals`]). The craft
|
||||
/// runtime's mode sync keeps an app's own curve for each mode (craft-libs#3589), so setting it once is enough (#7841).
|
||||
pub fn set_dark_text_curve(ctx: &egui::Context) {
|
||||
if cfg!(all(unix, not(target_os = "macos"))) {
|
||||
ctx.style_mut_of(egui::Theme::Dark, |s| {
|
||||
s.visuals.text_options.color_transfer_function = egui::epaint::FontColorTransferFunction::Gamma(DARK_TEXT_GAMMA);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// egui's visuals for one of our palettes.
|
||||
fn visuals(t: &Tokens) -> Visuals {
|
||||
let mut v = if t.dark { Visuals::dark() } else { Visuals::light() };
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use craft::font_manager::Catalog;
|
||||
use craft::font_manager::craft_font_catalog::{Limits, Source};
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{Props as _, Show as _};
|
||||
use egui::Key;
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
@@ -104,3 +106,119 @@ fn font_list_sections_skip_their_headings() {
|
||||
h.run_steps(2);
|
||||
assert_eq!(current_font(&mut h).as_deref(), Some(first_all.as_str()));
|
||||
}
|
||||
|
||||
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
|
||||
egui::Color32::from(craft::theme::Srgba::from(rgba))
|
||||
}
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn find_button_fill(shapes: &[egui::epaint::ClippedShape], rect: egui::Rect) -> Option<(egui::Color32, egui::CornerRadius)> {
|
||||
let mut flattened = Vec::new();
|
||||
collect_shapes(shapes, &mut flattened);
|
||||
flattened.into_iter().find_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if (r.rect.min.x - rect.min.x).abs() <= 1.5
|
||||
&& (r.rect.max.x - rect.max.x).abs() <= 1.5
|
||||
&& (r.rect.min.y - rect.min.y).abs() <= 1.5
|
||||
&& (r.rect.max.y - rect.max.y).abs() <= 1.5
|
||||
&& r.fill != egui::Color32::TRANSPARENT
|
||||
&& r.corner_radius != egui::CornerRadius::ZERO =>
|
||||
{
|
||||
Some((r.fill, r.corner_radius))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// #305: drawn buttons must react like standard buttons — resting at idle without a fill plate,
|
||||
/// fading in through an intermediate fill on pointer hover, settling on the theme's hover state
|
||||
/// token, darkening/transitioning to the pressed state token while held down, and clearing when
|
||||
/// unhovered.
|
||||
#[test]
|
||||
fn drawn_buttons_fade_in_on_hover_and_darken_while_pressed() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(200.0, 100.0)).with_step_dt(0.04).build_ui(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let _ = IconButton::new(crate::icons::id("save")).label("Save").show(ui);
|
||||
});
|
||||
});
|
||||
h.ctx.all_styles_mut(|s| s.animation_time = egui::Style::default().animation_time);
|
||||
h.step();
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let expected_hover = to_color32(env.tokens.color.state.hover);
|
||||
let expected_pressed = to_color32(env.tokens.color.state.pressed);
|
||||
|
||||
let node = h.get_by_role_and_label(Role::Button, "Save");
|
||||
let rect = node.rect();
|
||||
assert!(rect.is_positive(), "Save button must have positive rect");
|
||||
|
||||
// 1. Idle state: no hover or pressed fill plate
|
||||
let fill_before = find_button_fill(&h.output().shapes, rect);
|
||||
assert_eq!(fill_before, None, "Save button must have no hover fill before hover");
|
||||
|
||||
// 2. Hover state: fades in through an intermediate fill, then settles on the hover token
|
||||
node.hover();
|
||||
h.run_steps(2);
|
||||
let fill_mid = find_button_fill(&h.output().shapes, rect);
|
||||
assert!(fill_mid.is_some(), "Save button must paint an intermediate fill while fading in");
|
||||
let (mid_fill, _) = fill_mid.unwrap();
|
||||
assert!(
|
||||
mid_fill != expected_hover && mid_fill.a() > 0 && mid_fill.a() < expected_hover.a(),
|
||||
"Save button hover should fade in through an intermediate alpha: got {mid_fill:?}, expected settled {expected_hover:?}"
|
||||
);
|
||||
|
||||
h.run_steps(3);
|
||||
let fill_hovered = find_button_fill(&h.output().shapes, rect);
|
||||
assert!(fill_hovered.is_some(), "Save button must produce settled hover shape");
|
||||
let (hover_fill, radius) = fill_hovered.unwrap();
|
||||
assert_eq!(hover_fill, expected_hover, "Save button settled hover fill must match theme hover token");
|
||||
assert!(
|
||||
radius.nw > 0 && radius.nw == radius.ne && radius.nw == radius.sw && radius.nw == radius.se,
|
||||
"Save button corner radius must be uniformly rounded: {:?}",
|
||||
radius
|
||||
);
|
||||
|
||||
// 3. Pressed state: pressing pointer button darkens/transitions to theme's pressed state token
|
||||
h.event(egui::Event::PointerButton { pos: rect.center(), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(4);
|
||||
let fill_pressed = find_button_fill(&h.output().shapes, rect);
|
||||
assert!(fill_pressed.is_some(), "Save button must have fill while pressed");
|
||||
let (pressed_fill, _) = fill_pressed.unwrap();
|
||||
assert_eq!(pressed_fill, expected_pressed, "Save button pressed fill must match theme pressed token");
|
||||
|
||||
// 4. Release: releasing pointer button transitions back to hover state
|
||||
h.event(egui::Event::PointerButton {
|
||||
pos: rect.center(),
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(4);
|
||||
let fill_released = find_button_fill(&h.output().shapes, rect);
|
||||
assert!(fill_released.is_some(), "Save button must remain filled upon release");
|
||||
let (released_fill, _) = fill_released.unwrap();
|
||||
assert_eq!(released_fill, expected_hover, "Save button fill after release should return to hover token");
|
||||
|
||||
// 5. Unhover: pointer leaving the button clears the fill plate
|
||||
h.event(egui::Event::PointerMoved(egui::pos2(0.0, 0.0)));
|
||||
h.run_steps(4);
|
||||
let fill_after = find_button_fill(&h.output().shapes, rect);
|
||||
assert_eq!(fill_after, None, "Save button must clear hover fill after unhovering");
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+2
-1
File diff suppressed because one or more lines are too long
@@ -31,7 +31,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic
|
||||
| Line breaking (UAX #14 with Word's exceptions: no break after `/`, a break after `-` before a digit, before another `-` (a row of hyphens wraps at any hyphen), or before a slash and a letter (`Dataprotection-` / `/Secrecyviolation` in the #3408 report's Word PDF; `fitness-/1589` stays whole in the arabic_rice_benefits_article reference), no break between `.` and `(`) | ✅ | `layout::tests::no_line_break_right_after_a_slash`, `layout::tests::a_hyphen_before_digits_is_a_break_opportunity_like_word`, `layout::tests::a_hyphen_before_a_slash_is_a_break_opportunity_like_word`, `layout::tests::a_row_of_hyphens_wraps_at_any_hyphen_like_word`, `layout::tests::a_full_stop_before_a_parenthesis_is_no_break`, `layout::tests::a_bookmark_is_no_line_break_opportunity` | — |
|
||||
| A break before a slash that starts a word (" /word" wraps whole; not after a no-break space) | 🟡 | `layout::tests::a_word_after_a_slash_wraps_whole`, `layout::tests::a_no_break_space_before_a_slash_still_holds`; behaviour from the #2963 report, not compared with Word yet | — |
|
||||
| Narrow table cells | ✅ | `layout::tests::narrow_cells_keep_their_width`: usable widths below 12 pt wrap without expansion; oversized glyphs still make progress | 0 |
|
||||
| Justification, Word 2013+ space shrinking (compat mode 15) | ✅ | #109; spaces before a line's first character (paragraph indented with spaces, after a line break or a tab, a bookmark, hidden text or a floating object's anchor before them) keep their width in justified and distributed lines, `layout::tests::leading_spaces_keep_their_width_in_justified_lines` | — |
|
||||
| Justification, Word 2013+ space shrinking (compat mode 15) | ✅ | #109, #5847. A line with a tab shrinks too, counting only the spaces after its last tab, measured in Word for Mac (`layout::tests::justified_line_with_a_tab_shrinks_only_the_spaces_after_it`); spaces before a line's first character (paragraph indented with spaces, after a line break or a tab, a bookmark, hidden text or a floating object's anchor before them) keep their width in justified and distributed lines (`layout::tests::leading_spaces_keep_their_width_in_justified_lines`) | — |
|
||||
| Spaces at the end of a line hang past the right margin instead of wrapping; the caret after them stays at the margin, in the body and in headers and footers | ✅ | `layout::tests::caret_after_hanging_spaces_stays_at_the_margin` (#2146): a letter typed after them wraps to the next line | — |
|
||||
| Complex scripts (Myanmar, Khmer, Indic): shaped per script run with OpenType fallback fonts, one cluster per syllable, Myanmar wraps between syllables | 🟡 | `layout::tests::complex` (#604). Khmer, Thai and Lao still wrap only at spaces (need a dictionary) | 4–8 |
|
||||
| Cursive joining (Arabic, Syriac, Mongolian, N'Ko…) across runs: a letter takes its form from the text shown beside it, across a change of formatting, past a vowel sign in a run of its own and past hidden or tracked-deleted text left out of the view; a tab, break, object or drop cap still stops the join | ✅ | `layout::tests::bidi::letters_join_across_a_change_of_formatting`, `letters_join_past_text_left_out_of_the_layout`, `letters_join_past_a_mark_in_a_run_of_its_own`, `letters_stay_apart_where_nothing_joins_them` (#4093); not compared with Word on this machine | 0 |
|
||||
@@ -558,6 +558,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc
|
||||
| 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) |
|
||||
| 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller |
|
||||
| 2026-11-12 | minor | Added layout.fitOnePage: heuristic search over discrete font half-point steps and spacing compression with anti-clutter safeguards (line-spacing floor and font-size floor) to condense multi-page documents by one page while preserving hierarchy |
|
||||
| 2026-11-07 | trivial | A justified line with a tab shrinks its spaces to fit more text, counting only the spaces after the line's last tab, measured in Word for Mac; WordCraft never shrank a line with a tab, so a numbered paragraph's first line wrapped a word early (#5847) |
|
||||
| 2026-10-31 | trivial | Web addresses: no line break after the `?` of a query (`/?type=`) or after a slash before an underscore (`/portal/_back`). Word for Mac 16.93 kept such an address whole and moved it to the next line; WordCraft broke it there (UAX #14 allows both). With the address moved along the line one word at a time (60 paragraphs, Times New Roman 12pt), WordCraft's lines now match Word's line for line; 23 (query) and 19 (underscore) paragraphs broke inside the address before. A `?` keeps its break before anything but an ASCII letter, digit or underscore (CJK text), and a path after a space (`caption /_back`) wraps whole. `layout::tests::no_line_break_inside_a_query_address`, `a_path_after_a_space_wraps_whole`, `a_question_mark_in_cjk_text_keeps_its_break` |
|
||||
|
||||
Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box
|
||||
|
||||
+14
-12
@@ -32,35 +32,37 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
|
||||
| Editing | 41 | 41 |
|
||||
| Tools | 7 | 7 |
|
||||
|
||||
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 510 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
|
||||
|
||||
## Missing
|
||||
|
||||
### Home
|
||||
|
||||
- Voice › Dictate (`tools.dictate`)
|
||||
- Voice › Dictate (`tools.dictate`): headless: no, reach: os (speech recognition service)
|
||||
|
||||
### Insert
|
||||
|
||||
- Illustrations › Online Pictures (`insert.onlinePicture`)
|
||||
- Illustrations › 3D Models (`insert.model3d`)
|
||||
- Illustrations › Screenshot (`insert.screenshot`)
|
||||
- Add-ins › Get Add-ins (`addins.get`)
|
||||
- Media › Online Video (`insert.video`)
|
||||
- Symbols › Ink Equation (`insert.inkEquation`)
|
||||
- Illustrations › Online Pictures (`insert.onlinePicture`): headless: no, reach: os (online image search service)
|
||||
- Illustrations › 3D Models (`insert.model3d`): headless: no, reach: engine-gap (3-D model files could be inserted by a command)
|
||||
- Illustrations › Screenshot (`insert.screenshot`): headless: no, reach: os (screen capture of other windows)
|
||||
- Add-ins › Get Add-ins (`addins.get`): headless: no, reach: os (add-in store service)
|
||||
- Media › Online Video (`insert.video`): headless: no, reach: os (online video service)
|
||||
- Symbols › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
|
||||
|
||||
### Draw
|
||||
|
||||
- Convert › Ink to Math (`draw.inkToMath`)
|
||||
- Convert › Ink to Math (`draw.inkToMath`): headless: no, reach: os (handwriting recognition service)
|
||||
|
||||
### Review
|
||||
|
||||
- Language › Translate (`review.translate`)
|
||||
- Protect › Block Authors (`review.blockAuthors`)
|
||||
- Language › Translate (`review.translate`): headless: no, reach: os (online translation service)
|
||||
- Protect › Block Authors (`review.blockAuthors`): headless: no, reach: os (co-authoring service)
|
||||
|
||||
### Read Mode
|
||||
|
||||
- View › Layout (`view.readLayout`)
|
||||
- View › Layout (`view.readLayout`): headless: no, reach: window (Read Mode window layout)
|
||||
|
||||
### Equation
|
||||
|
||||
- Tools › Ink Equation (`insert.inkEquation`)
|
||||
- Tools › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
|
||||
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
@@ -71,9 +71,6 @@ fi
|
||||
|
||||
if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
(cd "$ROOT" && cargo build --release --locked ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"} -p wordcraft -p wordcraft-cli)
|
||||
# The man-and-completions example writes wordcraft-cli's man pages and shell completions below. It is built in its own
|
||||
# cargo run: built with the binaries, its dev-dependencies' features would be unified into them.
|
||||
(cd "$ROOT" && cargo build --release --locked ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"} -p wordcraft-cli --example man-and-completions)
|
||||
fi
|
||||
# Cargo puts a cross build under target/<triple>/release.
|
||||
BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release"
|
||||
@@ -86,21 +83,6 @@ mkdir -p "$STAGE/bin" "$STAGE/share/applications" "$STAGE/share/mime/packages" "
|
||||
"$STAGE/share/icons" "$STAGE/share/doc/wordcraft"
|
||||
install -m 755 "$BIN/wordcraft" "$BIN/wordcraft-cli" "$STAGE/bin/"
|
||||
strip "$STAGE/bin/wordcraft" "$STAGE/bin/wordcraft-cli" 2>/dev/null || true
|
||||
# wordcraft-cli's man pages and shell completions, from its clap definition, written by the example built above (a
|
||||
# --skip-build run needs it built too). Under /usr/local, man pages go in man/ and the completions in the directories
|
||||
# bash, zsh and fish read there.
|
||||
CLI_DOCS="$BIN/examples/man-and-completions"
|
||||
if [[ ! -x "$CLI_DOCS" ]]; then
|
||||
echo "error: $CLI_DOCS is not built (cargo build --release -p wordcraft-cli --example man-and-completions)" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$CLI_DOCS" "$WORK/cli-docs"
|
||||
mkdir -p "$STAGE/man/man1" "$STAGE/share/bash-completion/completions" "$STAGE/share/zsh/site-functions" \
|
||||
"$STAGE/share/fish/vendor_completions.d"
|
||||
install -m 644 "$WORK"/cli-docs/*.1 "$STAGE/man/man1/"
|
||||
install -m 644 "$WORK/cli-docs/wordcraft-cli.bash" "$STAGE/share/bash-completion/completions/wordcraft-cli"
|
||||
install -m 644 "$WORK/cli-docs/_wordcraft-cli" "$STAGE/share/zsh/site-functions/_wordcraft-cli"
|
||||
install -m 644 "$WORK/cli-docs/wordcraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/wordcraft-cli.fish"
|
||||
# The desktop entry, MIME type and metainfo are the freedesktop files the Linux packages use.
|
||||
install -m 644 "$LINUX/$APP_ID.desktop" "$STAGE/share/applications/$APP_ID.desktop"
|
||||
install -m 644 "$LINUX/$APP_ID.mime.xml" "$STAGE/share/mime/packages/$APP_ID.xml"
|
||||
|
||||
@@ -92,13 +92,6 @@ contents:
|
||||
dst: /usr/share/doc/${NFPM_NAME}/
|
||||
type: tree
|
||||
|
||||
# Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and
|
||||
# openSUSE's do (its debian/rules sets --enable-additional-fpath).
|
||||
- src: /usr/share/zsh/site-functions/_${NFPM_CLI}
|
||||
dst: /usr/share/zsh/vendor-completions/_${NFPM_CLI}
|
||||
type: symlink
|
||||
packager: deb
|
||||
|
||||
scripts:
|
||||
postinstall: packaging/linux/postinst.sh
|
||||
postremove: packaging/linux/postinst.sh
|
||||
|
||||
@@ -22,16 +22,6 @@ printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
cp "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
|
||||
chmod 755 "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
|
||||
# The man-and-completions example writes the files it does for a real build; this one writes placeholders.
|
||||
mkdir -p "$CARGO_TARGET_DIR/release/examples"
|
||||
cat >"$CARGO_TARGET_DIR/release/examples/man-and-completions" <<'EXAMPLE'
|
||||
#!/bin/sh
|
||||
mkdir -p "$1"
|
||||
for f in wordcraft-cli.bash _wordcraft-cli wordcraft-cli.fish wordcraft-cli.1 wordcraft-cli-run.1; do
|
||||
echo stub >"$1/$f"
|
||||
done
|
||||
EXAMPLE
|
||||
chmod 755 "$CARGO_TARGET_DIR/release/examples/man-and-completions"
|
||||
|
||||
# The tar format is first in package.sh's default set; a broken nightly tar aborted every run here.
|
||||
(cd "$ROOT" && bash packaging/linux/package.sh --skip-build --formats tar)
|
||||
|
||||
@@ -68,13 +68,8 @@ if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
else
|
||||
(cd "$ROOT" && cargo build --release --locked -p wordcraft -p wordcraft-cli)
|
||||
fi
|
||||
# The man-and-completions example writes wordcraft-cli's man pages and shell completions below. It is built in its own
|
||||
# cargo run: built with the binaries, its dev-dependencies' features would be unified into them. It runs on the build
|
||||
# host, so a cross build still builds it for the host.
|
||||
(cd "$ROOT" && cargo build --release --locked -p wordcraft-cli --example man-and-completions)
|
||||
fi
|
||||
BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release"
|
||||
HOST_BIN="$CARGO_TARGET_DIR/release"
|
||||
WORK="$CARGO_TARGET_DIR/linux-package"
|
||||
STAGE="$WORK/root"
|
||||
rm -rf "$WORK"
|
||||
@@ -83,19 +78,6 @@ rm -rf "$WORK"
|
||||
install -Dm755 "$BIN/wordcraft" "$STAGE/usr/bin/wordcraft"
|
||||
install -Dm755 "$BIN/wordcraft-cli" "$STAGE/usr/bin/wordcraft-cli"
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/wordcraft" "$STAGE/usr/bin/wordcraft-cli" 2>/dev/null || true
|
||||
# wordcraft-cli's man pages and shell completions, from its clap definition, written by the example built above (a
|
||||
# --skip-build run needs it built too). zsh reads site-functions on Fedora and openSUSE; the deb also links the
|
||||
# completion into Debian's vendor-completions (nfpm.yaml).
|
||||
CLI_DOCS="$HOST_BIN/examples/man-and-completions"
|
||||
if [[ ! -x "$CLI_DOCS" ]]; then
|
||||
echo "error: $CLI_DOCS is not built (cargo build --release -p wordcraft-cli --example man-and-completions)" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$CLI_DOCS" "$WORK/cli-docs"
|
||||
install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1
|
||||
install -Dm644 "$WORK/cli-docs/wordcraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/wordcraft-cli"
|
||||
install -Dm644 "$WORK/cli-docs/_wordcraft-cli" "$STAGE/usr/share/zsh/site-functions/_wordcraft-cli"
|
||||
install -Dm644 "$WORK/cli-docs/wordcraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/wordcraft-cli.fish"
|
||||
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
|
||||
@@ -181,13 +163,6 @@ if has deb || has rpm; then
|
||||
nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN"
|
||||
rm -f "$NFPM_STAGE/usr/bin/wordcraft"
|
||||
mv "$NFPM_STAGE/usr/bin/wordcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
|
||||
# The man pages and completions name the command they document: rename them for the nightly's command.
|
||||
for f in "$NFPM_STAGE"/usr/share/man/man1/wordcraft-cli*.1 "$NFPM_STAGE/usr/share/bash-completion/completions/wordcraft-cli" \
|
||||
"$NFPM_STAGE/usr/share/zsh/site-functions/_wordcraft-cli" "$NFPM_STAGE/usr/share/fish/vendor_completions.d/wordcraft-cli.fish"; do
|
||||
sed -e "s/wordcraft-cli/$NFPM_CLI/g" -e "s/wordcraft\\\\-cli/${NFPM_CLI//-/\\\\-}/g" "$f" >"${f//wordcraft-cli/$NFPM_CLI}.tmp"
|
||||
rm -f "$f"
|
||||
mv "${f//wordcraft-cli/$NFPM_CLI}.tmp" "${f//wordcraft-cli/$NFPM_CLI}"
|
||||
done
|
||||
mv "$NFPM_STAGE/usr/share/doc/wordcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
|
||||
sed -e "s#^Exec=wordcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
|
||||
-e "s|^TryExec=wordcraft$|TryExec=$NFPM_BIN|" \
|
||||
|
||||
@@ -11,7 +11,7 @@ sonar.python.coverage.reportPaths=python-coverage.xml
|
||||
# S4790 (weak hash): SHA-1 is a start-key and "SHA1/1K" checksum algorithm that ODF package
|
||||
# encryption (ODF 1.3 Part 2 §4.16) names, and older office suites wrote it. It is needed to open
|
||||
# those files, not chosen for new security: WordCraft writes a SHA-256 start key and checksum.
|
||||
sonar.issue.ignore.multicriteria=odt_sha1
|
||||
sonar.issue.ignore.multicriteria=odt_sha1,validate_py_paths
|
||||
sonar.issue.ignore.multicriteria.odt_sha1.ruleKey=rust:S4790
|
||||
sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/crypt.rs
|
||||
|
||||
@@ -22,3 +22,9 @@ sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/cry
|
||||
# os_window, control-key). process_identity.rs is Windows-only (the taskbar AUMID) and cannot run
|
||||
# on the Linux runner either.
|
||||
sonar.coverage.exclusions=packaging/**,apps/wordcraft/src/main.rs,apps/wordcraft-cli/src/main.rs,apps/wordcraft/src/process_identity.rs
|
||||
|
||||
# S8707 (path traversal): the crates/validate *.py scripts are developer tools run by hand to
|
||||
# regenerate checked-in files; reading and writing the paths given on their command line is
|
||||
# their purpose, and nothing passes them untrusted input.
|
||||
sonar.issue.ignore.multicriteria.validate_py_paths.ruleKey=pythonsecurity:S8707
|
||||
sonar.issue.ignore.multicriteria.validate_py_paths.resourceKey=crates/validate/**/*.py
|
||||
|
||||
Reference in New Issue
Block a user