mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 22:59:18 +00:00
Compare commits
341
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c658b7a3ba | ||
|
|
d89f035219 | ||
|
|
860d728dfd | ||
|
|
0282a6124f | ||
|
|
3bb8a438b0 | ||
|
|
f333552fe5 | ||
|
|
63dbe61cda | ||
|
|
722ee1b60d | ||
|
|
53e426820a | ||
|
|
e77669a552 | ||
|
|
55ee6bfcb8 | ||
|
|
b6adce3262 | ||
|
|
68c94e9a2b | ||
|
|
ae713e05a8 | ||
|
|
b8ba467e54 | ||
|
|
71a3072fec | ||
|
|
25af5ed462 | ||
|
|
8a24807722 | ||
|
|
a269d3e13d | ||
|
|
b5d21f1ba9 | ||
|
|
8bda45fefa | ||
|
|
ba31d08b3f | ||
|
|
b6ced6363b | ||
|
|
bcaba5a37c | ||
|
|
e927cd7e8e | ||
|
|
f5930f52ca | ||
|
|
3c22bd688c | ||
|
|
777aae19e5 | ||
|
|
cc1f3231a7 | ||
|
|
d81b0b503e | ||
|
|
7460b7f916 | ||
|
|
538597a7ea | ||
|
|
58a3e6cf5b | ||
|
|
53c9e64e98 | ||
|
|
3ee43d57d2 | ||
|
|
6c3c3d181e | ||
|
|
5b4302828e | ||
|
|
08e21b1abc | ||
|
|
a188a76506 | ||
|
|
e219a5a9c3 | ||
|
|
7810b05973 | ||
|
|
89f0d39e7f | ||
|
|
946a626f5c | ||
|
|
9769b941c4 | ||
|
|
769a799620 | ||
|
|
0de7b3a5aa | ||
|
|
9f813636cf | ||
|
|
7e70097130 | ||
|
|
4cb1d22b0e | ||
|
|
d9b3a8eb9c | ||
|
|
3c73997925 | ||
|
|
d7748aa732 | ||
|
|
f5a9d415b8 | ||
|
|
a5b4b22ebf | ||
|
|
4f7d01edac | ||
|
|
5aa1a78082 | ||
|
|
9986d9b4cd | ||
|
|
dd017d865d | ||
|
|
393103ffdd | ||
|
|
c7661b2b0e | ||
|
|
20dd292da4 | ||
|
|
988cfaa5f1 | ||
|
|
0bd4878a34 | ||
|
|
737a19bbb0 | ||
|
|
c5f0865fa7 | ||
|
|
319838ab02 | ||
|
|
21b1ceb1c1 | ||
|
|
845df1cd48 | ||
|
|
0c9e6054d9 | ||
|
|
8f6a40d3f4 | ||
|
|
9ce63943af | ||
|
|
74ffe933cf | ||
|
|
306040b646 | ||
|
|
65960089a8 | ||
|
|
ec4922027f | ||
|
|
cb919da767 | ||
|
|
aadcc80cab | ||
|
|
6bf2ef18bb | ||
|
|
3b929eac31 | ||
|
|
a895098132 | ||
|
|
82887db8bb | ||
|
|
ac99969305 | ||
|
|
76b74dec50 | ||
|
|
2daca588a4 | ||
|
|
ae4f2dbf48 | ||
|
|
591a5ace12 | ||
|
|
f6d1207be2 | ||
|
|
77aab09d31 | ||
|
|
ee9a8153d3 | ||
|
|
5ad1be0472 | ||
|
|
ae876e0cdc | ||
|
|
f0b95f73fb | ||
|
|
4c8296a5b1 | ||
|
|
9b1ef01485 | ||
|
|
a46514f5df | ||
|
|
6af5d8c650 | ||
|
|
1e91f5cc1e | ||
|
|
bd9529b083 | ||
|
|
a7396929c7 | ||
|
|
42df428b01 | ||
|
|
fbb26d0b85 | ||
|
|
84a8675092 | ||
|
|
bfa3d12bfa | ||
|
|
e92a4d45f8 | ||
|
|
f4431d6b63 | ||
|
|
5203e2e7dc | ||
|
|
bdae1b73ae | ||
|
|
bdb955d2c6 | ||
|
|
d78467b616 | ||
|
|
069a69a5eb | ||
|
|
50f4b803a6 | ||
|
|
b81f67dfab | ||
|
|
ddcaffe387 | ||
|
|
11f830907d | ||
|
|
3512da9553 | ||
|
|
9a349bf372 | ||
|
|
16b7706a4d | ||
|
|
ffdc0c2332 | ||
|
|
d813e02661 | ||
|
|
b2c183fc8b | ||
|
|
f900ac06c2 | ||
|
|
4bc5b97c31 | ||
|
|
3f70941206 | ||
|
|
f1583c3417 | ||
|
|
f4f182b900 | ||
|
|
f966ceaa25 | ||
|
|
9b9dc5b103 | ||
|
|
2c70194a5b | ||
|
|
57bdc13e28 | ||
|
|
f302f189a6 | ||
|
|
a12799387d | ||
|
|
c3696df3d9 | ||
|
|
b6022a338c | ||
|
|
1e4c3d52de | ||
|
|
3c1ea66dd9 | ||
|
|
55992a696b | ||
|
|
eaec70d125 | ||
|
|
b4db8a407c | ||
|
|
4094828264 | ||
|
|
6f7afc6a5d | ||
|
|
c634f6c83e | ||
|
|
6cc86be260 | ||
|
|
f5d1d992a2 | ||
|
|
f550268bab | ||
|
|
b3c7338b3c | ||
|
|
a1e458a1c0 | ||
|
|
31b7bd6a63 | ||
|
|
63e43ae563 | ||
|
|
c479c88bbc | ||
|
|
af3179b7e8 | ||
|
|
31001fc6df | ||
|
|
259c86f8f8 | ||
|
|
0d5052d76d | ||
|
|
c2d4f64766 | ||
|
|
2804833dae | ||
|
|
00eaa42e0d | ||
|
|
308d4b6b05 | ||
|
|
b6eafa3d09 | ||
|
|
6f4652f976 | ||
|
|
f70664a13c | ||
|
|
ba4d06c12d | ||
|
|
e319029fdf | ||
|
|
4431cc1fea | ||
|
|
010b065dad | ||
|
|
c8629cfe9c | ||
|
|
0dcf26fcd1 | ||
|
|
2b6160b528 | ||
|
|
167bde7ed4 | ||
|
|
1a79ad29d8 | ||
|
|
45a00707c7 | ||
|
|
f81608db32 | ||
|
|
add2a11697 | ||
|
|
a917d2a4de | ||
|
|
739454c0f3 | ||
|
|
887e2c7af0 | ||
|
|
a82e4003c9 | ||
|
|
35dafa9376 | ||
|
|
85a7c754b3 | ||
|
|
dffc8f903c | ||
|
|
26ef54f4df | ||
|
|
81d0cf4a01 | ||
|
|
82c9dc4a51 | ||
|
|
9866095090 | ||
|
|
41532af120 | ||
|
|
4d90a255ab | ||
|
|
fa1687eedf | ||
|
|
918772e8ed | ||
|
|
9fa7295ea6 | ||
|
|
6d09c5069c | ||
|
|
c7fe2a479d | ||
|
|
6eadc423fd | ||
|
|
2502cb5467 | ||
|
|
916b99cd1f | ||
|
|
c8b88a23a1 | ||
|
|
a22cb3d822 | ||
|
|
49a5373fa2 | ||
|
|
610ec99314 | ||
|
|
c555672b56 | ||
|
|
d417b835b0 | ||
|
|
4e35526836 | ||
|
|
3094b3e02f | ||
|
|
071dfbb228 | ||
|
|
d98742d1cb | ||
|
|
20f26da670 | ||
|
|
1b284b7532 | ||
|
|
74a6b48bf6 | ||
|
|
005e028be7 | ||
|
|
882cac2672 | ||
|
|
e6b39f3d0f | ||
|
|
08b54d1166 | ||
|
|
b1aabef2cf | ||
|
|
044f06a9c6 | ||
|
|
183342276b | ||
|
|
ba4c143c9d | ||
|
|
95748dc79d | ||
|
|
009a94b4d0 | ||
|
|
c1a23c6a1f | ||
|
|
79f0fef906 | ||
|
|
22325c2575 | ||
|
|
37981b4fca | ||
|
|
a4ad65c372 | ||
|
|
4781d91473 | ||
|
|
04a3c76c10 | ||
|
|
e8414db9a5 | ||
|
|
fbe41cca76 | ||
|
|
553f0058ee | ||
|
|
c4ab2fea70 | ||
|
|
47ef5ce7b3 | ||
|
|
824d3c431e | ||
|
|
d2c8ba2787 | ||
|
|
8370cf558d | ||
|
|
257bc77e69 | ||
|
|
c7b4dfab8b | ||
|
|
0171216a13 | ||
|
|
f0a323fdce | ||
|
|
6a3a18eba5 | ||
|
|
0242af0fdb | ||
|
|
4f8ac61c76 | ||
|
|
d7c01bcd05 | ||
|
|
789cabd832 | ||
|
|
6545c44f0a | ||
|
|
b22e901c45 | ||
|
|
c60c82d960 | ||
|
|
67bfa46a3d | ||
|
|
513ff0541f | ||
|
|
d4a565447f | ||
|
|
6f7b8156dc | ||
|
|
a21324bf78 | ||
|
|
a39f6adf9f | ||
|
|
b2dd74729f | ||
|
|
5ea160c706 | ||
|
|
8a7fef3ec6 | ||
|
|
caf9c8de8b | ||
|
|
ce2b01e005 | ||
|
|
c2a370cd67 | ||
|
|
0a31f5de5d | ||
|
|
b2dd18c916 | ||
|
|
7342c32b1e | ||
|
|
58f942aa62 | ||
|
|
c070c2a258 | ||
|
|
1f6eb8eceb | ||
|
|
17fecc43ec | ||
|
|
1a7b691293 | ||
|
|
a6e831e8ca | ||
|
|
187a36e16c | ||
|
|
903edaffc7 | ||
|
|
3e3975d3a0 | ||
|
|
48fca374b3 | ||
|
|
5833546550 | ||
|
|
08eb9ccbb2 | ||
|
|
e31df586db | ||
|
|
865fcf21eb | ||
|
|
a18747a686 | ||
|
|
bbe04de28d | ||
|
|
ead0870d33 | ||
|
|
6db58aa0c0 | ||
|
|
eff8661a58 | ||
|
|
acf8e9950d | ||
|
|
97daa4b3ed | ||
|
|
7b03696d8c | ||
|
|
8a58d674b7 | ||
|
|
ef81c547af | ||
|
|
3d53abc13a | ||
|
|
2ee73a0d33 | ||
|
|
b4f129911d | ||
|
|
3ecce1f442 | ||
|
|
dbc0c30fe1 | ||
|
|
caf58cd52a | ||
|
|
5d43bb5414 | ||
|
|
63f5623990 | ||
|
|
0ee236e6a4 | ||
|
|
0c461485fb | ||
|
|
a830b61074 | ||
|
|
f0933342d4 | ||
|
|
b6a4fd1266 | ||
|
|
db6a9105de | ||
|
|
d6a8db16b4 | ||
|
|
7addc314f9 | ||
|
|
859e03246f | ||
|
|
0a29a6d73a | ||
|
|
0c7ea7278c | ||
|
|
a29663bd95 | ||
|
|
a7e02482fe | ||
|
|
8619e257a7 | ||
|
|
6e55462d5a | ||
|
|
4b30633e03 | ||
|
|
6f6bf92576 | ||
|
|
b66f579e7b | ||
|
|
7df90b72cf | ||
|
|
117c098553 | ||
|
|
f94aecace7 | ||
|
|
366b89341d | ||
|
|
0c7f425e91 | ||
|
|
3b0469da57 | ||
|
|
0320a14c0a | ||
|
|
72f0577d0c | ||
|
|
3cda5d277b | ||
|
|
02c2bb66e4 | ||
|
|
154982988a | ||
|
|
cf6d23c918 | ||
|
|
80eef0e4ac | ||
|
|
5e097aa288 | ||
|
|
417cc45a1c | ||
|
|
ff7d032da6 | ||
|
|
0aaef7a5bd | ||
|
|
be5fe3d36f | ||
|
|
f053740960 | ||
|
|
7581392111 | ||
|
|
04e8e61e82 | ||
|
|
bf95e83642 | ||
|
|
bec88fd149 | ||
|
|
1b34471bc8 | ||
|
|
44badab540 | ||
|
|
e209b4f6fd | ||
|
|
68de4560b5 | ||
|
|
a11e4daae6 | ||
|
|
b1c6aafc33 | ||
|
|
45299ba839 | ||
|
|
78ea592cf4 | ||
|
|
c1a20368dc | ||
|
|
32d4d32292 |
@@ -73,7 +73,7 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
|
||||
- `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`.
|
||||
- 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`.
|
||||
- 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: plain `wordcraft-cli mcp` reaches the open window while ArtCraft Launcher › Settings › AI agents is on (`crates/ui-egui/src/agents.rs`, `crates/mcp/src/live.rs`); `--headless`, or the switch off, needs `--automation-read-root DIR --automation-write-root DIR`; 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
+26
@@ -1211,6 +1211,16 @@ dependencies = [
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ai-agents"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
@@ -1352,8 +1362,13 @@ name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1478,6 +1493,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
@@ -9346,6 +9371,7 @@ dependencies = [
|
||||
"craft",
|
||||
"craft-mcp-server",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wordcraft-control-key",
|
||||
"wordcraft-doc",
|
||||
|
||||
@@ -205,13 +205,17 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
|
||||
|
||||
WordCraft was designed to be driven by people *and* by AI agents.
|
||||
|
||||
With ArtCraft Launcher › Settings › AI agents on, AI apps reach the open WordCraft window through
|
||||
the launcher's one `ArtCraft` entry: tool calls act in the window, and files go to the agent folder
|
||||
(`Documents/ArtCraft/Agents/WordCraft`, or the folders in File › Options › Agents). Without the
|
||||
launcher:
|
||||
|
||||
```sh
|
||||
# headless documents; the agent reads only inside the first folder and writes only inside the second
|
||||
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
```
|
||||
|
||||
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
|
||||
the app confines its control channel to the same roots (#3695).
|
||||
A headless server needs both roots.
|
||||
|
||||
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
|
||||
`render_page` and `save_document`. Agents
|
||||
|
||||
@@ -156,6 +156,11 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
## Progress log
|
||||
|
||||
- 2026-12-04: Windows: a document window can be maximized again, by its maximize button, Win+Up or a drag to the top of the screen, and View › Window › Full Screen fills the screen again (#8838, #8861). Since v0.20.0, where each document is a window of its own, the window was sent back to its normal place a few passes after the system maximized it, so it shook and stayed its normal size, and full screen slid it to the side. The fix is in craft-libs (storytold/craft-libs#5339): a window's own state, read with its place, keeps the normal place from being sent while it is maximized, full screen or minimized. Readiness estimates unchanged.
|
||||
- 2026-11-21: Page text on the shared page view is sharp again. After the port, pages were rasterised at the view's own scale and rounded up to whole pixels, which left a picture a pixel or two larger than its place on screen (2017 × 2852 for 2016 × 2851); the shared painter fits a picture into its place, so it was squeezed by a twentieth of a percent and the text slid off the pixel grid and back down the page: a reporter's screenshot showed baselines spread over three pixel rows. Pictures are now made exactly as many pixels each way as the place the view last rested at, which the painter draws one pixel for one. A headless test through the real page view and picture store holds this at three zooms and two screen densities. Not yet seen in the running app. Readiness estimates unchanged.
|
||||
- 2026-11-20: The sharper page text, subpixel (LCD) text and the Screen text smoothing option are ported onto the shared page view and Options that the UI port (#7101) brought. Two things changed on the way. The page view asks for page pictures rounded up to a multiple of 16 pixels and scales them into place, which resamples every glyph (A4 at 100 % on a 2x screen: 2256 pixels for 2245), so pages are now rasterised at the view's own scale wherever it accounts for the side asked for, and subpixel text is drawn only on such pictures. And the app no longer reads the system's text settings itself: system access moved to craft-libs' `platform::appearance`, which has none, so pages are drawn each platform's fixed way plus the user's own Screen text smoothing choice until craft-libs reports them (the 2026-11-19 entry on following the system no longer holds). Two shared-API gaps are recorded in `docs/ui-parity.md`: the text settings reader, and drawing a screen-scale page picture at its own pixel size. Run on macOS only; not seen in the running app since the port. Readiness estimates unchanged.
|
||||
- 2026-11-19: Page text can be drawn with subpixel (LCD) antialiasing: File › Options › General › Screen text smoothing offers Use system setting, Grayscale and Subpixel (LCD); `view.textSmoothing` reaches the same setting headlessly. A page is rasterised three times with only its text a third of a pixel apart and each colour channel is taken from the pass that matches its stripe, so drawing order, coloured text, dark pages and rotated text need no special cases and nothing but text gets coloured edges. Once the system settings are read (nothing reads them yet), "Use system setting" will turn it on where the system asks for it (ClearType, or `rgba` antialiasing on a Linux desktop) on screens below 2x; macOS never asks, so there it is the user's choice. Exports are unchanged. Run on macOS only, on headless rasters: not yet seen on a 1x LCD, on Windows or on Linux, and not timed. Readiness estimates unchanged.
|
||||
- 2026-11-19: Page drawing can take the system's text settings (darkening strength, hinting, subpixel order), but nothing reads them from the system yet, so pages are drawn each platform's fixed way and "Use system setting" is greyscale. Readiness estimates unchanged.
|
||||
- 2026-11-19: Page text on macOS and Windows is no longer soft. Baselines sit on whole device pixels, so the feet of the letters fill one pixel row instead of greying two; and the macOS font smoothing we imitate thickens letters sideways only, by widening each outline and filling it once, where a stroke all round added a third of a pixel of grey above and below every letter. Found by comparing 144 dpi screenshots of the same paragraph in WordCraft, Preview and OpenOffice: none of the three used subpixel antialiasing; WordCraft alone had its serifs spread over two rows. Linux and BSD text was already hinted onto the grid; exports are unchanged. Readiness estimates unchanged.
|
||||
- 2026-12-01: Hindi interface language (`hi`): File › Options › Interface language offers हिन्दी, and `hi`, `hi-IN` and `hi_IN.UTF-8` system locales pick it. The catalog is craft-i18n's `locales/hi/wordcraft.tsv` (`craft-i18n.rev` at 217f413); interface text is drawn by the embedded Noto Sans Devanagari face. No Hindi proofing, so the Hindi interface doesn't set the language of new documents. Readiness estimates unchanged.
|
||||
- 2026-11-28: Layout indexes numbering definitions for each list and STYLEREF walk. List labels still follow the document's literal labels, start overrides and nested restart rules (#3615).
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ workspace = true
|
||||
[dependencies]
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-engine = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-render = { workspace = true }
|
||||
wordcraft-mcp = { workspace = true }
|
||||
wordcraft-zotero = { workspace = true }
|
||||
|
||||
+189
-42
@@ -54,16 +54,25 @@ USAGE:
|
||||
wordcraft-cli commands [--json] list every command
|
||||
wordcraft-cli parity [--markdown] feature-catalog parity
|
||||
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
|
||||
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
|
||||
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 HOST:PORT (bridge to the running app) is
|
||||
refused until the app confines its control channel
|
||||
(#3695, #5819).
|
||||
wordcraft-cli mcp [--automation-read-root DIR --automation-write-root DIR] [--headless]
|
||||
[--when-closed launch|headless|error] [--author NAME]
|
||||
MCP server on stdio. While AI agents are on in
|
||||
ArtCraft Launcher › Settings › AI agents, each tool
|
||||
call goes to the open WordCraft window, working in
|
||||
its agent folder (File › Options › Agents); while
|
||||
WordCraft is closed, --when-closed or that page's
|
||||
choice decides: open it, work without a window, or
|
||||
ask to open it. Otherwise, and with --headless, a
|
||||
headless session, which needs both roots: 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. Given with AI agents
|
||||
on, the roots replace the agent folder for headless
|
||||
work. --author names the author of a headless
|
||||
session's tracked changes and comments.
|
||||
--connect HOST:PORT is deprecated and ignored.
|
||||
wordcraft-cli zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
|
||||
run a Zotero command on a document (Zotero must be
|
||||
running): addEditCitation, addEditBibliography,
|
||||
@@ -261,6 +270,17 @@ fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp --author NAME`: absent is the default author; a flag without a name, or given twice, is a
|
||||
/// usage error, never an unnamed session or the next option taken as the name.
|
||||
fn mcp_author(args: &[String]) -> Result<Option<String>, String> {
|
||||
match find_option_arg(args, "--author") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
OptionArg::Duplicate => Err("mcp: duplicate --author option".into()),
|
||||
OptionArg::MissingValue => Err("mcp: --author requires a name".into()),
|
||||
OptionArg::Value(name) => Ok(Some(name.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
|
||||
match find_option_arg(args, "--page") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
@@ -376,13 +396,86 @@ const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_val
|
||||
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
|
||||
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
|
||||
|
||||
/// 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";
|
||||
/// Why `mcp` won't start while the suite's AI-MCP flag is on but the launcher's switch keeps agents
|
||||
/// out of the window: without roots it would have no folders to work in.
|
||||
const MCP_NEEDS_ROOTS_OR_AGENTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR, or \
|
||||
turn on AI agents in ArtCraft Launcher › Settings › AI agents to work in WordCraft's open window and its agent folder";
|
||||
|
||||
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }];
|
||||
/// `--connect HOST:PORT`, from before plain `mcp` found the window by itself: kept for one release,
|
||||
/// ignored with this note on stderr, then removed.
|
||||
const MCP_CONNECT_DEPRECATED: &str = "wordcraft-cli: --connect is deprecated and will be removed in the next release: \
|
||||
plain `wordcraft-cli mcp` finds the open WordCraft window by itself while AI agents are on in ArtCraft Launcher › \
|
||||
Settings › AI agents. The address given is not used.";
|
||||
|
||||
const MCP_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--headless", takes_value: false },
|
||||
OptionSpec { name: "--when-closed", takes_value: true },
|
||||
OptionSpec { name: "--author", takes_value: true },
|
||||
];
|
||||
|
||||
/// Takes the deprecated `--connect` out of `args`, with its value (written apart, unless it is
|
||||
/// another option, or as `--connect=…`): whether it was there.
|
||||
fn take_connect(args: &mut Vec<String>) -> bool {
|
||||
let mut found = false;
|
||||
let mut i = 0;
|
||||
while let Some(arg) = args.get(i) {
|
||||
if arg == "--connect" {
|
||||
found = true;
|
||||
let with_value = args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
|
||||
args.drain(i..if with_value { i + 2 } else { i + 1 });
|
||||
} else if arg.starts_with("--connect=") {
|
||||
found = true;
|
||||
args.remove(i);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The suite's AI-MCP flag and whether the ArtCraft Launcher's switch lets agents use WordCraft.
|
||||
#[cfg(not(test))]
|
||||
fn agents_state() -> (bool, bool) {
|
||||
let flag = wordcraft_mcp::live::mcp_flag();
|
||||
(flag, flag && wordcraft_mcp::live::agents_allowed_now())
|
||||
}
|
||||
|
||||
/// Unit tests run `mcp` as without the suite's flag, whatever this machine's flags say; the plan
|
||||
/// itself is tested for every combination (`mcp_plan`), and the binary's tests set the flag.
|
||||
#[cfg(test)]
|
||||
fn agents_state() -> (bool, bool) {
|
||||
(false, false)
|
||||
}
|
||||
|
||||
/// How `mcp` runs.
|
||||
#[derive(Debug)]
|
||||
enum McpPlan {
|
||||
/// A headless session confined to both roots.
|
||||
Headless(std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>),
|
||||
/// The open window while agents may use it, otherwise a headless session in the given roots
|
||||
/// or the app's agent folder ([`wordcraft_mcp::Live`]).
|
||||
Live(Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>),
|
||||
}
|
||||
|
||||
/// `mcp`'s plan. With `--headless`, or without the suite's AI-MCP flag (`flag`), a headless session
|
||||
/// that needs both roots (shared rule 18). With the flag, the live client when the launcher's
|
||||
/// switch lets agents in (`switch`) or both roots are given, so nothing it does is unconfined;
|
||||
/// otherwise a refusal.
|
||||
fn mcp_plan(
|
||||
roots: Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>,
|
||||
headless: bool,
|
||||
flag: bool,
|
||||
switch: bool,
|
||||
) -> Result<McpPlan, &'static str> {
|
||||
let both = roots.clone().filter(|r| r.read_root().is_some() && r.write_root().is_some());
|
||||
if headless || !flag {
|
||||
return both.map(McpPlan::Headless).ok_or(MCP_NEEDS_ROOTS);
|
||||
}
|
||||
if switch || both.is_some() {
|
||||
return Ok(McpPlan::Live(roots));
|
||||
}
|
||||
Err(MCP_NEEDS_ROOTS_OR_AGENTS)
|
||||
}
|
||||
const ZOTERO_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--cmd", takes_value: true },
|
||||
OptionSpec { name: "--save", takes_value: true },
|
||||
@@ -523,6 +616,10 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
}
|
||||
let password = password_from(rest)?;
|
||||
let mut s = open(&i, password.as_deref())?;
|
||||
// A refused strict export prints only its report, so its note waits for the export to succeed.
|
||||
if !strict {
|
||||
report_missing_metric_fonts();
|
||||
}
|
||||
if rest.iter().any(|a| a == "--update-fields") {
|
||||
update_fields(&mut s)?;
|
||||
}
|
||||
@@ -538,8 +635,11 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
if let Err(e) = r {
|
||||
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
eprintln!("wrote {o}");
|
||||
Ok(())
|
||||
if strict {
|
||||
report_missing_metric_fonts();
|
||||
}
|
||||
// The confirmation is a result, so it goes to stdout with the others (#7070).
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))
|
||||
}
|
||||
|
||||
fn load_run_script(rest: &[String], script_path: Option<&Path>) -> Result<Option<script::Script>, Failure> {
|
||||
@@ -563,6 +663,16 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
|
||||
(from_file, from_template)
|
||||
}
|
||||
|
||||
fn report_missing_metric_fonts() {
|
||||
for (word, used) in wordcraft_fonts::word::missing_metric_fonts() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"note: {word} and its metric-compatible twins aren't installed; the primary family is {used}, so lines and pages may not match Word's; uncovered characters may use glyph fallback"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show a successful command's result, or its warning when results aren't printed.
|
||||
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
|
||||
if print {
|
||||
@@ -724,7 +834,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
eprintln!("wrote {out}");
|
||||
// A reader that hung up only loses the confirmation; the remaining saves still run.
|
||||
match write_stdout(|w| writeln!(w, "wrote {out}")) {
|
||||
Ok(()) | Err(Failure::StdoutClosed) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -754,28 +868,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
"validate" => run_validate(file.as_deref(), &rest),
|
||||
"mcp" => {
|
||||
let (roots, rest) = automation_roots("mcp", &rest)?;
|
||||
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
|
||||
// "unknown option": a bare trailing `--connect` must not slip past either.
|
||||
if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
validate_options("mcp", &rest, MCP_OPTIONS)?;
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined.
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(MCP_NEEDS_ROOTS.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<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
eprintln!("wordcraft-cli: 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, arg_value(&rest, "--author").as_deref())?);
|
||||
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(), std::io::stdout())?)
|
||||
}
|
||||
"mcp" => run_mcp(&rest),
|
||||
"zotero" => {
|
||||
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
|
||||
let paths = positionals(&rest, ZOTERO_OPTIONS);
|
||||
@@ -815,7 +908,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
eprintln!("{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = arg_value(&rest, "--save") {
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
eprintln!("wrote {o}");
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -825,6 +918,60 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `wordcraft-cli mcp`: serves MCP on stdin and stdout, headless or through the open window.
|
||||
fn run_mcp(rest: &[String]) -> Result<(), Failure> {
|
||||
let (roots, mut rest) = automation_roots("mcp", rest)?;
|
||||
// Taken out before the option check, with or without a value, so it never reads as unknown.
|
||||
if take_connect(&mut rest) {
|
||||
eprintln!("{MCP_CONNECT_DEPRECATED}");
|
||||
}
|
||||
validate_options("mcp", &rest, MCP_OPTIONS)?;
|
||||
let when_closed = match (rest.iter().any(|a| a == "--when-closed"), arg_value(&rest, "--when-closed")) {
|
||||
(false, _) => None,
|
||||
(true, value) => {
|
||||
Some(value.as_deref().and_then(wordcraft_mcp::live::WhenAppClosed::parse).ok_or("mcp: --when-closed takes launch, headless or error")?)
|
||||
}
|
||||
};
|
||||
let author = mcp_author(&rest)?;
|
||||
let (flag, switch) = agents_state();
|
||||
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = match mcp_plan(roots, rest.iter().any(|a| a == "--headless"), flag, switch)? {
|
||||
McpPlan::Headless(roots) => {
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. Every thread of this process,
|
||||
// not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
Box::new(headless_mcp(roots, author.as_deref())?)
|
||||
}
|
||||
McpPlan::Live(roots) => {
|
||||
let mut config = wordcraft_mcp::LiveConfig::installed()
|
||||
.ok_or("mcp: can't find WordCraft's settings folder (no home folder; set WORDCRAFT_PROFILE_DIR)")?;
|
||||
if let Some(roots) = &roots {
|
||||
config.read_root = roots.read_root().map(std::path::Path::to_path_buf);
|
||||
config.write_root = roots.write_root().map(std::path::Path::to_path_buf);
|
||||
// Both roots given: every headless session works in them, so the whole process is confined to
|
||||
// them. Calls to the window run in the app, inside its agent folders.
|
||||
if config.read_root.is_some() && config.write_root.is_some() {
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
}
|
||||
}
|
||||
config.when_closed = when_closed;
|
||||
config.author = author;
|
||||
config.launch = std::env::current_exe().ok().and_then(|exe| wordcraft_mcp::live::launcher(&exe));
|
||||
eprintln!(
|
||||
"wordcraft-cli: tool calls go to the open WordCraft window while AI agents are on in ArtCraft Launcher, otherwise to a headless session (read root {}, write root {}; none: WordCraft's agent folder)",
|
||||
show(config.read_root.as_deref()),
|
||||
show(config.write_root.as_deref())
|
||||
);
|
||||
Box::new(wordcraft_mcp::Live::new(config))
|
||||
}
|
||||
};
|
||||
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(), std::io::stdout())?)
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
|
||||
@@ -38,7 +38,7 @@ fn validators_accept_only_the_documented_options() {
|
||||
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("mcp", &args(&["--headless", "--when-closed", "launch"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
@@ -326,18 +326,32 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// `mcp`'s plan never runs anything unconfined (shared rule 18): headless needs both roots, and
|
||||
/// with the suite's AI-MCP flag the live client runs without them only while the launcher's switch
|
||||
/// lets agents into the window, which confines them to its agent folder.
|
||||
#[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}");
|
||||
fn mcp_never_plans_an_unconfined_session() {
|
||||
let scratch = Scratch::new("mcp-plan");
|
||||
let root = |read: bool, write: bool| {
|
||||
let (r, w) = (read.then_some(scratch.0.as_path()), write.then_some(scratch.0.as_path()));
|
||||
wordcraft_engine::file_access::AutomationRoots::new(r, w).unwrap()
|
||||
};
|
||||
let both = || root(true, true);
|
||||
// --headless, or no flag: both roots or nothing.
|
||||
for (headless, flag, switch) in [(true, true, true), (true, false, false), (false, false, true), (false, false, false)] {
|
||||
assert!(matches!(mcp_plan(both(), headless, flag, switch), Ok(McpPlan::Headless(_))));
|
||||
for partial in [None, root(true, false), root(false, true)] {
|
||||
assert_eq!(mcp_plan(partial, headless, flag, switch).unwrap_err(), MCP_NEEDS_ROOTS);
|
||||
}
|
||||
}
|
||||
// The flag and the switch: the window, with or without roots.
|
||||
for roots in [None, root(true, false), both()] {
|
||||
assert!(matches!(mcp_plan(roots, false, true, true), Ok(McpPlan::Live(_))));
|
||||
}
|
||||
// The flag without the switch: only with both roots, which confine its headless sessions.
|
||||
assert!(matches!(mcp_plan(both(), false, true, false), Ok(McpPlan::Live(Some(_)))));
|
||||
for partial in [None, root(true, false), root(false, true)] {
|
||||
assert_eq!(mcp_plan(partial, false, true, false).unwrap_err(), MCP_NEEDS_ROOTS_OR_AGENTS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,19 +366,38 @@ 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.
|
||||
/// `mcp --author` without a name is refused, also when another option follows it, instead of
|
||||
/// starting with the default author or that option as the name.
|
||||
#[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}");
|
||||
fn mcp_author_needs_a_name() {
|
||||
assert_eq!(mcp_author(&args(&["--headless", "--author", "Claude"])), Ok(Some("Claude".to_string())));
|
||||
assert_eq!(mcp_author(&args(&["--headless"])), Ok(None));
|
||||
for given in [vec!["--author"], vec!["--author", "--headless"], vec!["--author", "A", "--author", "B"]] {
|
||||
assert!(mcp_author(&args(&given)).is_err(), "{given:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The deprecated `--connect` is taken out with its value, whether it has one, written apart or as
|
||||
/// `--connect=…`, and leaves the other options as they were.
|
||||
#[test]
|
||||
fn mcp_connect_is_taken_out_with_its_value() {
|
||||
for (given, left) in [
|
||||
(vec!["--connect", "127.0.0.1:9", "--author", "Claude"], vec!["--author", "Claude"]),
|
||||
(vec!["--connect"], vec![]),
|
||||
(vec!["--connect", "--author", "Claude"], vec!["--author", "Claude"]),
|
||||
(vec!["--headless", "--connect=127.0.0.1:9"], vec!["--headless"]),
|
||||
(vec!["--connect=", "--connect", "x"], vec![]),
|
||||
] {
|
||||
let mut rest = args(&given);
|
||||
assert!(take_connect(&mut rest), "{given:?}");
|
||||
assert_eq!(rest, args(&left), "{given:?}");
|
||||
assert!(validate_options("mcp", &rest, MCP_OPTIONS).is_ok());
|
||||
}
|
||||
let mut rest = args(&["--author", "Claude"]);
|
||||
assert!(!take_connect(&mut rest));
|
||||
assert_eq!(rest, args(&["--author", "Claude"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Removes the temporary test folder when the test finishes or panics.
|
||||
struct TempRoot(PathBuf);
|
||||
|
||||
impl TempRoot {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_saves_home_relative_paths_and_can_clear_the_override() {
|
||||
let root = TempRoot(std::env::temp_dir().join(format!("wc-custom-dictionary-{}", std::process::id())));
|
||||
let home = root.0.join("home");
|
||||
let profile = root.0.join("profile");
|
||||
for folder in [&home, &profile] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
std::fs::write(folder.join("custom.dic"), "wordcraftdictionary\n").unwrap();
|
||||
}
|
||||
let (preferred, fallback) = if cfg!(windows) { (&profile, &home) } else { (&home, &profile) };
|
||||
let options = |home: Option<&Path>, profile: Option<&Path>, paths: &[&str]| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(home) = home {
|
||||
cli.env("HOME", home);
|
||||
}
|
||||
if let Some(profile) = profile {
|
||||
cli.env("USERPROFILE", profile);
|
||||
}
|
||||
cli.args(["run", "--print"]);
|
||||
for path in paths {
|
||||
cli.args(["--cmd", &format!("file.options={}", json!({"customDictionary": path})), "--cmd", "file.options"]);
|
||||
}
|
||||
cli.output().unwrap()
|
||||
};
|
||||
let assert_saved = |home, profile, paths: &[&str], expected: &[Option<&Path>]| {
|
||||
let report = options(home, profile, paths);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), expected.len() * 2, "{out}");
|
||||
for (pair, expected) in reads.as_chunks::<2>().0.iter().zip(expected) {
|
||||
for read in pair {
|
||||
assert_eq!(read["customDictionary"].as_str().map(Path::new), *expected, "{out}");
|
||||
}
|
||||
}
|
||||
};
|
||||
let assert_refused = |home, profile, path, reason: &str| {
|
||||
let report = options(home, profile, &[path]);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
|
||||
let dic = preferred.join("custom.dic");
|
||||
let absolute = dic.to_str().unwrap();
|
||||
assert_saved(Some(&home), Some(&profile), &["~/custom.dic"], &[Some(&dic)]);
|
||||
assert_saved(None, None, &[absolute, "auto", absolute, ""], &[Some(&dic), None, Some(&dic), None]);
|
||||
let empty = Path::new("");
|
||||
let (empty_home, empty_profile) = if cfg!(windows) { (fallback.as_path(), empty) } else { (empty, fallback.as_path()) };
|
||||
assert_saved(Some(empty_home), Some(empty_profile), &["~/custom.dic"], &[Some(&fallback.join("custom.dic"))]);
|
||||
assert_refused(None, None, "~/custom.dic", "cannot expand");
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(&home), Some(&profile), &[r"~\custom.dic"], &[Some(&dic)]);
|
||||
assert_refused(None, None, r"~\custom.dic", "cannot expand");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\C:\custom.dic", "relative to the home folder");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\\custom.dic", "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(&home), Some(&profile), r"~\custom.dic", "isn't a full path");
|
||||
}
|
||||
root.remove().unwrap();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn folder_options_save_home_relative_paths_and_validate_before_reading() {
|
||||
let profile = std::env::temp_dir().join(format!("wc-folder-options-profile-{}", std::process::id()));
|
||||
let templates = profile.join("Templates").join("Personal");
|
||||
let dictionaries = profile.join("Dictionaries");
|
||||
std::fs::create_dir_all(&templates).unwrap();
|
||||
std::fs::create_dir_all(&dictionaries).unwrap();
|
||||
let options = |profile: Option<&Path>, params: Value| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(profile) = profile {
|
||||
cli.env(if cfg!(windows) { "USERPROFILE" } else { "HOME" }, profile);
|
||||
}
|
||||
cli.args(["run", "--print", "--cmd", &format!("file.options={params}"), "--cmd", "file.options"]).output().unwrap()
|
||||
};
|
||||
let assert_saved = |profile, params| {
|
||||
let report = options(profile, params);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), 2, "{out}");
|
||||
for read in reads {
|
||||
assert_eq!(Path::new(read["userTemplatesFolder"].as_str().unwrap()), templates);
|
||||
assert_eq!(Path::new(read["dictionariesFolder"].as_str().unwrap()), dictionaries);
|
||||
}
|
||||
};
|
||||
assert_saved(Some(profile.as_path()), json!({"userTemplatesFolder": "~/Templates/Personal", "dictionariesFolder": "~/Dictionaries"}));
|
||||
assert_saved(None, json!({"userTemplatesFolder": templates, "dictionariesFolder": dictionaries}));
|
||||
|
||||
let win_params = json!({"userTemplatesFolder": r"~\Templates/Personal", "dictionariesFolder": r"~\Dictionaries"});
|
||||
let assert_refused = |profile, params, reason: &str| {
|
||||
let report = options(profile, params);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(profile.as_path()), win_params.clone());
|
||||
assert_refused(None, win_params, "cannot expand");
|
||||
assert_refused(Some(profile.as_path()), json!({"userTemplatesFolder": r"~\C:\Templates"}), "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(profile.as_path()), win_params, "isn't a full path");
|
||||
}
|
||||
assert_refused(None, json!({"dictionariesFolder": "~/Dictionaries"}), "cannot expand");
|
||||
assert_refused(None, json!({"userTemplatesFolder": r"\\unreachable.invalid\share"}), "can't be a network folder");
|
||||
std::fs::remove_dir_all(profile).unwrap();
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod custom_dictionary;
|
||||
mod folder_options;
|
||||
mod help;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
@@ -12,3 +14,4 @@ mod picture_then_typing;
|
||||
mod reproducible_pdf;
|
||||
mod strict;
|
||||
mod text_tracked;
|
||||
mod wrote_on_stdout;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
|
||||
//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop
|
||||
//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files
|
||||
//! outside them, through the real binary.
|
||||
//! `--automation-read-root` and `--automation-write-root` unless the ArtCraft Launcher's switch
|
||||
//! lets agents into WordCraft's window (which confines them to its agent folder), takes the
|
||||
//! deprecated `--connect` with a note, and with both roots refuses files outside them, through the
|
||||
//! real binary. Each run gets its own suite flags, launcher folder and settings folder, so this
|
||||
//! machine's own never count.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -48,11 +50,17 @@ fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
|
||||
/// Run `wordcraft-cli mcp <args>` without the suite's AI-MCP flag, send `lines` on stdin, then hang up.
|
||||
fn mcp(args: &[String], lines: &[Value]) -> Output {
|
||||
mcp_with(args, lines, &[("CRAFT_FLAGS", "-AI-MCP".into())])
|
||||
}
|
||||
|
||||
/// [`mcp`] with these environment variables.
|
||||
fn mcp_with(args: &[String], lines: &[Value], env: &[(&str, std::ffi::OsString)]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.envs(env.iter().map(|(k, v)| (*k, v)))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -99,17 +107,60 @@ fn mcp_refuses_to_start_without_both_roots() {
|
||||
assert!(reply.get("error").is_none(), "{reply}");
|
||||
}
|
||||
|
||||
/// `--connect` is kept for one release: it says it is deprecated and is otherwise ignored, so a
|
||||
/// client configuration that still has it keeps working, and it opens no way around the roots.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
fn mcp_connect_is_a_deprecated_alias_of_plain_mcp() {
|
||||
let folders = Folders::new("connect");
|
||||
let base = folders.0.clone();
|
||||
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
|
||||
let why = ["--connect", "#3695", "#5819"];
|
||||
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why);
|
||||
refused_at_start(
|
||||
let out = mcp(
|
||||
&["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write],
|
||||
&why,
|
||||
&[serde_json::from_str(PING).unwrap()],
|
||||
);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "stderr: {stderr}");
|
||||
assert!(stderr.contains("--connect is deprecated"), "{stderr}");
|
||||
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
|
||||
assert_eq!(reply["id"], 1, "{reply}");
|
||||
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &["--connect is deprecated", "--automation-read-root"]);
|
||||
}
|
||||
|
||||
/// With the suite's AI-MCP flag: while the launcher's switch keeps agents out, `mcp` still needs
|
||||
/// both roots and says how to let agents in; once the launcher's list names WordCraft, plain `mcp`
|
||||
/// starts without roots and follows the closed-app choice (here: ask to open WordCraft).
|
||||
#[test]
|
||||
fn with_the_flag_the_launcher_switch_lets_plain_mcp_start() {
|
||||
let folders = Folders::new("switch");
|
||||
let base = folders.0.clone();
|
||||
let launcher = base.join("launcher");
|
||||
let settings = base.join("settings");
|
||||
std::fs::create_dir_all(&launcher).unwrap();
|
||||
std::fs::create_dir_all(&settings).unwrap();
|
||||
std::fs::write(settings.join("config.toml"), "schema_version = 1\n[integrations]\nwhenAppClosed = \"error\"\n").unwrap();
|
||||
let env = [
|
||||
("CRAFT_FLAGS", std::ffi::OsString::from("AI-MCP")),
|
||||
("CRAFT_MCP_DIR", launcher.clone().into_os_string()),
|
||||
("WORDCRAFT_PROFILE_DIR", settings.into_os_string()),
|
||||
];
|
||||
let ping: Value = serde_json::from_str(PING).unwrap();
|
||||
let off = mcp_with(&[], std::slice::from_ref(&ping), &env);
|
||||
let stderr = String::from_utf8_lossy(&off.stderr);
|
||||
assert!(!off.status.success() && off.stdout.is_empty(), "started with the switch off: {stderr}");
|
||||
assert!(stderr.contains("ArtCraft Launcher") && stderr.contains("--automation-read-root"), "{stderr}");
|
||||
|
||||
let cli = s(Path::new(env!("CARGO_BIN_EXE_wordcraft-cli")));
|
||||
let list = json!({"version": 1, "apps": [{"id": "wordcraft", "name": "WordCraft", "command": cli, "args": ["mcp"]}]});
|
||||
std::fs::write(launcher.join("apps.json"), list.to_string()).unwrap();
|
||||
let on = mcp_with(&[], &[ping, tool(2, "list_documents", json!({}))], &env);
|
||||
let stderr = String::from_utf8_lossy(&on.stderr);
|
||||
assert!(on.status.success(), "stderr: {stderr}");
|
||||
let replies: Vec<Value> =
|
||||
String::from_utf8_lossy(&on.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert!(replies.iter().any(|r| r["id"] == 1 && r.get("error").is_none()), "{replies:?}");
|
||||
let call = replies.iter().find(|r| r["id"] == 2).expect("the tool call is answered");
|
||||
assert_eq!(call["result"]["isError"], true, "{call}");
|
||||
assert!(call.to_string().contains("isn't running"), "the closed-app choice answers: {call}");
|
||||
}
|
||||
|
||||
/// `tools/call` request `id` for `name` with `arguments`.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! A write's `wrote <path>` confirmation is a result, so it goes to stdout, where a script that
|
||||
//! captures the output finds it; stderr keeps errors and diagnostics (#7070).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("wc-cli-wrote-{name}-{}", std::process::id()));
|
||||
// A failed run leaves its directory behind (cleanup runs only after the assertions), and a
|
||||
// later process can reuse the PID: start clean so a stale file cannot pass a check.
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The confirmation is on stdout and not on stderr, and the file is there.
|
||||
fn assert_wrote_on_stdout(run: &Output, out: &Path) {
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
assert!(out.is_file(), "{} was not written", out.display());
|
||||
let line = format!("wrote {}", out.display());
|
||||
assert!(stdout.lines().any(|l| l == line), "stdout lacks `{line}`: {stdout:?}");
|
||||
assert!(!stderr.contains("wrote "), "the confirmation is on stderr too: {stderr:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_confirms_the_write_on_stdout() {
|
||||
let d = dir("convert");
|
||||
let (input, out) = (d.join("in.txt"), d.join("out.docx"));
|
||||
std::fs::write(&input, "Hello").unwrap();
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&out).output().unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_confirms_each_save_on_stdout() {
|
||||
let d = dir("run");
|
||||
let out = d.join("out.docx");
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.args(["run", "--template", "blank", "--cmd", r#"text.insert={"text":"x"}"#, "--save"])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A reader that has already hung up does not stop the job: every save still runs, though its
|
||||
/// confirmation has nowhere to go. A PNG is written only in the confirming loop, so it shows a
|
||||
/// save that was skipped.
|
||||
#[test]
|
||||
fn run_keeps_saving_after_stdout_closes() {
|
||||
let d = dir("closed");
|
||||
let job = d.join("job.json");
|
||||
std::fs::write(
|
||||
&job,
|
||||
r#"{"template": "blank", "commands": [{"command": "text.insert", "params": {"text": "x"}}], "save": ["first.docx", "second.png"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (reader, writer) = std::io::pipe().unwrap();
|
||||
drop(reader);
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(["run", "--script"]).arg(&job).stdout(writer).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
for out in ["first.docx", "second.png"] {
|
||||
assert!(d.join(out).is_file(), "{out} was not written; stderr: {stderr}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -36,6 +36,7 @@ craft = { workspace = true, features = [
|
||||
"ui-app",
|
||||
"dialogs",
|
||||
"automation",
|
||||
"automation-agents",
|
||||
"gpu-startup",
|
||||
"print",
|
||||
"settings",
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! A connection authenticates once with the token (`docs/control-protocol.md`, Token). When no
|
||||
//! token or token file is supplied, the app generates a token and writes it to
|
||||
//! `<settings>/control-key.<instance>` (mode 0600) after the port is bound, and removes the file
|
||||
//! when the window closes.
|
||||
//! when the window closes. The server itself goes to the agent link for the run
|
||||
//! (`AgentLink::from_launch`), so File › Options › Agents says the launch options manage it.
|
||||
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -25,11 +26,28 @@ pub struct Control {
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// The server, for the agent link to keep for the whole run (`AgentLink::from_launch`), and the
|
||||
/// token file this run wrote, which the app removes when the window closes.
|
||||
pub fn split(self) -> (Listening, TokenFile) {
|
||||
(self.listening, TokenFile(self.created))
|
||||
}
|
||||
|
||||
/// Stop accepting connections and remove the token file this run wrote, if any.
|
||||
#[cfg(test)]
|
||||
pub fn shut_down(self) {
|
||||
let Self { listening, created } = self;
|
||||
let (listening, file) = self.split();
|
||||
drop(listening);
|
||||
remove(created.as_deref());
|
||||
file.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/// The default token file a run wrote, if any; a token file the user supplied is never removed.
|
||||
pub struct TokenFile(Option<PathBuf>);
|
||||
|
||||
impl TokenFile {
|
||||
/// Removes the file this run wrote.
|
||||
pub fn remove(self) {
|
||||
remove(self.0.as_deref());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+38
-10
@@ -67,8 +67,8 @@ struct App {
|
||||
settings: SharedSettings<Prefs>,
|
||||
/// The print spool, a handle on the one in the app's services: jobs being sent finish first.
|
||||
spool: Spool,
|
||||
/// The control server, when `--control` started one; it removes the token file it made.
|
||||
control: Option<control_server::Control>,
|
||||
/// The token file `--control` wrote, removed at exit; its server runs in the agent link.
|
||||
control: Option<control_server::TokenFile>,
|
||||
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
|
||||
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
|
||||
exit: Option<Box<dyn FnOnce()>>,
|
||||
@@ -118,8 +118,8 @@ impl App {
|
||||
if let Err(e) = self.settings.lock().flush() {
|
||||
log::warn!("preferences: {e}");
|
||||
}
|
||||
if let Some(control) = self.control.take() {
|
||||
control.shut_down();
|
||||
if let Some(file) = self.control.take() {
|
||||
file.remove();
|
||||
}
|
||||
if !launch_profile::current().is_nightly() {
|
||||
self.app.start_pending_update();
|
||||
@@ -858,13 +858,41 @@ fn main() -> eframe::Result {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents)
|
||||
// names WordCraft, the agent link serves them and publishes where, so `wordcraft-cli mcp`
|
||||
// finds the window. `--control` runs its own server for the whole run instead. Allow
|
||||
// Agent Control off (File › Options › Agents) refuses both. A Nightly window serves none.
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
if !nightly {
|
||||
let settings_dir = wordcraft_control_key::settings_dir();
|
||||
// A file a crashed launch left behind names a port nothing serves; before this
|
||||
// launch's own listener, so it doesn't keep it.
|
||||
if let Some(dir) = &settings_dir {
|
||||
craft::automation::agents::remove_stale_connection(dir);
|
||||
}
|
||||
let allow = settings.lock().get().integrations.allow_agent_control;
|
||||
let launched = match control.port {
|
||||
Some(port) if !allow => {
|
||||
complain(format_args!("File › Options › Agents › Allow Agent Control is off: not listening on port {port}"));
|
||||
None
|
||||
}
|
||||
Some(port) => control_server::start(&control, port, WindowHost::of(&ctx), settings_dir.as_deref()),
|
||||
None => None,
|
||||
};
|
||||
let link = match launched {
|
||||
Some((rx, started)) => {
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
let (listening, token_file) = started.split();
|
||||
control_server = Some(token_file);
|
||||
craft::automation::agents::AgentLink::from_launch(listening)
|
||||
}
|
||||
None => craft::automation::agents::AgentLink::new(settings_dir, format!("WordCraft {}", env!("CARGO_PKG_VERSION"))),
|
||||
};
|
||||
let switch = craft::automation::agents::AgentSwitch::watch(wordcraft_ui_egui::agents::LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
app = app.with_agents(wordcraft_ui_egui::agents::Agents::new(link, switch));
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
|
||||
@@ -206,6 +206,10 @@ display_name = "entropybeater"
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
|
||||
@@ -813,8 +813,14 @@ impl Document {
|
||||
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
|
||||
/// JSON, whose run lengths may overflow, fall short or split a character.
|
||||
pub fn normalize_runs(&mut self) {
|
||||
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
let separators = [&mut self.footnote_separators, &mut self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&mut s.separator, &mut s.continuation_separator, &mut s.continuation_notice])
|
||||
.flatten();
|
||||
let stories = std::iter::once(&mut self.body)
|
||||
.chain(self.parts.values_mut().map(|part| &mut part.blocks))
|
||||
.chain(separators)
|
||||
.chain(self.glossary.iter_mut().map(|entry| &mut entry.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
|
||||
|
||||
@@ -387,6 +387,14 @@ impl Counters {
|
||||
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
|
||||
}
|
||||
|
||||
/// The values counted so far for `num`, including implicitly counted ancestors and zero starts.
|
||||
/// An unstarted level has no value even when its definition has a default start.
|
||||
pub fn counted_values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> [Option<u32>; 9] {
|
||||
let Some(abs) = numbering.abstract_of(num) else { return [None; 9] };
|
||||
let (Some(values), Some(flags)) = (self.state.get(&abs.id), self.flags.get(&abs.id)) else { return [None; 9] };
|
||||
std::array::from_fn(|level| flags[level].started.then_some(values[level]))
|
||||
}
|
||||
|
||||
fn next_label_from(&mut self, n: &Num, abs: &AbstractNum, level: u8) -> Option<(String, Level)> {
|
||||
let num = n.id;
|
||||
let lv = (level as usize).min(8);
|
||||
@@ -493,16 +501,19 @@ impl Counters {
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholder_level(digit: char) -> Option<usize> {
|
||||
digit.to_digit(10).filter(|d| (1..=9).contains(d)).map(|d| (d - 1) as usize)
|
||||
}
|
||||
|
||||
/// The zero-based levels a label template shows (`"%1.%2"` → `[0, 1]`, `"(%3)"` → `[2]`).
|
||||
pub fn template_levels(text: &str) -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
let mut chars = text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
if !out.contains(&k) {
|
||||
out.push(k);
|
||||
}
|
||||
@@ -518,11 +529,9 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
|
||||
let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
&& (1..=9).contains(&d)
|
||||
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
let val = vals.get(k).copied().unwrap_or(0);
|
||||
let counted = started.get(k).is_some_and(|f| f.started);
|
||||
let level = level_def(k);
|
||||
@@ -869,6 +878,23 @@ mod tests {
|
||||
assert_eq!(labels, ["0.", "1.", "2."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_counted_zero_ancestor_replaces_the_unstarted_fallback() {
|
||||
let mut numbering = Numbering::default();
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
numbering.abstracts[0].levels[0].start = 7;
|
||||
numbering.abstracts[0].levels[1] = Level { text: "%1.%2.".into(), ..Default::default() };
|
||||
numbering.nums[0].start_overrides = vec![(0, 0)];
|
||||
let index = NumberingIndex::new(&numbering);
|
||||
let mut counters = Counters::default();
|
||||
|
||||
assert_eq!(counters.counted_values_indexed(&index, num)[0], None);
|
||||
assert_eq!(counters.current_label(&numbering, num, 1).as_deref(), Some("7.1."));
|
||||
let (label, _) = counters.next_label_indexed(&index, num, 1).unwrap();
|
||||
assert_eq!(label, "0.1.");
|
||||
assert_eq!(counters.counted_values_indexed(&index, num)[0], Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_percent_zero_is_preserved_as_literal() {
|
||||
let mut n = Numbering::default();
|
||||
@@ -878,6 +904,7 @@ mod tests {
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "%0 1.");
|
||||
assert_eq!(template_levels("%0 %2. %9 %2"), [1, 8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -773,6 +773,10 @@ pub struct SectionProps {
|
||||
pub page_w: f32,
|
||||
pub page_h: f32,
|
||||
pub landscape: bool,
|
||||
/// Top and bottom margins, points. Negative is Word's exact margin (`w:pgMar` `w:top` /
|
||||
/// `w:bottom` below zero, ECMA-376 §17.6.11; DOC `dyaTop` / `dyaBottom`): the text starts
|
||||
/// (ends) at the absolute value from the page edge even when the header (footer) is taller,
|
||||
/// and overlaps it.
|
||||
pub margin_top: f32,
|
||||
pub margin_bottom: f32,
|
||||
pub margin_left: f32,
|
||||
@@ -912,17 +916,21 @@ impl SectionProps {
|
||||
pub fn text_width(&self) -> f32 {
|
||||
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
|
||||
}
|
||||
/// Height of the text area between the margins, points (a negative, exact margin counts at
|
||||
/// its size).
|
||||
pub fn text_height(&self) -> f32 {
|
||||
(self.page_h - self.margin_top - self.margin_bottom).max(18.0)
|
||||
(self.page_h - self.margin_top.abs() - self.margin_bottom.abs()).max(18.0)
|
||||
}
|
||||
/// Swap to landscape/portrait (keeps margins relative to the paper as Word does: rotates them).
|
||||
/// An exact (negative) top or bottom turns into a side at its size, as in Word: only the top
|
||||
/// and bottom can be exact.
|
||||
pub fn set_landscape(&mut self, on: bool) {
|
||||
if on == self.landscape {
|
||||
return;
|
||||
}
|
||||
self.landscape = on;
|
||||
std::mem::swap(&mut self.page_w, &mut self.page_h);
|
||||
let (t, b, l, r) = (self.margin_top, self.margin_bottom, self.margin_left, self.margin_right);
|
||||
let (t, b, l, r) = (self.margin_top.abs(), self.margin_bottom.abs(), self.margin_left, self.margin_right);
|
||||
if on {
|
||||
self.margin_top = l;
|
||||
self.margin_bottom = r;
|
||||
|
||||
@@ -959,6 +959,25 @@ fn normalize_runs_reconciles_objects_with_markers() {
|
||||
// Deleting the first marker keeps B on the second.
|
||||
p.delete(1, 4).unwrap();
|
||||
assert_eq!(p.objects, vec![fs("B")]);
|
||||
|
||||
let mut d = build();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects.push(fs("Surplus"));
|
||||
p.runs[0].len = 1;
|
||||
d.footnote_separators.continuation_notice = Some(d.body.clone());
|
||||
d.endnote_separators.separator = Some(d.body.clone());
|
||||
d.glossary.push(BuildingBlock { name: "Quick Parts example".into(), blocks: d.body.clone(), ..Default::default() });
|
||||
d.normalize_runs();
|
||||
for (name, blocks) in [
|
||||
("footnote continuation notice", d.footnote_separators.continuation_notice.as_ref().unwrap()),
|
||||
("endnote separator", d.endnote_separators.separator.as_ref().unwrap()),
|
||||
("Quick Parts entry", &d.glossary[0].blocks),
|
||||
] {
|
||||
edit::each_para(&blocks[0], 0, &mut |p| {
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")], "{name} drops the surplus object");
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len(), "{name} repairs its runs");
|
||||
});
|
||||
}
|
||||
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
|
||||
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
|
||||
let reconcile = |extra: usize| {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::{NBSP, OBJ};
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
@@ -113,6 +114,47 @@ fn bidi_para(s: &Session) -> bool {
|
||||
|
||||
/// Left/Right: with a selection and no Shift, collapse to its edge.
|
||||
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
|
||||
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
|
||||
}
|
||||
lr_along(s, v, is_left)
|
||||
}
|
||||
|
||||
/// The text direction at the caret when it is in turned (vertical) text.
|
||||
fn turn(s: &mut Session) -> Option<TextDirection> {
|
||||
let l = s.layout();
|
||||
l.turn_at(&s.sel.focus, s.page_hint)
|
||||
}
|
||||
|
||||
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
|
||||
/// such line in the caret's flow (a table cell's only line, the last column), Left/Right step along
|
||||
/// the text as they did before (`is_left`: backwards).
|
||||
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
s.sel = Selection::caret(if next { b } else { a });
|
||||
s.goal_x = None;
|
||||
return sel_result(s);
|
||||
}
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
|
||||
Some((p, g)) => {
|
||||
s.goal_x = Some(g);
|
||||
p
|
||||
}
|
||||
None => return lr_along(s, v, is_left),
|
||||
};
|
||||
let gx = s.goal_x;
|
||||
apply(s, to, ext);
|
||||
s.goal_x = gx;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Left/Right as a step along the text (`is_left`: backwards).
|
||||
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
@@ -263,7 +305,7 @@ fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool)
|
||||
Pos { story, path, off }
|
||||
}
|
||||
|
||||
fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
fn visible_word_start(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let byte = off.checked_sub(1)?;
|
||||
let (i, range) = run_at_byte(para, byte)?;
|
||||
@@ -275,7 +317,7 @@ fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
let start = end.saturating_sub(run.len);
|
||||
let range_end = end.min(off);
|
||||
end = start;
|
||||
if run.props.del.is_some() {
|
||||
if hides(run.props.del) {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..range_end) else { continue };
|
||||
@@ -294,7 +336,7 @@ fn visible_word_start(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
seen_visible.then_some(idx)
|
||||
}
|
||||
|
||||
fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
fn visible_word_end(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let (i, range) = run_at_byte(para, off)?;
|
||||
let mut first_word = None;
|
||||
@@ -305,7 +347,7 @@ fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
let run_end = run_start.saturating_add(run.len);
|
||||
let start = run_start.max(off);
|
||||
run_start = run_end;
|
||||
if run.props.del.is_some() {
|
||||
if hides(run.props.del) {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..run_end) else { continue };
|
||||
@@ -328,9 +370,10 @@ fn visible_word_end(para: &Paragraph, off: usize) -> Option<usize> {
|
||||
}
|
||||
|
||||
fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
let hidden = s.layout_hides_deleted(p.story);
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if !s.view.show_markup {
|
||||
if let Some(off) = visible_word_start(para, p.off) {
|
||||
if hidden.any() {
|
||||
if let Some(off) = visible_word_start(para, p.off, |del| hidden.hides(&s.doc, del)) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off > 0 {
|
||||
@@ -341,9 +384,10 @@ fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
}
|
||||
|
||||
fn word_right(s: &mut Session, p: &Pos) -> Pos {
|
||||
let hidden = s.layout_hides_deleted(p.story);
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if !s.view.show_markup {
|
||||
if let Some(off) = visible_word_end(para, p.off) {
|
||||
if hidden.any() {
|
||||
if let Some(off) = visible_word_end(para, p.off, |del| hidden.hides(&s.doc, del)) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off < para.len() {
|
||||
@@ -374,6 +418,10 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
|
||||
}
|
||||
|
||||
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
|
||||
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
|
||||
}
|
||||
let ext = extend(v);
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
|
||||
@@ -26,6 +26,7 @@ use generated::ENTRY_STYLE;
|
||||
pub(crate) use generated::generated_list;
|
||||
use generated::table_of_figures;
|
||||
pub use generated::{figures_instr, update_generated};
|
||||
pub(super) use generated::{is_list_entry, wrapped_list};
|
||||
pub use render::{cite, entry};
|
||||
pub use sources::update_citations;
|
||||
use sources::{citation, sources};
|
||||
|
||||
@@ -65,6 +65,7 @@ fn generated_list_with(s: &mut Session, instr: &str, title: &str, leader: Option
|
||||
seed.props.tabs = Some(vec![TabStop { pos: 0.0, align: TabAlign::Right, leader }]);
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i.saturating_add(1)), Block::Para(seed))?;
|
||||
}
|
||||
s.touch();
|
||||
update_generated(s)
|
||||
}
|
||||
|
||||
@@ -74,7 +75,7 @@ const MAX_WRAPPED: usize = 10_000;
|
||||
/// A generated list (index, bibliography, table of figures or authorities) held as a complex
|
||||
/// field that starts at body block `i` and runs over its entries: its field code and the block
|
||||
/// it ends in. `None` for anything else (a TOC has its own update).
|
||||
fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
|
||||
pub(in crate::cmd) fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
|
||||
let p = s.doc.body.get(i)?.as_para()?;
|
||||
let (k, off, instr) = p.objects_with_offsets().enumerate().find_map(|(k, (off, o))| match o {
|
||||
InlineObject::FieldStart { instr, .. } => {
|
||||
@@ -197,9 +198,15 @@ fn caption_body(p: &Paragraph, label: &str) -> String {
|
||||
|
||||
pub(super) const ENTRY_STYLE: &str = "ListEntry";
|
||||
|
||||
/// A result paragraph can share its style with a field header split out of an imported list.
|
||||
pub(in crate::cmd) fn is_list_entry(p: &Paragraph) -> bool {
|
||||
p.props.style.as_deref() == Some(ENTRY_STYLE) && list_kind(p).is_none()
|
||||
}
|
||||
|
||||
/// Rebuild every generated list.
|
||||
pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
let mut i = 0;
|
||||
let mut relocated_index_leader = None;
|
||||
while i < s.doc.body.len() {
|
||||
// A list held as a field around its entries (as Word and ODT files hold them): made the
|
||||
// field's own paragraph, as WordCraft inserts one, its old entries rebuilt below.
|
||||
@@ -207,7 +214,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
// break, are the document's and stay.
|
||||
// (The field it is made: what comes before it in its paragraph may hold other fields.)
|
||||
let mut converted = None;
|
||||
let mut index_leader = None;
|
||||
if let Some((instr, start, last, end)) = wrapped_list(s, i) {
|
||||
if instr.starts_with("INDEX") {
|
||||
index_leader = crate::cmd::index::wrapped_entry_leader(s, i, start, last, end);
|
||||
}
|
||||
// The entries between its first and last paragraphs go.
|
||||
for _ in i.saturating_add(1)..last {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
@@ -247,9 +258,14 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
|
||||
if p.objects_with_offsets().any(|(off, o)| off < start && list_field(o).is_some()) {
|
||||
let list = p.split_off(start)?;
|
||||
// Rebuilding the preceding list can shift the new paragraph's block index.
|
||||
if let Some(leader) = index_leader.take() {
|
||||
relocated_index_leader = Some((list.rev, leader));
|
||||
}
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1), Block::Para(list))?;
|
||||
converted = None;
|
||||
}
|
||||
s.touch();
|
||||
}
|
||||
let kind = converted.or_else(|| s.doc.body.get(i).and_then(|b| b.as_para()).and_then(list_kind));
|
||||
let Some(kind) = kind else {
|
||||
@@ -258,7 +274,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
};
|
||||
add_entry_style(s);
|
||||
if kind.starts_with("INDEX") {
|
||||
crate::cmd::index::rebuild_from(s, i, None, kind)?;
|
||||
let index_leader = index_leader.or_else(|| {
|
||||
let rev = s.doc.body.get(i)?.as_para()?.rev;
|
||||
relocated_index_leader.take_if(|(relocated, _)| *relocated == rev).map(|(_, leader)| leader)
|
||||
});
|
||||
crate::cmd::index::rebuild_from(s, i, index_leader, kind)?;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -290,11 +310,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
.body
|
||||
.get(i + 1)
|
||||
.and_then(|b| b.as_para())
|
||||
.filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE))
|
||||
.filter(|p| is_list_entry(p))
|
||||
.and_then(|p| p.props.tabs.as_ref()?.last().map(|t| t.leader))
|
||||
.or(saved_leader)
|
||||
.unwrap_or(TabLeader::Dot);
|
||||
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
|
||||
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(is_list_entry) {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
}
|
||||
let lines = entries_for(s, &kind);
|
||||
@@ -310,6 +330,7 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
}
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1 + k), Block::Para(para))?;
|
||||
}
|
||||
s.touch();
|
||||
i += 1;
|
||||
}
|
||||
s.touch();
|
||||
@@ -563,4 +584,56 @@ mod tests {
|
||||
assert_eq!(lists, [Some("INDEX".to_string()), Some("BIBLIOGRAPHY".to_string())]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_index_keeps_its_leader_when_split_from_a_bibliography() {
|
||||
let old_entry = "Old entry\t1";
|
||||
let mut s = wrapped("Old entry\t1\n\nKilns are hot.", 0, 0, old_entry.len());
|
||||
s.run("select.text", &serde_json::json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &serde_json::json!({})).unwrap();
|
||||
s.doc.sources.push(wordcraft_doc::Source { tag: "a".into(), kind: "book".into(), title: "Listed Source".into(), ..Default::default() });
|
||||
|
||||
let props = CharProps::default();
|
||||
let instr = "INDEX \\e \"\t\"";
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects[0] = InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false };
|
||||
p.insert_object(
|
||||
0,
|
||||
InlineObject::Field {
|
||||
instr: "BIBLIOGRAPHY".into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
p.props.style = Some(ENTRY_STYLE.into());
|
||||
p.props.tabs = Some(vec![TabStop { pos: 120.0, align: TabAlign::Right, leader: TabLeader::Hyphen }]);
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
// A separate INDEX with the same instruction has no prior result and must get the default.
|
||||
p.insert_object(
|
||||
0,
|
||||
InlineObject::Field { instr: instr.into(), result: String::new(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
s.touch();
|
||||
let (_, start, last, end) = wrapped_list(&s, 0).unwrap();
|
||||
assert_eq!(crate::cmd::index::wrapped_entry_leader(&mut s, 0, start, last, end), Some(TabLeader::Hyphen));
|
||||
|
||||
for _ in 0..2 {
|
||||
update_generated(&mut s).unwrap();
|
||||
let paras: Vec<_> = s.doc.body.iter().filter_map(|b| b.as_para()).collect();
|
||||
assert_eq!(list_kind(paras[0]).as_deref(), Some("BIBLIOGRAPHY"));
|
||||
assert!(paras[1].plain_text().contains("Listed Source"), "the bibliography inserts an entry before the relocated index");
|
||||
for (header, leader) in [(2, TabLeader::Hyphen), (4, TabLeader::Dot)] {
|
||||
assert_eq!(list_kind(paras[header]).as_deref(), Some(instr));
|
||||
assert_eq!(paras[header + 1].plain_text(), "Kilns\t1");
|
||||
assert_eq!(paras[header + 1].props.tabs.as_ref().unwrap()[0].leader, leader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +332,6 @@ mod tests {
|
||||
|
||||
/// Drawing commands must not search every page again for each glued connector.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
fn glued_pages(n: u32) -> Session {
|
||||
@@ -363,34 +362,33 @@ mod tests {
|
||||
assert_eq!(s.layout().pages.len(), n as usize);
|
||||
s
|
||||
}
|
||||
// Use the running thread's CPU time on Linux; scheduler pauses are not reroute work.
|
||||
fn cpu_cost(mut f: impl FnMut()) -> f64 {
|
||||
let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::<u64>().ok();
|
||||
let (wall, before) = (std::time::Instant::now(), ran());
|
||||
f();
|
||||
match (before, ran()) {
|
||||
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
|
||||
_ => wall.elapsed().as_secs_f64(),
|
||||
}
|
||||
}
|
||||
const SMALL: u32 = 500;
|
||||
const SMALL: u32 = 32;
|
||||
const SCALE: u32 = 8;
|
||||
let (mut small_min, mut big_min) = (f64::INFINITY, f64::INFINITY);
|
||||
let mut last_big = None;
|
||||
for _ in 0..3 {
|
||||
let mut small = glued_pages(SMALL);
|
||||
small_min = small_min.min(cpu_cost(|| assert!(reroute(&mut small))));
|
||||
let mut big = glued_pages(SMALL * SCALE);
|
||||
big_min = big_min.min(cpu_cost(|| assert!(reroute(&mut big))));
|
||||
last_big = Some(big);
|
||||
}
|
||||
let ratio = big_min / small_min.max(1e-9);
|
||||
eprintln!("{SMALL} vs {} pages reroute: {small_min:.4}s vs {big_min:.4}s (ratio {ratio:.2}x)", SMALL * SCALE);
|
||||
assert!(ratio < SCALE as f64 * 3.0, "reroute scaled superlinearly: {small_min:.4}s -> {big_min:.4}s ({ratio:.2}x for {SCALE}x pages)");
|
||||
let mut big = last_big.unwrap();
|
||||
let mut small = glued_pages(SMALL);
|
||||
let mut big = glued_pages(SMALL * SCALE);
|
||||
let layout = big.layout();
|
||||
let small_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut small)));
|
||||
let big_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut big)));
|
||||
// One layout walk to build the index plus bounded work per connector: roughly 8x the
|
||||
// steps for 8x the pages. Allow room for fixed differences in the first and last pages.
|
||||
let budget = small_steps * 12;
|
||||
assert!(small_steps > 0 && big_steps > small_steps, "reroute steps: {small_steps} -> {big_steps}");
|
||||
assert!(big_steps <= budget, "reroute repeated lookup work: {small_steps} -> {big_steps} steps for {SCALE}x pages");
|
||||
|
||||
// The previous lookup starts at the caret's page for every connector. Run just that
|
||||
// part of the old route to verify it would exceed the same budget on this fixture.
|
||||
let connector_off = 2 * wordcraft_doc::para::OBJ.len_utf8();
|
||||
let scan_steps = wordcraft_doc::work::count(|| {
|
||||
for page in 0..layout.pages.len() {
|
||||
let hit = layout.object(&Pos::body(page, connector_off), 0).unwrap();
|
||||
assert_eq!(hit.page, page);
|
||||
}
|
||||
});
|
||||
assert!(scan_steps > budget, "per-connector scans took only {scan_steps} steps for a budget of {budget}");
|
||||
|
||||
for path in big.doc.para_paths(StoryRef::Body) {
|
||||
let para = big.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(connector_off).unwrap() else { panic!("connector") };
|
||||
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
|
||||
}
|
||||
big.touch();
|
||||
|
||||
@@ -7,6 +7,9 @@ use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
use super::{delete_selection, find_pattern, pos_json, sel_result};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
/// Ribbon location of the linked Cut, Copy and Paste commands.
|
||||
pub const LINKED_CLIPBOARD_LOCATION: &str = "Home › Clipboard";
|
||||
|
||||
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
|
||||
/// advertise a web alternative through the same registry/keymap as every other command.
|
||||
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
|
||||
@@ -72,8 +75,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.key("Mod+Y / Mod+Shift+Z")
|
||||
.pure(),
|
||||
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
CommandSpec::new("edit.cut", "Cut", LINKED_CLIPBOARD_LOCATION, cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", LINKED_CLIPBOARD_LOCATION, copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
|
||||
// Parts and AutoText insert it without emptying it, as in Word.
|
||||
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
|
||||
@@ -86,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("the Spike is empty")
|
||||
}
|
||||
}),
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
|
||||
CommandSpec::new("edit.paste", "Paste", LINKED_CLIPBOARD_LOCATION, paste)
|
||||
.key("Mod+V / Shift+Insert")
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
|
||||
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
|
||||
@@ -857,9 +860,20 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
found.push(results);
|
||||
}
|
||||
let n: usize = found.iter().map(Vec::len).sum();
|
||||
// The main text comes last, so under Track Changes the caret ends where it did before.
|
||||
let saved_sel = s.sel.clone();
|
||||
let orig_story = saved_sel.focus.story;
|
||||
let mut orig_story_sel = None;
|
||||
// The main text comes last, so under Track Changes keep the selection from the caret's own
|
||||
// story (or restore the saved selection if that story had no match, #9063 / #9186).
|
||||
for results in found.into_iter().rev() {
|
||||
let is_orig = results[0].a.story == orig_story;
|
||||
replace_found(s, results)?;
|
||||
if s.doc.settings.track_changes && is_orig {
|
||||
orig_story_sel = Some(s.sel.clone());
|
||||
}
|
||||
}
|
||||
if s.doc.settings.track_changes {
|
||||
s.sel = orig_story_sel.unwrap_or(saved_sel);
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
|
||||
@@ -956,14 +956,16 @@ pub fn state(s: &Session) -> Value {
|
||||
(*cached_state(s)).clone()
|
||||
}
|
||||
|
||||
/// The common East Asian family shown by the font controls. If a slot has no face, keep
|
||||
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
|
||||
/// The common East Asian family shown by the font controls. A theme slot without a face uses
|
||||
/// the run's ordinary font, as layout does. Resolve each theme slot once per selection.
|
||||
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
|
||||
let mut themes = HashMap::new();
|
||||
let mut fonts = runs.iter().map(|run| {
|
||||
run.font_ea_theme
|
||||
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
|
||||
.or(run.font_ea.as_deref())
|
||||
let mut fonts = runs.iter().map(|run| match run.font_ea_theme {
|
||||
Some(slot) => {
|
||||
let face = *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run));
|
||||
Some(face.unwrap_or(&run.font))
|
||||
}
|
||||
None => run.font_ea.as_deref(),
|
||||
});
|
||||
let first = fonts.next().flatten()?;
|
||||
fonts.all(|font| font == Some(first)).then_some(first)
|
||||
|
||||
@@ -9,6 +9,8 @@ use wordcraft_doc::para::InlineObject;
|
||||
use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
use wordcraft_doc::{Block, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::para::ClKind;
|
||||
use wordcraft_layout::{DocLayout, Placed, ViewMode};
|
||||
|
||||
use super::references::{FieldCode, field_arg, leader, page_at, page_formats, page_text};
|
||||
use super::sel_result;
|
||||
@@ -136,6 +138,98 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
|
||||
})
|
||||
}
|
||||
|
||||
fn laid_out_leader(layout: &DocLayout, path: Path, offset: usize) -> Option<TabLeader> {
|
||||
layout.index.get(&(StoryRef::Body, path))?.iter().find_map(|&(page, item)| {
|
||||
let Placed::Lines { para, l0, l1, .. } = layout.pages.get(page)?.items.get(item)? else { return None };
|
||||
para.lines.get(*l0..*l1)?.iter().find_map(|line| {
|
||||
let tab = (line.c0..line.c1).find(|&i| para.clusters.get(i).is_some_and(|c| c.start == offset && c.kind == ClKind::Tab))?;
|
||||
Some(line.leaders.iter().find(|&&(i, _)| i == tab).map_or(TabLeader::None, |&(_, leader)| leader))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Read the leader of the first page-number tab that is laid out. Layout chooses the next
|
||||
/// stop after the text, including inherited and non-right stops.
|
||||
fn entry_leader(s: &mut Session, tabs: &[(usize, usize)]) -> Option<TabLeader> {
|
||||
if tabs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let from_layout = |layout: &DocLayout| tabs.iter().find_map(|&(block, offset)| laid_out_leader(layout, Path::top(block), offset));
|
||||
// A screen view can reflow the index to a different width or hide its result.
|
||||
if !s.view.read_mode
|
||||
&& s.view.mode == ViewMode::Print
|
||||
&& !s.view.field_codes
|
||||
&& let Some(leader) = from_layout(&s.layout())
|
||||
{
|
||||
return Some(leader);
|
||||
}
|
||||
if let Some(leader) = from_layout(&s.output_layout_of(&s.doc, false, false)) {
|
||||
return Some(leader);
|
||||
}
|
||||
// Measure hidden separators without revealing other hidden text, which could move the tab
|
||||
// past a different stop. The measurement leaves the document and view unchanged.
|
||||
let mut measurement = s.doc.clone();
|
||||
for &(block, offset) in tabs {
|
||||
if let Ok(p) = measurement.para_mut(StoryRef::Body, &Path::top(block)) {
|
||||
let _ = p.format(offset, offset + 1, &|props| props.hidden = Some(false));
|
||||
}
|
||||
}
|
||||
if let Some(leader) = from_layout(&s.output_layout_of(&measurement, false, false)) {
|
||||
return Some(leader);
|
||||
}
|
||||
// If the tab is still absent, retain an unambiguous saved leader.
|
||||
let mut saved = tabs
|
||||
.iter()
|
||||
.filter_map(|&(block, _)| s.doc.body.get(block)?.as_para())
|
||||
.flat_map(|p| s.doc.styles.resolve_para(&p.props).tabs)
|
||||
.map(|tab| tab.leader);
|
||||
let leader = saved.next()?;
|
||||
saved.all(|other| other == leader).then_some(leader)
|
||||
}
|
||||
|
||||
fn inline_entry_leader(s: &mut Session, i: usize) -> Option<TabLeader> {
|
||||
let tabs: Vec<_> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(i + 1)
|
||||
.map_while(|(j, b)| Some((j, b.as_para().filter(|p| super::citations::is_list_entry(p))?)))
|
||||
.filter_map(|(j, p)| p.text.rfind('\t').map(|offset| (j, offset)))
|
||||
.collect();
|
||||
entry_leader(s, &tabs)
|
||||
}
|
||||
|
||||
/// Read the leader before replacing a wrapped INDEX result, within the field's bounds.
|
||||
pub(in crate::cmd) fn wrapped_entry_leader(s: &mut Session, i: usize, start: usize, last: usize, end: usize) -> Option<TabLeader> {
|
||||
let tabs: Vec<_> = (i..=last)
|
||||
.filter_map(|j| {
|
||||
let p = s.doc.body.get(j)?.as_para()?;
|
||||
let from = if j == i { start } else { 0 };
|
||||
let to = if j == last { end } else { p.len() };
|
||||
p.text.get(from..to)?.rfind('\t').map(|offset| (j, from + offset))
|
||||
})
|
||||
.collect();
|
||||
entry_leader(s, &tabs)
|
||||
}
|
||||
|
||||
/// The index Insert Index will update and the leader its current result shows.
|
||||
pub fn index_settings(s: &mut Session) -> Option<(FieldCode, Option<TabLeader>)> {
|
||||
if let Some((i, instr)) = index_field(s) {
|
||||
let leader = inline_entry_leader(s, i);
|
||||
return Some((FieldCode::parse(&instr), leader));
|
||||
}
|
||||
|
||||
(0..s.doc.body.len()).find_map(|i| {
|
||||
let (instr, start, last, end) = super::citations::wrapped_list(s, i)?;
|
||||
let field = FieldCode::parse(&instr);
|
||||
if field.name != "INDEX" {
|
||||
return None;
|
||||
}
|
||||
Some((field, wrapped_entry_leader(s, i, start, last, end)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
|
||||
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
|
||||
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
|
||||
@@ -188,6 +282,7 @@ fn range_index_after_text(s: &Session) -> bool {
|
||||
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let instr = index_instr(v);
|
||||
check_index_reachable(s)?;
|
||||
let leader = p::str(v, "tabLeader").map(leader).or_else(|| index_settings(s).and_then(|(_, leader)| leader)).unwrap_or(TabLeader::Dot);
|
||||
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
|
||||
// Update Index makes it, so it takes the new settings rather than a second index being added
|
||||
// beside it (#8034).
|
||||
@@ -213,7 +308,7 @@ fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
None => super::citations::generated_list(s, &instr, "Index")?,
|
||||
}
|
||||
if let Some((i, _)) = index_field(s) {
|
||||
rebuild(s, i, p::str(v, "tabLeader").map(leader))?;
|
||||
rebuild(s, i, Some(leader))?;
|
||||
}
|
||||
s.clamp_selection();
|
||||
sel_result(s)
|
||||
@@ -339,16 +434,18 @@ pub fn rebuild(s: &mut Session, i: usize, leader: Option<TabLeader>) -> Result<(
|
||||
pub fn rebuild_from(s: &mut Session, i: usize, leader: Option<TabLeader>, instr: String) -> Result<(), CmdError> {
|
||||
let f = FieldCode::parse(&instr);
|
||||
// Old entries go; keep their leader and the section their columns had.
|
||||
let mut old_leader = None;
|
||||
let leader = leader.or_else(|| inline_entry_leader(s, i)).unwrap_or(TabLeader::Dot);
|
||||
let old_len = s.doc.body.len();
|
||||
let mut old_sect = None;
|
||||
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
|
||||
old_leader = old_leader.or_else(|| p.props.tabs.as_ref().and_then(|t| t.last()).map(|t| t.leader));
|
||||
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| super::citations::is_list_entry(p)) {
|
||||
if p.section.is_some() {
|
||||
old_sect = p.section.clone();
|
||||
}
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
}
|
||||
let leader = leader.or(old_leader).unwrap_or(TabLeader::Dot);
|
||||
if s.doc.body.len() != old_len {
|
||||
s.touch();
|
||||
}
|
||||
let cols = f.arg('c').and_then(|c| c.trim().parse::<u32>().ok()).unwrap_or(1).clamp(1, 4);
|
||||
let sep = f.arg('e').map(str::to_string).unwrap_or_else(|| ", ".into());
|
||||
let run_in = f.has('r');
|
||||
@@ -545,6 +642,86 @@ mod tests {
|
||||
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keeps_the_leader_used_by_the_page_number_tab() {
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("references.markEntry", &json!({"entry": "Kilns"})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
let path = Path::top(i + 1);
|
||||
assert_eq!(s.doc.para(StoryRef::Body, &path).unwrap().plain_text(), "Kilns\t1");
|
||||
|
||||
for (align, leader, inherit_later_stop) in
|
||||
[(TabAlign::Left, TabLeader::Underscore, false), (TabAlign::Right, TabLeader::Hyphen, true), (TabAlign::Left, TabLeader::None, true)]
|
||||
{
|
||||
let generated_pos = s.doc.para(StoryRef::Body, &path).unwrap().props.tabs.as_ref().unwrap()[0].pos;
|
||||
Arc::make_mut(&mut s.doc.styles).get_mut(ENTRY_STYLE).unwrap().para.tabs =
|
||||
inherit_later_stop.then(|| vec![TabStop { pos: generated_pos + 0.75, align: TabAlign::Right, leader: TabLeader::Dot }]);
|
||||
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
|
||||
// The text already runs past the first stop. The next one wins over the later style stop.
|
||||
entry.props.tabs = Some(vec![TabStop { pos: 5.0, align: TabAlign::Right, leader: TabLeader::Dot }, TabStop { pos: 90.0, align, leader }]);
|
||||
entry.touch();
|
||||
s.touch();
|
||||
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "{align:?}, {inherit_later_stop}");
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "kept on update: {align:?}, {inherit_later_stop}");
|
||||
}
|
||||
|
||||
// Updating an imported field consumes the result, so its tab must be read before conversion.
|
||||
let (_, instr) = index_field(&s).unwrap();
|
||||
let header = s.doc.para_mut(StoryRef::Body, &Path::top(i)).unwrap();
|
||||
let offset = header.object_offsets()[0];
|
||||
header.delete(0, offset).unwrap();
|
||||
header.objects[0] = InlineObject::FieldStart { instr, locked: false, dirty: false };
|
||||
header.touch();
|
||||
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
|
||||
entry.props.tabs = Some(vec![TabStop { pos: 90.0, align: TabAlign::Center, leader: TabLeader::Hyphen }]);
|
||||
entry.insert_object(entry.len(), InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
s.touch();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen));
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert!(s.doc.field_ranges(StoryRef::Body).is_empty());
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen), "kept through wrapped field conversion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keeps_the_page_number_leader_when_the_first_tab_is_hidden() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns and wheels."));
|
||||
s.view.marks = false;
|
||||
s.prefs.marks.hidden = false;
|
||||
for entry in ["Kilns", "Wheels"] {
|
||||
s.run("references.markEntry", &json!({"entry": entry})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
assert_eq!(index_lines(&s), ["Kilns\t1", "Wheels\t1"]);
|
||||
|
||||
for (first, second, hide_second, expected) in [
|
||||
(TabLeader::Dot, TabLeader::Hyphen, false, TabLeader::Hyphen),
|
||||
(TabLeader::Hyphen, TabLeader::Hyphen, true, TabLeader::Hyphen),
|
||||
(TabLeader::Hyphen, TabLeader::None, false, TabLeader::None),
|
||||
] {
|
||||
for (block, leader, hidden) in [(i + 1, first, true), (i + 2, second, hide_second)] {
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(block)).unwrap();
|
||||
p.props.tabs.as_mut().unwrap()[0].leader = leader;
|
||||
let tab = p.text.rfind('\t').unwrap();
|
||||
p.format(tab, tab + 1, &|props| props.hidden = Some(hidden)).unwrap();
|
||||
}
|
||||
s.touch();
|
||||
let l = s.layout();
|
||||
assert_eq!(laid_out_leader(&l, Path::top(i + 1), "Kilns".len()), None, "the hidden tab has no layout leader");
|
||||
assert_eq!(laid_out_leader(&l, Path::top(i + 2), "Wheels".len()), (!hide_second).then_some(second));
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected));
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected), "kept on update");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
|
||||
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
|
||||
/// second index at the caret.
|
||||
|
||||
@@ -14,7 +14,7 @@ mod links;
|
||||
mod objects;
|
||||
|
||||
pub(crate) use header_footer::saved_copy;
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, remove_first_hf, strip_headers};
|
||||
pub use items::{
|
||||
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
|
||||
format_date_parts, format_date_parts_in,
|
||||
@@ -102,6 +102,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.removeHeader", "Remove Header", "Insert › Header & Footer › Header", |s, _| {
|
||||
if remove_first_hf(s, true)? {
|
||||
return sel_result(s);
|
||||
}
|
||||
s.doc.last_section.headers = Default::default();
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
if s.doc.para(StoryRef::Body, &path).is_some_and(|p| p.section.is_some())
|
||||
@@ -114,7 +117,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.removeFooter", "Remove Footer", "Insert › Header & Footer › Footer", |s, _| {
|
||||
s.doc.last_section.footers = Default::default();
|
||||
if !remove_first_hf(s, false)? {
|
||||
s.doc.last_section.footers = Default::default();
|
||||
}
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.dateTime", "Date & Time", "Insert › Text", date_time).params(r#"{"format"?: "M/d/yyyy", "update"?: bool, "language"?: "en-US|pt-BR"}"#),
|
||||
|
||||
@@ -120,6 +120,35 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
Ok(json!({"story": id}))
|
||||
}
|
||||
|
||||
/// Remove the first-page variant while it is being edited, keeping the other page variants.
|
||||
pub(super) fn remove_first_hf(s: &mut Session, header: bool) -> Result<bool, CmdError> {
|
||||
let StoryRef::Part(story) = s.sel.focus.story else { return Ok(false) };
|
||||
let page = s.page_hint;
|
||||
let layout = s.layout();
|
||||
let Some(page) = layout.pages.get(page) else { return Ok(false) };
|
||||
let shown = if header { page.header_story } else { page.footer_story };
|
||||
if page.hf_slot != wordcraft_layout::HfSlot::First || shown != Some(story) {
|
||||
return Ok(false);
|
||||
}
|
||||
let index = page.section;
|
||||
let sections = s.doc.sections();
|
||||
let Some(&(end, _)) = sections.get(index) else { return Ok(false) };
|
||||
let last = index + 1 == sections.len();
|
||||
let inherits_first = sections[..index].iter().any(|(_, sec)| if header { sec.headers.first.is_some() } else { sec.footers.first.is_some() });
|
||||
// An absent slot would show the previous section's first-page story again.
|
||||
let replacement = if inherits_first {
|
||||
let (kind, style) = if header { (PartKind::Header, "Header") } else { (PartKind::Footer, "Footer") };
|
||||
Some(s.doc.try_add_part(kind, vec![para_block(Paragraph::new().styled(style))])?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let section = if last { &mut s.doc.last_section } else { s.doc.section_mut(end) };
|
||||
let set = if header { &mut section.headers } else { &mut section.footers };
|
||||
set.first = replacement;
|
||||
s.sel = s.hf_return.take().unwrap_or_else(|| Selection::caret(s.doc.start_of(StoryRef::Body)));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The header (or footer) page `page` shows, if any; an error for a page that isn't there.
|
||||
fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, CmdError> {
|
||||
let layout = s.layout();
|
||||
|
||||
@@ -133,6 +133,108 @@ fn different_first_page_header_is_reachable_from_page_one() {
|
||||
assert_eq!((s.doc.last_section.footers.first, s.doc.last_section.footers.default), (Some(foot), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_first_page_header_or_footer_keeps_the_default() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
for (cmd, page, text) in [
|
||||
("insert.editHeader", 0, "Cover header"),
|
||||
("insert.editHeader", 1, "Default header"),
|
||||
("insert.editFooter", 0, "Cover footer"),
|
||||
("insert.editFooter", 1, "Default footer"),
|
||||
] {
|
||||
s.run(cmd, &json!({"page": page})).unwrap();
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
}
|
||||
let page_stories = |s: &mut Session| {
|
||||
let pages = &s.layout().pages;
|
||||
assert_eq!(pages.len(), 2);
|
||||
[(pages[0].header_story, pages[0].footer_story), (pages[1].header_story, pages[1].footer_story)]
|
||||
};
|
||||
let [first, default] = page_stories(&mut s);
|
||||
assert!(first.0.is_some() && first.1.is_some());
|
||||
assert!(default.0.is_some() && default.1.is_some());
|
||||
assert_ne!(first, default);
|
||||
|
||||
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.removeHeader", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [(None, first.1), default]);
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Body);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [first, default]);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.removeFooter", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [(first.0, None), default]);
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Body);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [first, default]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_first_page_removal_keeps_the_selection_for_close_header_and_footer() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
for (edit, text) in [("insert.editHeader", "Cover header"), ("insert.editFooter", "Cover footer")] {
|
||||
s.run(edit, &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
}
|
||||
s.run("select.text", &json!({"text": "Two"})).unwrap();
|
||||
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let body_selection = s.sel.clone();
|
||||
assert_eq!(s.selected_text(), "Two");
|
||||
let before = s.doc.clone();
|
||||
|
||||
for (edit, remove) in [("insert.editHeader", "insert.removeHeader"), ("insert.editFooter", "insert.removeFooter")] {
|
||||
s.run(edit, &json!({"page": 0})).unwrap();
|
||||
let editing = s.sel.clone();
|
||||
assert!(s.in_header_footer());
|
||||
let error = s.run(remove, &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("only the editable regions"), "{error}");
|
||||
assert_eq!(s.doc, before);
|
||||
assert_eq!(s.sel, editing, "the refusal leaves the editor in the first-page story");
|
||||
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, body_selection, "explicit Close returns to the saved selection after {remove}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_an_inherited_first_page_header_keeps_the_previous_section() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
let first = s.run("insert.editHeader", &json!({"page": 0})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("text.insert", &json!({"text": "Cover header"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section two"})).unwrap();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
// Start with a linked first-page slot in the later section.
|
||||
s.doc.last_section.headers.first = None;
|
||||
s.touch();
|
||||
let page = s.layout().pages.iter().position(|page| page.section == 1).unwrap();
|
||||
assert_eq!(s.layout().pages[page].header_story, Some(first));
|
||||
s.run("insert.editHeader", &json!({"page": page})).unwrap();
|
||||
s.run("insert.removeHeader", &json!({})).unwrap();
|
||||
let blank = s.doc.last_section.headers.first.unwrap();
|
||||
assert_ne!(blank, first);
|
||||
assert_eq!(s.layout().pages[0].header_story, Some(first));
|
||||
assert_eq!(s.layout().pages[page].header_story, Some(blank));
|
||||
assert!(s.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
|
||||
|
||||
let saved = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut reopened = Session::new(wordcraft_docx::read(&saved).unwrap());
|
||||
let reopened_layout = reopened.layout();
|
||||
let cover = reopened_layout.pages[0].header_story.unwrap();
|
||||
let blank = reopened_layout.pages.iter().find(|page| page.section == 1).unwrap().header_story.unwrap();
|
||||
assert_eq!(reopened.doc.para(StoryRef::Part(cover), &Path(vec![0])).unwrap().text.as_str(), "Cover header");
|
||||
assert!(reopened.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
|
||||
}
|
||||
|
||||
fn two_pages() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("text.insert", &json!({"text": "One"})).unwrap();
|
||||
|
||||
@@ -33,7 +33,9 @@ pub(crate) use select::select_object;
|
||||
pub(crate) use select::{edit_obj, has_shape_or_canvas};
|
||||
#[cfg(test)]
|
||||
use select::{has_group, holds_ink, obj_size, with_obj};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
|
||||
pub use select::{
|
||||
has_picture_format_target, min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use shape::can_link;
|
||||
pub(crate) use shape::set_text_body;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::select::{edit_obj, has_picture, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
@@ -190,7 +190,7 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
|
||||
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
|
||||
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
|
||||
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
|
||||
if picks.len() < 2 {
|
||||
if picks.is_empty() || (picks.len() == 1 && has_picture(s).is_none()) {
|
||||
return run(s);
|
||||
}
|
||||
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
|
||||
|
||||
@@ -7,6 +7,16 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether commands that already format multiple pictures have a target. A secondary
|
||||
/// picture counts when objects were explicitly picked, even if the primary object is a shape.
|
||||
pub fn has_picture_format_target(s: &Session) -> bool {
|
||||
has_picture(s).is_none() || (!s.also_selected.is_empty() && !target_objects(s, |o| matches!(o, InlineObject::Image { .. })).is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn has_any_picture(s: &Session) -> Option<&'static str> {
|
||||
(!has_picture_format_target(s)).then_some("select a picture first")
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a picture, shape, or active text box is selected.
|
||||
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
|
||||
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
|
||||
|
||||
@@ -4,9 +4,9 @@ use super::picture::{
|
||||
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
|
||||
};
|
||||
use super::select::{
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
|
||||
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
|
||||
with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_picture, has_any_shape, has_floating, has_group, has_movable, has_object,
|
||||
has_picture, has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box,
|
||||
target_objects, with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
};
|
||||
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
|
||||
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
@@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"percent": 0..100}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"tolerance"?: 0..255}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
|
||||
@@ -164,8 +164,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"maxPixels"?: n}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_any_picture),
|
||||
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
|
||||
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
@@ -220,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
|
||||
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
|
||||
// picture's pixels are never rewritten. A flip mirrors what is on the page, so a
|
||||
|
||||
@@ -432,6 +432,59 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
|
||||
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_border_uses_picked_pictures_even_when_a_shape_is_primary() {
|
||||
for (picked, expected) in
|
||||
[(&[2, 0][..], [true, false]), (&[2, 0, 1][..], [true, true]), (&[0, 2, 1][..], [true, true]), (&[2][..], [false, false])]
|
||||
{
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
for w in [20, 24] {
|
||||
let data = super::super::insert::base64_encode(&png(w, 10));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
for index in picked {
|
||||
s.run("select.addObject", &json!({"index": index})).unwrap();
|
||||
}
|
||||
let selection = s.sel.clone();
|
||||
let extras = s.also_selected.clone();
|
||||
let undo = s.undo_depth();
|
||||
let shape = |s: &Session| {
|
||||
let (_, object) = all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).unwrap();
|
||||
serde_json::to_value(object).unwrap()
|
||||
};
|
||||
let shape_before = shape(&s);
|
||||
let borders = |s: &Session| {
|
||||
all_objects(s)
|
||||
.into_iter()
|
||||
.filter_map(|(_, o)| match o {
|
||||
InlineObject::Image { media, .. } => Some(s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let result = s.run("picture.border", &json!({"width": 3}));
|
||||
if expected == [false, false] {
|
||||
assert!(result.is_err(), "a shape alone cannot take a picture border");
|
||||
assert_eq!(s.undo_depth(), undo);
|
||||
} else {
|
||||
result.unwrap();
|
||||
assert_eq!(s.undo_depth(), undo + 1);
|
||||
}
|
||||
assert_eq!(s.sel, selection);
|
||||
assert_eq!(s.also_selected, extras);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
assert_eq!(borders(&s), expected);
|
||||
if expected != [false, false] {
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(borders(&s), [false, false]);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #8832: a picture command on several selected pictures changes each, in one undo step.
|
||||
#[test]
|
||||
fn picture_border_applies_to_every_selected_picture() {
|
||||
@@ -2267,3 +2320,55 @@ fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
|
||||
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
|
||||
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_format_commands_stay_enabled_when_shape_is_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then one picture added.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.border", &json!({"color": "FF0000", "width": 3})).unwrap();
|
||||
assert!(matches!(
|
||||
&all_objects(&s)[1].1,
|
||||
InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.border.is_some())
|
||||
));
|
||||
|
||||
// Shape clicked first, then two pictures added.
|
||||
s.run("select.addObject", &json!({"index": 2})).unwrap();
|
||||
s.run("picture.style", &json!({"style": "rounded"})).unwrap();
|
||||
let objs = all_objects(&s);
|
||||
for idx in [1, 2] {
|
||||
assert!(
|
||||
matches!(&objs[idx].1, InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.style.as_deref() == Some("rounded"))),
|
||||
"picture {idx} should get rounded style"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_object_picture_commands_need_the_picture_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then the picture added: Crop, Change Picture and Alt Text would act on the shape.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
for (cmd, args) in [("picture.crop", json!({"left": 0.1})), ("picture.altText", json!({"text": "x"})), ("picture.change", json!({"data": data}))]
|
||||
{
|
||||
assert!(matches!(s.run(cmd, &args), Err(CmdError::Disabled(_))), "{cmd}");
|
||||
}
|
||||
|
||||
// Picture first: enabled.
|
||||
s.run("select.objects", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.crop", &json!({"left": 0.1})).unwrap();
|
||||
}
|
||||
|
||||
@@ -287,9 +287,39 @@ fn prepare_custom_dictionary(s: &Session, setting: Option<&str>) -> Result<(Opti
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's home folder: `USERPROFILE` first on Windows, `HOME` first elsewhere, skipping
|
||||
/// empty values. The recent list reads it in the same order (#8865), so `~/…` means one folder.
|
||||
fn home_dir() -> Option<std::path::PathBuf> {
|
||||
home_from(std::env::var_os("HOME"), std::env::var_os("USERPROFILE"))
|
||||
}
|
||||
|
||||
/// [`home_dir`] without the environment: the order the two values are read in depends on the
|
||||
/// platform, so it takes them as they are read.
|
||||
fn home_from(home: Option<std::ffi::OsString>, userprofile: Option<std::ffi::OsString>) -> Option<std::path::PathBuf> {
|
||||
let set = |v: Option<std::ffi::OsString>| v.filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let (first, second) = if cfg!(windows) { (userprofile, home) } else { (home, userprofile) };
|
||||
set(first).or_else(|| set(second))
|
||||
}
|
||||
|
||||
/// Expand a file or folder path under the home folder with the saved settings' platform-specific prefix.
|
||||
fn expand_home(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<std::path::PathBuf, CmdError> {
|
||||
let prefix = if cfg!(windows) && f.starts_with("~\\") { "~\\" } else { "~/" };
|
||||
let Some(rest) = f.strip_prefix(prefix) else { return Ok(std::path::PathBuf::from(f)) };
|
||||
let Some(home) = home else {
|
||||
return Err(CmdError::Params(format!("`{key}`: cannot expand `{prefix}` because HOME or USERPROFILE is not set")));
|
||||
};
|
||||
// A Windows drive, device or root in the suffix would replace the home path on join.
|
||||
if prefix == "~\\"
|
||||
&& matches!(std::path::Path::new(rest).components().next(), Some(std::path::Component::Prefix(_) | std::path::Component::RootDir))
|
||||
{
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} must be relative to the home folder")));
|
||||
}
|
||||
Ok(home.join(rest))
|
||||
}
|
||||
|
||||
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/`. With
|
||||
/// `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
/// With `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// that it exists would make Windows authenticate to that host.
|
||||
fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
@@ -299,11 +329,7 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
|
||||
return Err(CmdError::Params(format!("`{key}` isn't a folder path")));
|
||||
}
|
||||
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let path = match (f.strip_prefix("~/"), home) {
|
||||
(Some(rest), Some(h)) => h.join(rest),
|
||||
_ => std::path::PathBuf::from(f),
|
||||
};
|
||||
let path = expand_home(key, f, home_dir().as_deref())?;
|
||||
if local_only && (super::templates::is_network_path(f) || super::templates::is_network_path(&path.to_string_lossy())) {
|
||||
return Err(CmdError::Params(format!("`{key}` can't be a network folder")));
|
||||
}
|
||||
@@ -319,8 +345,12 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
}
|
||||
|
||||
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
|
||||
/// file, given as an absolute path or one starting with `~/`.
|
||||
/// file, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
file_setting_in(key, f, home_dir().as_deref())
|
||||
}
|
||||
|
||||
fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
|
||||
return Ok(None);
|
||||
@@ -328,15 +358,7 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
|
||||
return Err(CmdError::Params(format!("`{key}` isn't a file path")));
|
||||
}
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let path = if let Some(rest) = f.strip_prefix("~/") {
|
||||
match home {
|
||||
Some(h) => h.join(rest),
|
||||
None => return Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
|
||||
}
|
||||
} else {
|
||||
std::path::PathBuf::from(f)
|
||||
};
|
||||
let path = expand_home(key, f, home)?;
|
||||
if !path.is_absolute() {
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} isn't a full path")));
|
||||
}
|
||||
@@ -355,3 +377,90 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
pub fn use_dictionaries_folder(folder: Option<&str>) {
|
||||
wordcraft_proof::set_dictionaries_folder(folder.map(std::path::PathBuf::from));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{expand_home, file_setting_in, home_from};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn os(s: &str) -> Option<OsString> {
|
||||
Some(OsString::from(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_home_folder_is_the_profile_folder_on_windows_and_home_elsewhere() {
|
||||
let home = home_from(os("/home/u"), os("C:\\Users\\u"));
|
||||
let expected = if cfg!(windows) { PathBuf::from("C:\\Users\\u") } else { PathBuf::from("/home/u") };
|
||||
assert_eq!(home, Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_home_folder_is_skipped_for_the_other_one() {
|
||||
assert_eq!(home_from(os(""), os("C:\\Users\\u")), Some(PathBuf::from("C:\\Users\\u")));
|
||||
assert_eq!(home_from(os(""), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_home_folder_at_all_expands_to_nothing() {
|
||||
assert_eq!(home_from(None, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilde_path_expands_under_the_home_folder() {
|
||||
let home = Path::new("/home/u");
|
||||
assert_eq!(expand_home("dictionariesFolder", "~/dic", Some(home)).unwrap(), PathBuf::from("/home/u/dic"));
|
||||
assert_eq!(expand_home("dictionariesFolder", "/abs/dic", Some(home)).unwrap(), PathBuf::from("/abs/dic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilde_path_without_a_home_folder_is_refused() {
|
||||
let err = expand_home("dictionariesFolder", "~/dic", None).unwrap_err();
|
||||
assert!(format!("{err:?}").contains("cannot expand"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_expands_tilde_with_the_same_platform_prefix() {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
struct TempHome(PathBuf);
|
||||
impl TempHome {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
impl Drop for TempHome {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
let dir = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let candidate = std::env::temp_dir().join(format!("wc-options-home-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break TempHome(candidate),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", candidate.display()),
|
||||
}
|
||||
};
|
||||
let dic = dir.0.join("custom.dic");
|
||||
std::fs::write(&dic, "wordcraftdictionary\n").unwrap();
|
||||
let expected = dic.to_string_lossy().into_owned();
|
||||
|
||||
assert_eq!(file_setting_in("customDictionary", "~/custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let missing_home = file_setting_in("customDictionary", "~/custom.dic", None).unwrap_err();
|
||||
assert!(format!("{missing_home:?}").contains("cannot expand"), "{missing_home:?}");
|
||||
if cfg!(windows) {
|
||||
assert_eq!(file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let drive = file_setting_in("customDictionary", r"~\C:\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{drive:?}").contains("relative to the home folder"), "{drive:?}");
|
||||
} else {
|
||||
let backslash = file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{backslash:?}").contains("isn't a full path"), "{backslash:?}");
|
||||
}
|
||||
dir.remove().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::packs::{Backend, FixedBackend};
|
||||
|
||||
/// Tests that set the process-wide backend take turns.
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
|
||||
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
|
||||
|
||||
/// Puts the process back to no backend and no background thread when dropped, even when
|
||||
/// the test panicked.
|
||||
|
||||
@@ -520,20 +520,22 @@ fn margins(s: &mut Session, v: &Value) -> CmdResult {
|
||||
None => return Err(CmdError::Params(format!("unknown preset `{x}`"))),
|
||||
},
|
||||
None => {
|
||||
// A negative margin given counts as zero; one left out keeps its value, so an exact
|
||||
// (negative) top or bottom from the file stays exact when another side changes, as
|
||||
// in Word.
|
||||
let c = sect(s);
|
||||
let given = |k: &str| p::f32(v, k).map(|m| m.max(0.0));
|
||||
(
|
||||
p::f32(v, "top").unwrap_or(c.margin_top),
|
||||
p::f32(v, "bottom").unwrap_or(c.margin_bottom),
|
||||
p::f32(v, "left").unwrap_or(c.margin_left),
|
||||
p::f32(v, "right").unwrap_or(c.margin_right),
|
||||
given("top").unwrap_or(c.margin_top),
|
||||
given("bottom").unwrap_or(c.margin_bottom),
|
||||
given("left").unwrap_or(c.margin_left.max(0.0)),
|
||||
given("right").unwrap_or(c.margin_right.max(0.0)),
|
||||
)
|
||||
}
|
||||
};
|
||||
// Negative margins count as zero before the fit check, so one can't offset another.
|
||||
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
|
||||
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
|
||||
let cur = sect(s);
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t.abs(), b.abs(), l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
return Err(CmdError::Params("margins leave no room for text".into()));
|
||||
}
|
||||
// A preset picks mirrored or not, as does `mirror` (Page Setup's Multiple pages); plain numbers
|
||||
@@ -588,7 +590,7 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sections
|
||||
.iter()
|
||||
.find(|(e, _)| *e == block)
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), x.gutter))
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top.abs(), x.margin_bottom.abs(), x.margin_left, x.margin_right), x.gutter))
|
||||
};
|
||||
if !selected_section_ends(s).into_iter().all(fits) {
|
||||
return Err(CmdError::Params(MARGINS_DONT_FIT.into()));
|
||||
|
||||
@@ -433,3 +433,26 @@ fn page_number_format_keeps_or_clears_the_start() {
|
||||
assert_eq!(back["pageNumFormat"], "decimal");
|
||||
assert_eq!(back["pageNumStart"], 1);
|
||||
}
|
||||
|
||||
/// An exact (negative) top or bottom margin survives Margins and Orientation: changing another
|
||||
/// margin keeps it exact, and turning the page moves its size, as a plain margin, to the side it
|
||||
/// goes to.
|
||||
#[test]
|
||||
fn exact_margins_survive_margins_and_orientation() {
|
||||
let mut s = doc();
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.doc.last_section.margin_bottom = -40.0;
|
||||
s.run("layout.margins", &json!({"left": 80.0})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0));
|
||||
// A negative margin given still counts as zero.
|
||||
s.run("layout.margins", &json!({"top": -30.0})).unwrap();
|
||||
assert_eq!((s.doc.last_section.margin_top, s.doc.last_section.margin_bottom), (0.0, -40.0));
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert!(x.margin_left >= 0.0 && x.margin_right >= 0.0, "{x:?}");
|
||||
let mut sides = [x.margin_left, x.margin_right];
|
||||
sides.sort_by(f32::total_cmp);
|
||||
assert_eq!(sides, [40.0, 60.0], "the exact margins' sizes go to the sides");
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ pub(super) fn outline_step(s: &mut Session, promote: bool) -> CmdResult {
|
||||
// Outline view: the headings hidden under a collapsed heading move a level with it.
|
||||
let carried = crate::cmd::outline::hidden_subheadings(s);
|
||||
let (a, b) = s.sel.ordered();
|
||||
let paths = s.doc.paths_between(&a, &b);
|
||||
let paths = if s.cell_range().is_some_and(|range| !range.stream) { crate::cmd::selected_paths(s) } else { s.doc.paths_between(&a, &b) };
|
||||
// The heading before the selection, for promoted body text.
|
||||
let before = s
|
||||
.doc
|
||||
|
||||
@@ -187,12 +187,170 @@ pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"id": id}))
|
||||
}
|
||||
|
||||
/// Deserialize `T` from `v`, rejecting unknown fields on `T` and any nested structs (#9203, #9291).
|
||||
fn deserialize_strict<T: serde::de::DeserializeOwned>(section: &str, v: &Value) -> Result<T, CmdError> {
|
||||
use serde::de::{DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};
|
||||
|
||||
struct StrictDe<'a>(&'a Value);
|
||||
struct StrictSeq<'a>(std::slice::Iter<'a, Value>);
|
||||
struct StrictMap<'a>(serde_json::map::Iter<'a>, Option<&'a Value>);
|
||||
struct StrictEnum<'a>(&'a str, &'a Value);
|
||||
|
||||
// Internally tagged enums buffer their fields before decoding them, bypassing StrictMap.
|
||||
fn validate_text_fill(fill: &Value) -> Result<(), serde_json::Error> {
|
||||
let tag = fill.get("type").or_else(|| fill.get(0));
|
||||
// Serde's numeric variant indices follow the TextFill declaration order.
|
||||
let fields: &[_] = match (tag.and_then(Value::as_str), tag.and_then(Value::as_u64)) {
|
||||
(Some("none"), _) | (_, Some(0)) => &["type"],
|
||||
(Some("solid"), _) | (_, Some(1)) => &["type", "color", "transparency"],
|
||||
(Some("gradient"), _) | (_, Some(2)) => &["type", "stops", "angle"],
|
||||
_ => return Ok(()), // The regular decoder reports missing or unknown tags.
|
||||
};
|
||||
let stops = if let Some(map) = fill.as_object() {
|
||||
if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) {
|
||||
return Err(serde::de::Error::custom(format!("`textEffects.fill`: unknown field `{key}`")));
|
||||
}
|
||||
map.get("stops")
|
||||
} else if fields.contains(&"stops") {
|
||||
fill.get(1)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(stops) = stops.and_then(Value::as_array) {
|
||||
for stop in stops {
|
||||
<wordcraft_doc::wordart::GradStop as serde::Deserialize>::deserialize(StrictDe(stop))
|
||||
.map_err(|e| serde::de::Error::custom(format!("`textEffects.fill.stops`: {e}")))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<'de> SeqAccess<'de> for StrictSeq<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error> {
|
||||
self.0.next().map(|v| seed.deserialize(StrictDe(v))).transpose()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> MapAccess<'de> for StrictMap<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> {
|
||||
let Some((k, v)) = self.0.next() else { return Ok(None) };
|
||||
self.1 = Some(v);
|
||||
seed.deserialize(k.as_str().into_deserializer()).map(Some)
|
||||
}
|
||||
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Self::Error> {
|
||||
let v = self.1.take().ok_or_else(|| serde::de::Error::custom("missing map value"))?;
|
||||
seed.deserialize(StrictDe(v))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> VariantAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn unit_variant(self) -> Result<(), Self::Error> {
|
||||
serde::Deserialize::deserialize(self.1)
|
||||
}
|
||||
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Self::Error> {
|
||||
seed.deserialize(StrictDe(self.1))
|
||||
}
|
||||
fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
serde::Deserializer::deserialize_tuple(StrictDe(self.1), len, visitor)
|
||||
}
|
||||
fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> {
|
||||
serde::Deserializer::deserialize_struct(StrictDe(self.1), "", fields, visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> EnumAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
type Variant = Self;
|
||||
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> {
|
||||
let val = seed.deserialize(self.0.into_deserializer())?;
|
||||
Ok((val, self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserializer<'de> for StrictDe<'_> {
|
||||
type Error = serde_json::Error;
|
||||
|
||||
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
match self.0 {
|
||||
Value::Null => visitor.visit_unit(),
|
||||
Value::Bool(b) => visitor.visit_bool(*b),
|
||||
Value::Number(n) => n.deserialize_any(visitor),
|
||||
Value::String(s) => visitor.visit_str(s),
|
||||
Value::Array(arr) => visitor.visit_seq(StrictSeq(arr.iter())),
|
||||
Value::Object(map) => visitor.visit_map(StrictMap(map.iter(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
if self.0.is_null() { visitor.visit_none() } else { visitor.visit_some(self) }
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V: Visitor<'de>>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
match self.0 {
|
||||
Value::String(s) => visitor.visit_enum(s.as_str().into_deserializer()),
|
||||
Value::Object(map) if map.len() == 1 => {
|
||||
if let Some((k, v)) = map.iter().next() {
|
||||
visitor.visit_enum(StrictEnum(k, v))
|
||||
} else {
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V: Visitor<'de>>(
|
||||
self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
if name == "TextEffects" {
|
||||
let fill = match self.0 {
|
||||
Value::Array(values) => fields.iter().position(|&field| field == "fill").and_then(|index| values.get(index)),
|
||||
_ => self.0.get("fill"),
|
||||
};
|
||||
if let Some(fill) = fill {
|
||||
validate_text_fill(fill)?;
|
||||
}
|
||||
}
|
||||
if let Value::Object(map) = self.0 {
|
||||
for key in map.keys() {
|
||||
if !fields.contains(&key.as_str()) {
|
||||
return Err(serde::de::Error::custom(format!("unknown field `{key}`")));
|
||||
}
|
||||
}
|
||||
return visitor.visit_map(StrictMap(map.iter(), None));
|
||||
}
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
|
||||
unit unit_struct seq tuple tuple_struct map identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
T::deserialize(StrictDe(v)).map_err(|e| CmdError::Params(format!("`{section}`: {e}")))
|
||||
}
|
||||
|
||||
/// Modify a style's character and paragraph formatting, display name or next-paragraph style.
|
||||
pub(super) fn modify_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = style_id(s, p::req_str(v, "style")?)?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let para: Option<ParaProps> =
|
||||
v.get("para").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| deserialize_strict("chr", c)).transpose()?;
|
||||
let para: Option<ParaProps> = v.get("para").map(|c| deserialize_strict("para", c)).transpose()?;
|
||||
let next = p::str(v, "next").map(str::to_string);
|
||||
let name = p::str(v, "name").map(str::to_string);
|
||||
let d = &s.doc.styles.default_chr;
|
||||
|
||||
@@ -20,7 +20,8 @@ use fields::caption;
|
||||
#[cfg(test)]
|
||||
use fields::output_fields_with;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, caption_preview, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in,
|
||||
update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
|
||||
@@ -27,12 +27,29 @@ pub const CHAPTER_SEPARATORS: [&str; 5] = ["-", ".", ":", "\u{2014}", "\u{2013}"
|
||||
/// a chapter number (`STYLEREF n \s` and a separator) and a `SEQ label \* format \s n` number
|
||||
/// (ECMA-376 §17.16.5.56, §17.16.5.59).
|
||||
pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let text = p::str(v, "text").unwrap_or("");
|
||||
s.doc.insert_block(story, &at, Block::Para(caption_paragraph(v, text)?))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story, path: at, off });
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Number a prospective caption at its insertion site without changing the document or selection.
|
||||
pub fn caption_preview(s: &Session, v: &Value) -> Result<String, CmdError> {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let mut doc = s.doc.clone();
|
||||
doc.insert_block(story, &at, Block::Para(caption_paragraph(v, "")?))?;
|
||||
update_seq_in(&mut doc)?;
|
||||
Ok(doc.para(story, &at).map_or_else(String::new, Paragraph::plain_text))
|
||||
}
|
||||
|
||||
fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
|
||||
let label: String = p::str(v, "label").unwrap_or("Figure").chars().filter(|c| !matches!(c, '"' | '\\') && !c.is_control()).take(40).collect();
|
||||
let label = if label.trim().is_empty() { "Figure".to_string() } else { label.trim().to_string() };
|
||||
// SEQ identifiers are one word: Word joins a multi-word label with underscores.
|
||||
let ident = label.split_whitespace().collect::<Vec<_>>().join("_");
|
||||
let text = p::str(v, "text").unwrap_or("").to_string();
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let format = seq_format(p::str(v, "format").unwrap_or("ARABIC"));
|
||||
let chapter = p::u64(v, "chapter").filter(|l| (1..=9).contains(l));
|
||||
let sep = p::str(v, "separator").and_then(|x| CHAPTER_SEPARATORS.iter().find(|s| **s == x)).copied().unwrap_or("-");
|
||||
@@ -51,10 +68,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if !text.is_empty() {
|
||||
para.insert_text(para.len(), &format!(": {text}"), &CharProps::default())?;
|
||||
}
|
||||
Ok(para)
|
||||
}
|
||||
|
||||
fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
// A selected picture, shape or chart: next to the paragraph holding it, in the same cell or
|
||||
// text box (#1230). Otherwise next to the caret's top-level block: a paragraph, or the whole
|
||||
// table it is in.
|
||||
let f = s.sel.focus.clone();
|
||||
let f = &s.sel.focus;
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let at = match crate::cmd::objects::object_selection(s) {
|
||||
Some((pos, _)) => {
|
||||
let k = pos.path.last();
|
||||
@@ -65,11 +87,7 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Path::top(if above { top } else { top.saturating_add(1) })
|
||||
}
|
||||
};
|
||||
s.doc.insert_block(f.story, &at, Block::Para(para))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(f.story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story: f.story, path: at, off });
|
||||
sel_result(s)
|
||||
(f.story, at)
|
||||
}
|
||||
|
||||
/// Renumber the body's SEQ fields in document order, honouring `\* format`, `\s level` (restart
|
||||
@@ -78,11 +96,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// the last level-n heading's number, or its count when the heading isn't numbered) and the
|
||||
/// text or number of the nearest paragraph of a style.
|
||||
pub fn update_seq(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_seq_in(&mut s.doc)
|
||||
}
|
||||
|
||||
fn update_seq_in(doc: &mut wordcraft_doc::Document) -> Result<(), CmdError> {
|
||||
// Numbers first: a STYLEREF to a heading that holds a SEQ field shows its new number.
|
||||
let numbers = seq_results(&s.doc);
|
||||
apply_results(&mut s.doc, numbers)?;
|
||||
let refs = styleref_results(&s.doc);
|
||||
apply_results(&mut s.doc, refs)
|
||||
let numbers = seq_results(doc);
|
||||
apply_results(doc, numbers)?;
|
||||
let refs = styleref_results(doc);
|
||||
apply_results(doc, refs)
|
||||
}
|
||||
|
||||
/// A field's fresh result: its story and paragraph, its object index there and the text.
|
||||
|
||||
@@ -1129,6 +1129,36 @@ fn a_missing_references_error_is_in_the_interface_language() {
|
||||
assert_eq!(shown, [french, "Target"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_context_ref_keeps_an_ancestor_when_the_label_contains_literal_percent_zero() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::numbering::Level;
|
||||
use wordcraft_doc::props::NumRef;
|
||||
use wordcraft_doc::{Document, ListKind};
|
||||
|
||||
for (template, own, full) in [("%0-%2.", "%0-1", "1%0-1"), ("%1-%2.", "1-1", "1-1"), ("(%2).", "(1)", "1(1)")] {
|
||||
let mut doc = Document::from_text("Parent\nTarget\nRefs ");
|
||||
let numbering = Arc::make_mut(&mut doc.numbering);
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
numbering.nums[0].level_overrides = vec![(1, Level { text: template.into(), ..Default::default() })];
|
||||
for level in 0..=1u8 {
|
||||
doc.para_mut(StoryRef::Body, &Path::top(usize::from(level))).unwrap().props.numbering = Some(NumRef { num, level });
|
||||
}
|
||||
|
||||
let mut s = Session::new(doc);
|
||||
s.run("select.text", &json!({"text": "Target"})).unwrap();
|
||||
s.run("insert.bookmark", &json!({"name": "Mark"})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
for instr in [r"REF Mark \n", r"REF Mark \w"] {
|
||||
s.run("insert.field", &json!({"instr": instr})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " "})).unwrap();
|
||||
}
|
||||
let refs = stale_last_paragraph(&mut s, "stale");
|
||||
update_fields(&mut s).unwrap();
|
||||
assert_eq!(results_in(&s.doc, &refs), [own, full], "{template}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A REF showing the bookmarked paragraph's number (`\r`, `\n`, `\w`), which output doesn't
|
||||
/// compute, keeps its stored number when printed or exported rather than show the paragraph's
|
||||
/// text; a plain REF to the same bookmark is filled in.
|
||||
|
||||
@@ -264,8 +264,7 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph. Only apply it
|
||||
/// when paragraph removal or joining also moves the endpoint.
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph.
|
||||
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
|
||||
let Some(para) = s.doc.para_at(end) else { return end.off };
|
||||
let removed: usize = para
|
||||
@@ -307,6 +306,8 @@ fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcra
|
||||
|
||||
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
|
||||
s.sel.anchor.off = offsets[0];
|
||||
s.sel.focus.off = offsets[1];
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
@@ -319,10 +320,11 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing && remove_trailing_para(s, st, &path)? {
|
||||
// Selection ends in the removed paragraph go to the end of the one before it;
|
||||
// clamping later would keep their offsets in that paragraph's text (#8500).
|
||||
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
|
||||
// keep that offset through any later remapping when earlier edits resolve.
|
||||
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(&mut offsets) {
|
||||
if end.story == st && end.path == path {
|
||||
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
|
||||
*offset = end.off;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,6 +566,73 @@ fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_moves_follow_layout_visibility_for_balloons_and_hidden_marks() {
|
||||
use wordcraft_doc::{Path, Pos, Revision, RevisionKind, StoryRef};
|
||||
|
||||
let mut s = Session::new(Document::from_text("one del two"));
|
||||
let id = s.run("insert.header", &json!({"text": "one del two"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
let header = StoryRef::Part(id);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
let del_start = "one ".len();
|
||||
let two_start = "one del ".len();
|
||||
for story in [StoryRef::Body, header] {
|
||||
s.run("select.range", &json!({"anchor": Pos::new(story, Path::top(0), del_start), "focus": Pos::new(story, Path::top(0), two_start)}))
|
||||
.unwrap();
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
|
||||
assert!(s.revisions_in_balloons());
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, two_start), "Body in balloons skips deleted word on Ctrl+Right");
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Body in balloons skips deleted word on Ctrl+Left");
|
||||
|
||||
s.run("caret.set", &json!({"pos": Pos::new(header, Path::top(0), 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::new(header, Path::top(0), del_start), "Header inline keeps deleted word stop on Ctrl+Right");
|
||||
|
||||
s.run("view.commentsPane", &json!({"value": true})).unwrap();
|
||||
assert!(!s.revisions_in_balloons());
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, del_start), "Body stops at deleted word once revisions move inline");
|
||||
|
||||
let mut doc = Document::from_text("one del mov two");
|
||||
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
|
||||
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
|
||||
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
|
||||
doc.revisions.extend([deletion, source, destination]);
|
||||
let mov_start = "one del ".len();
|
||||
let end_two_start = "one del mov ".len();
|
||||
doc.format_range(&Pos::body(0, del_start), &Pos::body(0, mov_start), &|c| c.del = Some(0)).unwrap();
|
||||
doc.format_range(&Pos::body(0, mov_start), &Pos::body(0, end_two_start), &|c| c.del = Some(1)).unwrap();
|
||||
doc.format_range(&Pos::body(0, end_two_start), &Pos::body(0, "one del mov two".len()), &|c| c.ins = Some(2)).unwrap();
|
||||
let mut s = Session::new(doc);
|
||||
|
||||
for (delete_mark, move_from_mark, right_from, right_to, left_to) in [
|
||||
("strikethrough", "strikethrough", del_start, mov_start, mov_start),
|
||||
("hidden", "strikethrough", 0, mov_start, mov_start),
|
||||
("strikethrough", "hidden", del_start, end_two_start, del_start),
|
||||
("hidden", "hidden", 0, end_two_start, 0),
|
||||
] {
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, right_from)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, right_to), "Ctrl+Right ({delete_mark}, {move_from_mark})");
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, end_two_start)})).unwrap();
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, left_to), "Ctrl+Left ({delete_mark}, {move_from_mark})");
|
||||
}
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": "hidden", "moveFromMark": "strikethrough"})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, mov_start)})).unwrap();
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left from mov skips hidden del");
|
||||
}
|
||||
|
||||
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
|
||||
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
|
||||
}
|
||||
|
||||
@@ -123,12 +123,12 @@ pub(super) fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.push_undo("AutoFormat", doc, sel);
|
||||
// Undo right after it makes the capitalised word an exception.
|
||||
let depth = s.undo_steps_so_far();
|
||||
if let Some(c) = s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
c.depth = depth;
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.commit_depth(depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
s.set_ime_edit_outcome(outcome);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -87,22 +87,35 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
if f.off > 0 {
|
||||
let a = Pos { off: para.backspace_from(f.off), ..f.clone() };
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
let carried = deleted_char_props(s, &a, &f);
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome {
|
||||
classified: true,
|
||||
content_changed: effect.content_changed,
|
||||
state_changed: effect.state_changed,
|
||||
transformed: false,
|
||||
selection_changed: false,
|
||||
});
|
||||
let (content_changed, state_changed, transformed) = if let Some(start) =
|
||||
s.autocap.as_ref().and_then(|c| c.pronoun_before_separator(&a, &f, s.undo_steps_so_far()))
|
||||
&& matches!(para.text.get(start.off..f.off), Some("I " | "I," | "I." | "I;" | "I:" | "I!" | "I?"))
|
||||
{
|
||||
// This restores a letter in place. Ordinary typing over a selection removes its link.
|
||||
let props = para.props_of_char(start.off);
|
||||
let linked_letter = props.link.as_ref().map(|_| props.clone());
|
||||
s.sel = Selection { anchor: start.clone(), focus: f.clone() };
|
||||
let pending = std::mem::replace(&mut s.pending, linked_letter);
|
||||
let effect = crate::cmd::type_text_effect(s, "i");
|
||||
s.pending = pending;
|
||||
let effect = effect?;
|
||||
if let Some(c) = &mut s.autocap {
|
||||
c.note_backspace(&start, &f);
|
||||
}
|
||||
(effect.content_changed, effect.state_changed, true)
|
||||
} else {
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
(effect.content_changed, effect.state_changed, false)
|
||||
};
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome { classified: true, content_changed, state_changed, transformed, selection_changed: false });
|
||||
// As in Word, text typed next takes the deleted character's formatting until the caret
|
||||
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
|
||||
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
if content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
s.pending_at = carried.as_ref().map(|_| a.clone());
|
||||
s.pending = carried;
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
if let Some((doc, sel)) = plain {
|
||||
// Removes the marks, then AutoCorrects the word as without them.
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
let (done_doc, done_sel) = (std::mem::replace(&mut s.doc, doc), std::mem::replace(&mut s.sel, sel));
|
||||
let new = split_para(s, &at)?;
|
||||
let c = s.doc.para_at(&new).map(|p| p.mark.clone()).unwrap_or_default();
|
||||
@@ -165,7 +165,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
return Ok(());
|
||||
}
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
at = s.sel.focus.clone();
|
||||
}
|
||||
let new = split_para(s, &at)?;
|
||||
|
||||
@@ -268,6 +268,15 @@ fn plain_word(w: &str) -> bool {
|
||||
!w.trim().is_empty() && w.chars().count() <= MAX_FROM && !w.contains(|c: char| c.is_whitespace() || c == '\u{FFFC}')
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct PronounCap {
|
||||
depth: u64,
|
||||
story: wordcraft_doc::StoryRef,
|
||||
path: wordcraft_doc::Path,
|
||||
start: usize,
|
||||
backspaced: bool,
|
||||
}
|
||||
|
||||
/// The newest automatic capitalisation (a sentence capital, a TWo INitial CApitals fix), kept so
|
||||
/// that undoing it, or backspacing it and typing the word again, makes an exception (#1857).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -283,11 +292,64 @@ pub struct AutoCap {
|
||||
pub(super) prev: String,
|
||||
/// The TWo INitial CApitals word as typed ("TWo").
|
||||
pub(super) two_caps: Option<String>,
|
||||
/// The English replacement of lowercase i with uppercase I, kept alongside an earlier sentence
|
||||
/// capital so an automatic `I` does not wipe the pending first-letter exception.
|
||||
pub(super) pronoun: Option<PronounCap>,
|
||||
/// The user backspaced into the word after the change.
|
||||
pub(super) backspaced: bool,
|
||||
}
|
||||
|
||||
impl AutoCap {
|
||||
pub(crate) fn commit_depth(&mut self, depth: u64) {
|
||||
if self.depth == u64::MAX {
|
||||
self.depth = depth;
|
||||
}
|
||||
if let Some(p) = self.pronoun.as_mut().filter(|p| p.depth == u64::MAX) {
|
||||
p.depth = depth;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_uncommitted(slot: &mut Option<Self>) {
|
||||
if let Some(c) = slot.as_mut() {
|
||||
if c.pronoun.as_ref().is_some_and(|p| p.depth == u64::MAX) {
|
||||
c.pronoun = None;
|
||||
}
|
||||
if c.depth == u64::MAX {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn record_pronoun(slot: &mut Option<Self>, story: wordcraft_doc::StoryRef, path: wordcraft_doc::Path, start: usize) {
|
||||
let pronoun = PronounCap { depth: u64::MAX, story, path: path.clone(), start, backspaced: false };
|
||||
if let Some(c) = slot.as_mut().filter(|c| !c.prev.is_empty() || c.two_caps.is_some()) {
|
||||
c.pronoun = Some(pronoun);
|
||||
} else {
|
||||
*slot =
|
||||
Some(Self { depth: u64::MAX, story, path, start, prev: String::new(), two_caps: None, pronoun: Some(pronoun), backspaced: false });
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take_backspaced_pronoun(slot: &mut Option<Self>, english: bool, word: &str, f: &Pos, start: usize) -> bool {
|
||||
let Some(c) = slot.as_mut() else { return false };
|
||||
let Some(p) = c.pronoun.take() else { return false };
|
||||
if c.prev.is_empty() && c.two_caps.is_none() {
|
||||
*slot = None;
|
||||
}
|
||||
english && word == "i" && p.backspaced && p.story == f.story && p.path == f.path && p.start == start
|
||||
}
|
||||
|
||||
/// The start of a just-corrected I when Backspace removes the separator after it.
|
||||
pub(crate) fn pronoun_before_separator(&self, a: &Pos, f: &Pos, undo_steps: u64) -> Option<Pos> {
|
||||
let p = self.pronoun.as_ref()?;
|
||||
(!p.backspaced
|
||||
&& p.story == f.story
|
||||
&& p.path == f.path
|
||||
&& p.start.checked_add(1) == Some(a.off)
|
||||
&& p.depth.checked_add(1) == Some(undo_steps))
|
||||
.then(|| Pos { off: p.start, ..f.clone() })
|
||||
}
|
||||
|
||||
pub(crate) fn add_exceptions(self, ac: &mut AutoCorrectPrefs) {
|
||||
if ac.auto_add_first_letter && !self.prev.is_empty() {
|
||||
ac.add_exception(self.prev);
|
||||
@@ -304,6 +366,14 @@ impl AutoCap {
|
||||
if f.story == self.story && f.path == self.path && a.off <= self.start && f.off > self.start {
|
||||
self.backspaced = true;
|
||||
}
|
||||
if let Some(p) = &mut self.pronoun
|
||||
&& f.story == p.story
|
||||
&& f.path == p.path
|
||||
&& a.off <= p.start
|
||||
&& f.off > p.start
|
||||
{
|
||||
p.backspaced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,41 @@ fn resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_all_keeps_selection_with_surviving_multibyte_text_in_the_same_paragraph() {
|
||||
for (cmd, initial) in [("review.acceptAll", "雪漢字Q"), ("review.rejectAll", "漢字Q")] {
|
||||
let mut original = Session::new(Document::from_text(initial));
|
||||
let removed = "雪".len();
|
||||
let first_kept = "漢".len();
|
||||
original.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
if cmd == "review.acceptAll" {
|
||||
original.sel = Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, removed) };
|
||||
original.run("text.delete", &json!({})).unwrap();
|
||||
} else {
|
||||
original.sel = Selection::caret(Pos::body(0, 0));
|
||||
original.run("text.insert", &json!({"text": "雪"})).unwrap();
|
||||
}
|
||||
assert_eq!(original.doc.plain_text(StoryRef::Body), "雪漢字Q");
|
||||
|
||||
for (before, after, typed) in [
|
||||
(Selection::caret(Pos::body(0, removed)), Selection::caret(Pos::body(0, 0)), "!漢字Q"),
|
||||
(
|
||||
Selection { anchor: Pos::body(0, removed + first_kept), focus: Pos::body(0, removed) },
|
||||
Selection { anchor: Pos::body(0, first_kept), focus: Pos::body(0, 0) },
|
||||
"!字Q",
|
||||
),
|
||||
] {
|
||||
let mut s = Session::new(original.doc.clone());
|
||||
s.sel = before;
|
||||
s.run(cmd, &json!({"stopTracking": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "漢字Q", "{cmd}");
|
||||
assert_eq!(s.sel, after, "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "!"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), typed, "{cmd}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
|
||||
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
|
||||
@@ -163,19 +198,20 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
|
||||
#[test]
|
||||
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
|
||||
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
|
||||
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
|
||||
// same offsets of that paragraph's text (#8500).
|
||||
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
|
||||
for (orig, revised, cmd) in cases {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
|
||||
let keep = "A\nKeep this";
|
||||
// Both endpoints of the removed paragraph go to the preceding paragraph's end (#8500),
|
||||
// even if removing another paragraph subsequently shifts that paragraph up (#8913).
|
||||
for (changed, last) in [("A\nKeep this\nNEW", 2), ("A\nEarlier\nKeep this\nNEW", 3)] {
|
||||
for (orig, revised, cmd) in [(keep, changed, "review.rejectAll"), (changed, keep, "review.acceptAll")] {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(last, 0), "focus": Pos::body(last, 3)})).unwrap();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), keep, "{cmd}, last block {last}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}, last block {last}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}, last block {last}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
&& letters.chars().nth(1).is_some_and(char::is_uppercase)
|
||||
&& letters.chars().next().is_some_and(char::is_uppercase))
|
||||
.then(|| letters.clone()),
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
let fixed: String = reps.concat();
|
||||
@@ -84,7 +85,9 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
// A whole-word replacement, else "wait..." → "wait…". Proofing decides what is English the
|
||||
// same way (#835); every English (en-GB, en-CA…) counts (#1281).
|
||||
let english = s.doc.para_at(&f).is_none_or(|_| wordcraft_proof::ProofLang::from_tag(lang.as_deref()).is_english());
|
||||
let found = if ac.replace_text { ac.replacement_in(&word, english) } else { None };
|
||||
// A rejected pronoun is kept at this occurrence only, including at the start of a sentence.
|
||||
let keep_i = AutoCap::take_backspaced_pronoun(&mut s.autocap, english, &word, &f, start);
|
||||
let found = if ac.replace_text && !keep_i { ac.replacement_in(&word, english) } else { None };
|
||||
let (from, rep) = match found {
|
||||
Some(r) => (start, Some(r)),
|
||||
None if ac.replace_text && word.len() > 3 && word.ends_with("...") => (start + word.len() - 3, Some("…".to_string())),
|
||||
@@ -106,6 +109,9 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
para.insert_text(from, &rep, &props)?;
|
||||
caret = (f.off + rep.len()).saturating_sub(end - from);
|
||||
s.sel = Selection::caret(Pos { off: caret, ..f.clone() });
|
||||
if english && word == "i" && rep == "I" {
|
||||
AutoCap::record_pronoun(&mut s.autocap, f.story, f.path.clone(), start);
|
||||
}
|
||||
}
|
||||
let end = caret.saturating_sub(trigger);
|
||||
let Some(word) = s.doc.para_at(&f).and_then(|p| p.text.get(start..end)).map(str::to_string) else { return Ok(()) };
|
||||
@@ -147,7 +153,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
} else {
|
||||
last
|
||||
};
|
||||
let mut sentence = sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let mut sentence = !keep_i && sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let prev = if sentence { prev_token(before_word) } else { String::new() };
|
||||
// Typing the word again after backspacing an automatic capital: the user doesn't want it
|
||||
// (Word's "Automatically add words to list"); an exception, so no capital this time either.
|
||||
@@ -173,7 +179,16 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
match s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
Some(c) => c.prev = prev,
|
||||
None => {
|
||||
s.autocap = Some(AutoCap { depth: u64::MAX, story: f.story, path: f.path, start, prev, two_caps: None, backspaced: false })
|
||||
s.autocap = Some(AutoCap {
|
||||
depth: u64::MAX,
|
||||
story: f.story,
|
||||
path: f.path,
|
||||
start,
|
||||
prev,
|
||||
two_caps: None,
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
Ok(json!({"paperColor": color}))
|
||||
}).params(r#"{"value": "document" | "green" | "cream" | "gray"}"#).pure(),
|
||||
// How the edges of page text are smoothed on screen. Screen only; never in the document.
|
||||
CommandSpec::new("view.textSmoothing", "Screen Text Smoothing", "View › Display", |s, v| {
|
||||
let smoothing: TextSmoothing = serde_json::from_value(v.get("value").cloned().unwrap_or(Value::Null))
|
||||
.map_err(|_| CmdError::Params("screen text smoothing must be system, grayscale, or subpixel".into()))?;
|
||||
s.prefs.text_smoothing = smoothing;
|
||||
Ok(json!({"textSmoothing": smoothing}))
|
||||
})
|
||||
.params(r#"{"value": "system" | "grayscale" | "subpixel"}"#)
|
||||
.pure(),
|
||||
// Print Layout: hide the white space (margins, headers, footers) between pages. Screen only.
|
||||
CommandSpec::new("view.hideWhiteSpace", "Hide White Space", "View › Show", |s, v| toggle(s, v, |x| &mut x.hide_white_space))
|
||||
.params(r#"{"value"?: bool}"#)
|
||||
@@ -349,6 +358,35 @@ fn read_line_spacing(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"spacing": spacing}))
|
||||
}
|
||||
|
||||
/// How the edges of page text are smoothed on screen, saved with user preferences, never in the
|
||||
/// document. Exports, prints and PDFs are not affected.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextSmoothing {
|
||||
/// As the system is set: subpixel where it asks for it (ClearType on Windows, `rgba`
|
||||
/// antialiasing on a Linux desktop) and the screen is not a high-density one, else
|
||||
/// greyscale. macOS never asks for it.
|
||||
#[default]
|
||||
System,
|
||||
/// Greyscale antialiasing: grey edges, no colour.
|
||||
Grayscale,
|
||||
/// Subpixel (LCD) antialiasing, whatever the system says: edges three times as fine
|
||||
/// sideways, with faint colour in them. In the system's stripe order, RGB when it gives none.
|
||||
Subpixel,
|
||||
}
|
||||
|
||||
impl TextSmoothing {
|
||||
pub const ALL: [Self; 3] = [Self::System, Self::Grayscale, Self::Subpixel];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "Use system setting",
|
||||
Self::Grayscale => "Grayscale",
|
||||
Self::Subpixel => "Subpixel (LCD)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen-only paper presets, saved with user preferences, never in the document.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -273,7 +273,7 @@ pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), Str
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir, dict_test_lock};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -282,6 +282,11 @@ mod tests {
|
||||
/// Test lock serializing tests that access the global proofing dictionary.
|
||||
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Acquire [`DICT_TEST_LOCK`], recovering cleanly if an earlier test panicked while holding it.
|
||||
pub(crate) fn dict_test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
DICT_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// RAII guard for temporary directories in dictionary tests.
|
||||
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! `/work`), exactly: on Windows what exists is resolved to its real case first.
|
||||
//! - Writing replaces or removes a directory entry, so for write access the entry itself (its
|
||||
//! folder's links followed, its own name as given) must lie inside the root as well: a link
|
||||
//! folder's links followed, its own name as it stands) must lie inside the root as well: a link
|
||||
//! outside the root that leads into it is not a way to write outside (#3735).
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
@@ -76,6 +76,12 @@ impl AutomationRoots {
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// Roots that grant no access at all: what an agent gets when its folders can't be used, so it
|
||||
/// is refused rather than left unconfined.
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: None, write: None })
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_ref().map(|r| r.shown.as_path())
|
||||
@@ -216,14 +222,24 @@ fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
|
||||
/// The directory entry `path` names: its folder resolved as [`resolve`] resolves it, then its own
|
||||
/// name as given, so a link there is the entry itself, not what it leads to. That entry is what
|
||||
/// replacing or removing the file changes.
|
||||
/// replacing or removing the file changes. What exists and isn't a link gets its real case, which
|
||||
/// is how the root is spelled when another spelling of the root is named.
|
||||
fn resolve_entry(path: &str) -> Result<PathBuf, String> {
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?;
|
||||
let (Some(folder), Some(name)) = (absolute.parent(), absolute.file_name()) else {
|
||||
return Err(format!("automation path rejected: not a file name: {path}"));
|
||||
};
|
||||
let mut entry = resolve_absolute(path, folder)?;
|
||||
entry.push(name);
|
||||
let resolved_folder = resolve_absolute(path, folder)?;
|
||||
let entry = resolved_folder.join(name);
|
||||
// Only accept `canonicalize` (for on-disk case) when it stays in `resolved_folder` under the
|
||||
// same name, so a symlink swapped in after `symlink_metadata` cannot redirect outside -> inside (#9292).
|
||||
if std::fs::symlink_metadata(&entry).is_ok_and(|m| !m.file_type().is_symlink())
|
||||
&& let Ok(canon) = std::fs::canonicalize(&entry)
|
||||
&& canon.parent() == Some(resolved_folder.as_path())
|
||||
&& canon.file_name().is_some_and(|c| c.to_string_lossy().eq_ignore_ascii_case(&name.to_string_lossy()))
|
||||
{
|
||||
return Ok(canon);
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
@@ -264,30 +280,19 @@ fn resolve_absolute(path: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
/// Is `path` (resolved) `root` or inside it, component by component? Exactly, on Windows too: what
|
||||
/// exists has its real case from [`resolve`], and a folder that doesn't exist yet may be a different
|
||||
/// one from the root where a parent folder is case sensitive.
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
root.components().all(|r| path.next() == Some(r))
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return false;
|
||||
}
|
||||
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
|
||||
let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered =
|
||||
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
@@ -381,6 +386,7 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A root and a path reached through links are compared after the links are followed.
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
@@ -428,20 +434,78 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that differs in case is another name until the file system says otherwise.
|
||||
#[test]
|
||||
fn names_are_compared_exactly() {
|
||||
let root = Path::new("/work/In");
|
||||
assert!(inside(Path::new("/work/In/new/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/IN/a.docx"), root));
|
||||
assert!(!inside(Path::new("/WORK/In/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/in\u{212A}/a.docx"), Path::new("/work/ink")), "the Kelvin sign folds to k");
|
||||
if cfg!(windows) {
|
||||
let root = Path::new(r"C:\work\In");
|
||||
assert!(inside(Path::new(r"c:\work\In\a.docx"), root), "a drive letter is one drive in either case");
|
||||
assert!(!inside(Path::new(r"C:\work\IN\a.docx"), root));
|
||||
}
|
||||
}
|
||||
|
||||
/// In a case-sensitive folder, `IN` beside the root `in` is another folder, there or not yet.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
fn a_case_sensitive_folder_keeps_a_differently_cased_name_out() {
|
||||
let base = std::env::temp_dir().join(format!("wc-file-access-case-sensitive-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let set = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output();
|
||||
if !set.as_ref().is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: a case-sensitive folder can't be made here: {set:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir(base.join("in")).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("in"))).unwrap().unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/new.docx")), Access::Write), Ok(()));
|
||||
let e = roots.check(&s(base.join("IN/new.docx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
std::fs::create_dir(base.join("IN")).unwrap();
|
||||
std::fs::write(base.join("IN/secret.docx"), "x").unwrap();
|
||||
let e = roots.check(&s(base.join("IN/secret.docx")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On Windows a path finds its real case on disk, and device names are refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_finds_the_real_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/A.SVG"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(&s(base.join("In/Sub/New.docx")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT/New.docx")), Access::Write), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT")), Access::Write), Ok(()), "the root itself, in another spelling");
|
||||
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
|
||||
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A symlink beside the write root that leads into it is not inside the root: writing would replace the link.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sibling_symlink_into_the_write_root_is_rejected() {
|
||||
let (base, roots) = folders("sibling-link");
|
||||
let link = base.join("evil");
|
||||
std::os::unix::fs::symlink(base.join("out"), &link).unwrap();
|
||||
let e = roots.check(&s(link), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Scopes nest, and a scope applies only on the thread that set it.
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
@@ -463,12 +527,13 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// What is a device name, with superscript digits and a name before a colon, and what isn't.
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL "] {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x"] {
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,10 @@ pub struct Prefs {
|
||||
/// On-screen paper for pages without a document background; excluded from saved documents.
|
||||
#[serde(deserialize_with = "lenient_paper_color")]
|
||||
pub paper_color: crate::cmd::view::PaperColor,
|
||||
/// How the edges of page text are smoothed on screen (`view.textSmoothing`); excluded from
|
||||
/// saved documents.
|
||||
#[serde(deserialize_with = "lenient_text_smoothing")]
|
||||
pub text_smoothing: crate::cmd::view::TextSmoothing,
|
||||
/// Track Changes Options: what markup shows and how revisions are drawn (per user, as in
|
||||
/// Word).
|
||||
pub markup: wordcraft_layout::display::MarkupOptions,
|
||||
@@ -72,6 +76,7 @@ impl Default for Prefs {
|
||||
fn default() -> Self {
|
||||
Prefs {
|
||||
paper_color: Default::default(),
|
||||
text_smoothing: Default::default(),
|
||||
count_notes: true,
|
||||
markup: Default::default(),
|
||||
print_markup: false,
|
||||
@@ -119,6 +124,12 @@ fn lenient_paper_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Ignore an invalid saved text smoothing without discarding other preferences.
|
||||
fn lenient_text_smoothing<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::TextSmoothing, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Ignore an invalid saved Page Color without discarding other preferences.
|
||||
fn lenient_read_page_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::ReadPageColor, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
|
||||
@@ -300,6 +300,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let _dict_guard = crate::custom_dict::dict_test_lock();
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
|
||||
@@ -63,7 +63,10 @@ impl Session {
|
||||
/// A navigated style change is for the Accept or Reject that follows: a command that edits
|
||||
/// or moves the selection forgets it.
|
||||
fn forget_review_style(&mut self, id: &str, mutates: bool) {
|
||||
if (mutates && !matches!(id, "review.accept" | "review.reject")) || id.starts_with("caret.") || id.starts_with("select.") {
|
||||
if (mutates && !matches!(id, "review.accept" | "review.reject" | "review.acceptAndNext" | "review.rejectAndNext"))
|
||||
|| id.starts_with("caret.")
|
||||
|| id.starts_with("select.")
|
||||
{
|
||||
self.review_style = None;
|
||||
}
|
||||
}
|
||||
@@ -155,6 +158,8 @@ impl Session {
|
||||
// Commands may leave an equation (a whole-body replacement) even after they fail; put
|
||||
// the editing session back with the document.
|
||||
let math_before = spec.mutates.then(|| self.math.clone());
|
||||
// A header or footer edit can take its saved body selection before the protection check.
|
||||
let hf_return_before = spec.mutates.then(|| self.hf_return.clone()).flatten();
|
||||
let before_doc: Option<RunSnapshot> = if spec.mutates {
|
||||
Some((
|
||||
self.doc.clone(),
|
||||
@@ -300,6 +305,7 @@ impl Session {
|
||||
if let Some((d, s, h, r, t, ev, c)) = before_doc {
|
||||
self.doc = d;
|
||||
self.sel = s;
|
||||
self.hf_return = hf_return_before;
|
||||
self.history = h;
|
||||
self.redo = r;
|
||||
self.typing_open = t;
|
||||
|
||||
+296
-73
@@ -312,6 +312,9 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
|
||||
assert!(wordcraft_proof::user_dictionary().contains(&"zxqengconfined".to_string()), "kept in memory");
|
||||
wordcraft_proof::remove_word("zxqengconfined");
|
||||
assert!(!outside.exists(), "nothing written outside the write root");
|
||||
std::fs::write(&outside, "outsideword\n").unwrap();
|
||||
assert!(confined(&mut s, "file.options", json!({"customDictionary": outside})).is_err());
|
||||
assert_eq!(s.prefs.custom_dictionary, None);
|
||||
for key in ["dictionariesFolder", "userTemplatesFolder"] {
|
||||
assert!(confined(&mut s, "file.options", json!({key: base.join("outside").to_string_lossy()})).is_err(), "{key}");
|
||||
}
|
||||
@@ -407,33 +410,6 @@ fn custom_dictionary_freestanding_file_option() {
|
||||
let rel_err = s.run("file.options", &json!({"customDictionary": "relative/custom.dic"})).unwrap_err();
|
||||
assert!(format!("{rel_err:?}").contains("isn't a full path"));
|
||||
|
||||
// Accept ~/ path expansion when HOME points to a directory.
|
||||
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
|
||||
let home_dir = std::path::PathBuf::from(home);
|
||||
let test_name = format!(".wordcraft-test-tilde-{}.dic", std::process::id());
|
||||
let tilde_file = home_dir.join(&test_name);
|
||||
struct CleanFile(std::path::PathBuf);
|
||||
impl Drop for CleanFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
if let Ok(mut f) = opts.open(&tilde_file) {
|
||||
use std::io::Write;
|
||||
let _ = f.write_all(b"tildeword\n");
|
||||
let _cleaner = CleanFile(tilde_file.clone());
|
||||
let tilde_res = s.run("file.options", &json!({"customDictionary": format!("~/{test_name}")}));
|
||||
assert!(tilde_res.is_ok(), "tilde expansion succeeds: {:?}", tilde_res.err());
|
||||
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(tilde_file.to_string_lossy().as_ref()));
|
||||
assert!(wordcraft_proof::is_correct("tildeword"));
|
||||
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
|
||||
wordcraft_proof::remove_word("tildeword");
|
||||
wordcraft_proof::remove_word("defaultword");
|
||||
}
|
||||
}
|
||||
|
||||
let huge_dic = dir.path().join("huge.dic");
|
||||
std::fs::write(&huge_dic, vec![b'a'; (crate::custom_dict::MAX_CUSTOM_FILE_BYTES + 1024) as usize]).unwrap();
|
||||
assert!(s.run("file.options", &json!({"customDictionary": huge_dic.to_string_lossy()})).is_err());
|
||||
@@ -4532,6 +4508,14 @@ fn tracked_style_definition_changes_are_recorded_and_resolved() {
|
||||
run(&mut s, "review.acceptAll", json!({}));
|
||||
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.bold, Some(true), "accepting keeps the change");
|
||||
assert!(s.doc.revisions.is_empty());
|
||||
|
||||
for (command, italic) in [("review.rejectAndNext", None), ("review.acceptAndNext", Some(true))] {
|
||||
run(&mut s, "styles.modify", json!({"style": "Heading1", "chr": {"italic": true}}));
|
||||
run(&mut s, "review.nextChange", json!({}));
|
||||
run(&mut s, command, json!({}));
|
||||
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.italic, italic, "{command} resolves the navigated style definition");
|
||||
assert_eq!(run(&mut s, "review.changes", json!({})), json!([]), "{command} leaves no style change behind");
|
||||
}
|
||||
}
|
||||
|
||||
/// #2697 review: Update Style to Match Selection also rewrites the selected paragraph. Its body
|
||||
@@ -8455,6 +8439,156 @@ fn styles_apply_multi_paragraph_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9203: `styles.modify` rejects unknown keys in `para` and `chr` (such as snake_case names)
|
||||
/// instead of silently dropping them, while applying camelCase `ParaProps` fields.
|
||||
#[test]
|
||||
fn styles_modify_rejects_unknown_para_and_chr_fields() {
|
||||
let mut s = s();
|
||||
let err = s
|
||||
.run("styles.modify", &json!({"style": "Heading1", "para": {"space_before": 123, "page_break_before": true}, "chr": {"size": 33}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
|
||||
let h1 = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_ne!(h1.chr.size, Some(33.0), "rejected para block must not partially apply chr");
|
||||
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"unknownKey": true}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
|
||||
|
||||
// #9291: unknown keys inside nested structs (such as Borders / Border) are rejected too.
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"Top": {"width": 1.0}}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error for nested Borders key, got {err:?}");
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"top": {"bogus": 1.0}}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error for nested Border key, got {err:?}");
|
||||
|
||||
s.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "para": {"spaceBefore": 123.0, "pageBreakBefore": true, "borders": {"top": {"width": 1.5, "style": "single"}}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let h1 = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_eq!(h1.para.space_before, Some(123.0));
|
||||
assert_eq!(h1.para.page_break_before, Some(true));
|
||||
assert!(h1.para.borders.as_ref().and_then(|b| b.top).is_some_and(|t| (t.width - 1.5).abs() < 0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_tagged_text_fill_fields_before_changing_the_style() {
|
||||
use wordcraft_doc::wordart::TextFill;
|
||||
|
||||
let mut s = s();
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
let gradient_stops = json!([{"pos": 0, "color": "112233"}, {"pos": 100, "color": "445566", "transparency": 25}]);
|
||||
for (fill, field) in [
|
||||
(json!({"type": "solid", "color": "FF0000", "bogus": 1}), "bogus"),
|
||||
(json!({"type": "none", "color": "FF0000"}), "color"),
|
||||
(json!({"type": "gradient", "stops": gradient_stops, "color": "FF0000"}), "color"),
|
||||
(json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}), "bogus"),
|
||||
] {
|
||||
let err = s
|
||||
.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": {"fill": fill}}}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains(field)), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before), "rejected fill must leave the style unchanged");
|
||||
}
|
||||
|
||||
let fill = |s: &Session| s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap();
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "solid", "color": "FF0000"}}}})).unwrap();
|
||||
assert_eq!(fill(&s), TextFill::Solid { color: wordcraft_doc::Rgb(255, 0, 0), transparency: 0.0 });
|
||||
s.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "gradient", "angle": 45, "stops": gradient_stops}}}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(fill(&s), TextFill::Gradient { stops, angle } if angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "none"}}}})).unwrap();
|
||||
assert_eq!(fill(&s), TextFill::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_text_fills_in_positional_arguments() {
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::wordart::TextFill;
|
||||
|
||||
let chr_with = |text_effects: Value, positional: bool| {
|
||||
if positional {
|
||||
// CharProps puts textEffects after the first 30 optional fields.
|
||||
let mut fields = vec![Value::Null; 30];
|
||||
fields.push(text_effects);
|
||||
Value::Array(fields)
|
||||
} else {
|
||||
json!({"textEffects": text_effects})
|
||||
}
|
||||
};
|
||||
let mut s = s();
|
||||
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
|
||||
for (positional_chr, positional_effects) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let effects = |fill: Value| if positional_effects { json!([fill]) } else { json!({"fill": fill}) };
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
for fill in [
|
||||
json!({"type": "solid", "color": "FF0000", "bogus": 1}),
|
||||
json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
|
||||
json!(["gradient", [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
|
||||
] {
|
||||
let chr = chr_with(effects(fill), positional_chr);
|
||||
let params = json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": chr});
|
||||
let err = s.run("styles.modify", ¶ms).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
for fill in [json!({"type": "gradient", "stops": stops, "angle": 45}), json!(["gradient", stops, 45])] {
|
||||
let chr = chr_with(effects(fill), positional_chr);
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": chr})).unwrap();
|
||||
let fill = s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.as_ref().unwrap();
|
||||
assert!(matches!(fill, TextFill::Gradient { stops, angle } if *angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
|
||||
}
|
||||
}
|
||||
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
let old = chr_with(json!([{"type": "solid", "color": "FF0000", "bogus": 1}]), true);
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"fmtChange": {"rev": 0, "old": old}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_numeric_text_fill_tags() {
|
||||
let mut refused = s();
|
||||
let before = refused.doc.styles.get("Heading1").unwrap().clone();
|
||||
for fill in [
|
||||
json!({"type": 0, "bogus": 1}),
|
||||
json!({"type": 1, "color": "FF0000", "bogus": 1}),
|
||||
json!({"type": 2, "stops": [{"pos": 0, "color": "112233"}], "bogus": 1}),
|
||||
json!({"type": 2, "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
|
||||
json!([2, [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
|
||||
] {
|
||||
let err = refused
|
||||
.run("styles.modify", &json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": [fill]}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(refused.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
|
||||
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
|
||||
for (fill, named) in [
|
||||
(json!({"type": 0}), json!({"type": "none"})),
|
||||
(json!([0]), json!({"type": "none"})),
|
||||
(json!({"type": 1, "color": "FF0000"}), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
|
||||
(json!([1, "FF0000", 0]), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
|
||||
(json!({"type": 2, "stops": stops, "angle": 45}), json!({"type": "gradient", "stops": stops, "angle": 45})),
|
||||
(json!([2, stops, 45]), json!({"type": "gradient", "stops": stops, "angle": 45})),
|
||||
] {
|
||||
let set_fill = |fill| {
|
||||
let mut s = s();
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": fill}}})).unwrap();
|
||||
s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap()
|
||||
};
|
||||
assert_eq!(set_fill(fill), set_fill(named));
|
||||
}
|
||||
}
|
||||
|
||||
/// #865: `styles.modify` takes a colour the way `format.color` does (`RRGGBB`, `#RRGGBB`, `auto`),
|
||||
/// still reads the serialized forms, and rejects a bad colour without touching the style.
|
||||
#[test]
|
||||
@@ -11890,19 +12024,17 @@ fn next_footnote_skips_endnotes() {
|
||||
assert_eq!(s.sel.focus.off, 9);
|
||||
}
|
||||
|
||||
/// Tests that install a test dictionary wait for the dictionaries-folder test, which changes the
|
||||
/// folder and then reads what each language reports: an install in between reports no file.
|
||||
static DICTIONARIES: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Tests that read or mutate process-wide proofing dictionaries take turns through `DICT_TEST_LOCK`.
|
||||
fn dictionaries_turn() -> std::sync::MutexGuard<'static, ()> {
|
||||
DICTIONARIES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
crate::custom_dict::dict_test_lock()
|
||||
}
|
||||
|
||||
/// A tiny synthetic Polish Hunspell dictionary (written for these tests). Real dictionaries are
|
||||
/// installed on the system, never bundled; every Polish test installs this same one.
|
||||
fn polish_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn polish_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
wordcraft_proof::pl::install_dictionary(POLISH_TEST_AFF, POLISH_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const POLISH_TEST_AFF: &str = "SET UTF-8\nTRY aioeznrwcyszżtkpdmłjlubąęgh\nMAP 2\nMAP oó\nMAP zż\nREP 2\nREP ż rz\nREP rz ż\n";
|
||||
@@ -11910,9 +12042,10 @@ const POLISH_TEST_DIC: &str = "12\npłynie\nrzeka\na\nto\nwiem\nże\ntak\nw\nog
|
||||
|
||||
/// A tiny synthetic Portuguese Hunspell dictionary (written for these tests). Real dictionaries
|
||||
/// are installed on the system, never bundled; every Portuguese test installs this same one.
|
||||
fn portuguese_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn portuguese_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
wordcraft_proof::pt::install_dictionary(PORTUGUESE_TEST_AFF, PORTUGUESE_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const PORTUGUESE_TEST_AFF: &str =
|
||||
@@ -11987,7 +12120,7 @@ fn dictionaries_folder_option_is_saved_searched_and_reported() {
|
||||
/// grammar, suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn portuguese_proofing_through_the_review_commands() {
|
||||
portuguese_test_dictionary();
|
||||
let _turn = portuguese_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Saudade coraçao, e ele ele disse."}));
|
||||
// English by default: the Portuguese words are English misspellings.
|
||||
@@ -12018,9 +12151,10 @@ fn portuguese_proofing_through_the_review_commands() {
|
||||
assert_eq!(left.as_array().unwrap().len(), 1, "{left}");
|
||||
}
|
||||
|
||||
fn indonesian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn indonesian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
wordcraft_proof::id::install_dictionary(INDONESIAN_TEST_AFF, INDONESIAN_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
// Hand-written synthetic fixture (no system dictionary data).
|
||||
@@ -12031,7 +12165,7 @@ const INDONESIAN_TEST_DIC: &str = "8\nrumah\nsekolah\nanak\nbermain\ndi\nmakan/A
|
||||
/// Dictionary.
|
||||
#[test]
|
||||
fn indonesian_proofing_through_the_review_commands() {
|
||||
indonesian_test_dictionary();
|
||||
let _turn = indonesian_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Saya di sekolha, anak anak bermain."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12086,6 +12220,7 @@ fn english_dialects_through_the_review_commands() {
|
||||
if no_language_data("english_dialects_through_the_review_commands") {
|
||||
return;
|
||||
}
|
||||
let _turn = dictionaries_turn();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "The colour of the center."}));
|
||||
// US English by default: the British spelling is flagged, the American one isn't.
|
||||
@@ -12193,19 +12328,20 @@ const SPANISH_TEST_AFF: &str =
|
||||
const SPANISH_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\nhabéis\nvenido\ndecir\n";
|
||||
const URUGUAYAN_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\ntener\nvenir\ndecir\n";
|
||||
|
||||
fn spanish_test_dictionaries() {
|
||||
fn spanish_test_dictionaries() -> std::sync::MutexGuard<'static, ()> {
|
||||
use wordcraft_proof::ProofLang;
|
||||
let _turn = dictionaries_turn();
|
||||
let turn = dictionaries_turn();
|
||||
for (lang, dic) in [(ProofLang::Es, SPANISH_TEST_DIC), (ProofLang::EsUy, URUGUAYAN_TEST_DIC)] {
|
||||
wordcraft_proof::es::install_dictionary(lang, SPANISH_TEST_AFF, dic).unwrap();
|
||||
}
|
||||
turn
|
||||
}
|
||||
|
||||
/// #3553: Spanish proofing through the same commands as Review, F7, Change and Add to
|
||||
/// Dictionary: `prueva` and `corector` are flagged with `prueba` and `corrector` offered.
|
||||
#[test]
|
||||
fn spanish_proofing_through_the_review_commands() {
|
||||
spanish_test_dictionaries();
|
||||
let _turn = spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "esto es una prueva del corector. Habéis venido?"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12236,7 +12372,7 @@ fn spanish_proofing_through_the_review_commands() {
|
||||
/// bytes.
|
||||
#[test]
|
||||
fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
spanish_test_dictionaries();
|
||||
let _turn = spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
let text = "esto zqanade\u{301}do y zqignora\u{301}do";
|
||||
run(&mut s, "document.setText", json!({"text": text}));
|
||||
@@ -12265,7 +12401,7 @@ fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
/// Uruguayan Spanish accepts the `vos` forms, imperatives included, that Spain's flags.
|
||||
#[test]
|
||||
fn uruguayan_spanish_accepts_vos_forms() {
|
||||
spanish_test_dictionaries();
|
||||
let _turn = spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Vení, decime qué tenés."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12284,7 +12420,7 @@ fn uruguayan_spanish_accepts_vos_forms() {
|
||||
/// Czech proofing through the same commands as Review, F7, Change and Add to Dictionary.
|
||||
#[test]
|
||||
fn czech_proofing_through_the_review_commands() {
|
||||
czech_test_dict::install();
|
||||
let _turn = czech_test_dict::install();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Město pocitac, škola škola."}));
|
||||
assert!(run(&mut s, "review.issues", json!({})).as_array().unwrap().len() >= 3);
|
||||
@@ -12323,9 +12459,10 @@ fn czech_proofing_through_the_review_commands() {
|
||||
const ITALIAN_TEST_AFF: &str = "SET UTF-8\nTRY aeiortnsclcaffèéè\nMAP 2\nMAP aà\nMAP eéè\nREP 1\nREP caffe caffè\n";
|
||||
const ITALIAN_TEST_DIC: &str = "6\ncasa\ncaffè\nroma\ndisse\ne\nper\n";
|
||||
|
||||
fn italian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
wordcraft_proof::it::install_dictionary(ITALIAN_TEST_AFF, ITALIAN_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
/// Review › Language and the proofing commands work in Italian end to end: the language makes
|
||||
@@ -12333,7 +12470,7 @@ fn italian_test_dictionary() {
|
||||
/// suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn italian_proofing_through_the_review_commands() {
|
||||
italian_test_dictionary();
|
||||
let _turn = italian_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Casa caffe, e roma roma disse."}));
|
||||
// English by default: the Italian words are English misspellings.
|
||||
@@ -12366,7 +12503,7 @@ fn italian_proofing_through_the_review_commands() {
|
||||
|
||||
#[test]
|
||||
fn polish_proofing_through_the_review_commands() {
|
||||
polish_test_dictionary();
|
||||
let _turn = polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Płynie żeka, a wogóle to wiem że tak."}));
|
||||
// English by default: the Polish words are English misspellings.
|
||||
@@ -12406,6 +12543,7 @@ fn turkish_proofing_through_the_review_commands() {
|
||||
if !crate::proof::tr::has_dictionary() {
|
||||
return;
|
||||
}
|
||||
let _turn = dictionaries_turn();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bana bazen gelenler oldu ise de. Sana olacaklardan sonra sorna"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12433,7 +12571,7 @@ fn turkish_proofing_through_the_review_commands() {
|
||||
/// no parameters keep the old meaning (US English), and `default` needs a language.
|
||||
#[test]
|
||||
fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
polish_test_dictionary();
|
||||
let _turn = polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Hello wrold"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12454,6 +12592,7 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
// A language without proofing tools: no marks. `zxx` (no linguistic content) never has
|
||||
// them; a real language such as fr-FR does wherever its system Hunspell dictionary is installed.
|
||||
run(&mut s, "review.language", json!({"lang": "zxx"}));
|
||||
assert_eq!(run(&mut s, "format.state", json!({}))["lang"], "zxx");
|
||||
assert_eq!(run(&mut s, "review.issues", json!({})), json!([]));
|
||||
}
|
||||
|
||||
@@ -12461,7 +12600,7 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
/// the caret, not the document's default, so what is typed in them is proofed in that language.
|
||||
#[test]
|
||||
fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
polish_test_dictionary();
|
||||
let _turn = polish_test_dictionary();
|
||||
let cell_langs = |s: &Session| -> Vec<Option<String>> {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
t.rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).map(|p| p.mark.lang.clone()).collect()
|
||||
@@ -12505,7 +12644,7 @@ fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
/// a document with changes never does, and templates stay English.
|
||||
#[test]
|
||||
fn new_documents_follow_the_editing_language() {
|
||||
polish_test_dictionary();
|
||||
let _turn = polish_test_dictionary();
|
||||
let mut s = s();
|
||||
s.set_editing_language(Some("pl-PL"));
|
||||
assert_eq!(s.doc.styles.default_chr.lang.as_deref(), Some("pl-PL"), "the untouched blank document switches");
|
||||
@@ -12611,7 +12750,7 @@ fn rejected_default_proofing_language_does_not_survive_a_restart() {
|
||||
/// English run (`w:lang`) come back, and so does the proofing.
|
||||
#[test]
|
||||
fn proofing_languages_survive_a_docx_round_trip() {
|
||||
polish_test_dictionary();
|
||||
let _turn = polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Płynie żeka. Hello wrold."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -15055,7 +15194,7 @@ fn export_png_refuses_a_path_that_is_not_png() {
|
||||
#[test]
|
||||
fn ime_body_epoch_marks_body_replacements_not_edits() {
|
||||
let mut s = s();
|
||||
let id = s.document_id();
|
||||
let document_id = s.document_id();
|
||||
run(&mut s, "text.insert", json!({"text": "one"}));
|
||||
let first = s.ime_body_epoch();
|
||||
run(&mut s, "text.insert", json!({"text": " two"}));
|
||||
@@ -15064,7 +15203,7 @@ fn ime_body_epoch_marks_body_replacements_not_edits() {
|
||||
run(&mut s, "document.setText", json!({"text": "same text"}));
|
||||
let replaced = s.ime_body_epoch();
|
||||
assert!(replaced > first, "setText replaces the body under the same document id");
|
||||
assert_eq!(s.document_id(), id, "the document id itself is unchanged");
|
||||
assert_eq!(s.document_id(), document_id, "the document id itself is unchanged");
|
||||
|
||||
// The same text again still replaces the body: a composition must not survive on content
|
||||
// equality.
|
||||
@@ -15456,6 +15595,37 @@ fn export_png_rejects_a_page_number_that_does_not_fit() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_text_smoothing_is_a_persistent_preference_not_document_formatting() {
|
||||
use crate::cmd::view::TextSmoothing;
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Screen text test", "raw": true}));
|
||||
let before = serde_json::to_value(&s.doc).unwrap();
|
||||
let docx_before = wordcraft_docx::write(&s.doc).unwrap();
|
||||
s.dirty = false;
|
||||
assert_eq!(s.prefs.text_smoothing, TextSmoothing::System, "follows the system until the user chooses");
|
||||
for (value, expected) in [("subpixel", TextSmoothing::Subpixel), ("grayscale", TextSmoothing::Grayscale), ("system", TextSmoothing::System)] {
|
||||
let r = run(&mut s, "view.textSmoothing", json!({"value": value}));
|
||||
assert_eq!(r["textSmoothing"], value);
|
||||
assert_eq!(s.prefs.text_smoothing, expected);
|
||||
assert_eq!(serde_json::to_value(&s.doc).unwrap(), before);
|
||||
assert!(!s.dirty);
|
||||
assert_eq!(wordcraft_docx::write(&s.doc).unwrap(), docx_before);
|
||||
let restored: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
|
||||
assert_eq!(restored.text_smoothing, expected);
|
||||
}
|
||||
run(&mut s, "view.textSmoothing", json!({"value": "subpixel"}));
|
||||
for v in [json!({}), json!({"value": "lcd"}), json!({"value": 42}), json!({"value": null}), json!({"value": ["subpixel"]})] {
|
||||
assert!(s.run("view.textSmoothing", &v).is_err(), "{v}");
|
||||
assert_eq!(s.prefs.text_smoothing, TextSmoothing::Subpixel, "a refused value changes nothing");
|
||||
}
|
||||
let legacy: crate::Prefs = serde_json::from_value(json!({})).unwrap();
|
||||
assert_eq!(legacy.text_smoothing, TextSmoothing::System);
|
||||
let future: crate::Prefs = serde_json::from_value(json!({"textSmoothing":"future", "countNotes":false})).unwrap();
|
||||
assert_eq!(future.text_smoothing, TextSmoothing::System);
|
||||
assert!(!future.count_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_paper_color_is_a_persistent_preference_not_document_formatting() {
|
||||
use crate::cmd::view::PaperColor;
|
||||
@@ -15849,36 +16019,47 @@ fn page_down_and_up_move_by_a_page_in_the_continuous_views() {
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_never_stay_on_a_line_in_the_continuous_views() {
|
||||
// A page with less than an inch of text area: the views move by the one-inch minimum. The
|
||||
// caret ends a long line and the paragraphs after it are narrow (a large right indent): the
|
||||
// line a page away, not the one the caret is on, is where Page Down goes, however far right
|
||||
// of it the caret is.
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
// The text area is less than an inch high, so the views use a 72 pt step. A step can cross
|
||||
// different numbers of 30 pt lines in the two directions. Start inside the document so the
|
||||
// test exercises movement in both directions without running into the first line.
|
||||
let lead_in = 12;
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(2);
|
||||
let text = format!("{}{long}{}", "a\n".repeat(lead_in), "\na".repeat(60));
|
||||
for view in ["view.draft", "view.outline", "view.webLayout"] {
|
||||
let mut s = s();
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&text));
|
||||
run(&mut s, "layout.margins", json!({"top": 370, "bottom": 370}));
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(2);
|
||||
run(&mut s, "text.insert", json!({"text": long}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "para.indents", json!({"right": 700}));
|
||||
for i in 0..60 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
for (i, path) in s.doc.para_paths(StoryRef::Body).iter().enumerate() {
|
||||
let p = s.doc.para_mut(StoryRef::Body, path).unwrap();
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(30.0));
|
||||
if i != lead_in {
|
||||
p.props.indent_right = Some(700.0);
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": "a"}));
|
||||
}
|
||||
run(&mut s, view, json!({}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": lead_in}}));
|
||||
run(&mut s, "caret.end", json!({}));
|
||||
assert_eq!(s.sel.focus.off, long.chars().count(), "{view}: the first paragraph is one line");
|
||||
assert_eq!(s.sel.focus, Pos::body(lead_in, long.len()), "{view}: the long paragraph is one line");
|
||||
let mut at = s.sel.focus.clone();
|
||||
let layout = s.layout();
|
||||
let start = layout.caret(&at).unwrap();
|
||||
let first = layout.caret(&Pos::body(0, 0)).unwrap();
|
||||
assert!(start.top - first.top > 3.0 * 72.0, "{view}: there is room above the long line for all three reverse steps");
|
||||
for step in 0..3 {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
assert!(s.sel.focus > at, "{view}: Page Down {step} moves on from {at:?}");
|
||||
assert!(s.sel.focus.path > at.path, "{view}: Page Down {step} moves to a later paragraph from {at:?}");
|
||||
at = s.sel.focus.clone();
|
||||
if step == 0 {
|
||||
let next = s.layout().caret(&at).unwrap();
|
||||
assert!(next.x < start.x, "{view}: the destination line ends left of the starting caret");
|
||||
}
|
||||
}
|
||||
for step in 0..3 {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
assert!(s.sel.focus < at, "{view}: Page Up {step} moves back from {at:?}");
|
||||
assert!(s.sel.focus.path < at.path, "{view}: Page Up {step} moves to an earlier paragraph from {at:?}");
|
||||
at = s.sel.focus.clone();
|
||||
}
|
||||
}
|
||||
@@ -15967,6 +16148,48 @@ fn replace_all_replaces_in_every_story() {
|
||||
assert!(story_text(&t, StoryRef::Part(ids[0])).contains("Jane"));
|
||||
}
|
||||
|
||||
/// #9063: With Track Changes on, Replace All must not leave the caret in another story (e.g. a
|
||||
/// header or footnote) when the caret's original story had no match.
|
||||
#[test]
|
||||
fn replace_all_with_track_changes_keeps_caret_when_original_story_has_no_match() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Main text only."}));
|
||||
let header_id = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
t.sel = crate::session::Selection::caret(Pos::body(0, 0));
|
||||
let before = t.sel.clone();
|
||||
assert_eq!(before.focus.story, StoryRef::Body);
|
||||
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
assert_eq!(t.sel, before);
|
||||
assert!(!t.in_header_footer());
|
||||
assert!(
|
||||
t.doc.para_at(&wordcraft_doc::Pos::new(StoryRef::Part(header_id), wordcraft_doc::Path::top(0), 0)).is_some_and(|p| p.text.contains("Jane"))
|
||||
);
|
||||
}
|
||||
|
||||
/// #9186: With Track Changes on, Replace All must keep the caret in its original story even when
|
||||
/// both that story and the main text have matches.
|
||||
#[test]
|
||||
fn replace_all_with_track_changes_keeps_caret_in_original_story_when_both_match() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body: [NAME]."}));
|
||||
let header_id = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
let header_story = StoryRef::Part(header_id);
|
||||
t.sel = crate::session::Selection::caret(Pos::new(header_story, wordcraft_doc::Path::top(0), 0));
|
||||
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 2, "{r}");
|
||||
assert_eq!(t.sel.focus.story, header_story, "caret must stay in the header story");
|
||||
assert!(t.in_header_footer());
|
||||
assert!(t.doc.plain_text(StoryRef::Body).contains("Jane"));
|
||||
assert!(t.doc.plain_text(header_story).contains("Jane"));
|
||||
}
|
||||
|
||||
/// #9064: Replace All skips stories nothing shows any more (a removed header, a footnote whose
|
||||
/// reference was deleted without tracking) and does not count them.
|
||||
#[test]
|
||||
|
||||
@@ -54,6 +54,8 @@ to
|
||||
zqzakázané/F
|
||||
";
|
||||
|
||||
pub fn install() {
|
||||
pub fn install() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = super::dictionaries_turn();
|
||||
super::install_dictionary(AFF, DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
@@ -7,24 +7,31 @@ use crate::Session;
|
||||
use crate::cmd::insert::base64_encode;
|
||||
|
||||
#[test]
|
||||
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
|
||||
fn format_state_reports_the_east_asian_theme_face_and_per_run_fallbacks() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::ThemeFont;
|
||||
use wordcraft_doc::{Document, Path, StoryRef};
|
||||
|
||||
let mut doc = Document::from_text("漢字");
|
||||
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
|
||||
doc.para_mut(StoryRef::Body, &Path::top(0))
|
||||
.unwrap()
|
||||
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
|
||||
.unwrap();
|
||||
let first = "漢".len();
|
||||
let second = "漢字".len();
|
||||
let mut doc = Document::from_text("漢字文");
|
||||
let defaults = &mut Arc::make_mut(&mut doc.styles).default_chr;
|
||||
defaults.font = Some("Example Latin".into());
|
||||
defaults.font_ea = Some("Times New Roman".into());
|
||||
let para = doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
para.format(0, second, &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
|
||||
para.format(first, second, &|props| props.font = Some("Other Latin".into())).unwrap();
|
||||
let mut fallback = Session::new(doc.clone());
|
||||
fallback.run("select.all", &json!({})).unwrap();
|
||||
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
|
||||
for (start, end, family) in [(0, first, "Example Latin"), (first, second, "Other Latin")] {
|
||||
fallback.run("select.range", &json!({"anchor": Pos::body(0, start), "focus": Pos::body(0, end)})).unwrap();
|
||||
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], family);
|
||||
}
|
||||
fallback.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
|
||||
assert!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the unresolved slot uses each run's own font");
|
||||
|
||||
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
|
||||
let mut s = Session::new(doc);
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
|
||||
s.run("select.all", &json!({})).unwrap();
|
||||
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
|
||||
|
||||
@@ -3171,6 +3171,80 @@ fn undoing_a_replacement_adds_no_exception() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So teh and the ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspacing_an_automatic_i_keeps_the_retyped_word_lowercase() {
|
||||
let mut s = typed("so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i");
|
||||
typ(&mut s, " want this and i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i want this and I ");
|
||||
|
||||
let mut s = typed("so i ");
|
||||
typ(&mut s, "\u{8}\u{8}i want this and i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i want this and I ");
|
||||
|
||||
let s = typed("i \u{8}\u{8}i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "i ");
|
||||
|
||||
let s = typed("so I \u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_i_keeps_pending_first_letter_exception_from_earlier_sentence_capital() {
|
||||
let mut s = typed("hello there. so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So I ");
|
||||
// Backspacing back to "hello there. " and retyping "so " still learns "there.".
|
||||
typ(&mut s, "\u{8}\u{8}\u{8}\u{8}\u{8}so ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
|
||||
assert_eq!(first_letter_list(&s), ["there."]);
|
||||
|
||||
// Restoring lowercase "i" first still leaves the earlier sentence-capital record intact.
|
||||
let mut s = typed("hello there. so i ");
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So i");
|
||||
typ(&mut s, " \u{8}\u{8}\u{8}\u{8}\u{8}so ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
|
||||
assert_eq!(first_letter_list(&s), ["there."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_a_lowercase_i_preserves_the_deleted_separators_formatting_for_typing() {
|
||||
let mut s = typed("so ");
|
||||
run(&mut s, "format.bold", json!({"value": true}));
|
||||
typ(&mut s, "i");
|
||||
run(&mut s, "format.bold", json!({"value": false}));
|
||||
typ(&mut s, " ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
assert!(bold_at(&s, 3) && !bold_at(&s, 4));
|
||||
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i");
|
||||
assert!(bold_at(&s, 3));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
|
||||
typ(&mut s, "x");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So ix");
|
||||
assert!(!bold_at(&s, 4), "the deleted separator was plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_a_lowercase_i_keeps_its_hyperlink() {
|
||||
let mut s = typed("so ");
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "ab"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 4}}));
|
||||
typ(&mut s, " i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a I b");
|
||||
assert_eq!(links(&s), [("a I b".into(), false)]);
|
||||
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a ib");
|
||||
assert_eq!(links(&s), [("a ib".into(), false)]);
|
||||
typ(&mut s, "x");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a ixb");
|
||||
assert_eq!(links(&s), [("a ib".into(), false)], "the next letter uses the unlinked separator formatting");
|
||||
}
|
||||
|
||||
/// Checked in Word for Mac: the same rule as First Letter.
|
||||
#[test]
|
||||
fn undoing_an_initial_caps_fix_adds_an_initial_caps_exception() {
|
||||
@@ -3425,6 +3499,53 @@ fn backspace_deletes_selected_columns_and_delete_clears_them() {
|
||||
assert_eq!(table_cells(&s), [["a1", "", "c1"], ["a2", "", "c2"], ["a3", "", "c3"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_and_demote_only_change_list_levels_in_selected_cells() {
|
||||
for (command, changed_level) in [("para.promote", 0), ("para.demote", 2)] {
|
||||
let mut s = table_between(0, 1);
|
||||
let num = Arc::make_mut(&mut s.doc.numbering).try_add_list(wordcraft_doc::ListKind::Numbered).unwrap();
|
||||
let story = StoryRef::Body;
|
||||
for path in s.doc.para_paths(story) {
|
||||
s.doc.para_mut(story, &path).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 1 });
|
||||
}
|
||||
|
||||
run(&mut s, "table.selectColumn", json!({}));
|
||||
let range = s.cell_range().unwrap().clone();
|
||||
assert_eq!((range.rows, range.cols), ((0, 2), (1, 1)));
|
||||
let selected = s.sel.clone();
|
||||
run(&mut s, command, json!({}));
|
||||
assert_eq!(s.sel, selected);
|
||||
for path in s.doc.para_paths(story) {
|
||||
let expected = if path.cell().is_some_and(|(_, _, col)| col == 1) { changed_level } else { 1 };
|
||||
let actual = s.doc.para(story, &path).unwrap().props.numbering;
|
||||
assert_eq!(actual, Some(wordcraft_doc::props::NumRef { num, level: expected }), "{command}: {path:?}");
|
||||
}
|
||||
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
for path in s.doc.para_paths(story) {
|
||||
assert_eq!(
|
||||
s.doc.para(story, &path).unwrap().props.numbering,
|
||||
Some(wordcraft_doc::props::NumRef { num, level: 1 }),
|
||||
"undo {command}: {path:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_keeps_the_heading_at_the_end_of_a_text_selection_in_scope() {
|
||||
let mut s = typed("First\nSecond\nThird");
|
||||
for index in 0..3 {
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(index, 0)}));
|
||||
run(&mut s, "para.style", json!({"style": "Heading2"}));
|
||||
}
|
||||
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [2, 2, 2]);
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(1, 0)}));
|
||||
assert!(s.cell_range().is_none());
|
||||
run(&mut s, "para.promote", json!({}));
|
||||
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [1, 1, 2]);
|
||||
}
|
||||
|
||||
/// The first top-level table's cells, row by row, one entry per block: a paragraph's text, or
|
||||
/// `<table>` for a nested table.
|
||||
fn cell_blocks(s: &Session) -> Vec<Vec<Vec<String>>> {
|
||||
@@ -4876,3 +4997,81 @@ fn enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph() {
|
||||
assert_eq!(second.drop_cap_font, None, "{position}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8986: Up/Down step along vertical lines and Left/Right cross stacked lines (preserving
|
||||
/// goal distance, collapsing or extending selections, and falling back along the line when
|
||||
/// there is no adjacent line in the flow) for both `tbRl` (`"down"`) and `btLr` (`"up"`).
|
||||
#[test]
|
||||
fn arrow_keys_navigate_vertical_text() {
|
||||
use wordcraft_doc::Path;
|
||||
|
||||
let set = |s: &mut Session, anchor: Pos, focus: Pos| {
|
||||
s.sel = crate::Selection { anchor, focus };
|
||||
s.goal_x = None;
|
||||
};
|
||||
|
||||
// 1. Top-to-bottom (`tbRl`): Down advances, Up retreats; Left goes to next line, Right to previous.
|
||||
let mut doc = typed("abcd\nx\nabcd");
|
||||
run(&mut doc, "layout.textDirection", json!({"value": "down"}));
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(0, 1));
|
||||
run(&mut doc, "caret.down", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 2), "tbRl Down advances along the line");
|
||||
run(&mut doc, "caret.up", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 1), "tbRl Up moves back along the line");
|
||||
|
||||
set(&mut doc, Pos::body(0, 3), Pos::body(0, 3));
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "tbRl Left steps to the shorter next line");
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(2, 3), "tbRl Left keeps goal distance across the short middle line");
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "tbRl Right steps to the previous line");
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 3), "tbRl Right returns to offset 3 with preserved goal distance");
|
||||
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(2, 2), "tbRl Left collapses selection to end");
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(0, 1), "tbRl Right collapses selection to start");
|
||||
|
||||
set(&mut doc, Pos::body(1, 1), Pos::body(1, 1));
|
||||
run(&mut doc, "caret.left", json!({"extend": true}));
|
||||
assert_eq!((&doc.sel.anchor, &doc.sel.focus), (&Pos::body(1, 1), &Pos::body(2, 1)), "extend=true keeps anchor across lines");
|
||||
|
||||
// 2. Bottom-to-top (`btLr`): Up advances, Down retreats; Right goes to next line, Left to previous.
|
||||
run(&mut doc, "layout.textDirection", json!({"value": "up"}));
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(0, 1));
|
||||
run(&mut doc, "caret.up", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 2), "btLr Up advances along the line");
|
||||
run(&mut doc, "caret.down", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(0, 1), "btLr Down moves back along the line");
|
||||
|
||||
set(&mut doc, Pos::body(0, 3), Pos::body(0, 3));
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "btLr Right steps to the shorter next line");
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(2, 3), "btLr Right keeps goal distance across the short middle line");
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert_eq!(doc.sel.focus, Pos::body(1, 1), "btLr Left steps to the previous line");
|
||||
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.left", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(0, 1), "btLr Left collapses selection to start");
|
||||
set(&mut doc, Pos::body(0, 1), Pos::body(2, 2));
|
||||
run(&mut doc, "caret.right", json!({}));
|
||||
assert!(doc.sel.is_collapsed() && doc.sel.focus == Pos::body(2, 2), "btLr Right collapses selection to end");
|
||||
|
||||
// 3. Single-line vertical table cell fallback: Left/Right stay inside the cell and step along its text.
|
||||
let mut tbl = s();
|
||||
run(&mut tbl, "insert.table", json!({"rows": 1, "cols": 2}));
|
||||
run(&mut tbl, "text.insert", json!({"text": "abc"}));
|
||||
run(&mut tbl, "table.textDirection", json!({"value": "down"}));
|
||||
let cell0 = |off| Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off };
|
||||
set(&mut tbl, cell0(2), cell0(2));
|
||||
run(&mut tbl, "caret.left", json!({}));
|
||||
assert_eq!(tbl.sel.focus, cell0(1), "single-line vertical cell Left falls back backwards along text");
|
||||
run(&mut tbl, "caret.right", json!({}));
|
||||
assert_eq!(tbl.sel.focus, cell0(2), "single-line vertical cell Right falls back forwards along text");
|
||||
}
|
||||
|
||||
@@ -483,3 +483,17 @@ fn named_instances_and_collection_members_are_capped() {
|
||||
// (under 0.1 s on a loaded machine) only backs up "read once", with room for a busy CI.
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_calibri_without_carlito_reports_the_drawn_fallback() {
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
db.faces.write().unwrap().retain(|face| !face.family.eq_ignore_ascii_case("Carlito"));
|
||||
assert!(!db.has_family("Carlito"));
|
||||
|
||||
let missing = crate::word::missing_metric_fonts_in(&db);
|
||||
let used = missing.iter().find(|(family, _)| *family == "Calibri").map_or("", |(_, used)| used.as_str());
|
||||
assert!(!used.is_empty(), "Calibri should be reported without Carlito");
|
||||
assert_ne!(used, "Carlito");
|
||||
assert!(db.has_family(used), "the notice names the face actually drawn");
|
||||
}
|
||||
|
||||
@@ -76,10 +76,10 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
|
||||
}
|
||||
}
|
||||
const SERIF: &[&str] = &["Caladea", "Times New Roman", "Liberation Serif", "Georgia", "Noto Serif", "DejaVu Serif", "Source Serif 4"];
|
||||
const MONO: &[&str] = &["Courier New", "Liberation Mono", "Menlo", "Consolas", "DejaVu Sans Mono", "JetBrains Mono"];
|
||||
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
|
||||
const MONO: &[&str] = &["Courier New", "Liberation Mono", "Cousine", "Menlo", "Consolas", "DejaVu Sans Mono", "JetBrains Mono"];
|
||||
const ARIAL: &[&str] = &["Liberation Sans", "Arimo", "Helvetica", "Helvetica Neue", "Source Sans 3"];
|
||||
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Arimo", "Helvetica", "Helvetica Neue", "Source Sans 3"];
|
||||
const TIMES: &[&str] = &["Liberation Serif", "Tinos", "Times", "Source Serif 4"];
|
||||
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
|
||||
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
|
||||
// headings and screens. Open fonts with full Persian coverage first.
|
||||
@@ -494,6 +494,37 @@ fn substitute(db: &FontDb, family: &str) -> Option<&'static str> {
|
||||
.or_else(|| installed.first().copied())
|
||||
}
|
||||
|
||||
/// Word's core families, each with the open fonts that share its metrics. Without the family or
|
||||
/// a twin, text set in it wraps and paginates differently from Word (Times New Roman drawn in a
|
||||
/// wider serif fits fewer lines to a page).
|
||||
const CORE_METRIC_FONTS: &[(&str, &[&str])] = &[
|
||||
("Times New Roman", &["Liberation Serif", "Tinos"]),
|
||||
("Arial", &["Liberation Sans", "Arimo"]),
|
||||
("Courier New", &["Liberation Mono", "Cousine"]),
|
||||
("Calibri", &["Carlito"]),
|
||||
("Cambria", &["Caladea"]),
|
||||
];
|
||||
|
||||
/// Word's core families not drawn with themselves or a metric twin, paired with the primary
|
||||
/// resolved family. Glyphs the primary family cannot draw may still use glyph fallback.
|
||||
pub fn missing_metric_fonts() -> Vec<(&'static str, String)> {
|
||||
missing_metric_fonts_in(FontDb::global())
|
||||
}
|
||||
|
||||
pub(crate) fn missing_metric_fonts_in(db: &FontDb) -> Vec<(&'static str, String)> {
|
||||
CORE_METRIC_FONTS
|
||||
.iter()
|
||||
.filter_map(|(word, twins)| {
|
||||
let resolved = resolve_with_db(db, word, false, false);
|
||||
if has_metric_resolution(db.has_family(word), twins, &resolved.face.family) { None } else { Some((*word, resolved.face.family.clone())) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn has_metric_resolution(installed_word_font: bool, twins: &[&str], resolved_family: &str) -> bool {
|
||||
installed_word_font || twins.iter().any(|twin| resolved_family.eq_ignore_ascii_case(twin))
|
||||
}
|
||||
|
||||
fn style_name(bold: bool, italic: bool) -> &'static str {
|
||||
match (bold, italic) {
|
||||
(false, false) => "Regular",
|
||||
@@ -705,9 +736,7 @@ pub fn resolve(family: &str, bold: bool, italic: bool) -> Resolved {
|
||||
return *r;
|
||||
}
|
||||
}
|
||||
let (fam, substituted) = resolve_family(db, family);
|
||||
let face = db.face(&fam, style_name(bold, italic));
|
||||
let r = Resolved { synth_bold: bold && face.weight < 600.0, synth_italic: italic && !face.italic, substituted, face: FaceRef::of(&face) };
|
||||
let r = resolve_with_db(db, family, bold, italic);
|
||||
if cacheable {
|
||||
let mut c = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if c.0 == generation {
|
||||
@@ -728,6 +757,12 @@ pub fn resolve(family: &str, bold: bool, italic: bool) -> Resolved {
|
||||
r
|
||||
}
|
||||
|
||||
fn resolve_with_db(db: &FontDb, family: &str, bold: bool, italic: bool) -> Resolved {
|
||||
let (fam, substituted) = resolve_family(db, family);
|
||||
let face = db.face(&fam, style_name(bold, italic));
|
||||
Resolved { synth_bold: bold && face.weight < 600.0, synth_italic: italic && !face.italic, substituted, face: FaceRef::of(&face) }
|
||||
}
|
||||
|
||||
/// A line's (ascent, descent) from hhea values, both positive: the line gap goes above the ascent.
|
||||
fn hhea_line(ascender: i16, descender: i16, line_gap: i16) -> (f64, f64) {
|
||||
(f64::from(ascender) + f64::from(line_gap.max(0)), f64::from(descender).abs())
|
||||
@@ -1094,6 +1129,48 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_font_notice_uses_the_actual_installed_face() {
|
||||
const SERIF: &[u8] = include_bytes!("../../../assets/fonts/SourceSerif4-Regular.ttf");
|
||||
let database = |name: Option<&str>| {
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
if let Some(name) = name {
|
||||
assert_eq!(db.add_document_fonts(vec![(SERIF.to_vec(), name.to_owned())]), 1);
|
||||
}
|
||||
db
|
||||
};
|
||||
|
||||
let original = database(Some("Times New Roman"));
|
||||
assert!(missing_metric_fonts_in(&original).iter().all(|(family, _)| *family != "Times New Roman"));
|
||||
assert_eq!(resolve_with_db(&original, "Times New Roman", false, false).face.family, "Times New Roman");
|
||||
|
||||
let twin = database(Some("Liberation Serif"));
|
||||
assert!(missing_metric_fonts_in(&twin).iter().all(|(family, _)| *family != "Times New Roman"));
|
||||
assert_eq!(resolve_with_db(&twin, "Times New Roman", false, false).face.family, "Liberation Serif");
|
||||
|
||||
let fallback = database(None);
|
||||
assert_eq!(
|
||||
missing_metric_fonts_in(&fallback).iter().find(|(family, _)| *family == "Times New Roman"),
|
||||
Some(&("Times New Roman", "Source Serif 4".to_owned()))
|
||||
);
|
||||
assert_eq!(resolve_with_db(&fallback, "Times New Roman", false, false).face.family, "Source Serif 4");
|
||||
|
||||
let no_carlito = database(Some("DejaVu Sans"));
|
||||
assert!(!no_carlito.has_family("Carlito"));
|
||||
assert_eq!(resolve_with_db(&no_carlito, "Calibri", false, false).face.family, "DejaVu Sans");
|
||||
assert_eq!(
|
||||
missing_metric_fonts_in(&no_carlito).iter().find(|(family, _)| *family == "Calibri"),
|
||||
Some(&("Calibri", "DejaVu Sans".to_owned()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_but_uninstalled_carlito_does_not_hide_the_chosen_fallback() {
|
||||
assert!(!has_metric_resolution(false, &["Carlito"], "DejaVu Sans"));
|
||||
assert!(has_metric_resolution(false, &["Carlito"], "Carlito"));
|
||||
}
|
||||
|
||||
/// Semicolon-separated fallback lists resolve to the first installed family, or to a
|
||||
/// candidate's substitute when no listed family is installed.
|
||||
#[test]
|
||||
|
||||
+87
-16
@@ -4,7 +4,7 @@
|
||||
//! Export writes UTF-8 with CRLF line ends; list paragraphs get their label and a tab, table
|
||||
//! cells are separated by tabs.
|
||||
|
||||
use wordcraft_doc::Document;
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
pub use wordcraft_doc::encoding::cp1252;
|
||||
|
||||
@@ -66,12 +66,24 @@ pub fn decode_as(b: &[u8], label: &str) -> Option<String> {
|
||||
Some(enc.decode(b).0.into_owned())
|
||||
}
|
||||
|
||||
/// A document with one paragraph per line.
|
||||
/// A document with one paragraph per line, with vertical tabs as manual line breaks.
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
let text = decode(bytes);
|
||||
let text = text.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000B}' | '\u{000C}' | '\u{000E}')).collect();
|
||||
Document::from_text(&clean)
|
||||
let mut doc = Document::new();
|
||||
doc.body = clean
|
||||
.split('\n')
|
||||
.map(|line| {
|
||||
let paragraph = if line.contains('\u{000B}') {
|
||||
Paragraph::with_text(&line.replace('\u{000B}', "\n"), Default::default())
|
||||
} else {
|
||||
Paragraph::with_text(line, Default::default())
|
||||
};
|
||||
para_block(paragraph)
|
||||
})
|
||||
.collect();
|
||||
doc
|
||||
}
|
||||
|
||||
/// [`import`] onto `page`: plain text gives no page size (#1381).
|
||||
@@ -94,7 +106,12 @@ fn blocks_text(blocks: &[FBlock], out: &mut Vec<String>, lists: &mut ListCounter
|
||||
}
|
||||
None => lists.reset(),
|
||||
}
|
||||
line.push_str(&p.shown_text().replace('\n', "\r\n").replace(['\u{000C}', '\u{000E}'], ""));
|
||||
let text = p.shown_text();
|
||||
if depth == 0 {
|
||||
line.push_str(&text.replace('\n', "\r\n").replace(['\u{000C}', '\u{000E}'], ""));
|
||||
} else {
|
||||
line.push_str(&text.replace('\u{000C}', ""));
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
FBlock::Table(t) => {
|
||||
@@ -106,10 +123,16 @@ fn blocks_text(blocks: &[FBlock], out: &mut Vec<String>, lists: &mut ListCounter
|
||||
if c.covered || depth > 8 {
|
||||
cells.push(String::new());
|
||||
} else {
|
||||
let mut v = Vec::new();
|
||||
blocks_text(&c.blocks, &mut v, &mut ListCounter::default(), depth + 1);
|
||||
let text = v.join(" ").split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
cells.push(text);
|
||||
let mut parts = Vec::new();
|
||||
blocks_text(&c.blocks, &mut parts, &mut ListCounter::default(), depth + 1);
|
||||
parts.retain(|part| !part.is_empty());
|
||||
// Flatten structural separators while preserving spaces typed in the cell.
|
||||
cells.push(
|
||||
parts
|
||||
.join(" ")
|
||||
.replace("\r\n", " ")
|
||||
.replace(['\t', '\r', '\n', '\u{000B}', '\u{000E}', '\u{0085}', '\u{2028}', '\u{2029}'], " "),
|
||||
);
|
||||
}
|
||||
for _ in 1..c.colspan.clamp(1, 63) {
|
||||
cells.push(String::new());
|
||||
@@ -138,7 +161,8 @@ pub fn export(doc: &Document) -> Vec<u8> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{Cell, Fmt, Para};
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, PAGE_BREAK};
|
||||
use wordcraft_doc::{Block, CharProps, Paragraph, SectionProps, Table, para_block};
|
||||
|
||||
#[test]
|
||||
fn test_utf32_bom_decode_and_sniffing() {
|
||||
@@ -164,10 +188,57 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_import_preserves_soft_breaks() {
|
||||
let raw = b"Line 1\x0BSoft break\x0ECol break";
|
||||
let doc = import(raw);
|
||||
let text = doc.plain_text(StoryRef::Body);
|
||||
assert_eq!(text, "Line 1\u{000B}Soft break\u{000E}Col break");
|
||||
let page = SectionProps { page_w: 432.0, ..Default::default() };
|
||||
let doc = import_on(b"A\x0BB\nC\x0CD\x0EE\r\nF", &page);
|
||||
let first = format!("A{LINE_BREAK}B");
|
||||
let second = format!("C{PAGE_BREAK}D{COLUMN_BREAK}E");
|
||||
assert_eq!(doc.body.len(), 3);
|
||||
assert_eq!(doc.body[0].as_para().map(|p| p.text.as_str()), Some(first.as_str()));
|
||||
assert_eq!(doc.body[1].as_para().map(|p| p.text.as_str()), Some(second.as_str()));
|
||||
assert_eq!(doc.body[2].as_para().map(|p| p.text.as_str()), Some("F"));
|
||||
assert_eq!(doc.last_section, page);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_vertical_tab_round_trips_as_docx_line_break() -> Result<(), wordcraft_docx::DocxError> {
|
||||
let doc = import(b"A\x0BB\nC");
|
||||
let reopened = wordcraft_docx::read(&wordcraft_docx::write(&doc)?)?;
|
||||
let first = format!("A{LINE_BREAK}B");
|
||||
assert_eq!(reopened.body.len(), 2);
|
||||
assert_eq!(reopened.body[0].as_para().map(|p| p.text.as_str()), Some(first.as_str()));
|
||||
assert_eq!(reopened.body[1].as_para().map(|p| p.text.as_str()), Some("C"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_txt_export_preserves_spaces_inside_table_cells() {
|
||||
let paragraph = |text| para_block(Paragraph::with_text(text, CharProps::default()));
|
||||
let mut table = Table::new(2, 2, 200.0);
|
||||
table.rows[0].cells[0].blocks = vec![paragraph(" A\u{00A0}B C\tD\nE\u{000E}F"), paragraph("G\u{2009}H ")];
|
||||
table.rows[0].cells[1].blocks = vec![paragraph("Right")];
|
||||
table.rows[1].cells[1].blocks = vec![paragraph("Last")];
|
||||
let mut doc = Document::new();
|
||||
doc.body = vec![std::sync::Arc::new(Block::Table(table))];
|
||||
|
||||
assert_eq!(export(&doc), " A\u{00A0}B C D E F G\u{2009}H \tRight\r\n\tLast".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_table_export_flattens_record_separators_without_adding_spaces_for_empty_paragraphs() {
|
||||
let paragraph = |text| para_block(Paragraph::with_text(text, CharProps::default()));
|
||||
let mut nested = Table::new(1, 2, 40.0);
|
||||
nested.rows[0].cells[0].blocks = vec![paragraph("p")];
|
||||
nested.rows[0].cells[1].blocks = vec![paragraph("q")];
|
||||
let mut table = Table::new(2, 3, 200.0);
|
||||
table.rows[0].cells[0].blocks = vec![paragraph("A"), paragraph(""), paragraph("B"), paragraph("")];
|
||||
table.rows[0].cells[1].blocks = vec![paragraph("X"), std::sync::Arc::new(Block::Table(nested)), paragraph("")];
|
||||
table.rows[0].cells[2].blocks = vec![paragraph(" C\u{00A0}D E\u{0085}F\u{2028}G\u{2029}H\tI\nJ\u{000E}K ")];
|
||||
table.rows[1].cells[1].blocks = vec![paragraph("L"), paragraph(" "), paragraph("R")];
|
||||
table.rows[1].cells[2].blocks = vec![paragraph("End")];
|
||||
let mut doc = Document::new();
|
||||
doc.body = vec![std::sync::Arc::new(Block::Table(table))];
|
||||
|
||||
assert_eq!(export(&doc), "A B\tX p q\t C\u{00A0}D E F G H I J K \r\n\tL R\tEnd".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -175,7 +246,7 @@ mod tests {
|
||||
let mut t = crate::model::FTable::default();
|
||||
let mut c1 = Cell { colspan: 2, ..Default::default() };
|
||||
let mut p1 = Para::default();
|
||||
p1.push_text("Merged\nHeader\tItem", &Fmt::default());
|
||||
p1.push_text("Merged\r\nHeader\tItem\rWith\u{000B}Breaks", &Fmt::default());
|
||||
c1.blocks.push(FBlock::Para(p1));
|
||||
|
||||
let mut c2 = Cell::default();
|
||||
@@ -203,8 +274,8 @@ mod tests {
|
||||
blocks_text(&blocks, &mut out, &mut ListCounter::default(), 0);
|
||||
|
||||
assert_eq!(out.len(), 2);
|
||||
// Row 1: Merged Header Item (colspan 2) -> "Merged Header Item\t\tCol 3"
|
||||
assert_eq!(out[0], "Merged Header Item\t\tCol 3");
|
||||
// The second field pads the two-column span of the first cell.
|
||||
assert_eq!(out[0], "Merged Header Item With Breaks\t\tCol 3");
|
||||
// Row 2: Covered cell is empty -> "\tRow 2 Col 2\tRow 2 Col 3"
|
||||
assert_eq!(out[1], "\tRow 2 Col 2\tRow 2 Col 3");
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::ctx::{Ctx, Joining, page_anchored};
|
||||
use super::floats::{
|
||||
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
|
||||
AnchoredFloat, AreaKind, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions,
|
||||
wrap_area,
|
||||
};
|
||||
use super::flow::again;
|
||||
use super::page::PageFrame;
|
||||
use super::page::{PageFrame, margin_y};
|
||||
use super::placed::Placed;
|
||||
use super::table_flow::below;
|
||||
use super::{
|
||||
@@ -162,11 +163,11 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
|
||||
Some(float) => {
|
||||
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
|
||||
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
|
||||
exclusions.push((area, false, None, WrapText::BothSides, true));
|
||||
exclusions.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
float_tables.push(area);
|
||||
table_areas.push(area);
|
||||
if float.v_rel == Anchor::Page {
|
||||
page_table_wraps.push((area, false, None, WrapText::BothSides, true));
|
||||
page_table_wraps.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
}
|
||||
(rect.x, rect.y)
|
||||
}
|
||||
@@ -335,7 +336,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
let h = ctx.float_height(o, w, h);
|
||||
if let Some(pin) = ctx.pin.as_ref().filter(|pin| in_cell && pin.story == story && float.outside_cell && page_anchored(float)) {
|
||||
let page =
|
||||
PageFrame { sect: &pin.sect, margin_top: pin.margin_top, origin: (0.0, 0.0), number: pin.number, mirror: pin.mirror };
|
||||
PageFrame { sect: &pin.sect, margin_area: pin.margin_area, origin: (0.0, 0.0), number: pin.number, mirror: pin.mirror };
|
||||
pinned.insert(oi, float_rect(Some(page), (0.0, width), para_top, w, h, float));
|
||||
continue;
|
||||
}
|
||||
@@ -561,11 +562,7 @@ fn box_float_table_rect(
|
||||
let s = fr.sect;
|
||||
match f.v_rel {
|
||||
Anchor::Page => Some((0.0, s.page_h)),
|
||||
Anchor::Margin => {
|
||||
let mut reference = s.clone();
|
||||
reference.margin_top = fr.margin_top.unwrap_or(s.margin_top);
|
||||
Some((reference.margin_top, reference.text_height()))
|
||||
}
|
||||
Anchor::Margin => Some(margin_y(fr)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
@@ -812,7 +809,7 @@ impl Joint {
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, AreaKind::Joint)];
|
||||
// Just below the first row as the line breaker tests it: the breaker tests every row at
|
||||
// its estimate (`row_est`), not at the line's height, so the first row never meets this
|
||||
// area and every later row, starting lower, does and moves below it. The probe's own first
|
||||
@@ -820,7 +817,7 @@ impl Joint {
|
||||
// line), so its height can't be used here.
|
||||
let below = self.top + gap + probe.row_est + 0.01;
|
||||
if self.bottom() > below {
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false));
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, AreaKind::Joint));
|
||||
}
|
||||
(gap, areas)
|
||||
}
|
||||
|
||||
@@ -136,8 +136,8 @@ struct WrapAreas<'a> {
|
||||
pub(crate) struct Pin {
|
||||
pub(crate) story: StoryRef,
|
||||
pub(crate) sect: SectionProps,
|
||||
/// Rendered header Margin boundary; absent in footers and height probes.
|
||||
pub(crate) margin_top: Option<f32>,
|
||||
/// Rendered body top and bottom for header Margin anchors; absent in footers and height probes.
|
||||
pub(crate) margin_area: Option<(f32, f32)>,
|
||||
pub(crate) number: u32,
|
||||
pub(crate) mirror: bool,
|
||||
pub(crate) behind: Vec<Placed>,
|
||||
@@ -162,7 +162,7 @@ pub(crate) fn with_pin<T>(
|
||||
id: u32,
|
||||
sect: &SectionProps,
|
||||
number: u32,
|
||||
margin_top: Option<f32>,
|
||||
margin_area: Option<(f32, f32)>,
|
||||
f: impl FnOnce(&mut Ctx) -> T,
|
||||
) -> (T, Vec<Placed>, Vec<Placed>) {
|
||||
let tables = ctx.doc.parts.get(&id).is_some_and(|p| p.blocks.iter().any(|b| matches!(**b, Block::Table(_))));
|
||||
@@ -172,7 +172,7 @@ pub(crate) fn with_pin<T>(
|
||||
let pin = Pin {
|
||||
story: StoryRef::Part(id),
|
||||
sect: sect.clone(),
|
||||
margin_top,
|
||||
margin_area,
|
||||
number,
|
||||
mirror: ctx.mirror,
|
||||
behind: Vec::new(),
|
||||
|
||||
@@ -100,10 +100,10 @@ pub fn field_name(instr: &str) -> String {
|
||||
instr.split_whitespace().next().unwrap_or("").trim_start_matches('=').to_ascii_uppercase()
|
||||
}
|
||||
|
||||
/// REF's hyperlink switch links its cached result without updating that result.
|
||||
/// REF and PAGEREF use the hyperlink switch to link their displayed text to the bookmark.
|
||||
pub(crate) fn reference_link(instr: &str) -> Option<String> {
|
||||
let (name, args) = instr.trim_start().split_once(char::is_whitespace)?;
|
||||
if !name.eq_ignore_ascii_case("REF") {
|
||||
if !name.eq_ignore_ascii_case("REF") && !name.eq_ignore_ascii_case("PAGEREF") {
|
||||
return None;
|
||||
}
|
||||
let args = args.trim_start();
|
||||
|
||||
+30
-18
@@ -1,5 +1,5 @@
|
||||
use super::ctx::Ctx;
|
||||
use super::page::{PageBuilder, PageFrame};
|
||||
use super::page::{PageBuilder, PageFrame, margin_y};
|
||||
use super::placed::Placed;
|
||||
use super::table_flow::footer_table_wraps;
|
||||
use super::{
|
||||
@@ -82,16 +82,11 @@ pub(crate) fn float_rect(frame: Option<PageFrame>, col: (f32, f32), y0: f32, w:
|
||||
};
|
||||
let page_y = |f: &PageFrame| {
|
||||
let s = f.sect;
|
||||
let top = f.margin_top.unwrap_or(s.margin_top);
|
||||
match float.v_rel {
|
||||
Anchor::Page => Some((0.0, s.page_h)),
|
||||
Anchor::Margin => {
|
||||
let mut reference = s.clone();
|
||||
reference.margin_top = top;
|
||||
Some((top, reference.text_height()))
|
||||
}
|
||||
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top)),
|
||||
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom, s.margin_bottom)),
|
||||
Anchor::Margin => Some(margin_y(f)),
|
||||
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top.abs())),
|
||||
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom.abs(), s.margin_bottom.abs())),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
@@ -117,8 +112,22 @@ pub(crate) fn align_in((start, extent): (f32, f32), offset: f32, size: f32, alig
|
||||
|
||||
/// An area text keeps clear of: its bounds, whether text may only go above and below it, and
|
||||
/// (Tight and Through wrapping) the outline text follows inside it, the sides text may go on,
|
||||
/// and whether it comes from a floating table (inclusive line-bottom contact, #3977).
|
||||
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, bool);
|
||||
/// and what it comes from (a floating table: inclusive line-bottom contact, #3977; Tight and
|
||||
/// Through wrapping: a narrower gap beside it before Word 2013 layout, #6316).
|
||||
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, AreaKind);
|
||||
|
||||
/// What a [`WrapArea`] keeps text clear of.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AreaKind {
|
||||
/// A floating picture, shape, text box or chart wrapped Square or Top and Bottom.
|
||||
Object,
|
||||
/// A floating object wrapped Tight or Through, with or without an outline.
|
||||
Tight,
|
||||
/// A floating table.
|
||||
Table,
|
||||
/// A paragraph continuing after a hidden paragraph mark (`Joint::fit`).
|
||||
Joint,
|
||||
}
|
||||
|
||||
/// Wrap areas a page starts with (#2048): by page index, the floating objects (block, object
|
||||
/// index) placed above the top of their anchor paragraph, with text before it on the page, and
|
||||
@@ -210,13 +219,14 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
|
||||
if matches!(float.wrap, Wrap::Tight | Wrap::Through)
|
||||
&& let Some((area, c)) = outline.and_then(|o| contour::contour_area(r, float, o))
|
||||
{
|
||||
return Some((area, false, Some(Arc::new(c)), float.wrap_text, false));
|
||||
return Some((area, false, Some(Arc::new(c)), float.wrap_text, AreaKind::Tight));
|
||||
}
|
||||
let d = |v: f32| if v.is_finite() { v.clamp(0.0, 1584.0) } else { 0.0 };
|
||||
let (side, top, bottom) = (d(float.dist), d(float.dist_top), d(float.dist_bottom));
|
||||
// A rotated object keeps text clear of its rotated bounds.
|
||||
let r = float.spin().bounds(r);
|
||||
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
|
||||
let kind = if matches!(float.wrap, Wrap::Tight | Wrap::Through) { AreaKind::Tight } else { AreaKind::Object };
|
||||
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, kind))
|
||||
}
|
||||
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
|
||||
@@ -224,7 +234,7 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
|
||||
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
|
||||
let before = if space_before > 0.0 { space_before } else { 0.0 };
|
||||
excl.iter()
|
||||
.map(|(r, tb, c, side, table)| para::Exclusion {
|
||||
.map(|(r, tb, c, side, kind)| para::Exclusion {
|
||||
top: r.y - y0,
|
||||
bottom: r.bottom() - y0,
|
||||
left: r.x - x0,
|
||||
@@ -232,7 +242,9 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
|
||||
top_bottom: *tb,
|
||||
contour: c.clone(),
|
||||
side: *side,
|
||||
table: *table,
|
||||
table: *kind == AreaKind::Table,
|
||||
tight: *kind == AreaKind::Tight,
|
||||
joint: *kind == AreaKind::Joint,
|
||||
})
|
||||
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
|
||||
// room, with that space laid out again below them (#7143). Any ending at or above it
|
||||
@@ -429,7 +441,7 @@ pub(crate) fn place_late(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, oi:
|
||||
let Some(o) = p.objects.get(oi) else { return };
|
||||
let Some((w, h, float)) = floating(o) else { return };
|
||||
let h = ctx.float_height(o, w, h);
|
||||
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let frame = PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let rect = float_rect(Some(frame), (pb.col_x(), pb.col_w()), top, w, h, float);
|
||||
let outline = ctx.wrap_outline(o);
|
||||
let area = wrap_area(rect, float, outline.as_deref().map(Vec::as_slice)).map(|a| {
|
||||
@@ -505,7 +517,7 @@ fn anchor_floats_but(
|
||||
// The paragraph's top, and whether text was placed before it on the page.
|
||||
let top = y0 - before;
|
||||
let text_before = top > pb.top + 0.5 || pb.col > 0;
|
||||
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let frame = PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
// An object left out of the layout (hidden, or deleted in the final text) is not placed, so
|
||||
// it takes no room either.
|
||||
let left_out = left_out_objects(ctx.doc, p, None, ctx.opts.show_hidden, ctx.hide_deleted);
|
||||
@@ -562,7 +574,7 @@ fn anchor_floats_but(
|
||||
let page = pb.pages.len().saturating_sub(1);
|
||||
let top = y0 - before;
|
||||
let text_before = top > pb.top + 0.5 || pb.col > 0;
|
||||
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let frame = PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
for (oi, o) in p.objects.iter().enumerate() {
|
||||
let Some((_, _, float)) = floating(o) else { continue };
|
||||
let Some(&area) = areas.get(&oi) else { continue };
|
||||
|
||||
+105
-13
@@ -118,7 +118,7 @@ fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, blo
|
||||
add_notes(pb, new_notes, ¬es, pl.lines.last().map_or(0, |line| line.c1));
|
||||
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
|
||||
let float = frame_float(&fr);
|
||||
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let page = PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
|
||||
let path = [block as u32];
|
||||
if let Some(page) = pb.page() {
|
||||
@@ -652,6 +652,40 @@ impl<'a> Flow<'a> {
|
||||
true
|
||||
}
|
||||
|
||||
/// Keep with next for the end of a paragraph begun in an earlier column (#6829): in columns
|
||||
/// being balanced, the piece holding its last line must leave room below for the next
|
||||
/// paragraph to start (as [`Self::keep_together`] asks of a paragraph's start), or its last
|
||||
/// lines (two under widow/orphan control) go over with that paragraph, as in Word. All of
|
||||
/// them going over returns `l0`, and the caller moves on even from a column's top: the
|
||||
/// balancing pass then runs onto another page and the columns are tried taller. Nothing
|
||||
/// moves in the full-height pass that is the balancing's fallback, nor when the paragraph's
|
||||
/// tail and the next paragraph's start could not fit a full column.
|
||||
fn kept_tail_end(&self, ctx: &mut Ctx, pb: &PageBuilder, rooms: Rooms, fit: &Fit) -> usize {
|
||||
let (rp, n, l0) = (&self.pl.rp, self.n(), self.l0);
|
||||
// Not in the full-height fallback pass, which must keep the original layout.
|
||||
let column = pb.uncapped_bottom() - pb.top;
|
||||
let balancing = pb.balance.is_some_and(|(page, h)| page + 1 == pb.pages.len() && h + 0.01 < column);
|
||||
// A paragraph closing a section never shares its column with the next section's first block (#9206).
|
||||
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || self.p.section.is_some() || !balancing || pb.web {
|
||||
return fit.l1;
|
||||
}
|
||||
let (Some(first), Some(last)) = (self.pl.lines.get(l0), self.pl.lines.last()) else { return fit.l1 };
|
||||
let tail = last.top + last.height - first.top + rooms.bottom;
|
||||
let need = tail
|
||||
+ gap_after(ctx, self.block, rp, self.label.is_some())
|
||||
+ next_first_line(ctx, self.block, self.laid_width, 0, pb.next_starts_page, &mut ctx.counters.clone());
|
||||
// A need no column can hold is left alone, as `keep_together` leaves it.
|
||||
if pb.y + need <= pb.bottom + 0.01 || need > column + 0.01 {
|
||||
return fit.l1;
|
||||
}
|
||||
let mut l1 = n.saturating_sub(if rp.widow_control { 2 } else { 1 }).max(l0);
|
||||
// A row (text both sides of a floating object) stays together (`settled_end`).
|
||||
while l1 > l0 && self.pl.lines.get(l1).is_some_and(|l| l.beside) {
|
||||
l1 -= 1;
|
||||
}
|
||||
l1
|
||||
}
|
||||
|
||||
/// The end of the lines on this page after widow/orphan control, and keeping the rows beside
|
||||
/// floating objects together.
|
||||
/// Also says whether, balancing from Word 2013's layout, widow/orphan control alone moved every
|
||||
@@ -753,7 +787,7 @@ impl<'a> Flow<'a> {
|
||||
self.space_here = 0.0;
|
||||
// Pictures, shapes and text boxes in these lines (web view: floats placed by this piece).
|
||||
let at = ObjFrame {
|
||||
page: Some(PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror }),
|
||||
page: Some(PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror }),
|
||||
col: (x, self.width),
|
||||
para_y: if pb.web { y } else { self.anchor_y },
|
||||
table_chr: None,
|
||||
@@ -1080,11 +1114,14 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
let notes = para_notes(ctx.doc, p, &f.pl);
|
||||
let mut fit = f.fit_lines(ctx, pb, ¬es, lead);
|
||||
let (end, widowed) = f.settled_end(ctx, pb, &fit);
|
||||
let settled = end;
|
||||
fit.l1 = end;
|
||||
fit.l1 = f.kept_tail_end(ctx, pb, rooms, &fit);
|
||||
let kept_over = fit.l1 < settled;
|
||||
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
|
||||
// the lines on without emitting anything and must release their late floats as well.
|
||||
let overflow = end == f.l0 && f.fresh(pb) && !widowed;
|
||||
if f.settle_late(pb, end, overflow) {
|
||||
let overflow = fit.l1 == f.l0 && f.fresh(pb) && !widowed && !kept_over;
|
||||
if f.settle_late(pb, fit.l1, overflow) {
|
||||
continue;
|
||||
}
|
||||
if fit.l1 == f.l0 {
|
||||
@@ -1156,7 +1193,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
|
||||
let mut items = Vec::new();
|
||||
push_para(&mut items, (StoryRef::Body, &[block as u32]), &pl, (0, l1), (x, y), width, edges);
|
||||
let at = ObjFrame {
|
||||
page: Some(PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror }),
|
||||
page: Some(PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror }),
|
||||
col: (x, width),
|
||||
para_y: y,
|
||||
table_chr: None,
|
||||
@@ -1226,6 +1263,24 @@ fn space_after_kept(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::Resolv
|
||||
after
|
||||
}
|
||||
|
||||
/// The room the space after body paragraph `block` adds between it and the paragraph after it,
|
||||
/// beyond that paragraph's own space before (which [`next_first_line`] counts): the merged gap
|
||||
/// (the larger of the two, ISO/IEC 29500-1 §17.3.1.9), or both when they are summed. Nothing when
|
||||
/// contextual spacing or automatic spacing between list items drops it.
|
||||
fn gap_after(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::ResolvedPara, listed: bool) -> f32 {
|
||||
let after = space_after_kept(ctx, block, rp, listed);
|
||||
if after <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let Some(Block::Para(next)) = ctx.doc.body.get(block + 1).map(|b| &**b) else { return after };
|
||||
let nrp = ctx.doc.styles.resolve_para(&next.props);
|
||||
// The next paragraph's contextual spacing, and automatic spacing between two list items,
|
||||
// drop its own space before.
|
||||
let dropped = (nrp.style == rp.style && nrp.contextual_spacing) || (listed && nrp.before_auto && ctx.has_label(next));
|
||||
let before = if dropped { 0.0 } else { nrp.space_before.max(0.0) };
|
||||
if ctx.doc.settings.sum_paragraph_spacing { after } else { (after - before).max(0.0) }
|
||||
}
|
||||
|
||||
/// The room the paragraphs after `block` need on the page for keep with next: enough of the
|
||||
/// next one to start there — its first line, two of its lines with widow/orphan control (it
|
||||
/// doesn't leave a single line at the bottom of a page; it moves over whole instead), all three
|
||||
@@ -1271,16 +1326,21 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
// Its border room, unless it joins the paragraph before (or after) in one box.
|
||||
let own = Edges::own(&pl, 0, pl.lines.len());
|
||||
let top = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block), None) { 0.0 } else { own.top };
|
||||
// Contextual spacing and automatic spacing between list items drop this paragraph's space before (#9208).
|
||||
let prev_para = ctx.doc.body.get(block).and_then(|b| match &**b {
|
||||
Block::Para(prev) => Some(prev),
|
||||
_ => None,
|
||||
});
|
||||
let dropped_before = prev_para.is_some_and(|prev| {
|
||||
let prp = ctx.doc.styles.resolve_para(&prev.props);
|
||||
(pl.rp.style == prp.style && pl.rp.contextual_spacing) || (pl.rp.before_auto && ctx.has_label(prev) && ctx.has_label(p))
|
||||
});
|
||||
let space_before = if dropped_before { 0.0 } else { pl.rp.space_before };
|
||||
// The paragraph closing the section, when the next section starts a new page, keeps
|
||||
// with nothing on this page (Word ignores its Keep with next).
|
||||
if pl.rp.keep_next && depth < 8 && !(new_page && p.section.is_some()) {
|
||||
let bottom = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block + 2), None) { 0.0 } else { own.bottom };
|
||||
pl.rp.space_before
|
||||
+ top
|
||||
+ pl.height
|
||||
+ bottom
|
||||
+ pl.rp.space_after
|
||||
+ next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
|
||||
space_before + top + pl.height + bottom + pl.rp.space_after + next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
|
||||
} else {
|
||||
// The room this one needs to start on the page with the kept paragraph before
|
||||
// it (#966).
|
||||
@@ -1288,7 +1348,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
(Some(first), Some(last)) => last.top + last.height - first.top,
|
||||
_ => 0.0,
|
||||
};
|
||||
pl.rp.space_before
|
||||
space_before
|
||||
+ top
|
||||
+ if pl.rp.keep_lines {
|
||||
pl.height
|
||||
@@ -1314,6 +1374,38 @@ mod tests {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_geom::Rect;
|
||||
|
||||
#[test]
|
||||
fn kept_paragraphs_reserve_no_room_for_suppressed_spacing() {
|
||||
crate::test_fonts();
|
||||
let room = |doc: &Document| {
|
||||
let mut reserved = None;
|
||||
crate::pass::with_flow_page(doc, |ctx, pb| {
|
||||
reserved = Some(next_first_line(ctx, 0, pb.col_w(), 0, false, &mut ctx.counters.clone()));
|
||||
});
|
||||
reserved.expect("the flow page was measured")
|
||||
};
|
||||
for automatic_list in [false, true] {
|
||||
let mut base = Document::from_text("Kept paragraph\nFollowing paragraph");
|
||||
if automatic_list {
|
||||
let num = Arc::make_mut(&mut base.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
for block in 0..2 {
|
||||
base.para_mut(StoryRef::Body, &Path::top(block)).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 0 });
|
||||
}
|
||||
}
|
||||
let q = base.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
q.props.space_before = Some(0.0);
|
||||
let mut spaced = base.clone();
|
||||
let q = spaced.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
q.props.space_before = Some(48.0);
|
||||
if automatic_list {
|
||||
q.props.space_before_auto = Some(true);
|
||||
} else {
|
||||
q.props.contextual_spacing = Some(true);
|
||||
}
|
||||
assert_eq!(room(&spaced), room(&base), "suppressed spacing takes no room (list: {automatic_list})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
|
||||
crate::test_fonts();
|
||||
@@ -1332,7 +1424,7 @@ mod tests {
|
||||
pb.cap_columns();
|
||||
// A preceding floating object leaves a narrow strip of the first column, but does
|
||||
// not occupy the second column. The same kept paragraph fits there in one line.
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, crate::floats::AreaKind::Object));
|
||||
place_para_in_flow(ctx, pb, p, 0, top);
|
||||
|
||||
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
|
||||
|
||||
@@ -189,6 +189,34 @@ pub(crate) fn placed_cost_by(it: &Placed, limit: usize, cost: impl Fn(&Placed) -
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a header laid out with the rendered body area grows past `body_top` and retrying
|
||||
/// with the declared margins (`margin_area: None`) produces a shorter layout. Both
|
||||
/// [`header_table_areas`] and [`headers_footers`] use this so body table avoidance matches the
|
||||
/// header actually drawn.
|
||||
fn lay_header_box<T>(
|
||||
ctx: &mut Ctx,
|
||||
frame: PageFrame<'_>,
|
||||
header_y: f32,
|
||||
body_top: f32,
|
||||
measured: bool,
|
||||
mut lay: impl FnMut(&mut Ctx, PageFrame<'_>) -> (f32, T),
|
||||
) -> T {
|
||||
// List counters and equation numbers before the header, so a second layout counts from the
|
||||
// same place and only the layout kept advances them.
|
||||
let before = (ctx.counters.clone(), ctx.eq_count);
|
||||
let (laid_h, laid) = lay(ctx, frame);
|
||||
if measured && header_y + laid_h > body_top + 0.01 {
|
||||
let rendered = (std::mem::replace(&mut ctx.counters, before.0), ctx.eq_count);
|
||||
ctx.eq_count = before.1;
|
||||
let (measured_h, measured) = lay(ctx, PageFrame { margin_area: None, ..frame });
|
||||
if measured_h < laid_h - 0.01 {
|
||||
return measured;
|
||||
}
|
||||
(ctx.counters, ctx.eq_count) = rendered;
|
||||
}
|
||||
laid
|
||||
}
|
||||
|
||||
/// Header tables can displace a non-overlapping body table. Page-positioned drawings keep
|
||||
/// their own wrapping rules, so only table areas are retained from the header layout.
|
||||
pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
@@ -207,9 +235,10 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
return Vec::new();
|
||||
}
|
||||
let set = hf.heads.set(page.section);
|
||||
let even_page = !(sect.title_page && first) && ctx.doc.settings.even_odd_headers && page.number.is_multiple_of(2);
|
||||
let id = if sect.title_page && first {
|
||||
set.first
|
||||
} else if ctx.doc.settings.even_odd_headers && page.number.is_multiple_of(2) {
|
||||
} else if even_page {
|
||||
set.even.or(set.default)
|
||||
} else {
|
||||
set.default
|
||||
@@ -217,8 +246,11 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
let Some(id) = id else { return Vec::new() };
|
||||
let Some(part) = ctx.doc.parts.get(&id) else { return Vec::new() };
|
||||
let blocks = part.blocks.clone();
|
||||
// As in `headers_footers`: an even-page header with its own part was never measured for the body top.
|
||||
let header_measured = !even_page || set.even.is_none();
|
||||
let x = sect.margin_left + sect.gutter;
|
||||
let frame = PageFrame { sect, margin_top: Some(page.body.y), origin: (x, sect.header), number: page.number, mirror: ctx.mirror };
|
||||
let frame =
|
||||
PageFrame { sect, margin_area: Some((page.body.y, page.body.bottom())), origin: (x, sect.header), number: page.number, mirror: ctx.mirror };
|
||||
let base = hf.defining_width(false, page.section, Some(id));
|
||||
let counters = std::mem::take(&mut ctx.counters);
|
||||
let boxes = std::mem::take(&mut ctx.boxes);
|
||||
@@ -228,8 +260,11 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
let track = std::mem::replace(&mut ctx.track_totals, false);
|
||||
ctx.fields.page_format = sect.page_num_format;
|
||||
ctx.fields.page = page.number;
|
||||
let mut areas = again(ctx, 0, |ctx| {
|
||||
with_pct_base(ctx, base, |ctx| layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame)))).table_areas
|
||||
let mut areas = lay_header_box(ctx, frame, sect.header, page.body.y, header_measured, |ctx, frame| {
|
||||
let res = again(ctx, 0, |ctx| {
|
||||
with_pct_base(ctx, base, |ctx| layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame))))
|
||||
});
|
||||
(res.height, res.table_areas)
|
||||
});
|
||||
ctx.counters = counters;
|
||||
ctx.boxes = boxes;
|
||||
@@ -471,11 +506,29 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
|
||||
&& let Some(part) = ctx.doc.parts.get(&id)
|
||||
{
|
||||
let blocks = part.blocks.clone();
|
||||
let frame = PageFrame { sect, margin_top: Some(page.body.y), origin: (x, sect.header), number: page.number, mirror: ctx.mirror };
|
||||
let frame = PageFrame {
|
||||
sect,
|
||||
margin_area: Some((page.body.y, page.body.bottom())),
|
||||
origin: (x, sect.header),
|
||||
number: page.number,
|
||||
mirror: ctx.mirror,
|
||||
};
|
||||
let base = hf.defining_width(false, page.section, hid);
|
||||
let (mut items, behind, front) = with_pin(ctx, id, sect, page.number, frame.margin_top, |ctx| {
|
||||
with_pct_base(ctx, base, |c| layout_box(c, BoxInput::other(StoryRef::Part(id), &blocks, w, 0, Some(frame))).items)
|
||||
let lay_header = |ctx: &mut Ctx, frame: PageFrame| {
|
||||
with_pin(ctx, id, sect, page.number, frame.margin_area, |ctx| {
|
||||
with_pct_base(ctx, base, |c| layout_box(c, BoxInput::other(StoryRef::Part(id), &blocks, w, 0, Some(frame))))
|
||||
})
|
||||
};
|
||||
// The body top was measured with the declared margins (`body_top_for`), only for the
|
||||
// default and first-page headers of non-turned sections (`section_tops`). Even-page
|
||||
// headers and fixed-margin sections were never measured for `page.body.y`, so skip
|
||||
// the retry (#9226).
|
||||
let header_measured = !sect.text_direction.is_turned() && (page.hf_slot != HfSlot::Even || hf.heads.set(page.section).even.is_none());
|
||||
let (laid, behind, front) = lay_header_box(ctx, frame, sect.header, page.body.y, header_measured, |ctx, frame| {
|
||||
let res = lay_header(ctx, frame);
|
||||
(res.0.height, res)
|
||||
});
|
||||
let mut items = laid.items;
|
||||
for it in &mut items {
|
||||
it.translate(x, sect.header);
|
||||
}
|
||||
@@ -491,8 +544,8 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
|
||||
let (h, ..) = with_pin(ctx, id, sect, page.number, None, |ctx| {
|
||||
with_pct_base(ctx, base, |c| layout_box(c, BoxInput::other(StoryRef::Part(id), &blocks, w, 0, None)).height)
|
||||
});
|
||||
let frame = PageFrame { sect, margin_top: None, origin: (x, sect.page_h - sect.footer - h), number: page.number, mirror: ctx.mirror };
|
||||
let (mut items, behind, front) = with_pin(ctx, id, sect, page.number, frame.margin_top, |ctx| {
|
||||
let frame = PageFrame { sect, margin_area: None, origin: (x, sect.page_h - sect.footer - h), number: page.number, mirror: ctx.mirror };
|
||||
let (mut items, behind, front) = with_pin(ctx, id, sect, page.number, frame.margin_area, |ctx| {
|
||||
with_pct_base(ctx, base, |c| layout_box(c, BoxInput::other(StoryRef::Part(id), &blocks, w, 0, Some(frame))).items)
|
||||
});
|
||||
for it in &mut items {
|
||||
|
||||
@@ -141,7 +141,8 @@ fn all_objects(page: &Page, index: usize) -> impl Iterator<Item = ObjectHit> + '
|
||||
}
|
||||
|
||||
fn objects_in(items: &[Placed], index: usize) -> impl Iterator<Item = ObjectHit> + '_ {
|
||||
items.iter().rev().filter_map(move |it| match it {
|
||||
// Count each item inspected, including pages a lookup searches without finding its object.
|
||||
items.iter().rev().inspect(|_| wordcraft_doc::work::steps(1)).filter_map(move |it| match it {
|
||||
Placed::Object { rect, spin, story, path, off, text_box, wrap, origin, .. } => Some(ObjectHit {
|
||||
page: index,
|
||||
rect: *rect,
|
||||
@@ -786,6 +787,63 @@ impl DocLayout {
|
||||
None
|
||||
}
|
||||
|
||||
/// The text direction of the lines holding `pos`; `None` for upright (horizontal) text.
|
||||
pub fn turn_at(&self, pos: &Pos, page_hint: usize) -> Option<TextDirection> {
|
||||
self.pieces(pos.story, &pos.path, page_hint).into_iter().find_map(|(_, it)| match it {
|
||||
Placed::Lines { para, l0, l1, turn, .. } if turn.is_turned() && (*l0..*l1).contains(¶.line_of(pos.off)) => Some(*turn),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// In turned text, the position on the next (`next`) or previous line in reading order, at
|
||||
/// `goal` along the line (its own frame; `None` keeps the caret's). Returns it with that
|
||||
/// along-line coordinate. Only lines of the same flow count (the paragraphs of one story
|
||||
/// level or of one table cell, not another cell's). In the body the step crosses page
|
||||
/// boundaries, so `None` only at the first/last line of the flow; in any other story (laid
|
||||
/// out again on every page) it stops at the first/last line on the page.
|
||||
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
// Only the body flows from page to page: a header, a footer or a text box in one is laid
|
||||
// out again on every page, so the adjacent page holds the caret's own lines again.
|
||||
let crosses_pages = pos.story == StoryRef::Body;
|
||||
let page_lines = |page_idx: usize| -> Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> {
|
||||
let Some(page) = self.pages.get(page_idx) else { return Vec::new() };
|
||||
items_of(page, pos.story)
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { story, path, para, l0, l1, turn, .. }
|
||||
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
|
||||
{
|
||||
Some((path, para, *l0, *l1))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
|
||||
.collect()
|
||||
};
|
||||
let c = self.caret_on(pos, page_hint)?;
|
||||
let lines = page_lines(c.page);
|
||||
let here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
|
||||
let adjacent;
|
||||
let (path, para, li) = if next {
|
||||
if let Some(t) = lines.get(here + 1) {
|
||||
t
|
||||
} else {
|
||||
adjacent = if crosses_pages { page_lines(c.page + 1) } else { Vec::new() };
|
||||
adjacent.first()?
|
||||
}
|
||||
} else if let Some(prev) = here.checked_sub(1).and_then(|i| lines.get(i)) {
|
||||
prev
|
||||
} else {
|
||||
adjacent = if crosses_pages { page_lines(c.page.checked_sub(1)?) } else { Vec::new() };
|
||||
adjacent.last()?
|
||||
};
|
||||
let gx = match goal {
|
||||
Some(g) => g,
|
||||
None => lines[here].1.x_of(lines[here].2, pos.off)?,
|
||||
};
|
||||
let off = para.off_at_x(*li, gx);
|
||||
Some((Pos { story: pos.story, path: (*path).clone(), off }, gx))
|
||||
}
|
||||
|
||||
/// The position one line up (`dir < 0`) or down from `pos`, keeping `goal_x` (page x).
|
||||
pub fn vertical(&self, pos: &Pos, goal_x: Option<f32>, dir: i32, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
let c = self.caret_on(pos, page_hint)?;
|
||||
|
||||
@@ -386,7 +386,7 @@ impl PageBuilder<'_> {
|
||||
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
|
||||
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
|
||||
let bottom = self.body_bottom(body_top);
|
||||
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
|
||||
self.leading_floor = (s.page_h - s.margin_bottom.abs()).min(self.foot_top);
|
||||
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
|
||||
let mut decor = Vec::new();
|
||||
if !self.web {
|
||||
@@ -473,8 +473,12 @@ impl PageBuilder<'_> {
|
||||
self.bottom >= self.leading_floor - 0.01
|
||||
}
|
||||
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
|
||||
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
|
||||
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room. A
|
||||
/// negative bottom margin is exact: the body ends at its size and the footer overlaps it.
|
||||
fn body_bottom(&self, body_top: f32) -> f32 {
|
||||
if self.sect.margin_bottom < 0.0 {
|
||||
return self.sect.page_h + self.sect.margin_bottom;
|
||||
}
|
||||
// ODF keeps the footer's spacing above a footer too tall for the bottom margin.
|
||||
let gap = if self.sect.footer_gap.is_finite() { self.sect.footer_gap.clamp(0.0, 1584.0) } else { 0.0 };
|
||||
(self.sect.page_h - self.sect.margin_bottom).min((self.foot_top - gap).max(body_top + 36.0))
|
||||
@@ -569,13 +573,17 @@ pub(crate) fn item_bottom(y: f32, para: &ParaLayout, l0: usize, l1: usize) -> Op
|
||||
Some(y + l.top + l.height - f.top)
|
||||
}
|
||||
|
||||
/// Where body text starts: the top margin, or below the header if it's taller.
|
||||
/// Where body text starts: the top margin, or below the header if it's taller. A negative top
|
||||
/// margin is exact (ECMA-376 §17.6.11): the text starts at its size and the header overlaps it.
|
||||
pub(crate) fn body_top_for(ctx: &mut Ctx, sect: &SectionProps, header: Option<u32>) -> f32 {
|
||||
if sect.margin_top < 0.0 {
|
||||
return -sect.margin_top;
|
||||
}
|
||||
let Some(id) = header else { return sect.margin_top };
|
||||
let Some(part) = ctx.doc.parts.get(&id) else { return sect.margin_top };
|
||||
let blocks = part.blocks.clone();
|
||||
// Placed as `headers_footers` draws it, so page-relative floats wrap the same way.
|
||||
let frame = PageFrame { sect, margin_top: None, origin: (sect.margin_left + sect.gutter, sect.header), number: 1, mirror: ctx.mirror };
|
||||
let frame = PageFrame { sect, margin_area: None, origin: (sect.margin_left + sect.gutter, sect.header), number: 1, mirror: ctx.mirror };
|
||||
let track = std::mem::replace(&mut ctx.track_totals, false);
|
||||
let (h, ..) = with_pin(ctx, id, sect, 1, None, |ctx| {
|
||||
layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame))).height
|
||||
@@ -637,8 +645,10 @@ pub(crate) fn foot_top_for(ctx: &mut Ctx, sect: &SectionProps, footer: Option<u3
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct PageFrame<'a> {
|
||||
pub(crate) sect: &'a SectionProps,
|
||||
/// Override the Margin anchor area without changing the declared margin bands.
|
||||
pub(crate) margin_top: Option<f32>,
|
||||
/// Override the Margin anchor area (its top and bottom) with the rendered body's, without
|
||||
/// changing the declared margin bands: a header or footer that reaches past its margin moves
|
||||
/// the area Word measures from (#2485).
|
||||
pub(crate) margin_area: Option<(f32, f32)>,
|
||||
/// Page position of the box's (0, 0); (0, 0) for body text.
|
||||
pub(crate) origin: (f32, f32),
|
||||
/// The page's number: inside and outside are left and right on odd pages, the other way
|
||||
@@ -671,7 +681,19 @@ impl PageFrame<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Margin anchor area down the page, start and extent: the rendered body when `f` has one
|
||||
/// (both edges: Word centres a header picture between the body's top and the footer's top, not
|
||||
/// down to the declared bottom margin), else the declared margins; at least 18 pt, as
|
||||
/// [`SectionProps::text_height`].
|
||||
pub(crate) fn margin_y(f: &PageFrame) -> (f32, f32) {
|
||||
let s = f.sect;
|
||||
match f.margin_area {
|
||||
Some((top, bottom)) => (top, (bottom - top).max(18.0)),
|
||||
None => (s.margin_top.abs(), s.text_height()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The page `pb` is filling, for placing floating objects on it (`mirror`: [`Ctx::mirror`]).
|
||||
pub(crate) fn page_frame<'a>(pb: &PageBuilder<'a>, mirror: bool) -> PageFrame<'a> {
|
||||
PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror }
|
||||
PageFrame { sect: pb.sect, margin_area: None, origin: (0.0, 0.0), number: pb.number, mirror }
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ pub use bidi::{bidi_levels, visual_order};
|
||||
pub(crate) use builder::left_out;
|
||||
#[cfg(test)]
|
||||
use chars::{MISSING_ROMAN_FONT, lookup_family};
|
||||
#[cfg(test)]
|
||||
use chars::{MISSING_SANS_FONT, lookup_script_family};
|
||||
pub(crate) use chars::{caps_char, push_caps};
|
||||
pub use chars::{draws_something, east_asian_substitute_face, reported_font_name, substitute_face};
|
||||
#[cfg(test)]
|
||||
@@ -498,6 +500,77 @@ mod tests {
|
||||
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_font_not_classed_roman_is_looked_up_as_calibri() {
|
||||
// Measured in Word for Windows 16.0.20625: a run font that isn't installed and has no
|
||||
// alternate it can draw is drawn in Calibri whether the font table classes it as swiss,
|
||||
// modern, auto, decorative or script. The generic sans substitutes don't start with
|
||||
// Calibri (Carlito first, then Arial), so on Windows such a run came out in Arial.
|
||||
crate::test_fonts();
|
||||
let mut d = Document::new();
|
||||
assert_eq!(lookup_family(&d, "No Such Swiss Font"), MISSING_SANS_FONT);
|
||||
d.settings.modern_fonts = vec!["No Such Modern Font".into()];
|
||||
assert_eq!(lookup_family(&d, "No Such Modern Font"), MISSING_SANS_FONT);
|
||||
// An alternate that can't be drawn leaves a font that isn't roman in Calibri too.
|
||||
d.settings.font_alt_names = vec![("No Such Brand Font".into(), "No Such Alternate".into())];
|
||||
assert_eq!(lookup_family(&d, "No Such Brand Font"), MISSING_SANS_FONT);
|
||||
// The other rules still come first, and these fonts keep their name.
|
||||
d.settings.font_alt_names.push(("No Such Mono Brand".into(), "Courier New".into()));
|
||||
assert_eq!(lookup_family(&d, "No Such Mono Brand"), "Courier New");
|
||||
d.settings.roman_fonts = vec!["No Such Roman Font".into()];
|
||||
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
|
||||
let installed = wordcraft_fonts::FALLBACK_FAMILY;
|
||||
assert_eq!(lookup_family(&d, installed), installed);
|
||||
for kept in ["Wingdings", "Angsana New", "Times New Roman", "Liberation Sans;Arial"] {
|
||||
assert_eq!(lookup_family(&d, kept), kept, "{kept}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_font_named_after_a_core_font_is_drawn_in_that_font() {
|
||||
// Measured in Word for Windows 16.0.20625: a missing font whose name starts with Arial or
|
||||
// Helv is drawn in Arial, with Times in Times New Roman, with Courier in Courier New, with
|
||||
// Segoe UI in Segoe UI, whatever its family class; its font table alternate still comes
|
||||
// first. Other names (Verdana MT, Georgia Foo, Foo Arial) are drawn in Calibri.
|
||||
crate::test_fonts();
|
||||
let mut d = Document::new();
|
||||
d.settings.roman_fonts = vec!["Arial Foo".into(), "Times MT Missing".into()];
|
||||
d.settings.modern_fonts = vec!["Helvetica Foo".into()];
|
||||
for (font, drawn) in [
|
||||
("Arial MT", "Arial"),
|
||||
("ArialFoo", "Arial"),
|
||||
("Arial Foo", "Arial"),
|
||||
("Helvetica Foo", "Arial"),
|
||||
("Helv Foo", "Arial"),
|
||||
("Times MT Missing", "Times New Roman"),
|
||||
("Times New Roman Foo", "Times New Roman"),
|
||||
("Courier Foo", "Courier New"),
|
||||
("Segoe UI Foo", "Segoe UI"),
|
||||
("Verdana MT", MISSING_SANS_FONT),
|
||||
("Georgia Foo", MISSING_SANS_FONT),
|
||||
("Foo Arial", MISSING_SANS_FONT),
|
||||
] {
|
||||
assert_eq!(lookup_family(&d, font), drawn, "{font}");
|
||||
}
|
||||
d.settings.font_alt_names = vec![("Arial Foo".into(), "Courier New".into())];
|
||||
assert_eq!(lookup_family(&d, "Arial Foo"), "Courier New");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_east_asian_or_complex_script_font_keeps_its_name() {
|
||||
// Calibri has no CJK, Arabic or Hebrew: a missing East Asian or complex-script font with no
|
||||
// alternate keeps its name, so the script's own fallback draws it (Word: MS Mincho for
|
||||
// Chinese text in a missing `w:eastAsia` font).
|
||||
crate::test_fonts();
|
||||
let mut d = Document::new();
|
||||
assert_eq!(lookup_script_family(&d, "No Such East Asian Font"), "No Such East Asian Font");
|
||||
// Its alternate and the roman rule still apply.
|
||||
d.settings.font_alt_names = vec![("No Such East Asian Font".into(), "Courier New".into())];
|
||||
assert_eq!(lookup_script_family(&d, "No Such East Asian Font"), "Courier New");
|
||||
d.settings.roman_fonts = vec!["No Such Arabic Font".into()];
|
||||
assert_eq!(lookup_script_family(&d, "No Such Arabic 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]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::bidi::{Dir, bidi_levels, strong_rtl, visual_order};
|
||||
use super::chars::{
|
||||
SegKey, caps_expands, context_digit_dirs, draws_something, is_khmer, is_mark, is_numeral_digit, ligature_features, lookup_family, remap_range,
|
||||
reported_font_name, thai_run_face, upper_char,
|
||||
SegKey, caps_expands, context_digit_dirs, draws_something, is_khmer, is_mark, is_numeral_digit, ligature_features, lookup_family,
|
||||
lookup_script_family, remap_range, reported_font_name, thai_run_face, upper_char,
|
||||
};
|
||||
use super::grid::east_asian;
|
||||
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
|
||||
@@ -348,7 +348,7 @@ impl<'a> Builder<'a> {
|
||||
// A font isn't installed when it was substituted, or looked up as a missing roman font or
|
||||
// its font table alternate (#2702).
|
||||
let resolved_cs = rc_cs.as_ref().map(|r| {
|
||||
let family = lookup_family(self.env.doc, &r.font);
|
||||
let family = lookup_script_family(self.env.doc, &r.font);
|
||||
let resolved = wordcraft_fonts::word::resolve(family, r.bold, r.italic);
|
||||
(resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font))
|
||||
});
|
||||
@@ -358,7 +358,7 @@ impl<'a> Builder<'a> {
|
||||
// installed and has them.
|
||||
let wanted_ea =
|
||||
super::chars::east_asian_font(self.env.doc, rc).filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
|
||||
let family = lookup_family(self.env.doc, f);
|
||||
let family = lookup_script_family(self.env.doc, f);
|
||||
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
|
||||
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
|
||||
});
|
||||
@@ -425,7 +425,11 @@ impl<'a> Builder<'a> {
|
||||
};
|
||||
let rc = &rc;
|
||||
let small = key.small;
|
||||
let si = self.style(rc, key.face, small);
|
||||
// A complex-script segment the run's complex-script face covers is drawn in that face,
|
||||
// looked up as a script font ([`lookup_script_family`]): `style` would look its font
|
||||
// up as a run font, in Calibri or a core font, which have no Arabic or Hebrew.
|
||||
let face = key.face.or(primary_cs.filter(|_| key.complex));
|
||||
let si = self.style(rc, face, small);
|
||||
let Some(st) = self.styles.get(si as usize).cloned() else { continue };
|
||||
let upper = rc.caps || small;
|
||||
// All Caps and Small Caps draw a letter's full capital, which can be several
|
||||
|
||||
@@ -122,22 +122,44 @@ pub(crate) fn remap_range(map_starts: &[usize], orig_of: &[usize], orig_len: usi
|
||||
}
|
||||
|
||||
/// Word draws a font that isn't installed in Cambria when the document's font table classes it
|
||||
/// as roman (measured in Word; Calibri otherwise, which our own substitutes already match).
|
||||
/// as roman (measured in Word).
|
||||
pub(super) const MISSING_ROMAN_FONT: &str = "Cambria";
|
||||
|
||||
/// The family to look `font` up as. A font that isn't installed is drawn, as Word draws it
|
||||
/// (measured in Word 2024, #2702):
|
||||
/// Word draws a run font that isn't installed in Calibri when the font table doesn't class it as
|
||||
/// roman and it has no alternate that can be drawn: measured in Word for Windows 16.0.20625 for a
|
||||
/// font classed swiss, modern, auto, decorative or script. The generic sans substitutes start
|
||||
/// with Carlito, Calibri's metric twin, then Arial, so without this rule Windows drew Arial.
|
||||
pub(super) const MISSING_SANS_FONT: &str = "Calibri";
|
||||
|
||||
/// The family to look a run's font `font` up as. A font that isn't installed is drawn, as Word
|
||||
/// draws it (measured in Word 2024, #2702):
|
||||
/// 1. in the alternate the font table names for it (`w:altName`), when that one can be drawn:
|
||||
/// installed, or a font one of whose own substitutes is installed. That comes before the
|
||||
/// family class: a roman font with an installed alternate is drawn in the alternate;
|
||||
/// 2. in [`MISSING_ROMAN_FONT`] when the font table classes it as roman, or as modern with an
|
||||
/// alternate that can't be drawn either (a modern font with no alternate, and a swiss one with
|
||||
/// or without, take the generic substitutes, as Calibri does in Word). Not for a Thai font
|
||||
/// (drawn in a Thai face, #1549), a symbol font, or a font with substitutes of its own (Times
|
||||
/// New Roman is roman in every font table, and where it isn't installed Liberation Serif has
|
||||
/// its metrics; Word never meets it missing);
|
||||
/// 3. else as `font`, which [`wordcraft_fonts::word::resolve`] substitutes.
|
||||
/// 2. in the core font its name starts with ([`core_font_named_by`]: `Arial MT` in Arial), whatever
|
||||
/// its family class;
|
||||
/// 3. in [`MISSING_ROMAN_FONT`] when the font table classes it as roman, or as modern with an
|
||||
/// alternate that can't be drawn either;
|
||||
/// 4. in [`MISSING_SANS_FONT`] otherwise: a swiss font with or without an alternate, and a modern
|
||||
/// one with none.
|
||||
///
|
||||
/// Rules 2 to 4 skip a Thai font (drawn in a Thai face, #1549), a symbol font, and a font with
|
||||
/// substitutes of its own (Times New Roman is roman in every font table, and where it isn't
|
||||
/// installed Liberation Serif has its metrics; Word never meets it missing): those keep `font`,
|
||||
/// which [`wordcraft_fonts::word::resolve`] substitutes. Rules 2 and 4 also skip a fallback list
|
||||
/// (`Liberation Sans;Arial`, #5843), which its own candidates draw.
|
||||
pub(super) fn lookup_family<'f>(doc: &'f Document, font: &'f str) -> &'f str {
|
||||
lookup(doc, font, true)
|
||||
}
|
||||
|
||||
/// The family to look a run's East Asian (`w:eastAsia`) or complex-script (`w:cs`) font up as:
|
||||
/// rules 1 and 3 of [`lookup_family`], not the core fonts of rule 2 nor the Calibri of rule 4,
|
||||
/// which have no CJK; a missing one keeps its name, and the script's own fallback draws it.
|
||||
pub(super) fn lookup_script_family<'f>(doc: &'f Document, font: &'f str) -> &'f str {
|
||||
lookup(doc, font, false)
|
||||
}
|
||||
|
||||
fn lookup<'f>(doc: &'f Document, font: &'f str, run_font: bool) -> &'f str {
|
||||
let settings = &doc.settings;
|
||||
// A fallback list (`Liberation Serif;Times New Roman`) is in a class when one of its
|
||||
// candidates is.
|
||||
@@ -146,7 +168,7 @@ pub(super) fn lookup_family<'f>(doc: &'f Document, font: &'f str) -> &'f str {
|
||||
};
|
||||
let alternate = settings.font_alt_names.iter().find(|(f, _)| f.eq_ignore_ascii_case(font)).map(|(_, alt)| alt.as_str());
|
||||
let roman = listed(&settings.roman_fonts);
|
||||
if alternate.is_none() && !roman {
|
||||
if alternate.is_none() && !roman && (!run_font || font.trim().is_empty()) {
|
||||
return font;
|
||||
}
|
||||
let db = wordcraft_fonts::FontDb::global();
|
||||
@@ -166,18 +188,40 @@ pub(super) fn lookup_family<'f>(doc: &'f Document, font: &'f str) -> &'f str {
|
||||
}
|
||||
let modern_alternate_missing = alternate.is_some() && listed(&settings.modern_fonts);
|
||||
// Thai, symbol and fonts with substitutes of their own keep their name: those substitutes
|
||||
// draw them, Cambria wouldn't.
|
||||
if (roman || modern_alternate_missing)
|
||||
&& !wordcraft_fonts::word::is_thai_family(font)
|
||||
&& !wordcraft_doc::symbol_fonts::is_symbol_font(font)
|
||||
&& !wordcraft_fonts::word::has_named_substitutes(font)
|
||||
{
|
||||
// draw them, Cambria and Calibri wouldn't.
|
||||
let keeps_name = wordcraft_fonts::word::is_thai_family(font)
|
||||
|| wordcraft_doc::symbol_fonts::is_symbol_font(font)
|
||||
|| wordcraft_fonts::word::has_named_substitutes(font);
|
||||
if keeps_name {
|
||||
font
|
||||
} else if let Some(core) = run_font.then(|| core_font_named_by(font)).flatten() {
|
||||
core
|
||||
} else if roman || modern_alternate_missing {
|
||||
MISSING_ROMAN_FONT
|
||||
} else if run_font && !font.contains(';') {
|
||||
MISSING_SANS_FONT
|
||||
} else {
|
||||
font
|
||||
}
|
||||
}
|
||||
|
||||
/// The font Word draws a missing font in when its name starts with a core font's (measured in
|
||||
/// Word for Windows 16.0.20625, whatever the family class): Arial for `Arial MT`, `ArialFoo`,
|
||||
/// `Arial Narrow Foo` and the Helvetica names (`Helv…`), Times New Roman for `Times…`, Courier New
|
||||
/// for `Courier…`, Segoe UI for `Segoe UI…`. Only the start counts (`Foo Arial` is drawn in
|
||||
/// Calibri), and no other installed font is matched this way (`Verdana MT`, `Tahoma Foo` and
|
||||
/// `Georgia Foo` are drawn in Calibri). A fallback list (`;`) is left to its candidates.
|
||||
fn core_font_named_by(font: &str) -> Option<&'static str> {
|
||||
if font.contains(';') {
|
||||
return None;
|
||||
}
|
||||
let f = font.trim().to_ascii_lowercase();
|
||||
[("arial", "Arial"), ("helv", "Arial"), ("times", "Times New Roman"), ("courier", "Courier New"), ("segoe ui", "Segoe UI")]
|
||||
.into_iter()
|
||||
.find(|(prefix, _)| f.starts_with(prefix))
|
||||
.map(|(_, core)| core)
|
||||
}
|
||||
|
||||
/// One face for a run in a Thai font that isn't installed (#1549): Word substitutes one font
|
||||
/// (Cordia New) for the whole run, so the Latin letters, digits and ฿ keep the Thai letters' face
|
||||
/// and size. `None` unless `font` is a Thai family, it was substituted (or drawn in its font
|
||||
|
||||
@@ -173,6 +173,12 @@ pub struct Exclusion {
|
||||
pub side: WrapText,
|
||||
/// A floating table counts a line touching its top as overlapping; shapes do not (#3977).
|
||||
pub table: bool,
|
||||
/// Tight and Through wrapping: before Word 2013 layout text goes in a narrower gap beside
|
||||
/// it (#6316).
|
||||
pub tight: bool,
|
||||
/// A paragraph continuing after a hidden paragraph mark (`Joint::fit`): keeps the 20pt minimum
|
||||
/// span rather than the 18pt floating-object minimum (#9160).
|
||||
pub joint: bool,
|
||||
}
|
||||
|
||||
impl Exclusion {
|
||||
|
||||
+133
-19
@@ -30,6 +30,9 @@ struct Breaker<'e> {
|
||||
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
|
||||
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
|
||||
shrink_spaces: bool,
|
||||
/// Word 2013+ layout (compatibility mode 15): the narrowest span beside a Tight or Through
|
||||
/// object is the same as beside any other ([`min_span`]).
|
||||
layout_2013: 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.
|
||||
tight_indent: bool,
|
||||
@@ -208,6 +211,7 @@ impl<'e> Breaker<'e> {
|
||||
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
|
||||
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
|
||||
shrink_spaces: rp.align == Align::Justify && settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT,
|
||||
layout_2013: settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT,
|
||||
tight_indent: settings.do_not_suppress_indentation
|
||||
&& settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
|
||||
&& level.is_none()
|
||||
@@ -295,7 +299,9 @@ impl<'e> Breaker<'e> {
|
||||
}
|
||||
}
|
||||
let row = (self.top, self.est_h, self.table_h);
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent, self.layout_2013)
|
||||
.map(|mut spans| (spans.pop_front(), spans))
|
||||
{
|
||||
Ok((Some((a, b)), rest)) => {
|
||||
// Under Word 2003's indent rules a row can start left of the indent too.
|
||||
let moved = if self.tight_indent { (a - lo).abs() > 0.01 } else { a > lo };
|
||||
@@ -594,6 +600,7 @@ impl<'e> Breaker<'e> {
|
||||
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
|
||||
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
|
||||
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
|
||||
let picture_leading = if pictures_alone { font_natural } else { run_leading };
|
||||
// Keep the picture floor independent of list-label metrics.
|
||||
let natural = asc + desc;
|
||||
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
|
||||
@@ -603,7 +610,7 @@ impl<'e> Breaker<'e> {
|
||||
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
|
||||
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
|
||||
(LineSpacing::Multiple(m), None) => {
|
||||
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
|
||||
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * picture_leading), false)
|
||||
}
|
||||
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
|
||||
(LineSpacing::Exactly(v), _) => (v, false),
|
||||
@@ -1190,10 +1197,28 @@ fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
|
||||
/// Narrowest span text flows into beside a floating table, points. Word puts an empty
|
||||
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
|
||||
const MIN_SPAN: f32 = 20.0;
|
||||
|
||||
/// Narrowest span text flows into beside a floating picture or shape, points: Word puts a line
|
||||
/// in an 18pt gap to its wrap area but not in a 17.95pt one, for square, tight and through
|
||||
/// wrapping alike, whatever the text (#6316).
|
||||
const MIN_SPAN_OBJECT: f32 = 18.0;
|
||||
|
||||
/// Tight and Through wrapping before Word 2013 layout (compatibility mode 14 and below) need
|
||||
/// only half that: 9pt fits, 8.95pt doesn't.
|
||||
const MIN_SPAN_CONTOUR_OLD: f32 = 9.0;
|
||||
|
||||
/// The narrowest span text goes into beside `e`, with Word 2013 layout or later (`current`).
|
||||
fn min_span(e: &Exclusion, current: bool) -> f32 {
|
||||
match (e.table || e.joint, e.tight) {
|
||||
(true, _) => MIN_SPAN,
|
||||
(false, true) if !current => MIN_SPAN_CONTOUR_OLD,
|
||||
_ => MIN_SPAN_OBJECT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a row starts under Word 2003's indent rules: right after the floating objects that end
|
||||
/// at or before the indent `lo` on this row and let text past their right side (their outline's
|
||||
/// right edge for Tight and Through wrapping), never left of the paragraph's own left edge (0) or
|
||||
@@ -1224,16 +1249,18 @@ fn baseline_offset(spacing: LineSpacing, asc: f32, height: f32, desc: f32) -> f3
|
||||
}
|
||||
|
||||
/// The spans of a row at `top` (about `h` tall) between `lo` and `hi` that text can use around
|
||||
/// the exclusions, left to right (Square wrapping uses both sides of an object). `Err(y)`: none
|
||||
/// here, try again at `y` (below what's in the way). With `tight_indent` (Word 2003's indent
|
||||
/// rules, `w:doNotSuppressIndentation`) a row starts right after a floating object that ends
|
||||
/// before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented 1" tightly
|
||||
/// wraps an object at 0.25").
|
||||
/// the exclusions, left to right (Square wrapping uses both sides of an object); a span must be
|
||||
/// as wide as the minimum of each object it borders (`current`: Word 2013 layout or later).
|
||||
/// `Err(y)`: none here, try again at `y` (below what's in the way). With `tight_indent` (Word
|
||||
/// 2003's indent rules, `w:doNotSuppressIndentation`) a row starts right after a floating object
|
||||
/// that ends before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented
|
||||
/// 1" tightly wraps an object at 0.25").
|
||||
fn row_spans(
|
||||
exclusions: &[Exclusion],
|
||||
(top, h, table_h): (f32, f32, f32),
|
||||
(lo, hi): (f32, f32),
|
||||
tight_indent: bool,
|
||||
current: bool,
|
||||
) -> Result<VecDeque<(f32, f32)>, f32> {
|
||||
let lo = if tight_indent { tight_row_start(exclusions, (top, h, table_h), lo) } else { lo };
|
||||
let here: Vec<&Exclusion> = exclusions.iter().filter(|e| e.intersects_row(top, h, table_h, lo, hi)).collect();
|
||||
@@ -1241,13 +1268,14 @@ fn row_spans(
|
||||
return Err(below);
|
||||
}
|
||||
// What each object takes of the row: its whole area, or (Tight, Through) the stretches its
|
||||
// outline takes, as (left, right, bottom of the object's area).
|
||||
let mut taken: Vec<(f32, f32, f32)> = Vec::new();
|
||||
// outline takes, as (left, right, bottom of the object's area, the narrowest span beside it).
|
||||
let mut taken: Vec<(f32, f32, f32, f32)> = Vec::new();
|
||||
for e in &here {
|
||||
let first = taken.len();
|
||||
let min = min_span(e, current);
|
||||
match &e.contour {
|
||||
None => taken.push((e.left, e.right, e.bottom)),
|
||||
Some(c) => taken.extend(c.occupied(top - e.top, top + h - e.top).into_iter().map(|(a, b)| (a + e.left, b + e.left, e.bottom))),
|
||||
None => taken.push((e.left, e.right, e.bottom, min)),
|
||||
Some(c) => taken.extend(c.occupied(top - e.top, top + h - e.top).into_iter().map(|(a, b)| (a + e.left, b + e.left, e.bottom, min))),
|
||||
}
|
||||
// Text on one side only: the object's other side of the row is taken too.
|
||||
let Some(mine) = taken.get(first..).filter(|t| !t.is_empty() && !e.side.is_both()) else { continue };
|
||||
@@ -1260,23 +1288,109 @@ fn row_spans(
|
||||
_ => left - lo >= hi - right,
|
||||
};
|
||||
taken.truncate(first);
|
||||
taken.push(if text_left { (left, hi.max(right), e.bottom) } else { (lo.min(left), right, e.bottom) });
|
||||
taken.push(if text_left { (left, hi.max(right), e.bottom, min) } else { (lo.min(left), right, e.bottom, min) });
|
||||
}
|
||||
taken.retain(|(l, r, _)| *r > lo && *l < hi);
|
||||
taken.retain(|(l, r, _, _)| *r > lo && *l < hi);
|
||||
if taken.is_empty() {
|
||||
return Ok(VecDeque::from([(lo, hi)]));
|
||||
}
|
||||
let mut spans = vec![(lo, hi)];
|
||||
for &(left, right, _) in &taken {
|
||||
// Each span with the minimum of what borders it on the left and on the right (nothing at the
|
||||
// row's ends): an object cutting a span becomes the new edge of both pieces, and an object
|
||||
// ending right at a span's edge borders it too, the larger minimum winning (a picture and a
|
||||
// table both ending at 70: the span after them needs the table's).
|
||||
let mut spans = vec![(lo, hi, 0.0_f32, 0.0_f32)];
|
||||
for &(left, right, _, min) in &taken {
|
||||
spans = spans
|
||||
.into_iter()
|
||||
.flat_map(|(a, b)| if right <= a || left >= b { vec![(a, b)] } else { vec![(a, left.min(b)), (right.max(a), b)] })
|
||||
.flat_map(|(a, b, ml, mr)| {
|
||||
if right <= a || left >= b {
|
||||
let ml = if (right - a).abs() < 0.01 { ml.max(min) } else { ml };
|
||||
let mr = if (left - b).abs() < 0.01 { mr.max(min) } else { mr };
|
||||
vec![(a, b, ml, mr)]
|
||||
} else {
|
||||
vec![(a, left.min(b), ml, min), (right.max(a), b, min, mr)]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
spans.retain(|(a, b)| b - a >= MIN_SPAN);
|
||||
let spans: VecDeque<(f32, f32)> = spans.into_iter().filter(|(a, b, ml, mr)| b - a >= ml.max(*mr)).map(|(a, b, ..)| (a, b)).collect();
|
||||
if spans.is_empty() {
|
||||
// Nothing wide enough: the line goes below the first object that ends.
|
||||
return Err(taken.iter().map(|t| t.2).reduce(f32::min).unwrap_or(top));
|
||||
}
|
||||
Ok(spans.into())
|
||||
Ok(spans)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An exclusion from the row's left edge to `right`, 100pt tall.
|
||||
fn area(right: f32, table: bool, tight: bool) -> Exclusion {
|
||||
Exclusion {
|
||||
top: 0.0,
|
||||
bottom: 100.0,
|
||||
left: 0.0,
|
||||
right,
|
||||
top_bottom: false,
|
||||
contour: None,
|
||||
side: WrapText::BothSides,
|
||||
table,
|
||||
tight,
|
||||
joint: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a line at the top of a 100pt row finds a span `gap` points wide beside `e`.
|
||||
fn fits(e: Exclusion, gap: f32, current: bool) -> bool {
|
||||
let hi = e.right + gap;
|
||||
row_spans(&[e], (0.0, 12.0, 12.0), (0.0, hi), false, current).is_ok()
|
||||
}
|
||||
|
||||
/// #6316: 18pt beside pictures and shapes; Tight and Through 9pt before Word 2013 layout;
|
||||
/// floating tables keep 20.
|
||||
#[test]
|
||||
fn the_narrowest_span_depends_on_the_object() {
|
||||
for current in [true, false] {
|
||||
assert!(fits(area(50.0, false, false), 18.0, current) && !fits(area(50.0, false, false), 17.9, current));
|
||||
assert!(fits(area(50.0, true, false), 20.0, current) && !fits(area(50.0, true, false), 19.9, current));
|
||||
}
|
||||
assert!(fits(area(50.0, false, true), 18.0, true) && !fits(area(50.0, false, true), 17.9, true));
|
||||
assert!(fits(Exclusion { joint: true, ..area(50.0, false, false) }, 20.0, true));
|
||||
assert!(!fits(Exclusion { joint: true, ..area(50.0, false, false) }, 19.9, true));
|
||||
assert!(fits(area(50.0, false, true), 9.0, false) && !fits(area(50.0, false, true), 8.9, false));
|
||||
// A span between a picture and a table needs the table's 20.
|
||||
let both = |gap: f32| {
|
||||
let table = Exclusion { left: 50.0 + gap, right: 300.0, ..area(0.0, true, false) };
|
||||
row_spans(&[area(50.0, false, false), table], (0.0, 12.0, 12.0), (0.0, 300.0), false, true).is_ok()
|
||||
};
|
||||
assert!(both(20.0) && !both(19.9));
|
||||
// A span bordered only by a picture needs 18, whichever order the objects come in, also
|
||||
// when a table cut the span first (a table at 0..70, a picture at 80..100, a 19pt span
|
||||
// right of the picture).
|
||||
let table = area(70.0, true, false);
|
||||
let picture = Exclusion { left: 80.0, right: 100.0, ..area(0.0, false, false) };
|
||||
for order in [[table.clone(), picture.clone()], [picture.clone(), table.clone()]] {
|
||||
let spans = row_spans(&order, (0.0, 12.0, 12.0), (0.0, 119.0), false, true);
|
||||
assert_eq!(spans, Ok(VecDeque::from([(100.0, 119.0)])), "{order:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture and a table ending at the same edge: the span after them needs the table's 20,
|
||||
/// whichever comes first, and on the other side too.
|
||||
#[test]
|
||||
fn objects_sharing_an_edge_need_the_larger_minimum() {
|
||||
let row = (0.0, 12.0, 12.0);
|
||||
let (picture, table) = (area(70.0, false, false), area(70.0, true, false));
|
||||
for order in [[picture.clone(), table.clone()], [table.clone(), picture.clone()]] {
|
||||
assert!(row_spans(&order, row, (0.0, 89.0), false, true).is_err(), "19pt: {order:?}");
|
||||
assert_eq!(row_spans(&order, row, (0.0, 90.0), false, true), Ok(VecDeque::from([(70.0, 90.0)])), "20pt: {order:?}");
|
||||
}
|
||||
let picture = Exclusion { left: 30.0, right: 100.0, ..picture };
|
||||
let table = Exclusion { left: 30.0, right: 100.0, ..table };
|
||||
for order in [[picture.clone(), table.clone()], [table.clone(), picture.clone()]] {
|
||||
assert!(row_spans(&order, row, (11.0, 100.0), false, true).is_err(), "19pt: {order:?}");
|
||||
assert_eq!(row_spans(&order, row, (10.0, 100.0), false, true), Ok(VecDeque::from([(10.0, 30.0)])), "20pt: {order:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +291,7 @@ fn section_tops(ctx: &mut Ctx, hf: &HfLinks, (si, sect): (usize, &SectionProps),
|
||||
let (heads, feet) = (hf.heads.set(si), hf.feet.set(si));
|
||||
let hb = |i: Option<u32>| hf.defining_width(false, si, i);
|
||||
let fb = |i: Option<u32>| hf.defining_width(true, si, i);
|
||||
let body = if fixed { sect.margin_top } else { with_pct_base(ctx, hb(heads.default), |c| body_top_for(c, sect, heads.default)) };
|
||||
let body = if fixed { sect.margin_top.abs() } else { with_pct_base(ctx, hb(heads.default), |c| body_top_for(c, sect, heads.default)) };
|
||||
let first = if fixed || !sect.title_page { body } else { with_pct_base(ctx, hb(heads.first), |c| body_top_for(c, sect, heads.first)) };
|
||||
let foot = if fixed { f32::MAX } else { with_pct_base(ctx, fb(feet.default), |c| foot_top_for(c, sect, feet.default)) };
|
||||
let first_foot = if fixed || !sect.title_page { foot } else { with_pct_base(ctx, fb(feet.first), |c| foot_top_for(c, sect, feet.first)) };
|
||||
@@ -625,7 +625,7 @@ pub(crate) fn layout_pass(
|
||||
section_endnotes(&mut ctx, &mut pb, &mut endnotes, (sect, si, block));
|
||||
}
|
||||
if pb.pages.is_empty() {
|
||||
pb.new_page(0, sect_ref.margin_top);
|
||||
pb.new_page(0, sect_ref.margin_top.abs());
|
||||
}
|
||||
// The rest of the endnotes after the last paragraph.
|
||||
let rest: Vec<u32> = endnotes.into_iter().map(|(id, _)| id).collect();
|
||||
|
||||
@@ -188,13 +188,13 @@ impl StyleIndex {
|
||||
&& let Some((l, def)) = counters.next_label_indexed(&numbering, n.num, n.level)
|
||||
&& def.format != NumFormat::Bullet
|
||||
{
|
||||
let vals = counters.values_indexed(&numbering, n.num).unwrap_or_default();
|
||||
let vals = counters.counted_values_indexed(&numbering, n.num);
|
||||
for (k, v) in vals.iter().enumerate().take(usize::from(n.level.min(8)) + 1) {
|
||||
let Some(lv) = numbering.level(n.num, k as u8) else { continue };
|
||||
if matches!(lv.format, NumFormat::None | NumFormat::Bullet) {
|
||||
continue;
|
||||
}
|
||||
let v = if *v == 0 { lv.start } else { *v };
|
||||
let v = v.unwrap_or(lv.start);
|
||||
let fmt = if def.legal && lv.format != NumFormat::DecimalZero { NumFormat::Decimal } else { lv.format };
|
||||
levels.push((k as u8, fmt.format(v), def.text.contains(&format!("%{}", k + 1))));
|
||||
}
|
||||
|
||||
+249
-22
@@ -28,6 +28,23 @@ pub struct RowLayout {
|
||||
pub edge: f32,
|
||||
/// The row's cells: the items each one owns and where its content ends.
|
||||
pub cells: Vec<CellPart>,
|
||||
/// What a vertical merge running over a page break adds to this row.
|
||||
pub merge: MergeEdges,
|
||||
}
|
||||
|
||||
/// Items of a row for vertical merges crossing a page break (#8872). Rows are laid out before
|
||||
/// they meet a page, so these are placed only when the row starts or ends one.
|
||||
#[derive(Default)]
|
||||
pub struct MergeEdges {
|
||||
/// When the row is the first on a page: the continuing merge's fill and top border.
|
||||
pub top: Vec<Placed>,
|
||||
/// When the row is the last on a page: the closing bottom border of a merge running on.
|
||||
pub end: Vec<Placed>,
|
||||
/// `(x, w)` of each vertical merge in this row that continues onto the following row.
|
||||
pub spans: Vec<(f32, f32)>,
|
||||
/// `(x, w)` of each vertical merge that ends in this row: it too continues past the first part
|
||||
/// of the row when the row is split.
|
||||
pub ends: Vec<(f32, f32)>,
|
||||
}
|
||||
|
||||
/// A cell of a [`RowLayout`].
|
||||
@@ -336,8 +353,12 @@ pub fn autofit_widths(cols: &[(f32, f32)], avail: f32) -> Vec<f32> {
|
||||
/// How far left of its offset (`w:tblpX`) a floating table placed by one has its edge. Before
|
||||
/// Word 2013 layout the first cell's text is at the offset, moved by the table's indent; from it
|
||||
/// the edge is, moved in by half its left border, the indent ignored (measured in Word for
|
||||
/// Windows). A right-to-left table (`w:bidiVisual`) has its left edge at the offset in every
|
||||
/// mode: Word moves it by neither a cell margin nor the indent nor a border (#8517).
|
||||
/// Windows). A right-to-left table (`w:bidiVisual`) is put with its left edge at the offset in
|
||||
/// every mode, because Word moves it by neither a cell margin nor the indent nor a border (#8517).
|
||||
/// That matches Word before Word 2013 layout. From it Word still puts the table slightly off the
|
||||
/// offset: 0.72 pt to the right with no `w:left` border at its start, and 0.36 pt to the left
|
||||
/// with a 2 pt `w:left` border on its second cell. No rule for this was found, so it isn't
|
||||
/// modelled (#8949).
|
||||
pub(crate) fn float_offset_shift(ctx: &Ctx, t: &Table) -> f32 {
|
||||
if t.props.bidi_visual {
|
||||
return 0.0;
|
||||
@@ -899,6 +920,36 @@ fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember the fill and background picture (or none) each restart cell gives its merge's continuation.
|
||||
fn note_restarts<'a>(
|
||||
merge_fill: &mut std::collections::HashMap<usize, Rgb>,
|
||||
merge_picture: &mut std::collections::HashMap<usize, &'a wordcraft_doc::props::CellPicture>,
|
||||
table: &'a Table,
|
||||
ri: usize,
|
||||
cells: &[CellBox],
|
||||
) {
|
||||
for (ci, c) in cells.iter().enumerate().filter(|(_, c)| c.vmerge == VMerge::Restart) {
|
||||
match c.fill {
|
||||
Some(f) => merge_fill.insert(c.g, f),
|
||||
None => merge_fill.remove(&c.g),
|
||||
};
|
||||
match table.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()) {
|
||||
Some(pic) => merge_picture.insert(c.g, pic),
|
||||
None => merge_picture.remove(&c.g),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a cell's clipped background picture to `items` if it produces any placed images.
|
||||
fn push_cell_picture(items: &mut Vec<Placed>, pic: Option<&wordcraft_doc::props::CellPicture>, rect: Rect, story: StoryRef, path: &[u32]) {
|
||||
if let Some(pic) = pic {
|
||||
let images = cell_picture(pic, rect, story, path);
|
||||
if !images.is_empty() {
|
||||
items.push(Placed::Clip { rect, spin: wordcraft_geom::Spin::default(), items: images });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TableRows<'a> {
|
||||
story: StoryRef,
|
||||
table: &'a Table,
|
||||
@@ -915,6 +966,17 @@ struct TableRows<'a> {
|
||||
only: Option<(usize, f32)>,
|
||||
}
|
||||
|
||||
/// Total height of a vertical merge from row `ri` (starting at `rh`) through its continuing rows.
|
||||
fn cont_height(cont: &[Vec<usize>], heights: &[f32], ri: usize, g: usize, rh: f32) -> f32 {
|
||||
let mut total = rh;
|
||||
let mut k = ri + 1;
|
||||
while cont.get(k).is_some_and(|v| v.contains(&g)) {
|
||||
total += heights.get(k).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
|
||||
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
|
||||
/// the cell's text.
|
||||
@@ -938,25 +1000,23 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
.collect();
|
||||
// Second pass: place cells with their row height, fills and borders.
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
let mut merge_fill: std::collections::HashMap<usize, Rgb> = std::collections::HashMap::new();
|
||||
let mut merge_picture: std::collections::HashMap<usize, &wordcraft_doc::props::CellPicture> = std::collections::HashMap::new();
|
||||
for (ri, cells) in rows.into_iter().enumerate() {
|
||||
if only.is_some_and(|(row, _)| row != ri) {
|
||||
// The restart fills and background pictures of earlier rows still apply to the continuation of a merge.
|
||||
note_restarts(&mut merge_fill, &mut merge_picture, t, ri, &cells);
|
||||
continue;
|
||||
}
|
||||
let rh = heights.get(ri).copied().unwrap_or(0.0);
|
||||
let exact = t.rows.get(ri).is_some_and(|r| r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0));
|
||||
let mut items = Vec::new();
|
||||
let mut merge = MergeEdges::default();
|
||||
let mut parts = Vec::with_capacity(cells.len());
|
||||
for (ci, c) in cells.into_iter().enumerate() {
|
||||
let first = items.len();
|
||||
// A restart cell spans several rows: its height is their sum.
|
||||
let mut span_h = rh;
|
||||
if c.vmerge == VMerge::Restart {
|
||||
let mut k = ri + 1;
|
||||
while cont.get(k).is_some_and(|v| v.contains(&c.g)) {
|
||||
span_h += heights.get(k).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
let span_h = if c.vmerge == VMerge::Restart { cont_height(&cont, &heights, ri, c.g, rh) } else { rh };
|
||||
let rect = Rect::new(c.x, 0.0, c.w, span_h);
|
||||
if c.vmerge != VMerge::Continue
|
||||
&& let Some(f) = c.fill
|
||||
@@ -964,13 +1024,14 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
items.push(Placed::Fill { rect, color: f });
|
||||
}
|
||||
// Its background picture, over the shading and under the text, cut off at its edges.
|
||||
if c.vmerge != VMerge::Continue
|
||||
&& let Some(pic) = t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref())
|
||||
{
|
||||
let images = cell_picture(pic, rect, story, path);
|
||||
if !images.is_empty() {
|
||||
items.push(Placed::Clip { rect, spin: wordcraft_geom::Spin::default(), items: images });
|
||||
}
|
||||
if c.vmerge != VMerge::Continue {
|
||||
push_cell_picture(
|
||||
&mut items,
|
||||
t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()),
|
||||
rect,
|
||||
story,
|
||||
path,
|
||||
);
|
||||
}
|
||||
// Behind-text frames count towards vertical alignment even without inline content.
|
||||
// They do not increase the row's flow height.
|
||||
@@ -1046,8 +1107,39 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
items.push(Placed::Rule { x0: hx0, y0, x1: hx1, y1: y0, border: e });
|
||||
}
|
||||
let last_of_merge = c.vmerge == VMerge::None || !cont.get(ri + 1).is_some_and(|v| v.contains(&c.g));
|
||||
if last_of_merge && let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
items.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
if c.vmerge == VMerge::Restart {
|
||||
match c.fill {
|
||||
Some(f) => merge_fill.insert(c.g, f),
|
||||
None => merge_fill.remove(&c.g),
|
||||
};
|
||||
match t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()) {
|
||||
Some(pic) => merge_picture.insert(c.g, pic),
|
||||
None => merge_picture.remove(&c.g),
|
||||
};
|
||||
}
|
||||
if !last_of_merge {
|
||||
merge.spans.push((c.x, c.w));
|
||||
if let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
merge.end.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
}
|
||||
} else {
|
||||
if c.vmerge == VMerge::Continue {
|
||||
merge.ends.push((c.x, c.w));
|
||||
}
|
||||
if let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
items.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
}
|
||||
}
|
||||
if c.vmerge == VMerge::Continue {
|
||||
let left = cont_height(&cont, &heights, ri, c.g, rh);
|
||||
let cont_rect = Rect::new(c.x, 0.0, c.w, left);
|
||||
if let Some(color) = merge_fill.get(&c.g) {
|
||||
merge.top.push(Placed::Fill { rect: cont_rect, color: *color });
|
||||
}
|
||||
push_cell_picture(&mut merge.top, merge_picture.get(&c.g).copied(), cont_rect, story, path);
|
||||
if let Some(e) = b.top.filter(Border::is_visible) {
|
||||
merge.top.push(Placed::Rule { x0: hx0, y0, x1: hx1, y1: y0, border: e });
|
||||
}
|
||||
}
|
||||
if let Some(e) = b.left.filter(Border::is_visible) {
|
||||
items.push(Placed::Rule { x0, y0, x1: x0, y1, border: e });
|
||||
@@ -1075,6 +1167,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
bottom: bottoms.get(ri).copied().unwrap_or(0.0),
|
||||
edge: edges.get(ri).copied().unwrap_or(0.0),
|
||||
cells: parts,
|
||||
merge,
|
||||
});
|
||||
}
|
||||
TableLayout { x, width: total, rows: out }
|
||||
@@ -1374,11 +1467,70 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
}
|
||||
// The part left on the page is placed and never split again.
|
||||
Some((
|
||||
RowLayout { height: cut, items: a, bottom: row.bottom, edge: 0.0, cells: Vec::new() },
|
||||
RowLayout { height, items: b, bottom: row.bottom, edge: row.edge, cells: parts },
|
||||
RowLayout {
|
||||
height: cut,
|
||||
items: a,
|
||||
bottom: row.bottom,
|
||||
edge: 0.0,
|
||||
cells: Vec::new(),
|
||||
// Every merge in the row runs on from this part, those ending in the row too.
|
||||
merge: MergeEdges {
|
||||
top: row.merge.top.clone(),
|
||||
end: at_y(&row.merge.end, cut),
|
||||
spans: [row.merge.spans.as_slice(), &row.merge.ends].concat(),
|
||||
ends: Vec::new(),
|
||||
},
|
||||
},
|
||||
RowLayout {
|
||||
height,
|
||||
items: b,
|
||||
bottom: row.bottom,
|
||||
edge: row.edge,
|
||||
cells: parts,
|
||||
merge: MergeEdges {
|
||||
top: shorter(&row.merge.top, row.height - height),
|
||||
end: at_y(&row.merge.end, height),
|
||||
spans: row.merge.spans.clone(),
|
||||
ends: row.merge.ends.clone(),
|
||||
},
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Horizontal rules of a merge's edge moved to `y`.
|
||||
fn at_y(items: &[Placed], y: f32) -> Vec<Placed> {
|
||||
items
|
||||
.iter()
|
||||
.map(
|
||||
|it| {
|
||||
if let Placed::Rule { x0, x1, border, .. } = it {
|
||||
Placed::Rule { x0: *x0, y0: y, x1: *x1, y1: y, border: *border }
|
||||
} else {
|
||||
it.clone()
|
||||
}
|
||||
},
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Shorten a merge's continuation backgrounds by the height removed from its first row.
|
||||
fn shorter(items: &[Placed], by: f32) -> Vec<Placed> {
|
||||
let shorten = |rect: &Rect| Rect::new(rect.x, rect.y, rect.w, rect.h - by);
|
||||
items
|
||||
.iter()
|
||||
.map(|it| match it {
|
||||
Placed::Fill { rect, color } => Placed::Fill { rect: shorten(rect), color: *color },
|
||||
Placed::Clip { rect, spin, items } => {
|
||||
let rect = shorten(rect);
|
||||
// Keep the original picture geometry, including any tile that crosses the new bottom.
|
||||
let items = items.iter().filter(|it| !matches!(it, Placed::Image { rect: image, .. } if !rect.intersects(image))).cloned().collect();
|
||||
Placed::Clip { rect, spin: *spin, items }
|
||||
}
|
||||
other => other.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
type CellItems<'a> = Vec<std::borrow::Cow<'a, [Placed]>>;
|
||||
|
||||
/// The items of each cell of a row being split, with each cell's content end, and the cells
|
||||
@@ -1973,6 +2125,60 @@ fn autofit(grid: &mut [f32], content: &[(f32, f32)], t: &Table, avail: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod merged_min_height_tests {
|
||||
use super::*;
|
||||
|
||||
// The vertical merge used by turned-text layout in #6529, with three rows
|
||||
// in the right-hand column and a fourth row outside the merge.
|
||||
fn three_row_merge() -> Table {
|
||||
let mut table = Table::new(4, 2, 100.0);
|
||||
for (row, (merge, height)) in
|
||||
table.rows.iter_mut().zip([(VMerge::Restart, 24.0), (VMerge::Continue, 32.0), (VMerge::Continue, 40.0), (VMerge::None, 64.0)])
|
||||
{
|
||||
row.cells[1].props.vmerge = merge;
|
||||
row.props.height_rule = HeightRule::AtLeast;
|
||||
row.props.height = Some(height);
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_min_height_sums_all_three_rows() {
|
||||
assert_eq!(merged_min_height(&three_row_merge(), 0, 1), Some(96.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_min_height_requires_a_restart_followed_by_a_continuation() {
|
||||
let mut table = three_row_merge();
|
||||
assert_eq!(merged_min_height(&table, 1, 1), None, "a continuation is not a restart");
|
||||
table.rows[1].cells[1].props.vmerge = VMerge::None;
|
||||
assert_eq!(merged_min_height(&table, 0, 1), None, "a continuation below a gap does not count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_min_height_requires_valid_at_least_heights_throughout() {
|
||||
let mut table = three_row_merge();
|
||||
for i in 0..3 {
|
||||
let original = table.rows[i].props.clone();
|
||||
for (rule, height) in [
|
||||
(HeightRule::Auto, Some(32.0)),
|
||||
(HeightRule::Exact, Some(32.0)),
|
||||
(HeightRule::AtLeast, None),
|
||||
(HeightRule::AtLeast, Some(0.0)),
|
||||
(HeightRule::AtLeast, Some(-1.0)),
|
||||
(HeightRule::AtLeast, Some(f32::INFINITY)),
|
||||
(HeightRule::AtLeast, Some(f32::NAN)),
|
||||
] {
|
||||
table.rows[i].props.height_rule = rule;
|
||||
table.rows[i].props.height = height;
|
||||
assert_eq!(merged_min_height(&table, 0, 1), None, "row {i}: {rule:?}, {height:?}");
|
||||
}
|
||||
table.rows[i].props = original;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod width_tests {
|
||||
use super::*;
|
||||
@@ -2040,13 +2246,34 @@ mod width_tests {
|
||||
|
||||
#[test]
|
||||
fn grid_before_row_keeps_grid() {
|
||||
let mut table = Table::new(2, 3, 300.0);
|
||||
let cell_widths = [80.0, 100.0, 120.0];
|
||||
for row in &mut table.rows {
|
||||
for (cell, width) in row.cells.iter_mut().zip(cell_widths) {
|
||||
cell.props.width = Some(width);
|
||||
}
|
||||
}
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
assert_eq!(stale_grid_widths(&table, &table.grid).as_deref(), Some(cell_widths.as_slice()));
|
||||
|
||||
// Omit the first grid column. The cells still end at the same two edges as row one.
|
||||
let row = &mut table.rows[1];
|
||||
row.cells.remove(0);
|
||||
row.props.grid_before = 1;
|
||||
row.props.w_before = Some(cell_widths[0]);
|
||||
assert_eq!(stale_grid_widths(&table, &table.grid), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_after_row_keeps_grid() {
|
||||
let mut table = Table::new(2, 3, 300.0);
|
||||
for row in &mut table.rows {
|
||||
for cell in &mut row.cells {
|
||||
cell.props.width = Some(100.0);
|
||||
}
|
||||
}
|
||||
table.rows[1].props.grid_before = 1;
|
||||
table.rows[1].props.grid_after = 1;
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
let mut grid = table.grid.clone();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
|
||||
use super::ctx::{Ctx, with_pct_base};
|
||||
use super::floats::{WrapArea, align_in, body_wraps};
|
||||
use super::floats::{AreaKind, WrapArea, align_in, body_wraps};
|
||||
use super::flow::again;
|
||||
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
|
||||
use super::notes::table_notes;
|
||||
@@ -51,7 +51,7 @@ pub(crate) fn footer_table_wraps(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<WrapAre
|
||||
let story = StoryRef::Part(id);
|
||||
let h = layout_box(ctx, BoxInput::other(story, &blocks, sect.text_width(), 0, None)).height;
|
||||
let y = sect.page_h - sect.footer - h;
|
||||
let frame = PageFrame { sect, margin_top: None, origin: (x, y), number: page.number, mirror: ctx.mirror };
|
||||
let frame = PageFrame { sect, margin_area: None, origin: (x, y), number: page.number, mirror: ctx.mirror };
|
||||
let mut areas = layout_box(ctx, BoxInput::other(story, &blocks, sect.text_width(), 0, Some(frame))).page_table_wraps;
|
||||
for (rect, ..) in &mut areas {
|
||||
rect.x += x;
|
||||
@@ -247,18 +247,83 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
}
|
||||
}
|
||||
let repeated_height: f32 = header_rows.iter().filter_map(|i| tl.rows.get(*i)).map(|r| r.height).sum();
|
||||
let place = |pb: &mut PageBuilder, row: &table::RowLayout| {
|
||||
// The page of the last body row placed, and the closing borders of its merges that run on
|
||||
// (drawn if the next row starts a new page).
|
||||
let last_page = std::cell::Cell::new((0u32, usize::MAX));
|
||||
// Where the items of this table's rows on the page and column start; none before a row is placed.
|
||||
let page_from = std::cell::Cell::new(None::<usize>);
|
||||
let pending_end: std::cell::RefCell<Vec<Placed>> = std::cell::RefCell::new(Vec::new());
|
||||
let pending_spans: std::cell::RefCell<Vec<(f32, f32)>> = std::cell::RefCell::new(Vec::new());
|
||||
let in_spans = |spans: &[(f32, f32)], rect: &Rect| spans.iter().any(|&(sx, sw)| (rect.x - sx).abs() < 0.01 && (rect.w - sw).abs() < 0.01);
|
||||
let place = |pb: &mut PageBuilder, row: &table::RowLayout, body: bool| {
|
||||
let (x, y) = (pb.col_x() + tl.x, pb.y);
|
||||
let limit = pb.bottom.max(y + row.height);
|
||||
// A merged cell runs over the pages of its rows: on each its area is the rows there.
|
||||
let starts_page = body && last_page.get() != (pb.number, pb.col);
|
||||
if body {
|
||||
last_page.set((pb.number, pb.col));
|
||||
*pending_end.borrow_mut() = row
|
||||
.merge
|
||||
.end
|
||||
.iter()
|
||||
.map(|it| {
|
||||
let mut it = it.clone();
|
||||
it.translate(x, y);
|
||||
it
|
||||
})
|
||||
.collect();
|
||||
*pending_spans.borrow_mut() = row.merge.spans.iter().map(|&(mx, mw)| (x + mx, mw)).collect();
|
||||
}
|
||||
if let Some(pg) = pb.page() {
|
||||
for it in &row.items {
|
||||
if starts_page {
|
||||
page_from.set(Some(pg.items.len()));
|
||||
}
|
||||
// Continuing shading and pictures go under the row's content and borders.
|
||||
// The merge's opening border still goes above the row.
|
||||
let top = if starts_page { row.merge.top.as_slice() } else { &[] };
|
||||
let is_background = |it: &&Placed| matches!(it, Placed::Fill { .. } | Placed::Clip { .. });
|
||||
let backgrounds = top.iter().filter(is_background);
|
||||
let rules = top.iter().filter(|it| !is_background(it));
|
||||
for it in backgrounds.chain(&row.items).chain(rules) {
|
||||
let mut it = it.clone();
|
||||
let is_merge = match &it {
|
||||
Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } => in_spans(&row.merge.spans, rect),
|
||||
_ => false,
|
||||
};
|
||||
it.translate(x, y);
|
||||
// The merged cell's area ends at this page's bottom, #8872 / #9191.
|
||||
if is_merge
|
||||
&& let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = &mut it
|
||||
&& rect.bottom() > limit
|
||||
{
|
||||
rect.h = (limit - rect.y).max(0.0);
|
||||
}
|
||||
pg.items.push(it);
|
||||
}
|
||||
}
|
||||
pb.y += row.height;
|
||||
pb.content_bottom = pb.content_bottom.max(pb.y);
|
||||
};
|
||||
// The page ends here: close the merges running on to the next one.
|
||||
let close_merges = |pb: &mut PageBuilder| {
|
||||
let end = std::mem::take(&mut *pending_end.borrow_mut());
|
||||
let spans = std::mem::take(&mut *pending_spans.borrow_mut());
|
||||
let bottom = pb.y;
|
||||
if let Some(pg) = pb.page() {
|
||||
// Only the merged cells' areas end with the last row on the page (#9191).
|
||||
for it in pg.items.iter_mut().skip(page_from.get().unwrap_or(usize::MAX)) {
|
||||
if let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = it
|
||||
&& in_spans(&spans, rect)
|
||||
&& rect.y < bottom
|
||||
&& rect.bottom() > bottom
|
||||
{
|
||||
rect.h = bottom - rect.y;
|
||||
}
|
||||
}
|
||||
pg.items.extend(end);
|
||||
}
|
||||
page_from.set(None);
|
||||
};
|
||||
// Measured in Word: an at-least row's minimum height is reserved, not split. Where less room
|
||||
// than that is left on a page that already holds something, the row starts the next page
|
||||
// whole; a row taller than a page then splits from the top of that page.
|
||||
@@ -350,7 +415,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
};
|
||||
match split {
|
||||
Some((a, b)) => {
|
||||
place(pb, &a);
|
||||
place(pb, &a, true);
|
||||
table_notes(ctx, pb, &a.items);
|
||||
rest = Some(b);
|
||||
}
|
||||
@@ -359,18 +424,19 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
None if pb.at_top() || fresh => break,
|
||||
None => {}
|
||||
}
|
||||
close_merges(pb);
|
||||
pb.advance(block, body_top);
|
||||
// Repeat header rows, up to the layout's cap.
|
||||
if ri >= header_rows.len() && ctx.header_repeats.saturating_add(header_cost) <= header_cap {
|
||||
ctx.header_repeats = ctx.header_repeats.saturating_add(header_cost);
|
||||
for h in header_rows.iter().filter_map(|hr| tl.rows.get(*hr)) {
|
||||
place(pb, h);
|
||||
place(pb, h, false);
|
||||
}
|
||||
}
|
||||
fresh = true;
|
||||
}
|
||||
let last = rest.as_ref().or(aligned.as_ref()).unwrap_or(row);
|
||||
place(pb, last);
|
||||
place(pb, last, true);
|
||||
table_notes(ctx, pb, &last.items);
|
||||
}
|
||||
// Its own space below (ODT).
|
||||
@@ -395,7 +461,7 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
|
||||
// The text a table anchored to it stands in: where the next paragraph starts.
|
||||
let v_area = match f.v_rel {
|
||||
Anchor::Page => (0.0, s.page_h),
|
||||
Anchor::Margin => (s.margin_top, s.text_height()),
|
||||
Anchor::Margin => (s.margin_top.abs(), s.text_height()),
|
||||
_ => (pb.y, 0.0),
|
||||
};
|
||||
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
|
||||
@@ -435,7 +501,7 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
|
||||
pg.float_tables.push(Path::top(block));
|
||||
}
|
||||
let area = r.inset(-dl, -dt, -dr, -db);
|
||||
pb.excl.push((area, false, None, WrapText::BothSides, true));
|
||||
pb.excl.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
pb.float_tables.push(area);
|
||||
return;
|
||||
}
|
||||
|
||||
+851
-13
@@ -1505,7 +1505,7 @@ fn a_missing_font_is_drawn_in_its_font_table_alternate() {
|
||||
// Measured in Word 2024 and Word for Windows 16.0.20527 (#2702): a font that isn't installed is
|
||||
// drawn in the alternate its font table names (`w:altName`), before the roman rule; an
|
||||
// alternate that can't be drawn either leaves the family class in charge: Cambria for a roman
|
||||
// or modern font, the generic substitutes (Calibri in Word) for a swiss one.
|
||||
// or modern font, Calibri for a swiss one.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Family {
|
||||
Swiss,
|
||||
@@ -1532,7 +1532,10 @@ fn a_missing_font_is_drawn_in_its_font_table_alternate() {
|
||||
let face = |alt: Option<&str>, roman: bool| face_of(alt, if roman { Family::Roman } else { Family::Swiss });
|
||||
let resolve = |f: &str| wordcraft_fonts::word::resolve(f, false, false).face;
|
||||
let (courier, times, calibri, cambria) = (resolve("Courier New"), resolve("Times New Roman"), resolve("Calibri"), resolve("Cambria"));
|
||||
// A missing font that isn't roman is drawn in Calibri (Word for Windows 16.0.20625): here the
|
||||
// bundled face Calibri resolves to, on Windows Calibri itself.
|
||||
let generic = face(None, false);
|
||||
assert_eq!(generic, calibri);
|
||||
// Serif and sans faces are bundled, so these differ on any machine.
|
||||
assert_ne!(times, generic);
|
||||
assert_ne!(cambria, generic);
|
||||
@@ -1544,16 +1547,16 @@ fn a_missing_font_is_drawn_in_its_font_table_alternate() {
|
||||
// D: the alternate beats the roman rule.
|
||||
assert_eq!(face(Some("Times New Roman"), true), times);
|
||||
assert_eq!(face(Some("Courier New"), true), courier);
|
||||
// E: an alternate that is missing too, with no substitutes of its own: the roman rule, or the
|
||||
// generic substitutes for a font that isn't roman.
|
||||
// E: an alternate that is missing too, with no substitutes of its own: the roman rule, or
|
||||
// Calibri for a font that isn't roman.
|
||||
assert_eq!(face(Some("No Such Alternate"), true), cambria);
|
||||
assert_eq!(face(Some("No Such Alternate"), false), generic);
|
||||
// Word reads a value with a comma as one name, not a list (MS-OE376 2.1.264): no font is
|
||||
// called that, so the roman rule or the generic substitutes draw it.
|
||||
// called that, so the roman rule or Calibri draws it.
|
||||
assert_eq!(face(Some("No Such Alternate, Times New Roman"), false), generic);
|
||||
assert_eq!(face(Some("No Such Alternate, Times New Roman"), true), cambria);
|
||||
// A modern font: its installed alternate draws it, a missing alternate leaves it in Cambria,
|
||||
// and with no alternate at all it takes the generic substitutes (Calibri in Word).
|
||||
// and with no alternate at all it is drawn in Calibri.
|
||||
assert_eq!(face_of(Some("Courier New"), Family::Modern), courier);
|
||||
assert_eq!(face_of(Some("No Such Alternate"), Family::Modern), cambria);
|
||||
assert_eq!(face_of(None, Family::Modern), generic);
|
||||
@@ -3407,6 +3410,92 @@ fn a_vertical_merge_lays_out_as_one_cell() {
|
||||
assert_eq!((hit.2, hit.3), (0, 0));
|
||||
}
|
||||
|
||||
/// #8872: a merge running over a page break ends at the page's bottom; the rest is the
|
||||
/// continuation rows' own.
|
||||
#[test]
|
||||
fn a_vertical_merge_across_a_page_break_stays_inside_the_page() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::{HeightRule, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(40, 2, 468.0);
|
||||
for (i, row) in t.rows.iter_mut().enumerate() {
|
||||
row.props.height = Some(40.0);
|
||||
row.props.height_rule = HeightRule::Exact;
|
||||
row.cells[0].props.vmerge = match i {
|
||||
14 => VMerge::Restart,
|
||||
15..=18 => VMerge::Continue,
|
||||
_ => VMerge::None,
|
||||
};
|
||||
}
|
||||
t.rows[14].cells[0].props.shading = Some(wordcraft_doc::props::Rgb(200, 0, 0));
|
||||
let line = Some(wordcraft_doc::props::Border::single(1.0));
|
||||
t.props.borders = Some(wordcraft_doc::props::Borders { top: line, left: line, bottom: line, right: line, between: line, inside_v: line });
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let body = l.pages[0].body;
|
||||
// The merge closes at the end of its first page, and goes on with its fill on the next.
|
||||
let mut cell0 = None;
|
||||
let mut closes = false;
|
||||
for item in &l.pages[0].items {
|
||||
match item {
|
||||
Placed::Cell { rect, row: 14, cell: 0, .. } => cell0 = Some(*rect),
|
||||
Placed::Rule { x0, x1, y0, y1, .. } if y0 == y1 => {
|
||||
closes |= cell0.is_some_and(|r| *x0 <= r.x + 1.0 && *x1 >= r.x + r.w - 1.0 && *y0 >= r.bottom() - 0.01)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(closes, "a border closes the merged cell on its first page");
|
||||
let next = l.pages[1].items.iter().find_map(|i| match i {
|
||||
Placed::Fill { rect, .. } if rect.x < cell0.unwrap().x + 1.0 => Some(*rect),
|
||||
_ => None,
|
||||
});
|
||||
assert!(next.is_some_and(|r| r.y <= l.pages[1].body.y + 0.01 && r.h > 40.0), "the fill goes on at the top of the next page: {next:?}");
|
||||
let mut spanning = false;
|
||||
for item in &l.pages[0].items {
|
||||
if let Placed::Cell { rect, row: 14, cell: 0, .. } = item {
|
||||
spanning = rect.h > 40.0 * 1.5;
|
||||
}
|
||||
if let Placed::Cell { rect, .. } | Placed::Fill { rect, .. } = item {
|
||||
assert!(rect.bottom() <= body.bottom() + 0.01, "{rect:?} past the page's content area {body:?}");
|
||||
}
|
||||
}
|
||||
assert!(spanning, "the merge still spans the rows left on the page");
|
||||
}
|
||||
|
||||
/// The same when the merge's last row is the one split: on each page its area ends with the
|
||||
/// part of that row there, whether the merge starts on that page or runs on from an earlier one.
|
||||
#[test]
|
||||
fn a_vertical_merge_whose_last_row_splits_ends_with_each_part() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::{Rgb, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(20, 2, 468.0);
|
||||
for (i, row) in t.rows.iter_mut().enumerate() {
|
||||
row.cells[0].props.vmerge = match i {
|
||||
10 => VMerge::Restart,
|
||||
11..=13 => VMerge::Continue,
|
||||
_ => VMerge::None,
|
||||
};
|
||||
}
|
||||
t.rows[10].cells[0].props.shading = Some(Rgb(200, 0, 0));
|
||||
t.rows[13].cells[1].blocks = (0..80).map(|_| wordcraft_doc::para_block(Paragraph::with_text("line", Default::default()))).collect();
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let mut shaded_pages = 0;
|
||||
for page in &l.pages {
|
||||
// Where the rows on this page end, by the unmerged column.
|
||||
let rows_end =
|
||||
page.items.iter().filter_map(|i| if let Placed::Cell { rect, cell: 1, .. } = i { Some(rect.bottom()) } else { None }).fold(0.0, f32::max);
|
||||
let fills: Vec<Rect> = page.items.iter().filter_map(|i| if let Placed::Fill { rect, .. } = i { Some(*rect) } else { None }).collect();
|
||||
shaded_pages += usize::from(!fills.is_empty());
|
||||
for rect in fills {
|
||||
assert!(rect.bottom() <= rows_end + 0.01, "{rect:?} runs past the rows on its page, which end at {rows_end}");
|
||||
}
|
||||
}
|
||||
assert!(shaded_pages >= 3, "the last row splits over more than one page break: {shaded_pages}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertical_merge_aligns_its_text_with_the_first_page() {
|
||||
crate::test_fonts();
|
||||
@@ -6472,6 +6561,7 @@ fn split_row_rejects_a_hostile_cut() {
|
||||
items: vec![line(0.0), line(150.0)],
|
||||
bottom,
|
||||
cells: vec![CellPart { top: 2.0, items: 0..2, end: Some(170.0), align: None }],
|
||||
merge: Default::default(),
|
||||
};
|
||||
for cut in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -1.0, 200.0] {
|
||||
assert!(split_row(&row(200.0, 4.0), cut).is_none(), "{cut}");
|
||||
@@ -10392,11 +10482,14 @@ fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
|
||||
// run's own height to it, not (m - 1) x the line's (Word for Mac and Windows: 10pt Times New
|
||||
// Roman with 10pt Courier New, 18.09pt at 1.5 spacing where 1.5 x the 12.34pt line gives 18.51).
|
||||
let font = |(f, size): (&str, f32)| wordcraft_doc::CharProps { font: Some(f.into()), size: Some(size), ..Default::default() };
|
||||
let height = |fonts: &[(&str, f32)], m: f32| {
|
||||
let height = |fonts: &[(&str, f32)], m: f32, with_picture: bool| {
|
||||
let mut p = wordcraft_doc::Paragraph::with_text("run ", font(fonts[0]));
|
||||
for &f in &fonts[1..] {
|
||||
p.append(wordcraft_doc::Paragraph::with_text("run ", font(f)));
|
||||
}
|
||||
if with_picture {
|
||||
p.insert_object(p.len(), picture(30.0, 40.0, Default::default()), &font(fonts[0])).unwrap();
|
||||
}
|
||||
p.props = ParaProps { line_spacing: Some(wordcraft_doc::props::LineSpacing::Multiple(m)), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
@@ -10405,12 +10498,19 @@ fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
|
||||
};
|
||||
// The larger sans has the taller ascent, the serif the deeper descent.
|
||||
let (sans, serif) = (("Inter", 12.0), ("Source Serif 4", 10.5));
|
||||
let tallest = height(&[sans], 1.0).max(height(&[serif], 1.0));
|
||||
let mixed = height(&[sans, serif], 1.0);
|
||||
let tallest = height(&[sans], 1.0, false).max(height(&[serif], 1.0, false));
|
||||
let mixed = height(&[sans, serif], 1.0, false);
|
||||
assert!(mixed > tallest + 0.1, "the fonts don't make a taller line together: {mixed} vs {tallest}");
|
||||
for m in [1.5, 2.0] {
|
||||
let got = height(&[sans, serif], m);
|
||||
assert!((got - (mixed + (m - 1.0) * tallest)).abs() < 0.01, "{m}: {got}, line {mixed}, tallest run {tallest}");
|
||||
let with_picture = height(&[sans, serif], 1.0, true);
|
||||
assert!(with_picture > mixed, "the tall picture raises the line height");
|
||||
for (with_picture, single_height) in [(false, mixed), (true, with_picture)] {
|
||||
for m in [1.5, 2.0] {
|
||||
let got = height(&[sans, serif], m, with_picture);
|
||||
assert!(
|
||||
(got - (single_height + (m - 1.0) * tallest)).abs() < 0.01,
|
||||
"{m}, picture {with_picture}: {got}, line {single_height}, tallest run {tallest}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11977,6 +12077,7 @@ fn a_split_row_moves_shading_below_the_cut_with_it() {
|
||||
items: vec![line_row(0.0), line_row(150.0), fill(0.0, 200.0), fill(150.0, 50.0)],
|
||||
bottom: 0.0,
|
||||
cells: vec![CellPart { top: 2.0, items: 0..4, end: None, align: None }],
|
||||
merge: Default::default(),
|
||||
};
|
||||
let (a, b) = split_row(&row, 100.0).expect("splits");
|
||||
let fills = |r: &RowLayout| {
|
||||
@@ -12574,6 +12675,68 @@ fn tight_wrap_follows_an_ellipse() {
|
||||
assert_eq!(through, tight);
|
||||
}
|
||||
|
||||
/// #6316: how many of seven empty paragraphs (the first anchoring a 200pt-tall rectangle at the
|
||||
/// column's left with `wrap`) go in the `free` points it leaves on its right (column edge to its
|
||||
/// wrap area, 9pt from text included), in compatibility mode `mode`.
|
||||
fn empty_lines_beside(wrap: wordcraft_doc::para::Wrap, free: f32, mode: u32) -> usize {
|
||||
use wordcraft_doc::para::{Anchor, Float, ShapeKind};
|
||||
let w = 468.0 - 9.0 - free;
|
||||
let mut d = Document::from_text("");
|
||||
d.settings.compat_mode = mode;
|
||||
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, dist: 9.0, ..Default::default() };
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w,
|
||||
h: 200.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float,
|
||||
story: None,
|
||||
effects: Default::default(),
|
||||
freeform: None,
|
||||
extra: Default::default(),
|
||||
};
|
||||
d.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
|
||||
for i in 1..7 {
|
||||
d.insert_block(StoryRef::Body, &Path::top(i), wordcraft_doc::Block::Para(Default::default())).unwrap();
|
||||
}
|
||||
let l = lay(&d);
|
||||
let lines: Vec<(f32, f32)> =
|
||||
l.pages[0].items.iter().filter_map(|i| if let Placed::Lines { y, para, .. } = i { Some((para.lines[0].left, *y)) } else { None }).collect();
|
||||
let Some(top) = lines.iter().map(|l| l.1).reduce(f32::min) else { return 0 };
|
||||
lines.iter().filter(|(left, y)| *left >= w + 9.0 - 0.01 && *y < top + 200.0).count()
|
||||
}
|
||||
|
||||
/// #6316: Word puts a line beside a floating picture or shape when the gap between the column
|
||||
/// edge and the object's wrap area is at least 18pt, for square, tight and through wrapping; a
|
||||
/// tight-wrapped cover with 17.55 and 19.15pt gaps was pushed onto three pages by a 20pt minimum.
|
||||
#[test]
|
||||
fn text_goes_beside_a_float_in_an_18pt_gap() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::Wrap;
|
||||
let current = wordcraft_doc::COMPAT_MODE_CURRENT;
|
||||
for wrap in [Wrap::Square, Wrap::Tight, Wrap::Through] {
|
||||
assert_eq!(empty_lines_beside(wrap, 18.1, current), 7, "{wrap:?} 18.1");
|
||||
assert_eq!(empty_lines_beside(wrap, 17.9, current), 0, "{wrap:?} 17.9");
|
||||
}
|
||||
}
|
||||
|
||||
/// Before Word 2013 layout (mode 14 and below) a line goes beside a tight or through object in
|
||||
/// a 9pt gap; square wrapping still needs 18.
|
||||
#[test]
|
||||
fn tight_wrap_needs_only_9pt_beside_it_before_word_2013_layout() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::Wrap;
|
||||
for wrap in [Wrap::Tight, Wrap::Through] {
|
||||
assert_eq!(empty_lines_beside(wrap, 9.1, 14), 7, "{wrap:?} 9.1");
|
||||
assert_eq!(empty_lines_beside(wrap, 8.9, 14), 0, "{wrap:?} 8.9");
|
||||
assert_eq!(empty_lines_beside(wrap, 9.1, wordcraft_doc::COMPAT_MODE_CURRENT), 0, "{wrap:?} 9.1 in mode 15");
|
||||
}
|
||||
assert_eq!(empty_lines_beside(Wrap::Square, 17.9, 14), 0);
|
||||
assert_eq!(empty_lines_beside(Wrap::Square, 18.1, 14), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_wrap_turns_with_the_object() {
|
||||
crate::test_fonts();
|
||||
@@ -13131,6 +13294,271 @@ fn columns_before_a_continuous_break_are_balanced() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #6829's case: Letter page, three columns, exact 14 pt lines. 135 one-line filler paragraphs,
|
||||
/// then P (5 lines, kept with the next) with `space_after` after it, then Q, then a section after
|
||||
/// Q starting continuously, so the columns of the section ending at Q are balanced.
|
||||
fn continued_tail_doc(space_after: f32) -> (Document, usize) {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let filler = 135;
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q".into());
|
||||
text.push("After".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
p.insert_text(2, &format!("{lb}P2{lb}P3{lb}P4{lb}P5"), &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(true);
|
||||
p.props.space_after = Some(space_after);
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
(d, filler)
|
||||
}
|
||||
|
||||
/// Body paragraph `block`'s pieces in `l`: (page, x, top, line count).
|
||||
fn pieces_of(l: &DocLayout, block: usize) -> Vec<(usize, f32, f32, usize)> {
|
||||
l.pages
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(pi, pg)| {
|
||||
pg.items.iter().filter_map(move |it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, path, l0, l1, x, y, .. } if path.0[..] == [block as u32] => Some((pi, *x, *y, l1 - l0)),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// #6829: in balanced columns, the last lines of a paragraph begun on the page before stay with
|
||||
/// the paragraph after it when the paragraph is kept with the next (Word 16.0, compatibility
|
||||
/// mode 15: three columns, exact 14 pt lines, the tail P4–P5 and Q all in column 1).
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_with_the_next_paragraph() {
|
||||
crate::test_fonts();
|
||||
let (d, filler) = continued_tail_doc(0.0);
|
||||
let l = lay(&d);
|
||||
let pieces = pieces_of(&l, filler);
|
||||
assert_eq!(pieces.len(), 2, "P begins on page 1 and ends on page 2: {pieces:?}");
|
||||
let (tail_page, tail_x, tail_top, tail_lines) = pieces[1];
|
||||
assert_eq!((pieces[0].0, tail_page, tail_lines), (0, 1, 2), "P4 and P5 on page 2: {pieces:?}");
|
||||
let q = para_boxes(&l)[filler + 1];
|
||||
assert_eq!(q.0, 1, "Q on page 2: {q:?}");
|
||||
assert!((q.1 - tail_x).abs() < 0.5, "Q in the column of P4 and P5: Q {q:?}, P {pieces:?}");
|
||||
assert!((q.2 - (tail_top + 28.0)).abs() < 0.5, "Q right under P5: Q {q:?}, P {pieces:?}");
|
||||
}
|
||||
|
||||
/// #6829: the space after the continued paragraph counts too. With 28 pt after P, leaving room
|
||||
/// for P4–P5 and Q's first line alone takes Q past the end of the column, and the tail stays
|
||||
/// behind while Q moves on. The tail must go over with Q, and the columns grow to hold both.
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_with_the_space_after_it() {
|
||||
crate::test_fonts();
|
||||
let (d, filler) = continued_tail_doc(28.0);
|
||||
let l = lay(&d);
|
||||
let pieces = pieces_of(&l, filler);
|
||||
assert_eq!(pieces.len(), 2, "P begins on page 1 and ends on page 2: {pieces:?}");
|
||||
let (tail_page, tail_x, tail_top, tail_lines) = pieces[1];
|
||||
assert_eq!((pieces[0].0, tail_page, tail_lines), (0, 1, 2), "P4 and P5 on page 2: {pieces:?}");
|
||||
let q = para_boxes(&l)[filler + 1];
|
||||
assert_eq!(q.0, 1, "Q on page 2: {q:?}");
|
||||
assert!((q.1 - tail_x).abs() < 0.5, "Q in the column of P4 and P5: Q {q:?}, P {pieces:?}");
|
||||
assert!((q.2 - (tail_top + 28.0 + 28.0)).abs() < 0.5, "Q under P5's space after: Q {q:?}, P {pieces:?}");
|
||||
}
|
||||
|
||||
/// #9206: a paragraph that closes a balanced section with `keep_next` must not reserve column
|
||||
/// room in `kept_tail_end` for the next section's first paragraph.
|
||||
#[test]
|
||||
fn balanced_columns_do_not_keep_a_section_closing_tail_with_the_next_section() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let filler = 135;
|
||||
let make_doc = |keep_next: bool| {
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
let rest: String = (2..=12).map(|i| format!("{lb}P{i}")).collect();
|
||||
p.insert_text(2, &rest, &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(keep_next);
|
||||
p.section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
d
|
||||
};
|
||||
|
||||
let without = lay(&make_doc(false));
|
||||
let with_keep = lay(&make_doc(true));
|
||||
assert_eq!(pieces_of(&with_keep, filler), pieces_of(&without, filler), "keep_next on section-closing tail must not unbalance columns");
|
||||
assert_eq!(para_boxes(&with_keep)[filler + 1], para_boxes(&without)[filler + 1], "Q below the balanced section must stay at the same y");
|
||||
}
|
||||
|
||||
/// #9208: when the next paragraph's `space_before` is dropped by contextual spacing, `kept_tail_end`
|
||||
/// must not count it on top of `gap_after`.
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_without_dropped_space_before() {
|
||||
crate::test_fonts();
|
||||
let (base_doc, filler) = continued_tail_doc(14.0);
|
||||
let base_layout = lay(&base_doc);
|
||||
let base_pieces = pieces_of(&base_layout, filler);
|
||||
let base_q = para_boxes(&base_layout)[filler + 1];
|
||||
|
||||
let (mut ctx_doc, _) = continued_tail_doc(14.0);
|
||||
let q = ctx_doc.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
q.props.space_before = Some(28.0);
|
||||
q.props.contextual_spacing = Some(true);
|
||||
let ctx_layout = lay(&ctx_doc);
|
||||
let ctx_pieces = pieces_of(&ctx_layout, filler);
|
||||
let ctx_q = para_boxes(&ctx_layout)[filler + 1];
|
||||
|
||||
assert_eq!(ctx_pieces, base_pieces, "dropped space_before must not change tail placement");
|
||||
assert_eq!(ctx_q, base_q, "dropped space_before must not change Q placement");
|
||||
}
|
||||
|
||||
/// #6829: the lines going over with the next paragraph keep their row together. Text on the far
|
||||
/// side of a floating object is part of the same row (`settled_end`), and the end
|
||||
/// `kept_tail_end` picks must not split it: the whole row goes over with the next paragraph.
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_row_together() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let filler = 135;
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q1".into());
|
||||
text.push("After".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
p.insert_text(2, &format!("{lb}P2{lb}P3{lb}word word word word word"), &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(true);
|
||||
let q = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
q.insert_text(2, &format!("{lb}Q2{lb}Q3{lb}Q4{lb}Q5"), &Default::default()).unwrap();
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
// A float in the middle of the column, anchored at P's tail: each of its first rows holds a
|
||||
// word on each side of it.
|
||||
let f = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 36.0, ..Default::default() };
|
||||
d.insert_object(&Pos::body(filler, 9), rect_shape(60.0, 42.0, f), &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let mut continued = false;
|
||||
let mut row = false;
|
||||
for (pi, pg) in l.pages.iter().enumerate() {
|
||||
for it in &pg.items {
|
||||
let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, .. } = it else { continue };
|
||||
if path.0[..] != [filler as u32] || *l0 == 0 {
|
||||
continue;
|
||||
}
|
||||
continued = true;
|
||||
if pi == 1 {
|
||||
row |= para.lines[*l0..].iter().any(|l| l.beside);
|
||||
}
|
||||
if *l1 < para.lines.len() {
|
||||
assert!(!para.lines[*l1].beside, "a piece ends in the middle of a row: l0 {l0}, l1 {l1} of {}", para.lines.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(continued, "P continues on page 2");
|
||||
assert!(row, "the float splits a row beside the tail on page 2");
|
||||
assert_eq!(para_boxes(&l)[filler + 1].0, 1, "Q on page 2");
|
||||
}
|
||||
|
||||
/// Lines of body paragraph `block` placed in `l`, over all its pieces.
|
||||
fn placed_lines(l: &DocLayout, block: usize) -> usize {
|
||||
pieces_of(l, block).iter().map(|p| p.3).sum()
|
||||
}
|
||||
|
||||
/// #6829: when the tail of a continued paragraph and the next paragraph could never fit one
|
||||
/// column (a 60-line Q kept together), the tail stays where it is: nothing is pushed over to a
|
||||
/// third page and the columns are balanced on page 2 as without the rule.
|
||||
#[test]
|
||||
fn a_continued_tail_that_cannot_fit_with_the_next_paragraph_stays_in_place() {
|
||||
crate::test_fonts();
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let (mut d, filler) = continued_tail_doc(0.0);
|
||||
let q = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
let more: String = (2..=60).map(|i| format!("{lb}Q{i}")).collect();
|
||||
q.insert_text(1, &more, &Default::default()).unwrap();
|
||||
q.props.keep_lines = Some(true);
|
||||
let l = lay(&d);
|
||||
assert_eq!(l.pages.len(), 2, "everything on two pages");
|
||||
assert_eq!(placed_lines(&l, filler), 5, "P is placed whole");
|
||||
assert_eq!(placed_lines(&l, filler + 1), 60, "Q is placed whole");
|
||||
assert!(pieces_of(&l, filler + 1).iter().all(|p| p.0 == 1), "Q on page 2");
|
||||
assert!(pieces_of(&l, filler)[1..].iter().all(|p| p.0 == 1), "P's tail on page 2");
|
||||
}
|
||||
|
||||
/// #6829: when the rule cannot be satisfied at any height, the balancing's fallback (the original
|
||||
/// full-height columns) keeps the original layout and every paragraph is placed: a 49-line
|
||||
/// paragraph kept with the next fills column 1 of page 2, then Q and 91 one-line paragraphs
|
||||
/// fill the page.
|
||||
#[test]
|
||||
fn balancing_fallback_places_every_paragraph() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let (filler, after) = (135, 91);
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q".into());
|
||||
text.extend((0..after).map(|i| format!("A{i}")));
|
||||
text.push("Next".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
let more: String = (2..=49).map(|i| format!("{lb}P{i}")).collect();
|
||||
p.insert_text(2, &more, &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(true);
|
||||
let last = filler + 1 + after;
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
d.para_mut(StoryRef::Body, &Path::top(last)).unwrap().section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
let l = lay(&d);
|
||||
for block in 0..=last + 1 {
|
||||
let want = if block == filler { 49 } else { 1 };
|
||||
assert_eq!(placed_lines(&l, block), want, "block {block} is placed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_before_a_page_break_or_a_column_break_are_not_balanced() {
|
||||
crate::test_fonts();
|
||||
@@ -13338,8 +13766,8 @@ fn unproofed_languages_and_no_proof_runs_are_not_marked() {
|
||||
let text = "Nous écrivons beaucoup aujourd'hui.";
|
||||
let mut d = Document::from_text(text);
|
||||
assert!(issues(&d) > 0, "French words are English misspellings in an English document");
|
||||
Arc::make_mut(&mut d.styles).default_chr.lang = Some("fr-FR".into());
|
||||
assert_eq!(issues(&d), 0, "no French dictionary: no marks");
|
||||
Arc::make_mut(&mut d.styles).default_chr.lang = Some("zxx".into());
|
||||
assert_eq!(issues(&d), 0, "no linguistic content (`zxx`): no marks");
|
||||
Arc::make_mut(&mut d.styles).default_chr.lang = Some("pl-PL".into());
|
||||
let mut pl = Document::from_text("Płynie żeka.");
|
||||
Arc::make_mut(&mut pl.styles).default_chr.lang = Some("pl-PL".into());
|
||||
@@ -16240,6 +16668,7 @@ fn split_cell_moves_image_frame() {
|
||||
edge: 0.0,
|
||||
items: vec![kept, image, frame],
|
||||
cells: vec![CellPart { top, items: 0..3, end: Some(170.0), align: None }],
|
||||
merge: Default::default(),
|
||||
};
|
||||
let (first, rest) = split_row(&row, 100.0).unwrap();
|
||||
assert_eq!(first.items.len(), 1);
|
||||
@@ -19164,6 +19593,207 @@ fn header_boundary_pinned() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A header picture aligned in the Margin area when both the header and the footer reach past
|
||||
/// their margins: Word centres (or bottom-aligns) it in the rendered body, between the body's
|
||||
/// top and the footer's top, not down to the declared bottom margin.
|
||||
#[test]
|
||||
fn header_margin_tracks_body_bottom() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
for footer_tall in [false, true] {
|
||||
for align in [FloatAlign::Center, FloatAlign::End] {
|
||||
let mut doc = Document::from_text("Body");
|
||||
doc.last_section.margin_top = 20.0;
|
||||
doc.last_section.margin_bottom = 20.0;
|
||||
doc.last_section.header = 36.0;
|
||||
doc.last_section.footer = if footer_tall { 36.0 } else { 0.0 };
|
||||
let mut hp = boundary_header_para();
|
||||
let float =
|
||||
Float { wrap: Wrap::BehindText, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(align), x: 300.0, ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(40.0, 10.0, float), &Default::default()).unwrap();
|
||||
let header = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
|
||||
doc.last_section.headers.default = Some(header);
|
||||
if footer_tall {
|
||||
let footer = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
doc.last_section.footers.default = Some(footer);
|
||||
}
|
||||
let laid = lay(&doc);
|
||||
let page = &laid.pages[0];
|
||||
let s = &doc.last_section;
|
||||
assert!(page.body.y > s.margin_top, "the header reaches past the top margin");
|
||||
let bottom = page.body.bottom();
|
||||
assert_eq!(bottom < s.page_h - s.margin_bottom - 1.0, footer_tall, "footer_tall={footer_tall}: body {:?}", page.body);
|
||||
let expected = match align {
|
||||
FloatAlign::End => bottom - 10.0,
|
||||
_ => page.body.y + (bottom - page.body.y - 10.0) / 2.0,
|
||||
};
|
||||
let rects = shapes(&page.header);
|
||||
assert_eq!(rects.len(), 1);
|
||||
assert!(
|
||||
(rects[0].y - expected).abs() < 0.01,
|
||||
"footer_tall={footer_tall} {align:?}: {:?}, expected {expected}, body {:?}",
|
||||
rects[0],
|
||||
page.body
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tall picture bottom-aligned on the Margin in the header: the rendered body bottom (a footer
|
||||
/// taller than its margin) lifts it into the header's lines. The body top was measured with the
|
||||
/// declared margins, where it stays clear of them, so a picture that wraps text keeps that
|
||||
/// placement and the header's lines stay above the body; one behind the text follows the body.
|
||||
#[test]
|
||||
fn header_margin_wrap_keeps_measured_header_height() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
for wrap in [Wrap::BehindText, Wrap::Square] {
|
||||
let mut doc = Document::from_text("Body");
|
||||
let s = &mut doc.last_section;
|
||||
s.margin_top = 20.0;
|
||||
s.margin_bottom = 20.0;
|
||||
s.header = 36.0;
|
||||
s.footer = 36.0;
|
||||
let (pw, ph) = (s.page_w, s.page_h);
|
||||
// Five 10 pt header lines from 36 to 86; the footer's five lines top at ph - 86. Bottom
|
||||
// on the declared margin the picture's top is 116, below the lines; on the footer's top
|
||||
// it is 50, across them.
|
||||
let h = ph - 136.0;
|
||||
let mut hp = boundary_header_para();
|
||||
let float = Float { wrap, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(pw, h, float), &Default::default()).unwrap();
|
||||
let header = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
|
||||
doc.last_section.headers.default = Some(header);
|
||||
let footer = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
doc.last_section.footers.default = Some(footer);
|
||||
let laid = lay(&doc);
|
||||
let page = &laid.pages[0];
|
||||
assert_eq!((page.body.y, page.body.bottom()), (86.0, ph - 86.0), "{wrap:?}: body {:?}", page.body);
|
||||
let tops: Vec<f32> = page.header.iter().filter_map(|i| if let Placed::Lines { y, .. } = i { Some(*y) } else { None }).collect();
|
||||
assert_eq!(tops, [36.0], "{wrap:?}: the header's lines stay where the body top was measured");
|
||||
let expected = if wrap == Wrap::Square { ph - 20.0 - h } else { page.body.bottom() - h };
|
||||
let rects = shapes(&page.header);
|
||||
assert_eq!(rects.len(), 1);
|
||||
assert!((rects[0].y - expected).abs() < 0.01, "{wrap:?}: {:?}, expected {expected}", rects[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The header laid out again with the declared margins (above) counts its list labels from the
|
||||
/// same place as the layout it replaces: each page's header shows the next number, once.
|
||||
#[test]
|
||||
fn header_margin_wrap_retry_counts_labels_once() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
let labels = |wrap: Wrap| {
|
||||
let mut doc = Document::from_text(&"Body\n".repeat(120));
|
||||
let num = Arc::make_mut(&mut doc.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
let s = &mut doc.last_section;
|
||||
s.margin_top = 20.0;
|
||||
s.margin_bottom = 20.0;
|
||||
s.header = 36.0;
|
||||
s.footer = 36.0;
|
||||
let (pw, ph) = (s.page_w, s.page_h);
|
||||
let mut hp = boundary_header_para();
|
||||
hp.props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 0 });
|
||||
let float = Float { wrap, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
|
||||
let header = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
|
||||
doc.last_section.headers.default = Some(header);
|
||||
let footer = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
doc.last_section.footers.default = Some(footer);
|
||||
let laid = lay(&doc);
|
||||
assert!(laid.pages.len() >= 2, "{wrap:?}: {} pages", laid.pages.len());
|
||||
laid.pages
|
||||
.iter()
|
||||
.map(|p| {
|
||||
p.header.iter().find_map(|it| if let Placed::Lines { para, .. } = it { para.label.as_ref().map(|l| l.text.clone()) } else { None })
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let retried = labels(Wrap::Square);
|
||||
assert_eq!(retried, labels(Wrap::BehindText), "the retried header counts like the one laid out once");
|
||||
}
|
||||
|
||||
/// #9226: an even-page header is never measured for `page.body.y`, so it keeps its rendered
|
||||
/// margin-area layout instead of retrying with the declared margins.
|
||||
#[test]
|
||||
fn even_page_header_does_not_retry_with_declared_margins() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
let even_shape_y = |wrap: Wrap| {
|
||||
let mut doc = Document::from_text(&"Body\n".repeat(120));
|
||||
doc.settings.even_odd_headers = true;
|
||||
let s = &mut doc.last_section;
|
||||
s.margin_top = 20.0;
|
||||
s.margin_bottom = 20.0;
|
||||
s.header = 36.0;
|
||||
s.footer = 36.0;
|
||||
let (pw, ph) = (s.page_w, s.page_h);
|
||||
// Short default header/footer so `page.body.y == 36.0 + 10.0 = 46.0` (smaller than the even header).
|
||||
let def_h = doc.add_part(
|
||||
wordcraft_doc::PartKind::Header,
|
||||
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Odd", Default::default()))],
|
||||
);
|
||||
let def_f = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
let mut hp = boundary_header_para();
|
||||
let float = Float { wrap, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
|
||||
let even_h = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
|
||||
let s = &mut doc.last_section;
|
||||
s.headers.default = Some(def_h);
|
||||
s.headers.even = Some(even_h);
|
||||
s.footers.default = Some(def_f);
|
||||
let laid = lay(&doc);
|
||||
assert!(laid.pages.len() >= 2);
|
||||
shapes(&laid.pages[1].header)[0].y
|
||||
};
|
||||
assert!((even_shape_y(Wrap::Square) - even_shape_y(Wrap::BehindText)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_table_areas_match_retried_header_margin_fallback() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
use wordcraft_doc::props::{HeightRule, TableFloat};
|
||||
|
||||
let mut doc = Document::from_text("Body");
|
||||
let s = &mut doc.last_section;
|
||||
s.margin_top = 20.0;
|
||||
s.margin_bottom = 20.0;
|
||||
s.header = 36.0;
|
||||
s.footer = 36.0;
|
||||
let (pw, ph) = (s.page_w, s.page_h);
|
||||
|
||||
// Header has a wrapping Margin-bottom picture that triggers the retry with declared margins,
|
||||
// plus a Margin-bottom floating table.
|
||||
let mut hp = boundary_header_para();
|
||||
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
|
||||
let mut header_table = Table::new(1, 1, 80.0);
|
||||
header_table.rows[0].props.height = Some(20.0);
|
||||
header_table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
header_table.props.float =
|
||||
Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), x: 300.0, ..Default::default() });
|
||||
let header = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp), Arc::new(Block::Table(header_table))]);
|
||||
doc.last_section.headers.default = Some(header);
|
||||
|
||||
let footer = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
doc.last_section.footers.default = Some(footer);
|
||||
|
||||
// Place a body floating table at the rendered-area bottom position (ph - 86 - 20). Because the
|
||||
// drawn header falls back to declared margins (ph - 20 - 20), the two tables do not overlap
|
||||
// and the body table must stay at ph - 106.0.
|
||||
let mut body_table = Table::new(1, 1, 80.0);
|
||||
body_table.rows[0].props.height = Some(20.0);
|
||||
body_table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
let rendered_y = ph - 86.0 - 20.0;
|
||||
body_table.props.float = Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Page, x: 300.0, y: rendered_y, ..Default::default() });
|
||||
doc.body.insert(0, Arc::new(Block::Table(body_table)));
|
||||
|
||||
let laid = lay(&doc);
|
||||
let page = &laid.pages[0];
|
||||
let cell_y = |items: &[Placed]| items.iter().find_map(|it| if let Placed::Cell { rect, .. } = it { Some(rect.y) } else { None }).unwrap();
|
||||
let header_tbl_y = cell_y(&page.header);
|
||||
let body_tbl_y = cell_y(&page.items);
|
||||
assert!((header_tbl_y - (ph - 20.0 - 20.0)).abs() < 0.01, "header table at declared margin: {header_tbl_y}");
|
||||
assert!((body_tbl_y - rendered_y).abs() < 0.01, "body table should not avoid ghost rendered-area header table: {body_tbl_y} vs {rendered_y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_boundary_obstacle() {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
@@ -19341,6 +19971,89 @@ fn header_margin_table_area() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9383: the final part of a split continuation row keeps its own background extent.
|
||||
#[test]
|
||||
fn a_split_merge_continuation_picture_ends_at_the_following_row() {
|
||||
use display::Draw;
|
||||
use wordcraft_doc::props::{CellPicture, HeightRule, LineSpacing, PictureRepeat, Rgb, VMerge};
|
||||
|
||||
let paragraph = |text: &str| {
|
||||
let mut p = Paragraph::with_text(text, Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
wordcraft_doc::para_block(p)
|
||||
};
|
||||
let shade = Rgb(220, 185, 70);
|
||||
let tile = [30.0, 7.0];
|
||||
for split in [false, true] {
|
||||
let mut d = pagination_fixture_document("");
|
||||
d.last_section.page_h = 320.0;
|
||||
d.last_section.margin_top = 40.0;
|
||||
d.last_section.margin_bottom = 40.0;
|
||||
let media = d.add_media(vec![0u8; 8], "png");
|
||||
let mut table = Table::new(3, 2, 200.0);
|
||||
let start = &mut table.rows[0].cells[0];
|
||||
start.props.vmerge = VMerge::Restart;
|
||||
start.props.shading = Some(shade);
|
||||
start.props.picture = Some(Box::new(CellPicture { media: media.clone(), size: tile, repeat: PictureRepeat::Tile, align: [0.0, 0.0] }));
|
||||
start.blocks = vec![paragraph("Merged")];
|
||||
table.rows[0].cells[1].blocks = vec![paragraph("Start")];
|
||||
table.rows[1].cells[0].props.vmerge = VMerge::Continue;
|
||||
table.rows[1].cells[1].blocks = (0..if split { 26 } else { 3 }).map(|_| paragraph("Continued")).collect();
|
||||
table.rows[2].cells[0].blocks = vec![paragraph("Following")];
|
||||
if !split {
|
||||
// The short continuation moves on whole, so it still opens its second page.
|
||||
table.rows[0].props.height = Some(220.0);
|
||||
table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
table.rows[1].props.cant_split = true;
|
||||
}
|
||||
d.body = vec![Arc::new(Block::Table(table)), paragraph("Aftertable")];
|
||||
|
||||
let layout = lay(&d);
|
||||
let parts: Vec<_> = (0..layout.pages.len()).filter_map(|i| cell_rect(&layout, i, 1, 0).map(|rect| (i, rect))).collect();
|
||||
assert_eq!(parts.len(), if split { 2 } else { 1 }, "split={split}: {parts:?}");
|
||||
let &(last, continuation) = parts.last().unwrap();
|
||||
assert!(last > 0, "the final fragment opens a later page");
|
||||
let following = cell_rect(&layout, last, 2, 0).expect("the next row shares the final page");
|
||||
let draws = display::page_display(&d, &layout.pages[last], &display::DisplayOptions::default());
|
||||
let (clip, tiles) = draws
|
||||
.iter()
|
||||
.find_map(|draw| match draw {
|
||||
Draw::Clip { rect, items } if items.iter().any(|item| matches!(item, Draw::Image { media: key, .. } if *key == media)) => {
|
||||
Some((rect, items))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("continued background picture");
|
||||
assert!((clip.y - continuation.y).abs() < 0.01 && (clip.h - continuation.h).abs() < 0.01, "split={split}: {clip:?} vs {continuation:?}");
|
||||
assert!(clip.bottom() <= following.y + 0.01, "the picture ends before the following row");
|
||||
assert!(
|
||||
draws.iter().any(|draw| matches!(draw, Draw::Fill { rect, color, .. }
|
||||
if *color == shade && *rect == *clip)),
|
||||
"solid shading has the same extent"
|
||||
);
|
||||
|
||||
let images: Vec<_> = tiles
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
Draw::Image { rect, media: key, .. } if *key == media => Some(rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(images.iter().all(|image| clip.intersects(image) && image.w == tile[0] && image.h == tile[1]));
|
||||
assert!(images.iter().any(|image| (image.y - clip.y).abs() < 0.01), "the first tile stays at the top");
|
||||
assert!(images.iter().any(|image| image.bottom() >= clip.bottom() - 0.01), "the last tile reaches the clipped edge");
|
||||
for following_text in ["Following", "Aftertable"] {
|
||||
assert!(
|
||||
draws.iter().any(|draw| matches!(draw, Draw::Glyphs { text, glyphs, .. }
|
||||
if text == following_text && !glyphs.is_empty() && glyphs.iter().all(|g| g.2 > clip.bottom()))),
|
||||
"{following_text} is drawn below the background"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod shape_alpha;
|
||||
|
||||
/// A row with a background picture split over two pages: each part draws its own piece of the
|
||||
@@ -19371,6 +20084,131 @@ fn a_split_cells_background_picture_is_drawn_on_both_parts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9192 and #9362: a vertically merged cell draws its clipped background picture behind
|
||||
/// the text and borders on the first page and on continuation pages.
|
||||
#[test]
|
||||
fn a_merged_cells_background_picture_is_drawn_on_both_pages() {
|
||||
use display::Draw;
|
||||
use wordcraft_doc::props::{Border, Borders, CellPicture, PictureRepeat, Rgb, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = wordcraft_doc::Table::new(50, 2, 100.0);
|
||||
let media = d.add_media(vec![0u8; 8], "png");
|
||||
let shade = Rgb(240, 230, 150);
|
||||
let border_color = Rgb(20, 40, 150);
|
||||
let border = Some(Border { color: Some(border_color), ..Border::single(6.0) });
|
||||
t.props.borders = Some(Borders { left: border, inside_v: border, ..Default::default() });
|
||||
let restart = &mut t.rows[0].cells[0];
|
||||
restart.props.vmerge = VMerge::Restart;
|
||||
restart.props.shading = Some(shade);
|
||||
restart.props.picture = Some(Box::new(CellPicture { media, size: [30.0, 6.0], repeat: PictureRepeat::Tile, align: [0.0, 0.0] }));
|
||||
restart.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
if r > 0 {
|
||||
row.cells[0].props.vmerge = VMerge::Continue;
|
||||
}
|
||||
row.cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("Row {r}"), Default::default()))];
|
||||
}
|
||||
d.body = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(t)), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
|
||||
let l = lay(&d);
|
||||
assert!(l.pages.len() >= 2, "the merged table spans at least two pages");
|
||||
for (n, page) in l.pages.iter().take(2).enumerate() {
|
||||
let clips: Vec<Rect> = page.items.iter().filter_map(|it| if let Placed::Clip { rect, .. } = it { Some(*rect) } else { None }).collect();
|
||||
assert_eq!(clips.len(), 1, "page {n}: expected continued merged-cell picture clip, got {clips:?}");
|
||||
let picture_rect = clips[0];
|
||||
assert!(picture_rect.h > 0.0 && picture_rect.bottom() <= page.h + 0.01, "page {n}: {picture_rect:?}");
|
||||
let draws = display::page_display(&d, page, &display::DisplayOptions::default());
|
||||
let fill = draws
|
||||
.iter()
|
||||
.position(|item| matches!(item, Draw::Fill { color, rect, .. } if *color == shade && *rect == picture_rect))
|
||||
.expect("merged-cell shading");
|
||||
let picture = draws
|
||||
.iter()
|
||||
.position(|item| {
|
||||
matches!(item, Draw::Clip { rect, items }
|
||||
if *rect == picture_rect && items.iter().any(|item| matches!(item, Draw::Image { .. })))
|
||||
})
|
||||
.expect("clipped background picture");
|
||||
assert!(fill < picture, "page {n}: shading goes behind the picture");
|
||||
|
||||
for x in [picture_rect.x, picture_rect.right()] {
|
||||
let side = draws
|
||||
.iter()
|
||||
.position(|item| {
|
||||
matches!(item, Draw::Line { color, width, x0, y0, x1, y1, .. }
|
||||
if *color == border_color && *width >= 6.0 && (*x0 - x).abs() < 0.01 && (*x1 - x).abs() < 0.01
|
||||
&& (*y0 - picture_rect.y).abs() < 0.01 && *y1 > *y0)
|
||||
})
|
||||
.unwrap_or_else(|| panic!("page {n}: first-row border at x={x}"));
|
||||
assert!(picture < side, "page {n}: the picture must be behind the first-row side border at x={x}");
|
||||
}
|
||||
|
||||
let text = draws.iter().position(|item| matches!(item, Draw::Glyphs { text, .. } if !text.trim().is_empty())).expect("first row text");
|
||||
assert!(picture < text, "page {n}: the picture goes behind the text");
|
||||
}
|
||||
}
|
||||
|
||||
/// #9191: page-end trimming in `table_flow` must cut only continuing merged-cell areas, not
|
||||
/// unrelated `Clip` items (such as a floating drawing canvas anchored in a row).
|
||||
#[test]
|
||||
fn page_end_trimming_does_not_cut_a_floating_canvas_clip_in_a_table_row() {
|
||||
use wordcraft_doc::para::{Anchor, CanvasStyle, Float, GroupChild, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::{Rgb, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = wordcraft_doc::Table::new(50, 2, 200.0);
|
||||
t.rows[0].cells[0].props.vmerge = VMerge::Restart;
|
||||
t.rows[0].cells[0].props.shading = Some(Rgb(10, 20, 30));
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
if r > 0 {
|
||||
row.cells[0].props.vmerge = VMerge::Continue;
|
||||
}
|
||||
row.cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("Row {r}"), Default::default()))];
|
||||
}
|
||||
d.body = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(t)), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
|
||||
let probe = lay(&d);
|
||||
assert!(probe.pages.len() >= 2);
|
||||
let last_row = probe.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Cell { row, .. } => Some(*row),
|
||||
_ => None,
|
||||
})
|
||||
.max()
|
||||
.expect("page 0 has table rows");
|
||||
|
||||
let member = InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w: 40.0,
|
||||
h: 30.0,
|
||||
fill: Some(Fill::solid(Rgb(40, 50, 60))),
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Float::default(),
|
||||
story: None,
|
||||
effects: Default::default(),
|
||||
freeform: None,
|
||||
extra: Default::default(),
|
||||
};
|
||||
let canvas = InlineObject::Group {
|
||||
w: 80.0,
|
||||
h: 120.0,
|
||||
float: Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: 40.0, ..Default::default() },
|
||||
ch_w: 80.0,
|
||||
ch_h: 120.0,
|
||||
children: vec![GroupChild { x: 10.0, y: 10.0, obj: member }],
|
||||
canvas: Some(CanvasStyle { fill: Some(Fill::solid(Rgb(0xF0, 0xF4, 0xFF))), stroke: None, stroke_width: 0.0 }),
|
||||
};
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(&format!("Row {last_row}"), Default::default());
|
||||
p.insert_object(0, canvas, &Default::default()).unwrap();
|
||||
if let wordcraft_doc::Block::Table(tbl) = std::sync::Arc::make_mut(&mut d.body[0]) {
|
||||
tbl.rows[last_row].cells[1].blocks = vec![wordcraft_doc::para_block(p)];
|
||||
}
|
||||
|
||||
let l = lay(&d);
|
||||
let clips: Vec<Rect> = l.pages[0].items.iter().filter_map(|it| if let Placed::Clip { rect, .. } = it { Some(*rect) } else { None }).collect();
|
||||
assert!(clips.iter().any(|r| (r.h - 120.0).abs() < 0.01), "floating canvas clip must keep its full 120 pt height: {clips:?}");
|
||||
}
|
||||
|
||||
/// A table moved to a new page by a page break before its first paragraph shows the number of
|
||||
/// the page it lands on in that cell's PAGE field, not the page it was laid out for.
|
||||
#[test]
|
||||
|
||||
@@ -355,3 +355,26 @@ fn khmer_ignores_the_ligature_setting() {
|
||||
assert_eq!(gids(Some(hd)), gids(None));
|
||||
assert_eq!(gids(Ligatures::from_ooxml("none")), gids(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complex_script_run_is_drawn_in_its_script_font_lookup() {
|
||||
crate::test_fonts();
|
||||
// A missing complex-script font is looked up as a script font (#7064): it keeps its name,
|
||||
// and neither the core font its name starts with nor Calibri draws it. The text it covers is
|
||||
// shaped in that face, the one checked for coverage and reported as the substitute, not in
|
||||
// the run font lookup's (Courier New for a missing `Courier Foo`).
|
||||
let font = "Courier Foo 7064";
|
||||
let mut d = Document::from_text("Hello");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.runs[0].props.cs = Some(true);
|
||||
p.runs[0].props.font_cs = Some(font.into());
|
||||
let l = lay(&d);
|
||||
let pl = para_layout(&l, 0);
|
||||
let script = wordcraft_fonts::word::resolve(font, false, false).face;
|
||||
let core = wordcraft_fonts::word::resolve("Courier New", false, false).face;
|
||||
assert_ne!(script.id(), core.id(), "the two lookups differ on this machine");
|
||||
assert!(script.covers('H'));
|
||||
for c in &pl.clusters {
|
||||
assert_eq!(pl.styles[c.style as usize].face.id(), script.id(), "{}", pl.styles[c.style as usize].face.family);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1168,6 +1168,43 @@ fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() {
|
||||
assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]);
|
||||
}
|
||||
|
||||
/// Word's exact margins: a negative top (bottom) margin starts (ends) the body at its size from
|
||||
/// the page edge even when the header (footer) is taller, and the two overlap (ECMA-376
|
||||
/// §17.6.11, `w:pgMar` below zero; DOC `dyaTop` / `dyaBottom`), so the same text fits on fewer
|
||||
/// pages. Positive margins stay "at least": a taller header or footer pushes the body.
|
||||
#[test]
|
||||
fn negative_margins_are_exact_and_let_the_header_and_footer_overlap_the_body() {
|
||||
crate::test_fonts();
|
||||
let make = |top: f32, bottom: f32| {
|
||||
let mut d = Document::from_text(&"Body line\n".repeat(100));
|
||||
d.last_section.page_w = 595.3;
|
||||
d.last_section.page_h = 841.9;
|
||||
d.last_section.margin_top = top;
|
||||
d.last_section.margin_bottom = bottom;
|
||||
d.last_section.header = 36.0;
|
||||
d.last_section.footer = 36.0;
|
||||
let head = d.add_part(PartKind::Header, paras("Header line", 6));
|
||||
let foot = d.add_part(PartKind::Footer, paras("Footer line", 6));
|
||||
d.last_section.headers.default = Some(head);
|
||||
d.last_section.footers.default = Some(foot);
|
||||
let l = lay(&d);
|
||||
let body = extent(&l.pages[0].items, StoryRef::Body).unwrap();
|
||||
let header = extent(&l.pages[0].header, StoryRef::Part(head)).unwrap();
|
||||
let footer = extent(&l.pages[0].footer, StoryRef::Part(foot)).unwrap();
|
||||
(l.pages.len(), body, header, footer)
|
||||
};
|
||||
let (pages, body, header, footer) = make(-60.0, -60.0);
|
||||
assert!(header.1 > 60.0 && footer.0 < 841.9 - 60.0, "the bands reach past the margins: {header:?} {footer:?}");
|
||||
assert!((body.0 - 60.0).abs() < 0.5, "the body starts at the exact top margin, over the header: {body:?}");
|
||||
assert!(
|
||||
body.1 <= 841.9 - 60.0 + 0.01 && body.1 > footer.0,
|
||||
"the body runs down to the exact bottom margin, over the footer: {body:?} {footer:?}"
|
||||
);
|
||||
let (at_least_pages, at_least_body, at_least_header, at_least_footer) = make(60.0, 60.0);
|
||||
assert!(at_least_body.0 >= at_least_header.1 - 0.01 && at_least_body.1 <= at_least_footer.0 + 0.01, "{at_least_body:?}");
|
||||
assert!(pages < at_least_pages, "exact margins: {pages} pages, at least: {at_least_pages}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_keeps_a_multiple_spaced_picture_line_while_the_picture_fits() {
|
||||
// A paragraph holding only a picture, at 1.15 spacing, as the page's last line stays on the
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! STYLEREF fields in headers and footers (#775): each page shows its own result.
|
||||
|
||||
use crate::*;
|
||||
use wordcraft_doc::numbering::Level;
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
use wordcraft_doc::props::{CharProps, NumRef};
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
use wordcraft_doc::{ListKind, PartKind, Pos, para_block};
|
||||
|
||||
fn field(instr: &str) -> InlineObject {
|
||||
@@ -102,6 +104,38 @@ fn character_styles_and_paragraph_numbers() {
|
||||
assert_eq!(h[3], ["two", "3", "3.a", "3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styleref_preserves_a_counted_zero_in_plain_and_full_numbering() {
|
||||
crate::test_fonts();
|
||||
let codes = [r#"STYLEREF "Heading 1" \n \t"#, r#"STYLEREF "Heading 2" \n \t"#, r#"STYLEREF "Heading 2" \w"#, r#"STYLEREF "Heading 2" \r"#];
|
||||
let mut d = doc(&[("Heading1", "Chapter", false), ("Heading2", "Section", false)], &codes);
|
||||
let numbering = Arc::make_mut(&mut d.numbering);
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
let instance = &mut numbering.nums[0];
|
||||
instance.start_overrides = vec![(0, 0)];
|
||||
instance.level_overrides = vec![
|
||||
(0, Level { text: "Chapter%1.".into(), ..Default::default() }),
|
||||
(1, Level { format: NumFormat::DecimalZero, text: "%2.".into(), ..Default::default() }),
|
||||
];
|
||||
for level in 0..=1u8 {
|
||||
d.para_mut(StoryRef::Body, &Path::top(usize::from(level))).unwrap().props.numbering = Some(NumRef { num, level });
|
||||
}
|
||||
|
||||
let mut cache = LayoutCache::new();
|
||||
let laid_out = layout(&d, &mut cache, &LayoutOptions::default());
|
||||
let page = &laid_out.pages[0];
|
||||
let labels: Vec<&str> = page
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
Placed::Lines { para, .. } => para.label.as_ref().map(|label| label.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels, ["Chapter0.", "01."]);
|
||||
assert_eq!(shown(&page.header), ["0", "01", "0.01", "0.01"]);
|
||||
}
|
||||
|
||||
/// #4985: a heading on a "none" list level (its label is its text, `Note`) shows its parent's
|
||||
/// number in full context (`\w`): the parent is not taken for the heading's own level, which
|
||||
/// has no number to list.
|
||||
|
||||
@@ -171,3 +171,131 @@ fn a_click_outside_a_floating_table_in_a_vertical_section_skips_its_cells() {
|
||||
// Inside the table a click still lands in a cell.
|
||||
assert!(l.hit(0, cx, cy, StoryRef::Body).unwrap().path.0.len() > 1);
|
||||
}
|
||||
|
||||
/// #8986: in vertical text the next line is the next paragraph's, left of this one, at the same
|
||||
/// distance along it; the first and last lines have no previous/next.
|
||||
#[test]
|
||||
fn turned_line_steps_to_the_adjacent_column() {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text("abc\ndef\nghi");
|
||||
d.last_section.text_direction = TextDirection::Down;
|
||||
let l = lay(&d);
|
||||
let p = Pos::body(1, 1);
|
||||
assert_eq!(l.turn_at(&p, 0), Some(TextDirection::Down));
|
||||
let (next, g) = l.turned_line(&p, None, true, 0).unwrap();
|
||||
assert_eq!((next.path, next.off), (Path::top(2), 1));
|
||||
let (prev, _) = l.turned_line(&p, Some(g), false, 0).unwrap();
|
||||
assert_eq!((prev.path, prev.off), (Path::top(0), 1));
|
||||
assert!(l.turned_line(&Pos::body(2, 0), None, true, 0).is_none());
|
||||
assert_eq!(lay(&Document::from_text("abc")).turn_at(&Pos::body(0, 0), 0), None);
|
||||
}
|
||||
|
||||
/// #8986: in a table whose cells run vertical text, the next line is one of the same cell, never
|
||||
/// another cell's (a cell's only line has no previous/next).
|
||||
#[test]
|
||||
fn turned_line_stays_in_its_table_cell() {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text("before");
|
||||
let mut t = wordcraft_doc::Table::new(1, 3, 468.0);
|
||||
for (i, c) in t.rows[0].cells.iter_mut().enumerate() {
|
||||
c.props.text_direction = TextDirection::Down;
|
||||
let paras = if i == 1 { ["abc", "def"].as_slice() } else { ["xyz"].as_slice() };
|
||||
c.blocks = paras.iter().map(|s| wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(s, Default::default()))).collect();
|
||||
}
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let at = |cell: u32, para: u32, off: usize| Pos { story: StoryRef::Body, path: Path(vec![1, 0, cell, para]), off };
|
||||
let (next, _) = l.turned_line(&at(1, 0, 1), None, true, 0).unwrap();
|
||||
assert_eq!((next.path, next.off), (Path(vec![1, 0, 1, 1]), 1));
|
||||
assert!(l.turned_line(&at(1, 1, 1), None, true, 0).is_none());
|
||||
assert!(l.turned_line(&at(1, 0, 1), None, false, 0).is_none());
|
||||
for cell in [0, 2] {
|
||||
assert!(l.turned_line(&at(cell, 0, 1), None, true, 0).is_none());
|
||||
assert!(l.turned_line(&at(cell, 0, 1), None, false, 0).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// #9151: in a multi-page vertical section, stepping past the last column of page 0 enters the
|
||||
/// first column of page 1, and stepping back from page 1's first column returns to page 0.
|
||||
#[test]
|
||||
fn turned_line_crosses_page_boundary() {
|
||||
crate::test_fonts();
|
||||
let text = (0..60).map(|i| format!("col{i:02}")).collect::<Vec<_>>().join("\n");
|
||||
let mut d = Document::from_text(&text);
|
||||
d.last_section.text_direction = TextDirection::Down;
|
||||
let l = lay(&d);
|
||||
assert!(l.pages.len() >= 2, "expected multiple pages, got {}", l.pages.len());
|
||||
|
||||
let page0_last_para = l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
crate::Placed::Lines { path, .. } => Some(path.last()),
|
||||
_ => None,
|
||||
})
|
||||
.next_back()
|
||||
.expect("page 0 has turned lines");
|
||||
let page1_first_para = l.pages[1]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
crate::Placed::Lines { path, .. } => Some(path.last()),
|
||||
_ => None,
|
||||
})
|
||||
.next()
|
||||
.expect("page 1 has turned lines");
|
||||
assert_eq!(page1_first_para, page0_last_para + 1);
|
||||
|
||||
let last_on_p0 = Pos::body(page0_last_para, 2);
|
||||
let (next, g) = l.turned_line(&last_on_p0, None, true, 0).expect("steps onto page 1");
|
||||
assert_eq!((&next.path, next.off), (&Path::top(page1_first_para), 2));
|
||||
|
||||
let (back, _) = l.turned_line(&next, Some(g), false, 1).expect("steps back onto page 0");
|
||||
assert_eq!((back.path, back.off), (Path::top(page0_last_para), 2));
|
||||
}
|
||||
|
||||
/// #9151: a header is laid out again on every page, so a vertical text box in it holds the same
|
||||
/// columns on each; stepping past its last or first column stays in the box instead of entering
|
||||
/// the copy on the adjacent page.
|
||||
#[test]
|
||||
fn turned_line_does_not_cross_pages_in_a_header_text_box() {
|
||||
use wordcraft_doc::props::TextVert;
|
||||
use wordcraft_doc::{PartKind, TextBody, para_block};
|
||||
crate::test_fonts();
|
||||
let text = (0..200).map(|i| format!("line{i:03}")).collect::<Vec<_>>().join("\n");
|
||||
let mut d = Document::from_text(&text);
|
||||
let boxed = d.add_part(
|
||||
PartKind::TextBox,
|
||||
vec![para_block(Paragraph::with_text("ab", Default::default())), para_block(Paragraph::with_text("cd", Default::default()))],
|
||||
);
|
||||
if let Some(p) = d.parts.get_mut(&boxed) {
|
||||
p.body = TextBody { vert: TextVert::Vert, ..Default::default() };
|
||||
}
|
||||
let shape = InlineObject::Shape {
|
||||
kind: wordcraft_doc::para::ShapeKind::TextBox,
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: Default::default(),
|
||||
story: Some(boxed),
|
||||
effects: Default::default(),
|
||||
freeform: None,
|
||||
extra: Default::default(),
|
||||
};
|
||||
let mut p = Paragraph::with_text("Header", Default::default());
|
||||
p.insert_object(6, shape, &Default::default()).unwrap();
|
||||
let header = d.add_part(PartKind::Header, vec![para_block(p)]);
|
||||
d.last_section.headers.default = Some(header);
|
||||
let l = lay(&d);
|
||||
assert!(l.pages.len() >= 4, "expected several pages, got {}", l.pages.len());
|
||||
let at = |para: usize, off: usize| Pos { story: StoryRef::Part(boxed), path: Path::top(para), off };
|
||||
// Within the box, the columns still step.
|
||||
assert_eq!(l.turned_line(&at(0, 1), None, true, 1).map(|(p, _)| p.path), Some(Path::top(1)));
|
||||
// Past its edges, there is no further column, on any page.
|
||||
for page in 1..3 {
|
||||
assert!(l.turned_line(&at(1, 1), None, true, page).is_none(), "next from the last column on page {page}");
|
||||
assert!(l.turned_line(&at(0, 1), None, false, page).is_none(), "previous from the first column on page {page}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub(crate) fn unturned_sect(s: &SectionProps, body_top: f32) -> SectionProps {
|
||||
v.page_w = s.page_h;
|
||||
v.page_h = s.page_w;
|
||||
v.gutter = 0.0;
|
||||
let (top, right, bottom, left) = (body_top, s.margin_right, s.margin_bottom, s.margin_left + s.gutter);
|
||||
let (top, right, bottom, left) = (body_top, s.margin_right, s.margin_bottom.abs(), s.margin_left + s.gutter);
|
||||
// The unturned frame's (u, v) lands at (W - v, u) for `Down` and (v, H - u) for `Up`: its
|
||||
// top edge is the real right edge (left for `Up`), its left edge the real top (bottom).
|
||||
match s.text_direction {
|
||||
|
||||
@@ -20,4 +20,7 @@ log = { workspace = true }
|
||||
# lookup, which do not build for wasm32.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
wordcraft-control-key = { workspace = true }
|
||||
craft = { workspace = true, features = ["automation"] }
|
||||
# The control channel's client, and agents in the open window (`live`): the shared live client,
|
||||
# the agent folders and the app's saved agent settings, read as its settings store reads them.
|
||||
craft = { workspace = true, features = ["automation", "automation-agents", "control", "settings"] }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -16,4 +16,9 @@ pub trait Backend {
|
||||
fn has_ui(&self) -> bool;
|
||||
/// Short human description ("headless", "connected to 127.0.0.1:7981").
|
||||
fn describe(&self) -> String;
|
||||
/// The `agent_folders` tool's answer: `read_folder` and `write_folder`, each a path or `null`
|
||||
/// (`craft::control::agents::folders_answer`).
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
Err("this session has no agent folders".into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,9 @@ pub struct Remote {
|
||||
/// The connection leads to the app's 127.0.0.1: the control token may be sent.
|
||||
send_key: bool,
|
||||
find_token: TokenFinder,
|
||||
/// Sign in with the challenge handshake: the app proves it holds the token before anything
|
||||
/// derived from it is sent ([`Remote::window`]).
|
||||
challenge: bool,
|
||||
}
|
||||
|
||||
impl Remote {
|
||||
@@ -145,7 +148,7 @@ impl Remote {
|
||||
}
|
||||
|
||||
fn connect_with(addr: &str, find_token: TokenFinder) -> std::io::Result<Self> {
|
||||
let mut r = Self { addr: addr.to_string(), client: None, connected: false, send_key: false, find_token };
|
||||
let mut r = Self { addr: addr.to_string(), client: None, connected: false, send_key: false, find_token, challenge: false };
|
||||
r.reconnect().map_err(|c| std::io::Error::other(r.connect_error(c, false)))?;
|
||||
if let Some(w) = r.key_warning() {
|
||||
log::warn!("{w}");
|
||||
@@ -156,7 +159,16 @@ impl Remote {
|
||||
/// A remote that connects on first use: the app may start after the MCP server, and a
|
||||
/// server that exits at once reads as failed for the client's whole session (#4078).
|
||||
pub fn lazy(addr: &str) -> Self {
|
||||
Self { addr: addr.to_string(), client: None, connected: false, send_key: false, find_token: Box::new(find_token) }
|
||||
Self { addr: addr.to_string(), client: None, connected: false, send_key: false, find_token: Box::new(find_token), challenge: false }
|
||||
}
|
||||
|
||||
/// The open window the agent link published (`craft::automation::agents::Window`): its
|
||||
/// loopback address and the token from its token file. It connects on first use and signs in
|
||||
/// with the challenge handshake, so a program that took the port of an app that quit learns
|
||||
/// nothing derived from the token.
|
||||
pub fn window(addr: &str, token: String) -> Self {
|
||||
let find_token: TokenFinder = Box::new(move |_| Ok(Token { value: token.clone(), from_file: false }));
|
||||
Self { addr: addr.to_string(), client: None, connected: false, send_key: false, find_token, challenge: true }
|
||||
}
|
||||
|
||||
/// The address the app is reached at, as given.
|
||||
@@ -205,7 +217,9 @@ impl Remote {
|
||||
let mut refused_before = false;
|
||||
loop {
|
||||
let token = (self.find_token)(&self.addr)?;
|
||||
match ControlClient::connect(sa, &token.value) {
|
||||
let signed_in =
|
||||
if self.challenge { ControlClient::connect_challenged(sa, &token.value) } else { ControlClient::connect(sa, &token.value) };
|
||||
match signed_in {
|
||||
Ok(client) => return Ok(client),
|
||||
Err(ConnectError::Refused(_)) if token.from_file && !refused_before => refused_before = true,
|
||||
Err(ConnectError::Refused(e)) => return Err(Connect::Refused(e)),
|
||||
|
||||
+21
-5
@@ -1,17 +1,22 @@
|
||||
//! WordCraft's MCP server (Model Context Protocol, JSON-RPC 2.0 over stdio).
|
||||
//!
|
||||
//! Two backends: [`Headless`] runs an in-process editing session (no window); [`backend::Remote`]
|
||||
//! talks to a running WordCraft app through its control channel (`wordcraft --control PORT`), so
|
||||
//! agents can also click, type and screenshot the real UI.
|
||||
//! Two backends: [`Headless`] runs an in-process editing session (no window); [`Live`] sends each
|
||||
//! tool call to the open WordCraft window while the ArtCraft Launcher's switch lets agents use it
|
||||
//! (through [`backend::Remote`], the app's control channel), so agents can also click, type and
|
||||
//! screenshot the real UI, and otherwise to a headless session.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod backend;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod live;
|
||||
pub mod server;
|
||||
pub mod tools;
|
||||
|
||||
pub use backend::Backend;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use backend::Remote;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use live::{Live, LiveConfig};
|
||||
pub use server::Server;
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -21,8 +26,7 @@ use wordcraft_engine::Session;
|
||||
use wordcraft_engine::file_access::{self, AutomationRoots};
|
||||
|
||||
/// Methods that need the desktop app.
|
||||
pub const NEEDS_APP: &str =
|
||||
"needs the desktop app; `wordcraft-cli mcp --connect` is refused until the app confines its control channel to automation roots (#3695)";
|
||||
pub const NEEDS_APP: &str = "needs the open WordCraft window: turn on AI agents in ArtCraft Launcher › Settings › AI agents, open WordCraft, and use plain `wordcraft-cli mcp` (without --headless)";
|
||||
|
||||
/// An in-process session.
|
||||
pub struct Headless {
|
||||
@@ -38,6 +42,11 @@ impl Headless {
|
||||
self
|
||||
}
|
||||
|
||||
/// The folders the session's commands are confined to, if any.
|
||||
pub fn automation_roots(&self) -> Option<&Arc<AutomationRoots>> {
|
||||
self.roots.as_ref()
|
||||
}
|
||||
|
||||
/// Answer `method`; a document method addressed to another open document (`doc`) runs on
|
||||
/// that document, and the active one stays active.
|
||||
fn answer(&mut self, method: &str, mut params: Value) -> Result<Value, String> {
|
||||
@@ -111,6 +120,13 @@ impl Backend for Headless {
|
||||
fn describe(&self) -> String {
|
||||
"headless session (no window)".into()
|
||||
}
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
let shown = |p: Option<&std::path::Path>| p.map(|p| p.to_string_lossy().into_owned());
|
||||
let roots = self.roots.as_deref();
|
||||
Ok(
|
||||
json!({"read_folder": shown(roots.and_then(AutomationRoots::read_root)), "write_folder": shown(roots.and_then(AutomationRoots::write_root))}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//! Plain `wordcraft-cli mcp`: each tool call goes to the open WordCraft window while the person
|
||||
//! lets agents use it (the ArtCraft Launcher's switch), found through the connection file its
|
||||
//! agent link publishes, and otherwise to a session without a window. The file is read again
|
||||
//! before every call, so the app may start, quit or move to another port while the MCP client
|
||||
//! stays connected, and the client's configuration holds no port and no token.
|
||||
//!
|
||||
//! While agents may use the app but it is closed, the closed-app choice of File › Options › Agents
|
||||
//! (or `--when-closed`) decides: start WordCraft and wait for it, work without a window in the
|
||||
//! agent folders, or answer with an error that asks to open it. A session that went headless stays
|
||||
//! headless, so documents don't move under the agent.
|
||||
//!
|
||||
//! The lookup is the framework's, shared by every Craft app (`craft::automation::agents::Live`);
|
||||
//! this module supplies WordCraft's parts: its saved agent settings, its window client
|
||||
//! ([`Remote::window`], with the challenge handshake) and its headless session ([`Headless`],
|
||||
//! always confined to folders).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft::automation::agents::{self, AgentSettings, Consent, HeadlessFolders, LaunchFn, Route, Window};
|
||||
use craft::settings::{Location, OpenOptions, Settings, SettingsStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use wordcraft_engine::file_access::AutomationRoots;
|
||||
|
||||
use crate::Headless;
|
||||
use crate::backend::{Backend, Remote};
|
||||
|
||||
pub use craft::automation::agents::WhenAppClosed;
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names WordCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "wordcraft";
|
||||
/// The app's name in messages and in its default agent folder.
|
||||
pub const APP_NAME: &str = "WordCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
const APP_EXE: &str = "wordcraft";
|
||||
|
||||
/// The part of the app's saved settings `mcp` reads: File › Options › Agents, the `integrations`
|
||||
/// section of `config.toml`, read as the app's settings store reads it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct AgentPrefs {
|
||||
integrations: AgentSettings,
|
||||
}
|
||||
|
||||
impl Settings for AgentPrefs {
|
||||
const APP_ID: &'static str = "wordcraft";
|
||||
const SCHEMA_VERSION: u32 = 1;
|
||||
}
|
||||
|
||||
/// The agent settings saved in the settings folder `dir`; the defaults when nothing is saved or
|
||||
/// the file can't be read (a value that doesn't fit resets only itself, as in the app). The CLI
|
||||
/// never fails over the app's settings.
|
||||
pub fn read_agent_settings(dir: &Path) -> AgentSettings {
|
||||
SettingsStore::<AgentPrefs>::read(&OpenOptions::new(Location::Dir(dir.to_path_buf()))).0.integrations
|
||||
}
|
||||
|
||||
/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`): without it the launcher's
|
||||
/// switch means nothing and `mcp` is headless, as before the switch.
|
||||
pub fn mcp_flag() -> bool {
|
||||
agents::mcp_flag()
|
||||
}
|
||||
|
||||
/// Whether the person lets agents use the open window now: the suite's `AI-MCP` flag and the
|
||||
/// launcher's switch. WordCraft had no consent of its own before the switch.
|
||||
pub fn agents_allowed_now() -> bool {
|
||||
agents::agents_allowed(agents::mcp_flag(), agents::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// What `mcp` needs to find the window, and to work without one.
|
||||
pub struct LiveConfig {
|
||||
/// The app's settings folder: connection file, token file and settings.
|
||||
pub config_dir: PathBuf,
|
||||
/// Overrides the closed-app choice (`--when-closed`).
|
||||
pub when_closed: Option<WhenAppClosed>,
|
||||
/// The folders a headless session uses (`--automation-read-root`, `--automation-write-root`);
|
||||
/// while agents may use the app they replace its agent folders.
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// The author of a headless session's tracked changes and comments (`--author`).
|
||||
pub author: Option<String>,
|
||||
/// Starts the app; `None` when this install can't ([`launcher`]).
|
||||
pub launch: Option<LaunchFn>,
|
||||
pub launch_timeout: Duration,
|
||||
/// Whether the person lets agents use the app now ([`agents_allowed_now`]); tests replace it.
|
||||
pub allowed: fn() -> bool,
|
||||
/// The folder agents use when the person chose none: `Documents/ArtCraft/Agents/WordCraft`;
|
||||
/// tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The app with its settings in `config_dir`, as it is installed.
|
||||
pub fn new(config_dir: PathBuf) -> Self {
|
||||
Self {
|
||||
config_dir,
|
||||
when_closed: None,
|
||||
read_root: None,
|
||||
write_root: None,
|
||||
author: None,
|
||||
launch: None,
|
||||
launch_timeout: agents::LAUNCH_TIMEOUT,
|
||||
allowed: agents_allowed_now,
|
||||
default_folder: craft::control::agents::default_folder(APP_NAME),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::new`] for the app's own settings folder (`WORDCRAFT_PROFILE_DIR`, otherwise the
|
||||
/// platform's); `None` without one (no home folder).
|
||||
pub fn installed() -> Option<Self> {
|
||||
wordcraft_control_key::settings_dir().map(Self::new)
|
||||
}
|
||||
}
|
||||
|
||||
type Shared = agents::Live<Arc<Mutex<Remote>>, Arc<Mutex<Headless>>>;
|
||||
|
||||
/// The backend of plain `mcp`; see the module docs.
|
||||
pub struct Live {
|
||||
shared: Shared,
|
||||
config_dir: PathBuf,
|
||||
default_folder: Option<PathBuf>,
|
||||
/// What `agent_folders` needs to tell where the next call will work before any call ran.
|
||||
when_closed: Option<WhenAppClosed>,
|
||||
read_root: Option<PathBuf>,
|
||||
write_root: Option<PathBuf>,
|
||||
allowed: fn() -> bool,
|
||||
}
|
||||
|
||||
/// A headless session confined to `folders`: never one without folders (rule 18).
|
||||
fn headless(folders: &HeadlessFolders, author: Option<&str>) -> Result<Arc<Mutex<Headless>>, String> {
|
||||
let read = folders.read.first().map(PathBuf::as_path);
|
||||
let roots = AutomationRoots::new(read, folders.write.as_deref())?.ok_or_else(|| {
|
||||
format!(
|
||||
"no folders to work in: give --automation-read-root DIR and --automation-write-root DIR, or turn on AI agents in ArtCraft Launcher › Settings › AI agents to use {APP_NAME}'s agent folder"
|
||||
)
|
||||
})?;
|
||||
let mut session = Headless::default().with_automation_roots(Some(roots));
|
||||
if let Some(name) = author {
|
||||
session.session.run("file.setAuthor", &serde_json::json!({"name": name})).map_err(|e| format!("--author: {e}"))?;
|
||||
}
|
||||
Ok(Arc::new(Mutex::new(session)))
|
||||
}
|
||||
|
||||
impl Live {
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, when_closed, read_root, write_root, author, launch, launch_timeout, allowed, default_folder } = cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_agent_settings(dir));
|
||||
let connect = |w: &Window| Ok(Arc::new(Mutex::new(Remote::window(&w.addr(), w.token.clone()))));
|
||||
let make_headless = move |folders: &HeadlessFolders| headless(folders, author.as_deref());
|
||||
let mut shared = agents::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, make_headless);
|
||||
shared.when_closed = when_closed;
|
||||
shared.read_roots = read_root.clone().into_iter().collect();
|
||||
shared.write_root = write_root.clone();
|
||||
shared.launch = launch;
|
||||
shared.launch_timeout = launch_timeout;
|
||||
shared.default_folder = default_folder.clone();
|
||||
Self { shared: agents::Live::new(shared), config_dir, default_folder, when_closed, read_root, write_root, allowed }
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Live {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.shared.resolve()? {
|
||||
Route::Window(window) => window.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(session) => session.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
matches!(self.shared.current(), Some(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
match self.shared.current() {
|
||||
Some(Route::Window(window)) => window.lock().unwrap_or_else(PoisonError::into_inner).describe(),
|
||||
Some(Route::Headless(_)) => "headless session (no window)".into(),
|
||||
None => {
|
||||
format!("the open {APP_NAME} window while AI agents are on in ArtCraft Launcher › Settings › AI agents, otherwise a headless session")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A headless session's own folders; the window's when calls go to it: its saved agent folders,
|
||||
/// the default agent folder for an empty one, as the app's agent link opens them. Before the
|
||||
/// first call, the folders the next call will work in, found as `Live` would without starting
|
||||
/// anything: the window's while one accepts agents or the app would be opened or asked for,
|
||||
/// otherwise those of the headless session it would make (the folders given to `mcp` win).
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
let answer = |folders: &craft::control::agents::AgentFolders| Ok(craft::control::agents::folders_answer(folders));
|
||||
match self.shared.current() {
|
||||
Some(Route::Headless(session)) => return session.lock().unwrap_or_else(PoisonError::into_inner).agent_folders(),
|
||||
Some(Route::Window(_)) => return answer(&read_agent_settings(&self.config_dir).folders_with(self.default_folder.as_deref())),
|
||||
None => {}
|
||||
}
|
||||
let settings = read_agent_settings(&self.config_dir);
|
||||
let window = matches!(agents::find_window(&self.config_dir, APP_NAME), Ok(Some(_)));
|
||||
let allowed = (self.allowed)() && settings.allow_agent_control;
|
||||
let headless = !window && (!allowed || self.when_closed.unwrap_or(settings.when_app_closed) == WhenAppClosed::Headless);
|
||||
if !headless {
|
||||
return answer(&settings.folders_with(self.default_folder.as_deref()));
|
||||
}
|
||||
let (read, write) = (self.read_root.clone(), self.write_root.clone());
|
||||
if !allowed {
|
||||
let mut folders = craft::control::agents::AgentFolders::default();
|
||||
(folders.read, folders.write) = (read, write);
|
||||
return answer(&folders);
|
||||
}
|
||||
// Only looked up (and the default made) when the command leaves a direction open, as `Live` does.
|
||||
let mut folders = if read.is_some() && write.is_some() { Default::default() } else { settings.folders_with(self.default_folder.as_deref()) };
|
||||
folders.read = read.or(folders.read);
|
||||
folders.write = write.or(folders.write);
|
||||
answer(&folders)
|
||||
}
|
||||
}
|
||||
|
||||
/// How to start the desktop app that ships beside the CLI at `cli` (detached, with no standard
|
||||
/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client).
|
||||
pub fn launcher(cli: &Path) -> Option<LaunchFn> {
|
||||
agents::launcher(cli, APP_EXE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "live/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Plain `wordcraft-cli mcp` (`live.rs`): calls reach the open window through its connection file
|
||||
//! with the challenge handshake, and otherwise run headless, never unconfined. The lookup itself
|
||||
//! (closed-app choice, launch, stale files) has its own tests in craft-control.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use craft::automation::agents::{Connection, TOKEN_FILE, write_connection};
|
||||
use craft::automation::security::{AuthStep, CHALLENGE_METHOD, ServerHandshake};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// A fresh folder, removed when dropped.
|
||||
struct Folder(PathBuf);
|
||||
|
||||
impl Folder {
|
||||
fn new(tag: &str) -> Self {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-live-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
fn sub(&self, name: &str) -> PathBuf {
|
||||
let dir = self.0.join(name);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A config for the settings folder `dir`, the person letting agents in or not, an agent folder in
|
||||
/// `dir`, and nothing to start.
|
||||
fn config(dir: &Folder, allowed: fn() -> bool) -> LiveConfig {
|
||||
let mut cfg = LiveConfig::new(dir.sub("settings"));
|
||||
cfg.allowed = allowed;
|
||||
cfg.default_folder = Some(dir.0.join("Agents").join("WordCraft"));
|
||||
cfg.when_closed = Some(WhenAppClosed::Error);
|
||||
cfg
|
||||
}
|
||||
|
||||
/// The window's control server as the app's agent link runs it: the shared handshake with `TOKEN`
|
||||
/// on loopback, its connection file in `settings` and the token in an owner-only file. Answers
|
||||
/// every request with its method; sends the first frame of each connection on `first`.
|
||||
fn serve_window(settings: &std::path::Path) -> mpsc::Receiver<Value> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let token_file = settings.join(TOKEN_FILE);
|
||||
std::fs::write(&token_file, TOKEN).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
write_connection(settings, &Connection::new(port, token_file, "WordCraft test")).unwrap();
|
||||
let (first, frames) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { return };
|
||||
let first = first.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut out = stream;
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut authenticated = false;
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).is_ok_and(|n| n > 0) {
|
||||
let request: Value = serde_json::from_str(&line).unwrap_or(Value::Null);
|
||||
let reply = if authenticated {
|
||||
json!({"id": request["id"], "ok": true, "result": {"window": request["method"]}})
|
||||
} else {
|
||||
if request["id"] == json!(0) || request["method"] == "auth" && request["id"] == json!(1) {
|
||||
let _ = first.send(request.clone());
|
||||
}
|
||||
let (reply, step) = handshake.reply(&line, TOKEN);
|
||||
authenticated = step == AuthStep::Authenticated;
|
||||
if step == AuthStep::Rejected {
|
||||
let _ = out.write_all(format!("{reply}\n").as_bytes());
|
||||
return;
|
||||
}
|
||||
reply
|
||||
};
|
||||
let _ = out.write_all(format!("{reply}\n").as_bytes());
|
||||
line.clear();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
frames
|
||||
}
|
||||
|
||||
/// While agents may use the app and its window publishes a connection, calls go to the window,
|
||||
/// signed in with the challenge handshake: the token never crosses the wire.
|
||||
#[test]
|
||||
fn a_call_reaches_the_open_window_with_the_challenge_handshake() {
|
||||
let dir = Folder::new("window");
|
||||
let cfg = config(&dir, || true);
|
||||
let frames = serve_window(&cfg.config_dir);
|
||||
let mut live = Live::new(cfg);
|
||||
let reply = live.call("document.inspect", json!({})).unwrap();
|
||||
assert_eq!(reply["window"], "document.inspect");
|
||||
assert!(live.has_ui());
|
||||
let challenge = frames.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
assert_eq!(challenge["method"], CHALLENGE_METHOD, "the first frame is the challenge");
|
||||
let proof = frames.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
assert!(proof["params"].get("token").is_none() && !proof.to_string().contains(TOKEN), "{proof}");
|
||||
}
|
||||
|
||||
/// Without the launcher's switch (the app then publishes no window) a call runs headless in the
|
||||
/// folders given to the command; with no folders at all it is refused rather than run unconfined.
|
||||
#[test]
|
||||
fn without_the_switch_calls_run_headless_and_never_unconfined() {
|
||||
let dir = Folder::new("off");
|
||||
let mut live = Live::new(config(&dir, || false));
|
||||
let refused = live.call("document.inspect", json!({})).unwrap_err();
|
||||
assert!(refused.contains("--automation-read-root"), "{refused}");
|
||||
|
||||
let work = dir.sub("work");
|
||||
let mut cfg = config(&dir, || false);
|
||||
cfg.read_root = Some(work.clone());
|
||||
cfg.write_root = Some(work.clone());
|
||||
let mut live = Live::new(cfg);
|
||||
assert!(live.call("document.inspect", json!({})).is_ok());
|
||||
assert!(!live.has_ui(), "headless, not the window");
|
||||
let outside = dir.0.join("outside.docx");
|
||||
assert!(live.call("engine.execute", json!({"command": "file.save", "params": {"path": outside}})).is_err());
|
||||
assert!(!outside.exists());
|
||||
let folders = live.agent_folders().unwrap();
|
||||
assert!(folders["write_folder"].as_str().is_some_and(|f| f.ends_with("work")), "{folders}");
|
||||
}
|
||||
|
||||
/// With agents allowed and the app closed, "work without a window" uses the agent folder: files go
|
||||
/// there and nowhere else.
|
||||
#[test]
|
||||
fn a_closed_app_works_without_a_window_in_the_agent_folder() {
|
||||
let dir = Folder::new("closed");
|
||||
let mut cfg = config(&dir, || true);
|
||||
cfg.when_closed = Some(WhenAppClosed::Headless);
|
||||
let agent_folder = cfg.default_folder.clone().unwrap();
|
||||
let mut live = Live::new(cfg);
|
||||
let inside = agent_folder.join("made.docx");
|
||||
live.call("engine.execute", json!({"command": "file.save", "params": {"path": inside}})).unwrap();
|
||||
assert!(inside.is_file());
|
||||
let outside = dir.0.join("outside.docx");
|
||||
assert!(live.call("engine.execute", json!({"command": "file.save", "params": {"path": outside}})).is_err());
|
||||
assert!(!outside.exists());
|
||||
}
|
||||
|
||||
/// The agent settings come from the app's `config.toml` as its store reads them: a value that
|
||||
/// doesn't fit resets only itself, and a missing or broken file gives the defaults.
|
||||
#[test]
|
||||
fn the_agent_settings_come_from_the_apps_config_file() {
|
||||
let dir = Folder::new("prefs");
|
||||
let settings = dir.sub("settings");
|
||||
assert_eq!(read_agent_settings(&settings), AgentSettings::default());
|
||||
std::fs::write(settings.join("config.toml"), "not toml [").unwrap();
|
||||
assert_eq!(read_agent_settings(&settings), AgentSettings::default());
|
||||
std::fs::write(
|
||||
settings.join("config.toml"),
|
||||
"schema_version = 1\ntab = \"home\"\n[integrations]\nwhenAppClosed = \"headless\"\nreadRoot = \"/in\"\ncontrolPort = \"x\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let read = read_agent_settings(&settings);
|
||||
assert_eq!(read.when_app_closed, WhenAppClosed::Headless);
|
||||
assert_eq!(read.read_folder(), Some(PathBuf::from("/in")));
|
||||
assert_eq!(read.control_port, AgentSettings::default().control_port, "the bad port alone takes its default");
|
||||
|
||||
// The window's folders, as `agent_folders` reports them before any call: the saved ones, the
|
||||
// default agent folder for an empty one.
|
||||
let mut live = Live::new(config(&dir, || true));
|
||||
let folders = live.agent_folders().unwrap();
|
||||
assert_eq!(folders["read_folder"], json!("/in"));
|
||||
assert!(folders["write_folder"].as_str().is_some_and(|f| f.ends_with("WordCraft")), "{folders}");
|
||||
}
|
||||
|
||||
/// Before the first call, `agent_folders` names the folders the next call will work in: with the
|
||||
/// app closed and "work without a window", the folders given to `mcp` win over the agent folder.
|
||||
#[test]
|
||||
fn agent_folders_before_the_first_call_follow_the_given_roots() {
|
||||
let dir = Folder::new("folders-first");
|
||||
let work = dir.sub("work");
|
||||
let mut cfg = config(&dir, || true);
|
||||
cfg.when_closed = Some(WhenAppClosed::Headless);
|
||||
cfg.read_root = Some(work.clone());
|
||||
cfg.write_root = Some(work.clone());
|
||||
let mut live = Live::new(cfg);
|
||||
let before = live.agent_folders().unwrap();
|
||||
live.call("document.inspect", json!({})).unwrap();
|
||||
let after = live.agent_folders().unwrap();
|
||||
assert!(before["write_folder"].as_str().is_some_and(|f| f.ends_with("work")), "{before}");
|
||||
assert!(after["write_folder"].as_str().is_some_and(|f| f.ends_with("work")), "{after}");
|
||||
}
|
||||
@@ -406,11 +406,12 @@ fn every_documented_call_passes_the_argument_check() {
|
||||
("click", json!({"x": 1, "y": 2, "count": 2, "button": "right", "shift": true, "alt": true, "cmd": true, "ctrl": true, "command": true})),
|
||||
("key", json!({"key": "B", "shift": true, "alt": true, "cmd": true, "ctrl": true, "command": true})),
|
||||
("ui_inspect", json!({})),
|
||||
("agent_folders", json!({})),
|
||||
] {
|
||||
assert_eq!(check_arguments(defs, name, &args), Ok(()), "{name}");
|
||||
}
|
||||
// Every tool is covered above.
|
||||
assert_eq!(defs.len(), 18);
|
||||
assert_eq!(defs.len(), 19);
|
||||
}
|
||||
|
||||
/// Hostile and random input never panics or breaks the stream: every reply is one JSON line.
|
||||
|
||||
+40
-2
@@ -4,9 +4,10 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::backend::Backend;
|
||||
|
||||
/// An image tool result from a reply carrying base64 PNG in `png`.
|
||||
/// An image tool result from a reply carrying base64 PNG in `png` (the engine's renders) or
|
||||
/// `base64` (the window's `ui.screenshot`, the framework's capture reply).
|
||||
fn png_result(v: &Value, info: &Value) -> ToolResult {
|
||||
match v.get("png").and_then(Value::as_str) {
|
||||
match v.get("png").or_else(|| v.get("base64")).and_then(Value::as_str) {
|
||||
Some(png) if !png.is_empty() => ToolResult::image(png.to_string(), info),
|
||||
_ => ToolResult::error("the reply carried no picture"),
|
||||
}
|
||||
@@ -64,6 +65,21 @@ fn tool(name: &str, title: &str, desc: &str, schema: Value, ro: bool) -> Value {
|
||||
|
||||
/// Every MCP tool with its title, description, input schema and annotations (`tools/list`).
|
||||
pub fn tool_definitions() -> Value {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return listed_tools();
|
||||
// Where agents put and find files: the suite's tool, the same in every Craft app.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use craft::control::agents::{FOLDERS_TOOL, FOLDERS_TOOL_DESCRIPTION};
|
||||
let mut tools = listed_tools();
|
||||
if let Some(list) = tools.as_array_mut() {
|
||||
list.push(tool(FOLDERS_TOOL, "Agent folders", FOLDERS_TOOL_DESCRIPTION, obj(json!({}), &[]), true));
|
||||
}
|
||||
tools
|
||||
}
|
||||
}
|
||||
|
||||
fn listed_tools() -> Value {
|
||||
json!([
|
||||
tool(
|
||||
"list_commands",
|
||||
@@ -349,6 +365,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, a: &Value) -> ToolResult {
|
||||
"click" => wrap(b.call("ui.click", a.clone())),
|
||||
"key" => wrap(b.call("ui.key", a.clone())),
|
||||
"ui_inspect" => wrap(b.call("ui.inspect", json!({}))),
|
||||
"agent_folders" => wrap(b.agent_folders()),
|
||||
other => ToolResult::error(format!("unknown tool `{other}`")),
|
||||
}
|
||||
}
|
||||
@@ -416,6 +433,27 @@ mod tests {
|
||||
assert!(b.seen.take().expect("called").1.get("doc").is_none());
|
||||
}
|
||||
|
||||
/// The window's screenshot reply carries the picture as `base64`; the tool returns it as an image.
|
||||
#[test]
|
||||
fn a_window_screenshot_reply_is_an_image() {
|
||||
struct Window;
|
||||
impl Backend for Window {
|
||||
fn call(&mut self, _: &str, _: Value) -> Result<Value, String> {
|
||||
Ok(json!({"base64": "iVBORw0KGgo=", "mime": "image/png", "width": 2, "height": 1}))
|
||||
}
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
"window".into()
|
||||
}
|
||||
}
|
||||
let r = call_tool(&mut Window, "screenshot", &json!({}));
|
||||
assert!(!r.is_error, "{r:?}");
|
||||
assert_eq!(r.content[0]["type"], "image");
|
||||
assert_eq!(r.content[0]["data"], "iVBORw0KGgo=");
|
||||
}
|
||||
|
||||
/// The password has to be in the schema, or a client has no way to know it can be sent.
|
||||
#[test]
|
||||
fn the_schema_advertises_the_password_as_optional() {
|
||||
|
||||
+25
-13
@@ -351,8 +351,8 @@ impl Exporter<'_> {
|
||||
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
|
||||
let draws = shown.draws(it, &dopts);
|
||||
match it {
|
||||
Placed::Lines { story, path, para, .. } => {
|
||||
let idx = self.entry(*story, path, para);
|
||||
Placed::Lines { story, path, para, l0, l1, .. } => {
|
||||
let idx = self.entry(*story, path, para, *l0..*l1);
|
||||
for d in &draws {
|
||||
self.line_item(s, d, idx, *story, path);
|
||||
}
|
||||
@@ -412,21 +412,33 @@ impl Exporter<'_> {
|
||||
p.text_without(&dropped)
|
||||
}
|
||||
|
||||
/// The structure entry for a paragraph on this page (created on first sight, in reading order).
|
||||
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout) -> usize {
|
||||
if let Some(i) = self.tag_index.get(&(story, path.clone())) {
|
||||
return *i;
|
||||
}
|
||||
let kind: TagKind = match self.doc.para(story, path).map(|p| self.doc.styles.resolve_para(&p.props).outline_level) {
|
||||
Some(Some(l)) if l < 6 => {
|
||||
/// The structure entry for a paragraph on this page. A heading starts at its first visible line.
|
||||
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout, lines: std::ops::Range<usize>) -> usize {
|
||||
let key = (story, path.clone());
|
||||
let existing = self.tag_index.get(&key).copied();
|
||||
let heading: Option<TagKind> = match self.doc.para(story, path).map(|p| self.doc.styles.resolve_para(&p.props).outline_level) {
|
||||
Some(Some(l)) if l < 6 && lines.contains(&nav::first_heading_line(pl)) => {
|
||||
let title = self.doc.para(story, path).map(|p| self.title_text(p, pl).trim().chars().take(200).collect::<String>());
|
||||
Tag::Hn(NonZeroU16::new(u16::from(l) + 1).unwrap_or(NonZeroU16::MIN), title).into()
|
||||
Some(Tag::Hn(NonZeroU16::new(u16::from(l) + 1).unwrap_or(NonZeroU16::MIN), title).into())
|
||||
}
|
||||
_ => Tag::P.into(),
|
||||
_ => None,
|
||||
};
|
||||
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
|
||||
if let Some(i) = existing {
|
||||
// A break-only piece in an earlier column can already have opened an entry: empty, or
|
||||
// holding only the list number the layout still draws before a column break.
|
||||
if let Some(kind) = heading
|
||||
&& !matches!(self.tags[i].kind, TagKind::Hn(..))
|
||||
{
|
||||
self.tags[i].kind = kind;
|
||||
if self.tags[i].children.is_empty() {
|
||||
self.tags[i].at = self.at;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
self.tags.push(TagEntry { kind: heading.unwrap_or_else(|| Tag::P.into()), children: Vec::new(), source: Some(key.clone()), at: self.at });
|
||||
let i = self.tags.len() - 1;
|
||||
self.tag_index.insert((story, path.clone()), i);
|
||||
self.tag_index.insert(key, i);
|
||||
i
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
use wordcraft_doc::numbering::NumberingIndex;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
use super::{
|
||||
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, LinkTag, Outline, OutlineNode, Placed, Point, StoryRef, Target,
|
||||
XyzDestination, krilla, write,
|
||||
};
|
||||
|
||||
/// A leading page or column break can be placed separately from the heading.
|
||||
pub(super) fn first_heading_line(para: &wordcraft_layout::para::ParaLayout) -> usize {
|
||||
para.lines
|
||||
.iter()
|
||||
.take_while(|line| {
|
||||
matches!(line.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
|
||||
&& para
|
||||
.clusters
|
||||
.get(line.c0..line.c1)
|
||||
.is_some_and(|cs| cs.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::ColumnBreak | ClKind::Marker)))
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
impl Exporter<'_> {
|
||||
/// Where a bookmark is: (output page, x, y) — the page and line its start lands on, which
|
||||
/// in a paragraph split across pages need not be the paragraph's first page.
|
||||
@@ -80,6 +97,7 @@ impl Exporter<'_> {
|
||||
/// The outline from body headings (outline levels 1–9) on the exported pages.
|
||||
pub(crate) fn outline(&self, pages: &[usize]) -> Option<Outline> {
|
||||
let mut flat: Vec<(u8, String, usize, f32, f32)> = Vec::new();
|
||||
let numbering = NumberingIndex::new(&self.doc.numbering);
|
||||
for pi in pages {
|
||||
let Some((out, fit)) = self.out_index.get(pi) else { continue };
|
||||
let Some(page) = self.lay.pages.get(*pi) else { continue };
|
||||
@@ -87,27 +105,33 @@ impl Exporter<'_> {
|
||||
let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, x, y, .. } = it else { continue };
|
||||
let Some(p) = self.doc.para(StoryRef::Body, path) else { continue };
|
||||
let Some(level) = self.doc.styles.resolve_para(&p.props).outline_level else { continue };
|
||||
// A leading page break can be placed on the previous page without the heading.
|
||||
let first = para
|
||||
.lines
|
||||
.iter()
|
||||
.take_while(|line| {
|
||||
line.end == LineEnd::PageBreak
|
||||
&& para
|
||||
.clusters
|
||||
.get(line.c0..line.c1)
|
||||
.is_some_and(|cs| cs.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker)))
|
||||
})
|
||||
.count();
|
||||
let first = first_heading_line(para);
|
||||
if !(*l0..*l1).contains(&first) {
|
||||
continue;
|
||||
}
|
||||
let Some(line) = para.lines.get(first) else { continue };
|
||||
let Some(piece) = para.lines.get(*l0) else { continue };
|
||||
let title: String = self.title_text(p, para).split_whitespace().collect::<Vec<_>>().join(" ").chars().take(200).collect();
|
||||
if title.is_empty() {
|
||||
let text = self.title_text(p, para);
|
||||
if text.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Layout already counted the label in document order, including headings on omitted pages.
|
||||
let number = para.label.as_ref().filter(|_| {
|
||||
p.props
|
||||
.numbering
|
||||
.or(para.rp.numbering)
|
||||
.and_then(|n| numbering.level(n.num, n.level.min(8)))
|
||||
.is_some_and(|level| !matches!(level.format, NumFormat::Bullet | NumFormat::None))
|
||||
});
|
||||
let title: String = number
|
||||
.map_or("", |label| label.text.as_str())
|
||||
.split_whitespace()
|
||||
.chain(text.split_whitespace())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.chars()
|
||||
.take(200)
|
||||
.collect();
|
||||
let (x, y) = fit.point(*x, *y + line.top - piece.top);
|
||||
flat.push((level.min(8), title, *out, x, y));
|
||||
}
|
||||
|
||||
+92
-12
@@ -2047,6 +2047,41 @@ fn ref_fields_export_cached_links() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_keeps_numbered_heading_labels() {
|
||||
use hayro_syntax::object::{Dict, String as PdfString};
|
||||
use wordcraft_doc::numbering::Level;
|
||||
|
||||
let mut d = Document::new();
|
||||
let numbering = Arc::make_mut(&mut d.numbering);
|
||||
let sections = numbering
|
||||
.try_add_levels(None, vec![Level { text: "%1".into(), ..Default::default() }, Level { text: "%1.%2".into(), ..Default::default() }])
|
||||
.unwrap();
|
||||
let bullets = numbering.add_list(ListKind::Bullet);
|
||||
let mut overview = Paragraph::with_text("Overview", CharProps::default()).styled("Heading1");
|
||||
overview.props.numbering = Some(NumRef { num: sections, level: 0 });
|
||||
Arc::make_mut(&mut d.styles).get_mut("Heading2").unwrap().para.numbering = Some(NumRef { num: sections, level: 1 });
|
||||
let details = Paragraph::with_text("Details", CharProps::default()).styled("Heading2");
|
||||
let blank = Paragraph::new().styled("Heading2");
|
||||
let summary = Paragraph::with_text("Summary", CharProps::default()).styled("Heading1");
|
||||
let mut notes = Paragraph::with_text("Notes", CharProps::default()).styled("Heading1");
|
||||
notes.props.numbering = Some(NumRef { num: bullets, level: 0 });
|
||||
d.body = [overview, details, blank, summary, notes].into_iter().map(para_block).collect();
|
||||
|
||||
let pdf = hayro_syntax::Pdf::new(export(&d, &PdfOptions::default()).unwrap()).unwrap();
|
||||
let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
|
||||
let outline = catalog.get::<Dict<'_>>(b"Outlines").unwrap();
|
||||
let title = |node: &Dict<'_>| pdf_text_string(node.get::<PdfString<'_>>(b"Title").unwrap().as_bytes());
|
||||
let overview = outline.get::<Dict<'_>>(b"First").unwrap();
|
||||
let details = overview.get::<Dict<'_>>(b"First").unwrap();
|
||||
assert_eq!(title(&overview), "1 Overview");
|
||||
assert_eq!(title(&details), "1.1 Details");
|
||||
assert!(details.get::<Dict<'_>>(b"Next").is_none(), "blank headings keep no outline entry");
|
||||
let summary = overview.get::<Dict<'_>>(b"Next").unwrap();
|
||||
assert_eq!(title(&summary), "Summary");
|
||||
assert_eq!(title(&summary.get::<Dict<'_>>(b"Next").unwrap()), "Notes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_after_leading_breaks() {
|
||||
use hayro_syntax::object::{Array, Dict};
|
||||
@@ -2070,8 +2105,9 @@ fn outline_after_leading_breaks() {
|
||||
assert!(target > 0, "the heading follows a page break");
|
||||
for pages in [None, Some(vec![target]), Some(vec![target, 0]), Some(vec![0])] {
|
||||
let expected = pages.as_ref().map_or(Some(target), |p| p.iter().position(|i| *i == target));
|
||||
let bytes = export(&d, &PdfOptions { pages, ..Default::default() }).unwrap();
|
||||
let bytes = export(&d, &PdfOptions { pages, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
assert_eq!(heading_one_tags(&pdf), usize::from(expected.is_some()), "heading tags follow the visible heading past leading breaks");
|
||||
let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
|
||||
let outlines = catalog.get::<Dict<'_>>(b"Outlines");
|
||||
let Some(expected) = expected else {
|
||||
@@ -2086,6 +2122,37 @@ fn outline_after_leading_breaks() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_heading_after_column_break_keeps_heading_tag() {
|
||||
let mut d = Document::from_text("");
|
||||
d.last_section.columns = wordcraft_doc::section::Columns { count: 2, space: 36.0, separator: false, widths: Vec::new() };
|
||||
let list = Arc::make_mut(&mut d.numbering).add_list(ListKind::Numbered);
|
||||
let mut heading = Paragraph::with_text("\u{e}Second column heading", CharProps::default()).styled("Heading1");
|
||||
heading.props.numbering = Some(NumRef { num: list, level: 0 });
|
||||
d.body = vec![para_block(Paragraph::with_text("First column", CharProps::default())), para_block(heading)];
|
||||
let bytes = export(&d, &PdfOptions { tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
assert_eq!(heading_one_tags(&pdf), 1, "the heading is tagged where its text starts, though its number is drawn before the column break");
|
||||
}
|
||||
|
||||
fn heading_one_tags(pdf: &hayro_syntax::Pdf) -> usize {
|
||||
use hayro_syntax::object::{Dict, Name, Object};
|
||||
|
||||
fn count(node: Object<'_>) -> usize {
|
||||
match node {
|
||||
Object::Array(array) => array.iter::<Object>().map(count).sum(),
|
||||
Object::Dict(dict) => {
|
||||
let heading = dict.get::<Name>(b"S").is_some_and(|role| role.as_ref() == b"H1");
|
||||
usize::from(heading) + dict.get::<Object>(b"K").map_or(0, count)
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
let catalog = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
|
||||
catalog.get::<Dict>(b"StructTreeRoot").and_then(|tree| tree.get::<Object>(b"K")).map_or(0, count)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_keeps_visible_objects() {
|
||||
use hayro_syntax::object::{Array, Dict};
|
||||
@@ -3590,21 +3657,31 @@ fn figure_tags_keep_story_paths_and_reordered_pages() {
|
||||
/// as Word's export does, where the document stores "9" for both.
|
||||
#[test]
|
||||
fn exported_page_references_show_the_page_or_words_error() {
|
||||
use hayro_syntax::object::{Array, Dict};
|
||||
|
||||
let field =
|
||||
|instr: &str| InlineObject::Field { instr: instr.into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() };
|
||||
let mut d = Document::from_text("See \nMissing \nTarget");
|
||||
for (i, instr) in [(0, "PAGEREF Target"), (1, "PAGEREF NoSuchMark")] {
|
||||
let mut d = Document::from_text("See \nUnlinked \nMissing \nTarget");
|
||||
for (i, instr) in [(0, r"PAGEREF Target \h"), (1, "PAGEREF Target"), (2, r"PAGEREF NoSuchMark \h")] {
|
||||
let p = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(i)).unwrap();
|
||||
let n = p.len();
|
||||
p.insert_object(n, field(instr), &CharProps::default()).unwrap();
|
||||
}
|
||||
let target = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap();
|
||||
let target = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(3)).unwrap();
|
||||
target.props.page_break_before = Some(true);
|
||||
target.insert_object(0, InlineObject::BookmarkStart { name: "Target".into() }, &CharProps::default()).unwrap();
|
||||
let text = extract_text(&export(&d, &PdfOptions::default()).unwrap());
|
||||
let bytes = export(&d, &PdfOptions::default()).unwrap();
|
||||
let text = extract_text(&bytes);
|
||||
let first = squash(&text[0]);
|
||||
assert!(first.contains("See 2"), "{first}");
|
||||
assert!(first.contains("Unlinked 2"), "{first}");
|
||||
assert!(first.contains("Missing Error! Bookmark not defined."), "{first}");
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
let annotations = pdf.pages()[0].raw().get::<Array>(b"Annots").expect("the linked page reference produces an annotation");
|
||||
let destinations: Vec<_> = annotations.iter::<Dict>().filter_map(|a| a.get::<Array>(b"Dest")).collect();
|
||||
assert_eq!(destinations.len(), 1, "only the linked, existing bookmark has a destination");
|
||||
let linked_page = destinations[0].raw_iter().next().unwrap().as_obj_ref().map(Into::into);
|
||||
assert_eq!(linked_page, pdf.pages()[1].raw().obj_id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4096,9 +4173,9 @@ fn table_cell_links_with_same_target_stay_in_their_own_cells() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph's continuation must follow the footer and header between its pages.
|
||||
/// A split heading has one heading tag, with its continuation read after the intervening footer and header.
|
||||
#[test]
|
||||
fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
fn spanning_heading_has_one_heading_tag_and_keeps_link_order() {
|
||||
use hayro_syntax::object::{Array, Dict, Name, Object};
|
||||
|
||||
let mut d = Document::new();
|
||||
@@ -4109,7 +4186,9 @@ fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
let footer = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(linked("Footer", "footer"))]);
|
||||
d.last_section.headers.default = Some(header);
|
||||
d.last_section.footers.default = Some(footer);
|
||||
d.body = vec![para_block(linked("First page\u{c}Second page", "body"))];
|
||||
let mut heading = linked("First page\u{c}Second page", "body");
|
||||
heading.props.outline_level = Some(0);
|
||||
d.body = vec![para_block(heading)];
|
||||
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
@@ -4123,14 +4202,14 @@ fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
expected.push(format!("{:?}", annots[i].obj_id().unwrap()));
|
||||
}
|
||||
}
|
||||
fn collect(o: Object<'_>, out: &mut Vec<String>) {
|
||||
fn collect(o: Object<'_>, links: &mut Vec<String>) {
|
||||
match o {
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, out)),
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, links)),
|
||||
Object::Dict(d) => {
|
||||
if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") {
|
||||
out.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
|
||||
links.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
|
||||
} else if let Some(k) = d.get::<Object>(b"K") {
|
||||
collect(k, out);
|
||||
collect(k, links);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -4140,5 +4219,6 @@ fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
let tree = root.get::<Dict>(b"StructTreeRoot").unwrap();
|
||||
let mut actual = Vec::new();
|
||||
collect(tree.get::<Object>(b"K").unwrap(), &mut actual);
|
||||
assert_eq!(heading_one_tags(&pdf), 1, "the second page continues the heading text without a duplicate heading tag");
|
||||
assert_eq!(actual, expected, "links must follow page reading order across a split paragraph");
|
||||
}
|
||||
|
||||
+260
-54
@@ -159,13 +159,29 @@ pub struct RenderOptions {
|
||||
/// Colour for formatting marks.
|
||||
pub mark_color: Rgb,
|
||||
/// Thicken glyphs slightly the way macOS draws text on screen ("font smoothing"), so pages
|
||||
/// look like they do in other Mac apps. For on-screen rasters only: exports stay exact.
|
||||
pub text_darkening: bool,
|
||||
/// look like they do in other Mac apps: 0 is none, 1 the system's default strength
|
||||
/// ([`stem_darkening`]), and other values scale it, up to twice (the system's own setting
|
||||
/// has a lighter and a stronger step). A value that isn't a number is none. For on-screen
|
||||
/// rasters only: exports stay exact.
|
||||
pub text_darkening: f32,
|
||||
/// Put every glyph's baseline on a whole device pixel, for text that is neither rotated nor
|
||||
/// mirrored. A baseline between two pixel rows spreads the feet of the letters (serifs, the
|
||||
/// bottoms of stems) over both rows as two grey rows instead of one solid one, which reads as
|
||||
/// blur. A glyph moves by half a pixel at most and never sideways, so lines break as without
|
||||
/// it. Hinted text already sits like this. For on-screen rasters only: exports stay exact.
|
||||
pub baseline_snap: bool,
|
||||
/// Hint text for the screen the way FreeType's `hintslight` does on Linux desktops: glyph
|
||||
/// baselines sit on whole pixels and their horizontal edges (x-height, cap height) are moved
|
||||
/// onto the pixel grid, so text looks as crisp as in other apps there. Nothing moves
|
||||
/// sideways, so lines break as without it. For on-screen rasters only: exports stay exact.
|
||||
pub hinting: bool,
|
||||
/// Subpixel (LCD) antialiasing for text, for a screen whose colour stripes run in this order
|
||||
/// (see [`LcdOrder`]); `None` is greyscale antialiasing. Text gets three times the detail
|
||||
/// sideways, where slanted and round strokes need it most, at the price of faint colour at
|
||||
/// its edges, and the page is rasterised three times. Everything but text is drawn as
|
||||
/// without it. For on-screen rasters only, and only where the raster's pixels are the
|
||||
/// screen's own: exports stay exact.
|
||||
pub lcd: Option<LcdOrder>,
|
||||
/// Dark page (View › Switch Modes): every colour but pictures has its lightness inverted, so
|
||||
/// white paper turns black and black text white while hues stay the same. Screen only.
|
||||
pub dark: bool,
|
||||
@@ -176,6 +192,20 @@ pub struct RenderOptions {
|
||||
pub read_paper: Option<Rgb>,
|
||||
}
|
||||
|
||||
/// The order of a screen's red, green and blue stripes, left to right, within each pixel.
|
||||
///
|
||||
/// With [`RenderOptions::lcd`] set, each colour channel of a pixel takes the text's coverage
|
||||
/// around its own stripe, a third of a pixel to one side of the pixel's middle or the other,
|
||||
/// instead of all three taking the coverage of the whole pixel. A pixel's stripes are a pixel
|
||||
/// wide in all, so each channel still averages over one pixel's width: this is the result of
|
||||
/// rasterising text at three times the width and averaging three neighbours (the box filter
|
||||
/// FreeType calls its light LCD filter), with no sharper filter and no fringe reduction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum LcdOrder {
|
||||
Rgb,
|
||||
Bgr,
|
||||
}
|
||||
|
||||
/// Default grey for a dark page's paper.
|
||||
pub const DARK_PAPER: u8 = 0x33;
|
||||
|
||||
@@ -267,8 +297,10 @@ impl Default for RenderOptions {
|
||||
display: DisplayOptions::default(),
|
||||
paper: Rgb::WHITE,
|
||||
mark_color: Rgb(0x2B, 0x57, 0x9A),
|
||||
text_darkening: false,
|
||||
text_darkening: 0.0,
|
||||
baseline_snap: false,
|
||||
hinting: false,
|
||||
lcd: None,
|
||||
dark: false,
|
||||
dark_paper: DARK_PAPER,
|
||||
read_paper: None,
|
||||
@@ -296,6 +328,52 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
|
||||
// Over the cap the whole picture is drawn smaller, not cropped.
|
||||
let view = if (cw, ch) == (w, h) { view } else { Affine::scale_non_uniform(cw as f64 / w as f64, ch as f64 / h as f64) * view };
|
||||
let (w16, h16) = (cw as u16, ch as u16);
|
||||
let drew_text = std::cell::Cell::new(false);
|
||||
let mut pixels = raster_page(doc, page, (w16, h16), view, opts, Pass { shift: 0.0, drew_text: &drew_text });
|
||||
// Subpixel text: the page twice more, its text a third of a pixel to each side, for the
|
||||
// channels whose stripes sit there. A page without text is the same all three times.
|
||||
if let Some(order) = opts.lcd
|
||||
&& drew_text.get()
|
||||
{
|
||||
let side = |shift: f64| raster_page(doc, page, (w16, h16), view, opts, Pass { shift, drew_text: &drew_text });
|
||||
let (text_right, text_left) = (side(LCD_SHIFT), side(-LCD_SHIFT));
|
||||
let (red, blue) = match order {
|
||||
LcdOrder::Rgb => (&text_right, &text_left),
|
||||
LcdOrder::Bgr => (&text_left, &text_right),
|
||||
};
|
||||
take_lcd_channels(&mut pixels, red, blue);
|
||||
}
|
||||
Rendered { width: w16 as u32, height: h16 as u32, pixels }
|
||||
}
|
||||
|
||||
/// How far, in device pixels, the middle of a pixel's first or last colour stripe is from the
|
||||
/// middle of the pixel.
|
||||
const LCD_SHIFT: f64 = 1.0 / 3.0;
|
||||
|
||||
/// One rasterisation of a page among the one or three that make its raster.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Pass<'a> {
|
||||
/// How far to the right text is drawn from its place, in device pixels (see
|
||||
/// [`RenderOptions::lcd`]). Nothing else moves.
|
||||
shift: f64,
|
||||
/// Set once the pass has drawn text that `shift` moves.
|
||||
drew_text: &'a std::cell::Cell<bool>,
|
||||
}
|
||||
|
||||
/// The red of `pixels` from `red` and its blue from `blue`, two rasters of the same size
|
||||
/// (premultiplied RGBA8). Text shifted right puts under each pixel's middle what lay a third of a
|
||||
/// pixel to its left, where an RGB screen's red stripe is, and so on. The alpha stays, and
|
||||
/// no channel is left above it.
|
||||
fn take_lcd_channels(pixels: &mut [u8], red: &[u8], blue: &[u8]) {
|
||||
for ((px, r), b) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(red.as_chunks::<4>().0).zip(blue.as_chunks::<4>().0) {
|
||||
px[0] = r[0].min(px[3]);
|
||||
px[2] = b[2].min(px[3]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterise a page into `size` pixels (premultiplied RGBA8) with `view` (page points → pixels).
|
||||
fn raster_page(doc: &Document, page: &Page, size: (u16, u16), view: Affine, opts: &RenderOptions, pass: Pass) -> Vec<u8> {
|
||||
let (w16, h16) = size;
|
||||
let mut ctx = context_pool::CONTEXTS.take(w16, h16);
|
||||
ctx.set_transform(Affine::IDENTITY);
|
||||
ctx.set_paint(color(opts.paper_of(doc), 1.0));
|
||||
@@ -314,7 +392,7 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
|
||||
ctx.push_opacity_layer(alpha);
|
||||
}
|
||||
for it in &items {
|
||||
draw(&mut ctx, doc, it, view, &visible, opts);
|
||||
draw(&mut ctx, doc, it, view, &visible, opts, pass);
|
||||
}
|
||||
if faded {
|
||||
ctx.pop_layer();
|
||||
@@ -327,7 +405,7 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
|
||||
ctx.render(pm, &mut res);
|
||||
}
|
||||
context_pool::CONTEXTS.give_back(ctx);
|
||||
Rendered { width: w16 as u32, height: h16 as u32, pixels }
|
||||
pixels
|
||||
}
|
||||
|
||||
/// The on-screen colour behind page point (`x`, `y`): the paper (page colour), then any
|
||||
@@ -495,24 +573,30 @@ fn draw_watermark(ctx: &mut RenderContext, view: Affine, page: &Page, wm: &wordc
|
||||
|
||||
/// Does `view` map page points to device pixels without rotation, skew or mirroring, scaling both
|
||||
/// axes alike? Only then do hinted outlines (made on the pixel grid) line up with the screen.
|
||||
/// "Alike" allows the two axes a fifth of a percent apart: a page raster made to fill a whole
|
||||
/// number of pixels each way ([`render_area_to`]) is scaled that little differently across and
|
||||
/// down (a pixel in some two thousand), and is as upright as any.
|
||||
fn is_upright(view: Affine) -> bool {
|
||||
let [a, b, c, d, e, f] = view.as_coeffs();
|
||||
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 1e-6
|
||||
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 2e-3
|
||||
}
|
||||
|
||||
/// How far, in device pixels, macOS-style font smoothing pushes each side of a glyph outline out
|
||||
/// at `ppem` device pixels per em. Values from Pathfinder (MIT/Apache-2.0), which measured them
|
||||
/// against macOS: 1.21% of the pixel size horizontally and 1.25 times that vertically, each
|
||||
/// capped at 0.3 px, and no darkening past 72 px per em. We stroke the outline, which grows it
|
||||
/// evenly, so this is the mean of the two.
|
||||
/// sideways at `ppem` device pixels per em. The value is Pathfinder's (MIT/Apache-2.0), which
|
||||
/// measured it against macOS: 1.21% of the pixel size, capped at 0.3 px, and no darkening past
|
||||
/// 72 px per em. Pathfinder also grows glyphs up and down (1.25 times as far). We don't: a third
|
||||
/// of a pixel of grey above and below every letter is what made page text look out of focus
|
||||
/// beside other Mac apps, whose letters end on a clean pixel row. Stems get thicker, which is
|
||||
/// the weight the smoothing is for; the tops and feet of the letters stay where the font puts
|
||||
/// them.
|
||||
pub fn stem_darkening(ppem: f64) -> f64 {
|
||||
const FACTOR: [f64; 2] = [0.0121, 0.0121 * 1.25];
|
||||
const FACTOR: f64 = 0.0121;
|
||||
const MAX_PX: f64 = 0.3;
|
||||
const MAX_PPEM: f64 = 72.0;
|
||||
if !ppem.is_finite() || ppem <= 0.0 || ppem > MAX_PPEM {
|
||||
return 0.0;
|
||||
}
|
||||
FACTOR.iter().map(|f| (ppem * f).min(MAX_PX)).sum::<f64>() / 2.0
|
||||
(ppem * FACTOR).min(MAX_PX)
|
||||
}
|
||||
|
||||
/// A wavy line from `(x0, y0)` to `(x1, y1)`; at most 20 000 units long, so a huge extent can't make it endless.
|
||||
@@ -596,6 +680,7 @@ struct Frame<'a> {
|
||||
opts: &'a RenderOptions,
|
||||
view: Affine,
|
||||
visible: &'a kurbo::Rect,
|
||||
pass: Pass<'a>,
|
||||
}
|
||||
|
||||
/// The rectangle in kurbo's terms.
|
||||
@@ -607,12 +692,12 @@ fn kurbo_rect(rect: &wordcraft_geom::Rect) -> kurbo::Rect {
|
||||
/// `visible` is a culling area in those point coordinates; nested clips intersect it and turns
|
||||
/// transform it into the child's coordinates. Shape and path strokes apply their stored caps,
|
||||
/// while ink uses its tool's round ends and joins.
|
||||
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions) {
|
||||
let fr = Frame { doc, opts, view, visible };
|
||||
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions, pass: Pass) {
|
||||
let fr = Frame { doc, opts, view, visible, pass };
|
||||
match it {
|
||||
Draw::Figure { draws, .. } => {
|
||||
for d in draws {
|
||||
draw(ctx, doc, d, view, visible, opts);
|
||||
draw(ctx, doc, d, view, visible, opts, pass);
|
||||
}
|
||||
}
|
||||
Draw::Fill { .. } => draw_fill(ctx, &fr, it),
|
||||
@@ -634,7 +719,7 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
|
||||
ctx.push_clip_layer(&r.to_path(0.1));
|
||||
let local = r.intersect(*visible);
|
||||
for it in items {
|
||||
draw(ctx, doc, it, view, &local, opts);
|
||||
draw(ctx, doc, it, view, &local, opts, pass);
|
||||
}
|
||||
ctx.pop_layer();
|
||||
}
|
||||
@@ -642,14 +727,14 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
|
||||
let m = Affine::new(Draw::turn_matrix(*turn, *x, *y).map(f64::from));
|
||||
let local = m.inverse().transform_rect_bbox(*visible);
|
||||
for it in items {
|
||||
draw(ctx, doc, it, view * m, &local, opts);
|
||||
draw(ctx, doc, it, view * m, &local, opts, pass);
|
||||
}
|
||||
}
|
||||
Draw::Rotated { cx, cy, spin, items } => {
|
||||
let m = Affine::new(spin.matrix(*cx, *cy).map(f64::from));
|
||||
let local = m.inverse().transform_rect_bbox(*visible);
|
||||
for it in items {
|
||||
draw(ctx, doc, it, view * m, &local, opts);
|
||||
draw(ctx, doc, it, view * m, &local, opts, pass);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -704,7 +789,8 @@ fn draw_line(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
}
|
||||
_ => {
|
||||
let (st, off) = match snap_rule(fr.view, (x0, y0, x1, y1), w) {
|
||||
Some((w_px, off)) => (kurbo::Stroke { width: w_px / fr.view.as_coeffs()[0], ..st }, off),
|
||||
// The width is across the rule: in points by the scale that way.
|
||||
Some((w_px, off)) => (kurbo::Stroke { width: w_px / rule_scale(fr.view, y0 == y1), ..st }, off),
|
||||
None => (st, (0.0, 0.0)),
|
||||
};
|
||||
ctx.set_stroke(st);
|
||||
@@ -721,11 +807,13 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
|
||||
if !is_upright(view) {
|
||||
return None;
|
||||
}
|
||||
let [k, _, _, _, tx, ty] = view.as_coeffs();
|
||||
let [_, _, _, _, tx, ty] = view.as_coeffs();
|
||||
if y0 == y1 && x0 != x1 {
|
||||
let k = rule_scale(view, true);
|
||||
let (w_px, c) = snap_hairline(y0 * k + ty, width * k);
|
||||
Some((w_px, (0.0, (c - ty) / k - y0)))
|
||||
} else if x0 == x1 && y0 != y1 {
|
||||
let k = rule_scale(view, false);
|
||||
let (w_px, c) = snap_hairline(x0 * k + tx, width * k);
|
||||
Some((w_px, ((c - tx) / k - x0, 0.0)))
|
||||
} else {
|
||||
@@ -733,6 +821,16 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
|
||||
}
|
||||
}
|
||||
|
||||
/// Device pixels per point across a rule: down the page for a level rule, across it for an
|
||||
/// upright one. An upright view ([`is_upright`]) may scale the two a little differently (a page
|
||||
/// raster made to fill a whole number of pixels each way), and a rule's place and width are
|
||||
/// measured across it: with the other scale, a level rule low on such a page was snapped up to
|
||||
/// a pixel from where it lies, its edges between pixel rows.
|
||||
fn rule_scale(view: Affine, level: bool) -> f64 {
|
||||
let [across, _, _, down, ..] = view.as_coeffs();
|
||||
if level { down } else { across }
|
||||
}
|
||||
|
||||
/// A line `width_px` wide centred at device coordinate `centre`, moved so both edges fall on whole
|
||||
/// pixels. Returns the width, made a whole number of pixels (at least one), and the new centre.
|
||||
fn snap_hairline(centre: f64, width_px: f64) -> (f64, f64) {
|
||||
@@ -762,23 +860,25 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
// Scaled letters (`w:w`): each glyph stretched across from its pen position.
|
||||
let sx = if x_scale.is_finite() && *x_scale > 0.0 { f64::from(*x_scale) } else { 1.0 };
|
||||
let skew = Affine::scale_non_uniform(sx, 1.0) * skew;
|
||||
// Outline strokes, in font units: synthetic bold, then on-screen stem darkening (a
|
||||
// stroke grows the outline by half its width on each side). Darkening is skipped for
|
||||
// translucent text, where the stroke overlapping the fill would show as a darker rim.
|
||||
// Synthetic bold strokes the outline, in font units.
|
||||
let px_per_pt = view.determinant().abs().sqrt();
|
||||
let darken_px = if opts.text_darkening && *alpha >= 1.0 { stem_darkening(*size as f64 * px_per_pt) } else { 0.0 };
|
||||
let darken = if darken_px > 0.0 && k * px_per_pt > 0.0 { 2.0 * darken_px / (k * px_per_pt) } else { 0.0 };
|
||||
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 } + darken;
|
||||
let join = if darken > 0.0 { kurbo::Join::Round } else { kurbo::Join::Miter };
|
||||
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 };
|
||||
if outline_stroke > 0.0 {
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
|
||||
}
|
||||
// Emoji and other colour glyphs (#1269) are drawn from the font's colour data.
|
||||
let colour = face.has_color_glyphs();
|
||||
let ppem = *size as f64 * px_per_pt;
|
||||
// Hinted outlines are in device pixels: only for an upright, unmirrored, evenly scaled
|
||||
// view (not rotated text boxes), where the pixel grid lines up with the glyphs.
|
||||
let hint_ppem = (opts.hinting && !colour && is_upright(view)).then_some(ppem as f32);
|
||||
// On-screen stem darkening: each outline is widened along its own x axis, in one piece (see
|
||||
// [`stem_darkening`] and [`widened`]). Skipped for translucent text, as it always was.
|
||||
let strength = if opts.text_darkening.is_finite() { f64::from(opts.text_darkening).clamp(0.0, 2.0) } else { 0.0 };
|
||||
let darken_px = if *alpha >= 1.0 { stem_darkening(ppem) * strength } else { 0.0 };
|
||||
// Hinted outlines are in device pixels, and a snapped baseline is a row of them: only for an
|
||||
// upright, unmirrored, evenly scaled view (not rotated text boxes), where the pixel grid
|
||||
// lines up with the glyphs.
|
||||
let upright = is_upright(view);
|
||||
let hint_ppem = (opts.hinting && !colour && upright).then_some(ppem as f32);
|
||||
let snap = opts.baseline_snap && upright;
|
||||
// The outline strokes in device pixels, for the hinted outlines.
|
||||
let stroke_px = outline_stroke * k * px_per_pt;
|
||||
let mut hinted_stroke = false;
|
||||
@@ -795,39 +895,130 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
ctx.set_paint(color(opts.ink(*c), *alpha));
|
||||
continue;
|
||||
}
|
||||
if let Some(o) = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p)) {
|
||||
if o.elements().is_empty() {
|
||||
continue;
|
||||
let pen = view * kurbo::Point::new(gx, gy);
|
||||
let hinted = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p));
|
||||
let hinted_now = hinted.is_some();
|
||||
let (o, at) = if let Some(o) = hinted {
|
||||
if outline_stroke > 0.0 && !hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(kurbo::Join::Miter));
|
||||
hinted_stroke = true;
|
||||
}
|
||||
// The baseline on a whole pixel, as the hinting assumes.
|
||||
let at = view * kurbo::Point::new(gx, gy);
|
||||
ctx.set_transform(Affine::translate((at.x, at.y.round())) * skew);
|
||||
ctx.fill_path(&o);
|
||||
if outline_stroke > 0.0 {
|
||||
if !hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(join));
|
||||
hinted_stroke = true;
|
||||
}
|
||||
ctx.stroke_path(&o);
|
||||
(o, Affine::translate((pen.x, pen.y.round())) * skew)
|
||||
} else {
|
||||
if outline_stroke > 0.0 && hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
|
||||
hinted_stroke = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let o = db.outline(face, *gid);
|
||||
let at = view * Affine::translate((gx, gy)) * skew * Affine::scale(k);
|
||||
// The same baseline for text drawn from the font's own outlines.
|
||||
let lift = if snap && pen.y.is_finite() { pen.y.round() - pen.y } else { 0.0 };
|
||||
(db.outline(face, *gid), Affine::translate((0.0, lift)) * at)
|
||||
};
|
||||
if o.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
ctx.set_transform(view * Affine::translate((gx, gy)) * skew * Affine::scale(k));
|
||||
ctx.fill_path(&o);
|
||||
// This pass's sideways shift, across the screen whichever way the text is turned.
|
||||
fr.pass.drew_text.set(true);
|
||||
ctx.set_transform(Affine::translate((fr.pass.shift, 0.0)) * at);
|
||||
// The darkened outline is the glyph: synthetic bold strokes it too. Stroking the font's own
|
||||
// outline there would cover the widening (the stroke reaches further than it does) and
|
||||
// leave such text as light as without darkening.
|
||||
let wide = (darken_px > 0.0).then(|| widened(&o, darken_px / widen_unit(hinted_now, k * px_per_pt, sx)));
|
||||
let shape = wide.as_ref().unwrap_or(&o);
|
||||
ctx.fill_path(shape);
|
||||
if outline_stroke > 0.0 {
|
||||
if hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
|
||||
hinted_stroke = false;
|
||||
}
|
||||
ctx.stroke_path(&o);
|
||||
ctx.stroke_path(shape);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many device pixels one unit of a glyph outline is across the screen, for turning a
|
||||
/// widening in device pixels into the outline's own units: a hinted outline is in device pixels
|
||||
/// already and the font's own in font units (`font_px` device pixels each), and both are then
|
||||
/// stretched `stretch` times across by scaled letters (`w:w`). Without the stretch for hinted
|
||||
/// outlines, text scaled to 400 % was widened four times too far.
|
||||
fn widen_unit(hinted: bool, font_px: f64, stretch: f64) -> f64 {
|
||||
if hinted { stretch } else { font_px * stretch }
|
||||
}
|
||||
|
||||
/// `path` with every edge moved `d` sideways, away from the ink: the shape a glyph makes when it
|
||||
/// is smeared `d` to the left and `d` to the right, so stems get `2 d` thicker while nothing
|
||||
/// grows up or down. One outline, filled once, so partly covered pixels are counted once (the
|
||||
/// outline drawn again beside itself counted them two and three times, which read as bold).
|
||||
///
|
||||
/// Each point moves with the edges it joins: by `d` where both face the same side, or one of
|
||||
/// them is level; not at all at the top or the foot of a curve, where one faces left and the
|
||||
/// other right. Curve control points move by the same rule along the control polygon. Which side
|
||||
/// of an edge is ink follows from the direction the outline runs in, read off its signed area,
|
||||
/// so the holes of letters narrow as their stems widen. An outline with no area, or with
|
||||
/// numbers that aren't finite, is returned as it is.
|
||||
fn widened(path: &BezPath, d: f64) -> BezPath {
|
||||
use kurbo::PathEl;
|
||||
let els = path.elements();
|
||||
// The control polygon of each contour, as (first point index, point count).
|
||||
let mut pts: Vec<kurbo::Point> = Vec::with_capacity(els.len() * 2);
|
||||
let mut contours: Vec<(usize, usize)> = Vec::new();
|
||||
let mut start = 0;
|
||||
for el in els {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
if pts.len() > start {
|
||||
contours.push((start, pts.len() - start));
|
||||
}
|
||||
start = pts.len();
|
||||
pts.push(*p);
|
||||
}
|
||||
PathEl::LineTo(p) => pts.push(*p),
|
||||
PathEl::QuadTo(c, p) => pts.extend([*c, *p]),
|
||||
PathEl::CurveTo(c1, c2, p) => pts.extend([*c1, *c2, *p]),
|
||||
PathEl::ClosePath => {}
|
||||
}
|
||||
}
|
||||
if pts.len() > start {
|
||||
contours.push((start, pts.len() - start));
|
||||
}
|
||||
let ring = |first: usize, n: usize, i: usize| pts.get(first + i % n.max(1)).copied().unwrap_or_default();
|
||||
let area: f64 =
|
||||
contours.iter().map(|&(first, n)| (0..n).map(|i| ring(first, n, i).to_vec2().cross(ring(first, n, i + 1).to_vec2())).sum::<f64>()).sum();
|
||||
if !(d.is_finite() && d > 0.0 && area.is_finite() && area != 0.0) {
|
||||
return path.clone();
|
||||
}
|
||||
// Which way the edge from `a` to `b` faces: 1 right, -1 left, 0 for a level edge.
|
||||
let faces = |a: kurbo::Point, b: kurbo::Point| {
|
||||
let (run, rise) = ((b.x - a.x).abs(), b.y - a.y);
|
||||
if rise.abs() <= 1e-6 * (run + rise.abs()) { 0.0 } else { (rise * area).signum() }
|
||||
};
|
||||
let mut moved = pts.clone();
|
||||
for &(first, n) in &contours {
|
||||
for i in 0..n {
|
||||
let at = ring(first, n, i);
|
||||
// The nearest different points before and after: a contour may repeat a point (a
|
||||
// run of more than a few is left where it is).
|
||||
let before = (1..n.min(8)).map(|step| ring(first, n, i + n - step)).find(|p| *p != at);
|
||||
let after = (1..n.min(8)).map(|step| ring(first, n, i + step)).find(|p| *p != at);
|
||||
let (Some(before), Some(after)) = (before, after) else { continue };
|
||||
let push = (faces(before, at) + faces(at, after)).clamp(-1.0, 1.0);
|
||||
if let Some(p) = moved.get_mut(first + i) {
|
||||
p.x += push * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut next = moved.into_iter();
|
||||
let mut take = || next.next().unwrap_or_default();
|
||||
let mut out = BezPath::with_capacity(els.len());
|
||||
for el in els {
|
||||
out.push(match el {
|
||||
PathEl::MoveTo(_) => PathEl::MoveTo(take()),
|
||||
PathEl::LineTo(_) => PathEl::LineTo(take()),
|
||||
PathEl::QuadTo(..) => PathEl::QuadTo(take(), take()),
|
||||
PathEl::CurveTo(..) => PathEl::CurveTo(take(), take(), take()),
|
||||
PathEl::ClosePath => PathEl::ClosePath,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn draw_mark(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
let Draw::Mark { x, baseline, size, ch, color: mark } = it else { return };
|
||||
let face = wordcraft_fonts::word::resolve("Source Sans 3", false, false).face;
|
||||
@@ -1280,6 +1471,19 @@ pub fn render_area(doc: &Document, page: &Page, area: wordcraft_geom::Rect, scal
|
||||
render_region(doc, page, pw, ph, view, opts)
|
||||
}
|
||||
|
||||
/// Render the page `area` (points) into exactly `w`×`h` pixels: the area fills the raster, scaled
|
||||
/// across and down by whatever that takes. For a raster that must be a given number of device
|
||||
/// pixels each way, where [`render_area`]'s single scale gives the next whole pixel up: a picture
|
||||
/// one pixel larger than its place on screen is scaled into it, and every glyph resampled.
|
||||
pub fn render_area_to(doc: &Document, page: &Page, area: wordcraft_geom::Rect, w: u32, h: u32, opts: &RenderOptions) -> Rendered {
|
||||
let (w, h) = (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE));
|
||||
let (sx, sy) = (f64::from(w) / f64::from(area.w), f64::from(h) / f64::from(area.h));
|
||||
let fine = |v: f64| v.is_finite() && v > 0.0;
|
||||
let (sx, sy) = if fine(sx) && fine(sy) && area.x.is_finite() && area.y.is_finite() { (sx, sy) } else { (1.0, 1.0) };
|
||||
let (x, y) = if area.x.is_finite() && area.y.is_finite() { (f64::from(area.x), f64::from(area.y)) } else { (0.0, 0.0) };
|
||||
render_region(doc, page, w, h, Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y)), opts)
|
||||
}
|
||||
|
||||
/// Draw `items` (page points) alone, on nothing, over the page `area` (points) at `scale` px/pt:
|
||||
/// no paper, no watermark. A dragged object's preview.
|
||||
pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect, scale: f32, opts: &RenderOptions) -> Rendered {
|
||||
@@ -1293,8 +1497,10 @@ pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect,
|
||||
* Affine::translate((-x as f64, -y as f64));
|
||||
let mut ctx = RenderContext::new_with(w16, h16, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() });
|
||||
let visible = view.inverse().transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, w16 as f64, h16 as f64)).inflate(40.0, 40.0);
|
||||
// One pass, text in its place: an area raster (a preview, a dragged object) is greyscale.
|
||||
let drew_text = std::cell::Cell::new(false);
|
||||
for it in items {
|
||||
draw(&mut ctx, doc, it, view, &visible, opts);
|
||||
draw(&mut ctx, doc, it, view, &visible, opts, Pass { shift: 0.0, drew_text: &drew_text });
|
||||
}
|
||||
ctx.flush();
|
||||
let mut pixels = vec![0u8; w16 as usize * h16 as usize * 4];
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user