mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 22:59:18 +00:00
Compare commits
269
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca0d5ed68d | ||
|
|
a1e458a1c0 | ||
|
|
172b1ac37d | ||
|
|
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 | ||
|
|
8f627faed0 | ||
|
|
8cc1912dc0 | ||
|
|
0eda97fe8c | ||
|
|
db301eb1ba | ||
|
|
ab05f3f6d4 | ||
|
|
440243e3d7 | ||
|
|
18369a756e | ||
|
|
e8b2c87781 | ||
|
|
bf556a1cd6 | ||
|
|
0bcb856280 | ||
|
|
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 | ||
|
|
241bf8c94d | ||
|
|
a4ad65c372 | ||
|
|
4781d91473 | ||
|
|
04a3c76c10 | ||
|
|
e8414db9a5 | ||
|
|
fbe41cca76 | ||
|
|
553f0058ee | ||
|
|
c4ab2fea70 | ||
|
|
47ef5ce7b3 | ||
|
|
824d3c431e | ||
|
|
d2c8ba2787 | ||
|
|
8370cf558d | ||
|
|
257bc77e69 | ||
|
|
c7b4dfab8b | ||
|
|
f086af023f | ||
|
|
0171216a13 | ||
|
|
f9ff36d67c | ||
|
|
f0a323fdce | ||
|
|
6a3a18eba5 | ||
|
|
0242af0fdb | ||
|
|
4f8ac61c76 | ||
|
|
d7c01bcd05 | ||
|
|
789cabd832 | ||
|
|
6545c44f0a | ||
|
|
b22e901c45 | ||
|
|
c60c82d960 | ||
|
|
67bfa46a3d | ||
|
|
513ff0541f | ||
|
|
d4a565447f | ||
|
|
6f7b8156dc | ||
|
|
a21324bf78 | ||
|
|
a39f6adf9f | ||
|
|
b2dd74729f | ||
|
|
5ea160c706 | ||
|
|
84118adcf9 | ||
|
|
8a7fef3ec6 | ||
|
|
0ec775a9b9 | ||
|
|
caf9c8de8b | ||
|
|
135c1f72b1 | ||
|
|
c07b649e7b | ||
|
|
c70ad1bab2 | ||
|
|
4358f546d8 | ||
|
|
6b79b722d3 | ||
|
|
eba89475f6 | ||
|
|
64ef08c60a | ||
|
|
bc71452511 | ||
|
|
fb9276c4a6 | ||
|
|
ce2b01e005 | ||
|
|
c2a370cd67 | ||
|
|
0a31f5de5d | ||
|
|
1129aa51f2 | ||
|
|
4ad6272409 | ||
|
|
70e181a966 | ||
|
|
496d276873 | ||
|
|
b2dd18c916 | ||
|
|
dc9327501c | ||
|
|
b2021313ab | ||
|
|
41b351d770 | ||
|
|
3fbc536eba | ||
|
|
7342c32b1e | ||
|
|
0f0551351a | ||
|
|
c99d119543 | ||
|
|
a60bd414ed | ||
|
|
53d83510d7 | ||
|
|
58b595835f | ||
|
|
438c12d54a | ||
|
|
fb813b7988 | ||
|
|
58f942aa62 | ||
|
|
0739eb7379 | ||
|
|
67aa8ca4b7 | ||
|
|
b8ac6de3d0 | ||
|
|
db92b5cf2e | ||
|
|
18a8326ff0 | ||
|
|
b1de6f8556 | ||
|
|
d2ed8a334b | ||
|
|
c583679407 | ||
|
|
e6ff55e758 | ||
|
|
84e7aee82f | ||
|
|
dfb7e2647e | ||
|
|
c070c2a258 | ||
|
|
b7f52b6c78 | ||
|
|
4d7be007da | ||
|
|
14280d1c03 | ||
|
|
2bf03bcfc6 | ||
|
|
ea2e2f2970 | ||
|
|
f5892400de | ||
|
|
874184f066 | ||
|
|
501dddf7b5 | ||
|
|
1f6eb8eceb | ||
|
|
087bf2535b | ||
|
|
7a408c7eb3 | ||
|
|
7b213b331b | ||
|
|
d62508ca40 | ||
|
|
a1ad0f4cbc | ||
|
|
9c54fc1446 | ||
|
|
fbde8c47a3 | ||
|
|
481207f29d | ||
|
|
e3f9ed8134 | ||
|
|
4add275c07 | ||
|
|
5f39de62f8 | ||
|
|
830065bd62 | ||
|
|
31b2be75f4 | ||
|
|
195f103ceb | ||
|
|
96b8c1c58b | ||
|
|
de30199f1f | ||
|
|
14ed0bfa28 | ||
|
|
bf54864f37 | ||
|
|
61893e1950 | ||
|
|
b6777d494c | ||
|
|
434d9b223e | ||
|
|
802a2e2120 | ||
|
|
83f437ec89 | ||
|
|
3bae0c1cdb | ||
|
|
aa2c33e5a9 | ||
|
|
c26f801e20 | ||
|
|
7b1d234029 | ||
|
|
7361228721 | ||
|
|
05dda70d5c | ||
|
|
17fecc43ec | ||
|
|
0d8409ea36 | ||
|
|
4281ebbcb1 | ||
|
|
3843ada39b | ||
|
|
ed17e883e5 | ||
|
|
a0ca3766b3 | ||
|
|
1a7b691293 | ||
|
|
3ebe82eb5e | ||
|
|
e9708b91ae | ||
|
|
9f28b67cbc | ||
|
|
2ddf619270 | ||
|
|
27da3abc76 | ||
|
|
a6e831e8ca | ||
|
|
ecd8b5db7b | ||
|
|
ffadc1d8de | ||
|
|
06d7d3e9a6 | ||
|
|
94aa34729c | ||
|
|
d0dbc425ee | ||
|
|
6e67012f78 | ||
|
|
187a36e16c | ||
|
|
903edaffc7 | ||
|
|
3e3975d3a0 | ||
|
|
a526c03c12 | ||
|
|
18f4fe32cb | ||
|
|
7ed38e7cb3 | ||
|
|
08eb9ccbb2 | ||
|
|
e31df586db | ||
|
|
865fcf21eb | ||
|
|
a18747a686 | ||
|
|
bbe04de28d | ||
|
|
b3302eeef3 | ||
|
|
1342420920 | ||
|
|
b917ca74c1 | ||
|
|
03070810eb | ||
|
|
4b772c030c | ||
|
|
3794d9718e | ||
|
|
97daa4b3ed | ||
|
|
7b03696d8c | ||
|
|
bbad606bc3 | ||
|
|
49f89569d0 | ||
|
|
408dcc0367 | ||
|
|
dbc0c30fe1 | ||
|
|
caf58cd52a | ||
|
|
0ee236e6a4 | ||
|
|
0c461485fb | ||
|
|
db6a9105de | ||
|
|
d6a8db16b4 | ||
|
|
7addc314f9 | ||
|
|
859e03246f | ||
|
|
0c7ea7278c | ||
|
|
8619e257a7 | ||
|
|
4b30633e03 | ||
|
|
f94aecace7 | ||
|
|
366b89341d | ||
|
|
0c7f425e91 | ||
|
|
3b0469da57 | ||
|
|
0320a14c0a | ||
|
|
72f0577d0c | ||
|
|
3cda5d277b | ||
|
|
02c2bb66e4 | ||
|
|
9cdc60b2c1 | ||
|
|
8e90f8f336 | ||
|
|
a11e4daae6 | ||
|
|
59e818424c | ||
|
|
02e7bbc640 |
@@ -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
+123
-96
@@ -1173,7 +1173,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1211,10 +1211,20 @@ 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"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1226,7 +1236,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1234,7 +1244,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1259,11 +1269,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-keymap",
|
||||
"craft-theme",
|
||||
"craft-tracked",
|
||||
@@ -1277,7 +1288,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1295,12 +1306,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1308,7 +1319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1317,12 +1328,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1330,7 +1341,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1350,10 +1361,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1361,7 +1377,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1371,7 +1387,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1379,7 +1395,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1405,7 +1421,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
@@ -1422,7 +1438,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1430,7 +1446,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1450,7 +1466,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1469,7 +1485,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
@@ -1478,10 +1494,20 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1491,7 +1517,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1506,7 +1532,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1525,7 +1551,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1534,7 +1560,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1557,7 +1583,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-subset"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"harfbuzz-subset-sys",
|
||||
@@ -1570,7 +1596,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-font-subset",
|
||||
]
|
||||
@@ -1578,7 +1604,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gpu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"egui-wgpu",
|
||||
"log",
|
||||
@@ -1590,7 +1616,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1603,7 +1629,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1616,7 +1642,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.1",
|
||||
@@ -1646,7 +1672,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1673,7 +1699,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1691,7 +1717,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1699,7 +1725,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1714,7 +1740,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
@@ -1725,7 +1751,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
@@ -1735,7 +1761,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"roxmltree",
|
||||
@@ -1745,7 +1771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp-server"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1753,7 +1779,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1771,7 +1797,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
@@ -1783,7 +1809,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1794,7 +1820,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
@@ -1805,7 +1831,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1814,7 +1840,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1840,7 +1866,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
@@ -1851,7 +1877,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1868,7 +1894,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1879,7 +1905,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1895,7 +1921,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"serde",
|
||||
@@ -1905,7 +1931,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-channel",
|
||||
@@ -1943,7 +1969,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1967,7 +1993,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1978,7 +2004,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1991,7 +2017,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2010,7 +2036,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -2023,7 +2049,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2040,17 +2066,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
@@ -2067,7 +2093,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2079,7 +2105,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2103,7 +2129,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2118,7 +2144,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2133,7 +2159,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2143,7 +2169,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2152,7 +2178,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2167,12 +2193,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2186,7 +2212,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2203,7 +2229,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2241,7 +2267,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2252,7 +2278,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2270,7 +2296,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2291,7 +2317,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2312,7 +2338,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-test-kit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2323,7 +2349,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2342,7 +2368,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2374,7 +2400,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2385,7 +2411,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-platform",
|
||||
@@ -2397,7 +2423,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2405,7 +2431,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2437,7 +2463,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -2451,7 +2477,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -2464,7 +2490,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -2476,7 +2502,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2486,7 +2512,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -3879,7 +3905,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3888,7 +3914,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3906,7 +3932,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3924,12 +3950,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4658,7 +4684,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4797,7 +4823,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
@@ -9346,6 +9372,7 @@ dependencies = [
|
||||
"craft",
|
||||
"craft-mcp-server",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wordcraft-control-key",
|
||||
"wordcraft-doc",
|
||||
@@ -10067,4 +10094,4 @@ source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f
|
||||
[[patch.unused]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
|
||||
+39
-39
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -85,28 +85,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -174,14 +174,14 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
+164
-38
@@ -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 },
|
||||
@@ -754,28 +847,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);
|
||||
@@ -825,6 +897,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
|
||||
|
||||
@@ -38,11 +38,19 @@ fn run_saves_the_document_opened_last() {
|
||||
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
|
||||
}
|
||||
|
||||
struct TempFile(std::path::PathBuf);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_commands_still_exit_with_an_error() {
|
||||
let script = std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id()));
|
||||
std::fs::write(&script, r#"{"commands":["no.such.command"]}"#).unwrap();
|
||||
let script_path = script.to_string_lossy();
|
||||
let script = TempFile(std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id())));
|
||||
std::fs::write(&script.0, r#"{"commands":["no.such.command"]}"#).unwrap();
|
||||
let script_path = script.0.to_string_lossy();
|
||||
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
|
||||
for (args, expected) in cases {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
@@ -52,5 +60,4 @@ fn failed_run_commands_still_exit_with_an_error() {
|
||||
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
|
||||
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
|
||||
}
|
||||
std::fs::remove_file(script).unwrap();
|
||||
}
|
||||
|
||||
@@ -9,5 +9,6 @@ mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
mod picture_then_typing;
|
||||
mod reproducible_pdf;
|
||||
mod strict;
|
||||
mod text_tracked;
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,10 +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))
|
||||
&& 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);
|
||||
@@ -842,6 +852,61 @@ mod tests {
|
||||
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_zero_counters_increment_properly() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(a) = n.abstracts.first_mut() {
|
||||
a.levels[0].start = 0;
|
||||
a.levels[0].text = "Item %1.".into();
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 0.");
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 1.");
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 2.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_override_of_zero_starts_at_zero() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
|
||||
num.start_overrides = vec![(0, 0)];
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
let labels: Vec<String> = (0..3).map(|_| c.next_label(&n, id, 0).unwrap().0).collect();
|
||||
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();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(a) = n.abstracts.first_mut() {
|
||||
a.levels[0].text = "%0 %1.".into();
|
||||
}
|
||||
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]
|
||||
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
|
||||
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
|
||||
|
||||
@@ -122,7 +122,6 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
</w:p>
|
||||
"#;
|
||||
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
let expected_styles = [
|
||||
("Dot", Some(EmphasisMark::Dot)),
|
||||
("Comma", Some(EmphasisMark::Comma)),
|
||||
@@ -130,21 +129,33 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
("UnderDot", Some(EmphasisMark::UnderDot)),
|
||||
("NoMark", Some(EmphasisMark::None)),
|
||||
];
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark);
|
||||
}
|
||||
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None));
|
||||
let expected_runs = [
|
||||
Some(EmphasisMark::Dot),
|
||||
Some(EmphasisMark::Comma),
|
||||
Some(EmphasisMark::Circle),
|
||||
Some(EmphasisMark::UnderDot),
|
||||
Some(EmphasisMark::None),
|
||||
None,
|
||||
(Some("Dot"), None, EmphasisMark::Dot),
|
||||
(Some("Comma"), None, EmphasisMark::Comma),
|
||||
(Some("Circle"), None, EmphasisMark::Circle),
|
||||
(Some("UnderDot"), None, EmphasisMark::UnderDot),
|
||||
(Some("Dot"), Some(EmphasisMark::None), EmphasisMark::None),
|
||||
(Some("NoMark"), None, EmphasisMark::None),
|
||||
(None, Some(EmphasisMark::Dot), EmphasisMark::Dot),
|
||||
(None, Some(EmphasisMark::Comma), EmphasisMark::Comma),
|
||||
(None, Some(EmphasisMark::Circle), EmphasisMark::Circle),
|
||||
(None, Some(EmphasisMark::UnderDot), EmphasisMark::UnderDot),
|
||||
(None, Some(EmphasisMark::None), EmphasisMark::None),
|
||||
(None, None, EmphasisMark::None),
|
||||
];
|
||||
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
|
||||
assert_eq!(run.props.emphasis, mark);
|
||||
}
|
||||
let assert_state = |doc: &wordcraft_doc::Document, stage: &str| {
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "{stage}: style {id}");
|
||||
}
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
let actual: Vec<_> = p
|
||||
.runs
|
||||
.iter()
|
||||
.map(|r| (r.props.style.as_deref(), r.props.emphasis, doc.styles.resolve_char(p.props.style.as_deref(), &r.props).emphasis))
|
||||
.collect();
|
||||
assert_eq!(actual, expected_runs, "{stage}");
|
||||
};
|
||||
assert_state(&doc, "initial read");
|
||||
|
||||
for pass in 0..2 {
|
||||
let out = wordcraft_docx::write(&doc).unwrap();
|
||||
@@ -156,17 +167,7 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
|
||||
assert!(document_xml.contains("default dot"));
|
||||
doc = wordcraft_docx::read(&out).unwrap();
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "pass {pass}");
|
||||
}
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
for index in [0, 1, 2, 3, 5] {
|
||||
assert_eq!(p.runs[index].props.emphasis, None, "pass {pass}: run {index}");
|
||||
}
|
||||
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None), "pass {pass}: run 4",);
|
||||
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
|
||||
assert_eq!(run.props.emphasis, mark, "pass {pass}");
|
||||
}
|
||||
assert_state(&doc, &format!("pass {pass}"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -513,6 +513,7 @@ fn split_para_as(s: &mut Session, at: &Pos, enter: bool) -> Result<Pos, CmdError
|
||||
let para = s.doc.para_mut(at.story, &at.path)?;
|
||||
if n.level > 0 {
|
||||
para.props.numbering = Some(wordcraft_doc::props::NumRef { num: n.num, level: n.level - 1 });
|
||||
para::drop_direct_indents(&mut para.props);
|
||||
para.touch();
|
||||
} else {
|
||||
leave_list(para);
|
||||
|
||||
@@ -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,46 +332,67 @@ 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};
|
||||
let mut doc = Document::new();
|
||||
doc.body = (0..8000u32)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::default();
|
||||
p.props.page_break_before = Some(i > 0);
|
||||
let id = i * 2 + 1;
|
||||
for (kind, x, extra) in [
|
||||
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
|
||||
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
|
||||
(
|
||||
ShapeKind::ElbowConnector,
|
||||
0.0,
|
||||
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
|
||||
),
|
||||
] {
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
|
||||
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
|
||||
}
|
||||
para_block(p)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Session::new(doc);
|
||||
s.view.proofing = false;
|
||||
s.page_hint = 0;
|
||||
assert_eq!(s.layout().pages.len(), 8000);
|
||||
let started = std::time::Instant::now();
|
||||
assert!(reroute(&mut s));
|
||||
let elapsed = started.elapsed();
|
||||
eprintln!("8000-page reroute: {elapsed:?}");
|
||||
assert!(elapsed < std::time::Duration::from_secs(5), "reroute took {elapsed:?}");
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
let para = s.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
|
||||
fn glued_pages(n: u32) -> Session {
|
||||
let mut doc = Document::new();
|
||||
doc.body = (0..n)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::default();
|
||||
p.props.page_break_before = Some(i > 0);
|
||||
let id = i * 2 + 1;
|
||||
for (kind, x, extra) in [
|
||||
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
|
||||
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
|
||||
(
|
||||
ShapeKind::ElbowConnector,
|
||||
0.0,
|
||||
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
|
||||
),
|
||||
] {
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
|
||||
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
|
||||
}
|
||||
para_block(p)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Session::new(doc);
|
||||
s.view.proofing = false;
|
||||
s.page_hint = 0;
|
||||
assert_eq!(s.layout().pages.len(), n as usize);
|
||||
s
|
||||
}
|
||||
const SMALL: u32 = 32;
|
||||
const SCALE: u32 = 8;
|
||||
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(connector_off).unwrap() else { panic!("connector") };
|
||||
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
|
||||
}
|
||||
s.touch();
|
||||
assert!(!reroute(&mut s), "rerouting must settle after refreshing the layout");
|
||||
big.touch();
|
||||
assert!(!reroute(&mut big), "rerouting must settle after refreshing the layout");
|
||||
}
|
||||
|
||||
/// The per-case shape/geometry of one scaled-group reroute case.
|
||||
|
||||
@@ -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)
|
||||
@@ -161,7 +164,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted); replaces in the main text, headers, footers, footnotes, endnotes and text boxes, wherever the caret is"#),
|
||||
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
|
||||
.key("Mod+Alt+G / F5")
|
||||
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
|
||||
@@ -827,16 +830,52 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
/// the replacement (`^p`) splits the paragraph.
|
||||
/// The stories Replace All covers, as in Word: the main text, then the headers, footers,
|
||||
/// footnotes, endnotes and text boxes the document shows. Hidden stories (a removed header, a
|
||||
/// deleted note's text) and comments keep their words.
|
||||
fn replace_stories(s: &Session) -> Vec<StoryRef> {
|
||||
s.doc.shown_stories()
|
||||
}
|
||||
|
||||
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
|
||||
/// stay valid (one undo step). A `\r` in the replacement (`^p`) splits the paragraph. Locked
|
||||
/// content in any story stops it before anything changes.
|
||||
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
need_query(s, v)?;
|
||||
read_opts(s, v);
|
||||
let story = s.sel.focus.story;
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
let n = results.len();
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
let mut found = Vec::new();
|
||||
// A protected document only lets the editable regions change: matches elsewhere (in a header,
|
||||
// say) stay as they are, so they don't make the whole command fail.
|
||||
let editable = super::protect::editable_ranges(s);
|
||||
for story in replace_stories(s) {
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let mut results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
if let Some(ranges) = &editable {
|
||||
results.retain(|f| ranges.iter().any(|(from, to)| f.a.story == from.story && f.a >= *from && f.b <= *to));
|
||||
}
|
||||
if results.is_empty() {
|
||||
continue;
|
||||
}
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
found.push(results);
|
||||
}
|
||||
let n: usize = found.iter().map(Vec::len).sum();
|
||||
let saved_sel = s.sel.clone();
|
||||
let orig_story_matched = found.iter().any(|r| r[0].a.story == saved_sel.focus.story);
|
||||
// The main text comes last, so under Track Changes the caret ends where it did before;
|
||||
// when the original story had no match, restore the selection so it stays there.
|
||||
for results in found.into_iter().rev() {
|
||||
replace_found(s, results)?;
|
||||
}
|
||||
if s.doc.settings.track_changes && !orig_story_matched {
|
||||
s.sel = saved_sel;
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
}
|
||||
|
||||
/// Replace the matches of one story, last first.
|
||||
fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
|
||||
for Found { a, b, rep, .. } in results.into_iter().rev() {
|
||||
let with = rep.unwrap_or_default();
|
||||
if s.doc.settings.track_changes {
|
||||
@@ -857,8 +896,7 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -668,6 +668,18 @@ fn recipient_lists_in_legacy_and_utf16_encodings() {
|
||||
assert_eq!(s.merge.rows, [["José"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipient_list_with_generic_utf32_uses_its_big_endian_bom() {
|
||||
let mut data = vec![0x00, 0x00, 0xFE, 0xFF];
|
||||
for c in "Name,City\nAda,A🌍\n".chars() {
|
||||
data.extend_from_slice(&(c as u32).to_be_bytes());
|
||||
}
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("mailings.recipients", &json!({"path": "list.csv", "data": b64(&data), "encoding": "utf-32"})).unwrap();
|
||||
assert_eq!(s.merge.headers, ["Name", "City"]);
|
||||
assert_eq!(s.merge.rows, [["Ada", "A🌍"]]);
|
||||
}
|
||||
|
||||
/// #778: legacy Excel 97–2003 workbooks are recipient lists; a CSV named .xls reads as text.
|
||||
#[test]
|
||||
fn recipients_from_an_xls_workbook() {
|
||||
|
||||
@@ -287,6 +287,30 @@ 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))
|
||||
}
|
||||
|
||||
/// The path a folder setting names: `~/…` under the home folder, or the path as given. With no
|
||||
/// home folder to expand under, `~/` is refused rather than left as a relative path.
|
||||
fn expand_home(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<std::path::PathBuf, CmdError> {
|
||||
match (f.strip_prefix("~/"), home) {
|
||||
(Some(rest), Some(h)) => Ok(h.join(rest)),
|
||||
(Some(_), None) => Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
|
||||
(None, _) => Ok(std::path::PathBuf::from(f)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -299,11 +323,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")));
|
||||
}
|
||||
@@ -355,3 +375,45 @@ 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, home_from};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("para.heading3", "Heading 3", "Home › Styles", |s, _| apply_style(s, &json!({"style": "Heading3"}))).key("Mod+Alt+3"),
|
||||
CommandSpec::new("para.bullets", "Bullets", "Home › Paragraph", |s, v| list(s, v, ListKind::Bullet)).params(r#"{"kind"?: "bullet" | single char, "off"?: bool}"#).key("Mod+Shift+L"),
|
||||
CommandSpec::new("para.numbering", "Numbering", "Home › Paragraph", |s, v| list(s, v, ListKind::Numbered))
|
||||
.params(r#"{"kind"?: "numbered|numberedParen|upperLetter|lowerLetter|lowerRoman|outline", "off"?: bool}"#),
|
||||
.params(r#"{"kind"?: "numbered|numberedParen|outline|upperLetter|lowerLetter|lowerLetterDot|lowerRoman", "off"?: bool}"#),
|
||||
CommandSpec::new("para.multilevel", "Multilevel List", "Home › Paragraph", |s, v| list(s, v, ListKind::Legal)).params(r#"{"kind"?: "legal|outline"}"#),
|
||||
CommandSpec::new("para.listLevel", "Change List Level", "Home › Paragraph › Bullets", |s, v| {
|
||||
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
|
||||
|
||||
@@ -13,13 +13,24 @@ pub(super) fn list(s: &mut Session, v: &Value, default: ListKind) -> CmdResult {
|
||||
.map(|p| s.doc.para(a.story, p).and_then(|x| s.doc.styles.resolve_para(&x.props).numbering).filter(|n| n.num != 0))
|
||||
.collect();
|
||||
let same_kind = |n: &NumRef| {
|
||||
s.doc.numbering.level(n.num, n.level).is_some_and(|l| {
|
||||
let want = wordcraft_doc::numbering::levels_for(kind);
|
||||
want.get(usize::from(n.level)).is_some_and(|w| {
|
||||
let want = wordcraft_doc::numbering::levels_for(kind);
|
||||
// Is the list's level `i` (with this list's own overrides) the preset's level `i`?
|
||||
let level_is = |i: u8, with_text: bool| match (s.doc.numbering.level(n.num, i), want.get(usize::from(i))) {
|
||||
(Some(l), Some(w)) => {
|
||||
(w.format == wordcraft_doc::section::NumFormat::Bullet) == (l.format == wordcraft_doc::section::NumFormat::Bullet)
|
||||
&& (p::str(v, "kind").is_none() || w.text == l.text)
|
||||
})
|
||||
})
|
||||
// A named preset is the same one only in its number style and text: "1." and "A." are
|
||||
// both `%1.`, so picking one over the other changes the list, not switches it off (#4281).
|
||||
&& (!with_text || (w.text == l.text && w.format == l.format))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let named = p::str(v, "kind").is_some();
|
||||
// A named preset is told by its first level as well as the paragraph's own, as deeper levels of
|
||||
// two presets can look alike; unless the list starts with the other kind of marker (a bullet
|
||||
// above numbers, or the reverse), where the paragraph's own level decides.
|
||||
let is_bullet = |i: u8| s.doc.numbering.level(n.num, i).map(|l| l.format == wordcraft_doc::section::NumFormat::Bullet);
|
||||
let one_kind_throughout = is_bullet(0) == is_bullet(n.level);
|
||||
level_is(n.level, named) && (!named || !one_kind_throughout || level_is(0, true))
|
||||
};
|
||||
let remove = off || (!current.is_empty() && current.iter().all(|n| n.as_ref().is_some_and(same_kind)));
|
||||
if remove {
|
||||
|
||||
@@ -695,6 +695,27 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
|
||||
Pos { off, ..p.clone() }
|
||||
}
|
||||
|
||||
/// The ranges, in any story, that a document protected as read only, comments only or forms
|
||||
/// lets this author edit; `None` when the protection doesn't limit where edits may land. A command
|
||||
/// that searches the whole document keeps only its matches inside them, so a match in protected
|
||||
/// content (a header repeating a placeholder) is left alone instead of failing the command.
|
||||
pub(crate) fn editable_ranges(s: &Session) -> Option<Vec<(Pos, Pos)>> {
|
||||
match s.doc.settings.protection.as_deref()? {
|
||||
"forms" => {
|
||||
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
|
||||
Some(
|
||||
stories
|
||||
.flat_map(|story| s.doc.control_ranges(story))
|
||||
.filter(|r| r.control.lock.can_edit())
|
||||
.map(|r| (r.content_start(), r.end))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
"readOnly" | "comments" => Some(s.doc.perm_ranges().into_iter().filter(|r| editable_by(r, &s.author)).map(|r| (r.start, r.end)).collect()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first position in an editable range after `from` (wrapping round), for Find Next Region
|
||||
/// I Can Edit; with it, the range's end. Filling in forms: the next fillable control's content.
|
||||
pub fn next_region(s: &Session, from: &Pos) -> Option<(Pos, Pos)> {
|
||||
|
||||
@@ -32,6 +32,30 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
|
||||
assert_eq!(s.doc.settings.protection.as_deref(), Some("readOnly"));
|
||||
}
|
||||
|
||||
/// Replace All covers every story, but in a protected document only the editable regions change:
|
||||
/// the same placeholder in a header, a footnote or the locked body text is left as it is, and
|
||||
/// the replacement in the editable region still goes through.
|
||||
#[test]
|
||||
fn replace_all_in_a_protected_document_skips_protected_matches() {
|
||||
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
|
||||
let header = s.run("insert.header", &json!({"text": "Header [NAME]"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
let note = s.run("references.footnote", &json!({"text": "Note [NAME]"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
s.sel = Selection::caret(Pos::body(0, 0));
|
||||
select(&mut s, "Fill [NAME] in.");
|
||||
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let r = s.run("edit.replaceAll", &json!({"text": "[NAME]", "with": "Jane"})).unwrap();
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
let body = s.doc.plain_text(StoryRef::Body).replace(OBJ, "");
|
||||
assert!(body.contains("Locked [NAME]."), "{body}");
|
||||
assert!(body.contains("Fill Jane in."), "{body}");
|
||||
for id in [header, note] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(s.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exception that starts a line: Home, Left and Down put the caret before its start
|
||||
/// marker, and Enter and typing there go inside the exception. A caret after the end marker at
|
||||
/// the end of the line goes back inside it too.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -155,6 +155,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 +302,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;
|
||||
|
||||
+202
-49
@@ -3775,14 +3775,14 @@ fn select_all_keeps_the_whole_story_when_it_ends_in_a_table() {
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
run(&mut s, "text.insert", json!({"text": "A1"}));
|
||||
s.doc.body.pop();
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
let whole = (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body));
|
||||
assert!(s.doc.end_of(StoryRef::Body).path.cell().is_some());
|
||||
assert_eq!(s.sel.ordered(), whole);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
assert!(s.column.is_none());
|
||||
assert_eq!(s.sel.ordered(), whole);
|
||||
}
|
||||
@@ -11890,19 +11890,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 +11908,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 +11986,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 +12017,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 +12031,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 +12086,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 +12194,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 +12238,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 +12267,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 +12286,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 +12325,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 +12336,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 +12369,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 +12409,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 +12437,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!({}));
|
||||
@@ -12461,7 +12465,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 +12509,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 +12615,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!({}));
|
||||
@@ -15456,6 +15460,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 +15884,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(4);
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -15916,6 +15962,113 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #3300: Replace All, as in Word, replaces in the main text, headers, footers, footnotes,
|
||||
/// endnotes and text boxes, wherever the caret is. Comments keep their words.
|
||||
#[test]
|
||||
fn replace_all_replaces_in_every_story() {
|
||||
use wordcraft_doc::{CharProps, Paragraph, PartKind, StoryRef, para_block};
|
||||
let story_text = |t: &Session, story: StoryRef| {
|
||||
let first = wordcraft_doc::Pos::new(story, wordcraft_doc::Path::top(0), 0);
|
||||
if story == StoryRef::Body { t.doc.plain_text(story) } else { t.doc.para_at(&first).map(|p| p.text.clone()).unwrap_or_default() }
|
||||
};
|
||||
let build = || {
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body: [NAME] and [NAME]."}));
|
||||
// A text box the body shows (one nothing shows is pruned with the next command).
|
||||
let boxed = run(&mut t, "insert.textBox", json!({"text": "Text box: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let header = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
let footer = run(&mut t, "insert.footer", json!({"text": "Footer: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let footnote = run(&mut t, "references.footnote", json!({"text": "Footnote: [NAME]"}))["id"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let endnote = run(&mut t, "references.endnote", json!({"text": "Endnote: [NAME]"}))["id"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let comment = t.doc.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment: [NAME]", CharProps::default()))]);
|
||||
let ids = [header, footer, footnote, endnote, boxed, comment];
|
||||
(t, ids)
|
||||
};
|
||||
let (mut t, ids) = build();
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 7, "{r}");
|
||||
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: Jane and Jane.");
|
||||
let texts: Vec<String> = ids.iter().map(|id| story_text(&t, StoryRef::Part(*id)).replace(wordcraft_doc::para::OBJ, "")).collect();
|
||||
assert_eq!(texts, ["Header: Jane", "Footer: Jane", " Footnote: Jane", " Endnote: Jane", "Text box: Jane", "Comment: [NAME]"]);
|
||||
// One undo step brings every story back.
|
||||
run(&mut t, "edit.undo", json!({}));
|
||||
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: [NAME] and [NAME].");
|
||||
assert_eq!(story_text(&t, StoryRef::Part(ids[0])), "Header: [NAME]");
|
||||
assert_eq!(story_text(&t, StoryRef::Part(ids[2])).replace(wordcraft_doc::para::OBJ, ""), " Footnote: [NAME]");
|
||||
// From the caret in a footnote the body is replaced too.
|
||||
let (mut t, ids) = build();
|
||||
t.sel = crate::session::Selection::caret(wordcraft_doc::Pos::new(StoryRef::Part(ids[2]), wordcraft_doc::Path::top(0), 0));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 7, "{r}");
|
||||
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: Jane and Jane.");
|
||||
// Under Track Changes the replacements are revisions in every story, and nothing breaks.
|
||||
let (mut t, ids) = build();
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 7, "{r}");
|
||||
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"))
|
||||
);
|
||||
}
|
||||
|
||||
/// #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]
|
||||
fn replace_all_skips_removed_header_and_deleted_footnote_stories() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body."}));
|
||||
let header = run(&mut t, "insert.header", json!({"text": "Header [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "insert.removeHeader", json!({}));
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let footnote = run(&mut t, "references.footnote", json!({"text": "Footnote [NAME]"}))["id"].as_u64().unwrap() as u32;
|
||||
// Delete the footnote reference from the body without Track Changes, leaving the part behind.
|
||||
t.doc.delete_range(&Pos::body(0, 0), &Pos::body(0, 1)).unwrap();
|
||||
t.sel = crate::session::Selection::caret(Pos::body(0, 0));
|
||||
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 0, "{r}");
|
||||
assert_eq!(t.status, "All done. We made 0 replacements.");
|
||||
for id in [header, footnote] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(t.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
|
||||
// A match in a shown story still replaces, without touching or counting the hidden ones.
|
||||
run(&mut t, "document.setText", json!({"text": "Body [NAME]."}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
assert_eq!(t.doc.plain_text(StoryRef::Body), "Body Jane.");
|
||||
for id in [header, footnote] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(t.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -195,6 +195,68 @@ fn enter_on_an_empty_nested_item_moves_it_up_a_level_first() {
|
||||
assert_eq!(paras(&s), vec![para("A", Some(0)), para("B", Some(1)), para("text", None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_outdents_an_empty_list_item_and_drops_direct_indents() {
|
||||
use wordcraft_doc::props::{NumRef, ParaProps};
|
||||
use wordcraft_doc::styles::Style;
|
||||
|
||||
let fixture = typed("* One\n\tTwo\n");
|
||||
let at = fixture.sel.focus.clone();
|
||||
let item = fixture.doc.para_at(&at).unwrap();
|
||||
assert!(item.is_empty());
|
||||
let nested = item.props.numbering.unwrap();
|
||||
assert_eq!(nested.level, 1);
|
||||
let promoted = NumRef { level: 0, ..nested };
|
||||
|
||||
let mut doc = fixture.doc.clone();
|
||||
Arc::make_mut(&mut doc.styles).upsert(Style {
|
||||
id: "NestedFixture".into(),
|
||||
name: "Nested Fixture".into(),
|
||||
para: ParaProps { numbering: Some(nested), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let caret_x = |s: &mut Session| s.layout().caret(&at).expect("the empty list item's caret").x;
|
||||
for inherited in [false, true] {
|
||||
let mut doc = doc.clone();
|
||||
let props = &mut doc.para_mut(at.story, &at.path).unwrap().props;
|
||||
props.style = Some("NestedFixture".into());
|
||||
props.numbering = (!inherited).then_some(nested);
|
||||
props.indent_right = Some(12.0);
|
||||
props.space_after = Some(9.0);
|
||||
let mut expected = props.clone();
|
||||
expected.numbering = Some(promoted);
|
||||
|
||||
let mut control = Session::new(doc.clone());
|
||||
control.sel = crate::Selection::caret(at.clone());
|
||||
typ(&mut control, "\n");
|
||||
assert_eq!(control.doc.para_at(&at).unwrap().props, expected);
|
||||
let promoted_x = caret_x(&mut control);
|
||||
|
||||
for chars in [false, true] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
s.sel = crate::Selection::caret(at.clone());
|
||||
let props = &mut s.doc.para_mut(at.story, &at.path).unwrap().props;
|
||||
if chars {
|
||||
props.indent_left_chars = Some(8.0);
|
||||
props.indent_first_chars = Some(-2.0);
|
||||
} else {
|
||||
props.indent_left = Some(144.0);
|
||||
props.indent_first = Some(-18.0);
|
||||
}
|
||||
let before = props.clone();
|
||||
let depth = s.undo_depth();
|
||||
typ(&mut s, "\n");
|
||||
|
||||
assert_eq!(s.doc.para_at(&at).unwrap().props, expected, "inherited={inherited}, chars={chars}");
|
||||
assert_eq!(caret_x(&mut s), promoted_x, "indent matches the new level without an override");
|
||||
assert_eq!(s.sel.focus, at);
|
||||
assert_eq!(s.undo_depth(), depth + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.para_at(&at).unwrap().props, before, "Undo restores both numbering and indentation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #2143: in a Word file whose list comes from the paragraph styles (List Number, List Number 2
|
||||
/// with `w:numPr` in styles.xml, none on the paragraphs), Enter on an empty nested item moves it
|
||||
/// up a level and then ends the list, as with direct numbering.
|
||||
@@ -2834,23 +2896,12 @@ fn typing_rtl_letters_into_an_empty_paragraph_makes_it_rtl() {
|
||||
#[test]
|
||||
fn select_all_then_delete_removes_tables() {
|
||||
let tables = |s: &Session| s.doc.body.iter().filter(|b| b.as_table().is_some()).count();
|
||||
// With the caret in a table, Select All grows the selection a step at a time (cell, row,
|
||||
// table, document; #1478): press it until the whole document is selected.
|
||||
let select_whole_document = |s: &mut Session| {
|
||||
for _ in 0..6 {
|
||||
let before = s.sel.clone();
|
||||
run(s, "select.all", json!({}));
|
||||
if s.sel == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
for key in ["text.delete", "text.backspace"] {
|
||||
let mut s = typed("");
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
typ(&mut s, "cell");
|
||||
assert_eq!(tables(&s), 1);
|
||||
select_whole_document(&mut s);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, key, json!({}));
|
||||
assert_eq!(tables(&s), 0, "{key}: a table at the start of the document goes");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "", "{key}");
|
||||
@@ -2859,7 +2910,7 @@ fn select_all_then_delete_removes_tables() {
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
typ(&mut s, "cell");
|
||||
assert_eq!(tables(&s), 1);
|
||||
select_whole_document(&mut s);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, key, json!({}));
|
||||
assert_eq!(tables(&s), 0, "{key}: a table after text goes");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "", "{key}");
|
||||
@@ -3598,6 +3649,7 @@ fn change_case_follows_turkic_case_mapping() {
|
||||
}
|
||||
// Other languages keep the Unicode default.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
@@ -3617,6 +3669,18 @@ fn change_case_follows_turkic_case_mapping() {
|
||||
run(&mut s, "format.changeCase", json!({"mode": mode}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want, "mixed runs {mode}");
|
||||
}
|
||||
// Mixed runs tagged on selections within existing text: each run's own language decides.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "text.insert", json!({"text": "IŞIK IŞIK", "raw": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 5), "extend": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 11), "extend": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "ışık işik", "mixed runs on selection");
|
||||
}
|
||||
|
||||
// Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves
|
||||
@@ -4648,6 +4712,60 @@ fn issues_1281_1045_english_dialects_proof_typed_text() {
|
||||
assert_eq!(words, ["21th"]);
|
||||
}
|
||||
|
||||
/// #4281: Home › Numbering offers every preset, "a. b. c." among them, and picking another preset
|
||||
/// for a list that is already numbered changes its style (only picking the same one again turns it off).
|
||||
#[test]
|
||||
fn the_numbering_gallery_presets_each_apply_and_switch_between_each_other() {
|
||||
let labels = |s: &mut Session| numbers(s).into_iter().map(|(l, _)| l.unwrap_or_default()).collect::<Vec<_>>();
|
||||
for (kind, want) in [
|
||||
("numbered", ["1.", "2.", "3."]),
|
||||
("numberedParen", ["1)", "2)", "3)"]),
|
||||
("outline", ["I.", "II.", "III."]),
|
||||
("upperLetter", ["A.", "B.", "C."]),
|
||||
("lowerLetter", ["a)", "b)", "c)"]),
|
||||
("lowerLetterDot", ["a.", "b.", "c."]),
|
||||
("lowerRoman", ["i.", "ii.", "iii."]),
|
||||
] {
|
||||
let mut s = s();
|
||||
typ(&mut s, "One\nTwo\nThree");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "para.numbering", json!({"kind": kind}));
|
||||
assert_eq!(labels(&mut s), want, "{kind}");
|
||||
// Picking the same preset again turns the list off.
|
||||
run(&mut s, "para.numbering", json!({"kind": kind}));
|
||||
assert_eq!(labels(&mut s), ["", "", ""], "{kind} again");
|
||||
}
|
||||
// From one preset to another: the list changes style, it doesn't go off.
|
||||
let mut s = s();
|
||||
typ(&mut s, "One\nTwo\nThree");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "para.numbering", json!({"kind": "numbered"}));
|
||||
for (kind, want) in [("upperLetter", "A."), ("lowerLetterDot", "a."), ("lowerRoman", "i."), ("outline", "I."), ("numbered", "1.")] {
|
||||
run(&mut s, "para.numbering", json!({"kind": kind}));
|
||||
assert_eq!(labels(&mut s)[0], want, "to {kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4281: whatever level a list item is on, picking a different Numbering preset changes the list
|
||||
/// and never turns it off; deeper levels of two presets can look alike.
|
||||
#[test]
|
||||
fn another_numbering_preset_never_switches_a_list_off_at_any_level() {
|
||||
let kinds = ["numbered", "numberedParen", "outline", "upperLetter", "lowerLetter", "lowerLetterDot", "lowerRoman"];
|
||||
for a in kinds {
|
||||
for b in kinds.into_iter().filter(|b| *b != a) {
|
||||
for level in 0..9 {
|
||||
let mut s = s();
|
||||
typ(&mut s, "One");
|
||||
run(&mut s, "para.numbering", json!({"kind": a}));
|
||||
run(&mut s, "para.listLevel", json!({"level": level}));
|
||||
run(&mut s, "para.numbering", json!({"kind": b}));
|
||||
let label = numbers(&mut s).into_iter().next().and_then(|(l, _)| l);
|
||||
assert!(label.is_some(), "{a} -> {b} at level {level} turned the list off");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the first paragraph's list label starts (points from the page's text edge), and where its text starts.
|
||||
fn label_and_text_x(s: &mut Session) -> (f32, f32) {
|
||||
let l = s.layout();
|
||||
@@ -4758,3 +4876,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");
|
||||
}
|
||||
|
||||
+186
-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;
|
||||
|
||||
@@ -13,23 +13,77 @@ use crate::model::{FBlock, ListCounter, from_doc};
|
||||
#[cfg(test)]
|
||||
mod legacy_oracle_tests;
|
||||
|
||||
const UTF32_LE_BOM: &[u8] = &[0xFF, 0xFE, 0x00, 0x00];
|
||||
const UTF32_BE_BOM: &[u8] = &[0x00, 0x00, 0xFE, 0xFF];
|
||||
|
||||
fn utf32(b: &[u8], le: bool) -> String {
|
||||
let units: Vec<char> = b
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let u = if le { u32::from_le_bytes(*c) } else { u32::from_be_bytes(*c) };
|
||||
char::from_u32(u).unwrap_or('\u{FFFD}')
|
||||
})
|
||||
.collect();
|
||||
units.into_iter().collect()
|
||||
}
|
||||
|
||||
fn decode_utf32_bom(b: &[u8]) -> Option<String> {
|
||||
if let Some(rest) = b.strip_prefix(UTF32_LE_BOM) {
|
||||
return Some(utf32(rest, true));
|
||||
}
|
||||
b.strip_prefix(UTF32_BE_BOM).map(|rest| utf32(rest, false))
|
||||
}
|
||||
|
||||
// Detection is shared with the other Craft apps. WordCraft's `cp1252` and encoding_rs agree on
|
||||
// every byte (pinned by `legacy_oracle_tests`), so a Windows-1252 guess needs no local mapping.
|
||||
pub use craft_mime::detect::{decode, is_text, legacy};
|
||||
pub use craft_mime::detect::legacy;
|
||||
|
||||
/// Does `b` look like plain text ([`craft_mime::detect::is_text`])? A UTF-32 BOM counts as text.
|
||||
pub fn is_text(b: &[u8]) -> bool {
|
||||
b.starts_with(UTF32_LE_BOM) || b.starts_with(UTF32_BE_BOM) || craft_mime::detect::is_text(b)
|
||||
}
|
||||
|
||||
/// Decode text bytes: a UTF-32 BOM first, then [`craft_mime::detect::decode`] (other BOMs, UTF-16
|
||||
/// without BOM, UTF-8, the legacy encoding the bytes look like).
|
||||
pub fn decode(b: &[u8]) -> String {
|
||||
decode_utf32_bom(b).unwrap_or_else(|| craft_mime::detect::decode(b))
|
||||
}
|
||||
|
||||
/// Decode bytes in a named encoding (a WHATWG label such as `gbk`, `gb18030`, `big5`,
|
||||
/// `shift_jis`, `euc-kr`, `utf-16le`, `windows-1251`); `None` when the label isn't known.
|
||||
/// The generic `utf-32` label honors either BOM and defaults to little-endian without one.
|
||||
pub fn decode_as(b: &[u8], label: &str) -> Option<String> {
|
||||
let enc = encoding_rs::Encoding::for_label(label.trim().as_bytes())?;
|
||||
let clean = label.trim().to_ascii_lowercase();
|
||||
match clean.as_str() {
|
||||
"utf-32" => return Some(decode_utf32_bom(b).unwrap_or_else(|| utf32(b, true))),
|
||||
"utf-32le" => return Some(utf32(b.strip_prefix(UTF32_LE_BOM).unwrap_or(b), true)),
|
||||
"utf-32be" => return Some(utf32(b.strip_prefix(UTF32_BE_BOM).unwrap_or(b), false)),
|
||||
_ => {}
|
||||
}
|
||||
let enc = encoding_rs::Encoding::for_label(clean.as_bytes())?;
|
||||
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{000C}')).collect();
|
||||
Document::from_text(&clean)
|
||||
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000B}' | '\u{000C}' | '\u{000E}')).collect();
|
||||
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).
|
||||
@@ -52,23 +106,33 @@ 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) => {
|
||||
lists.reset();
|
||||
let cols = t.cols();
|
||||
for row in &t.rows {
|
||||
let cells: Vec<String> = row
|
||||
.iter()
|
||||
.map(|c| {
|
||||
if depth > 8 {
|
||||
return String::new();
|
||||
}
|
||||
let mut cells: Vec<String> = Vec::new();
|
||||
for c in row {
|
||||
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);
|
||||
v.join(" ")
|
||||
})
|
||||
.collect();
|
||||
// Flatten breaks and tabs inside a field without changing its spacing.
|
||||
cells.push(v.join(" ").replace("\r\n", " ").replace(['\t', '\r', '\n', '\u{000B}', '\u{000E}'], " "));
|
||||
}
|
||||
for _ in 1..c.colspan.clamp(1, 63) {
|
||||
cells.push(String::new());
|
||||
}
|
||||
}
|
||||
cells.resize(cols, String::new());
|
||||
out.push(cells.join("\t"));
|
||||
}
|
||||
}
|
||||
@@ -86,3 +150,109 @@ pub fn export(doc: &Document) -> Vec<u8> {
|
||||
blocks_text(&flow.blocks, &mut lines, &mut ListCounter::default(), 0);
|
||||
lines.join("\r\n").into_bytes()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{Cell, Fmt, Para};
|
||||
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() {
|
||||
let mut u32le = vec![0xFF, 0xFE, 0x00, 0x00];
|
||||
for c in "Hello 🦀".chars() {
|
||||
u32le.extend((c as u32).to_le_bytes());
|
||||
}
|
||||
assert!(is_text(&u32le));
|
||||
assert_eq!(decode(&u32le), "Hello 🦀");
|
||||
assert_eq!(decode_as(&u32le, "utf-32"), Some("Hello 🦀".into()));
|
||||
assert_eq!(decode_as(&u32le, "utf-32le"), Some("Hello 🦀".into()));
|
||||
assert_eq!(decode_as(&u32le[4..], "utf-32"), Some("Hello 🦀".into()));
|
||||
|
||||
let mut u32be = vec![0x00, 0x00, 0xFE, 0xFF];
|
||||
for c in "World 🌍".chars() {
|
||||
u32be.extend((c as u32).to_be_bytes());
|
||||
}
|
||||
assert!(is_text(&u32be));
|
||||
assert_eq!(decode(&u32be), "World 🌍");
|
||||
assert_eq!(decode_as(&u32be, "utf-32"), Some("World 🌍".into()));
|
||||
assert_eq!(decode_as(&u32be, "utf-32be"), Some("World 🌍".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_import_preserves_soft_breaks() {
|
||||
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 test_table_export_colspan_covered_and_newline_cleaning() {
|
||||
let mut t = crate::model::FTable::default();
|
||||
let mut c1 = Cell { colspan: 2, ..Default::default() };
|
||||
let mut p1 = Para::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();
|
||||
let mut p2 = Para::default();
|
||||
p2.push_text("Col 3", &Fmt::default());
|
||||
c2.blocks.push(FBlock::Para(p2));
|
||||
|
||||
let c3 = Cell { covered: true, ..Default::default() };
|
||||
|
||||
let mut c4 = Cell::default();
|
||||
let mut p4 = Para::default();
|
||||
p4.push_text("Row 2 Col 2", &Fmt::default());
|
||||
c4.blocks.push(FBlock::Para(p4));
|
||||
|
||||
let mut c5 = Cell::default();
|
||||
let mut p5 = Para::default();
|
||||
p5.push_text("Row 2 Col 3", &Fmt::default());
|
||||
c5.blocks.push(FBlock::Para(p5));
|
||||
|
||||
t.rows.push(vec![c1, c2]);
|
||||
t.rows.push(vec![c3, c4, c5]);
|
||||
|
||||
let mut out = Vec::new();
|
||||
let blocks = vec![FBlock::Table(t)];
|
||||
blocks_text(&blocks, &mut out, &mut ListCounter::default(), 0);
|
||||
|
||||
assert_eq!(out.len(), 2);
|
||||
// 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::Object)];
|
||||
// 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::Object));
|
||||
}
|
||||
(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(),
|
||||
|
||||
+25
-16
@@ -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,14 +82,9 @@ 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::Margin => Some(margin_y(f)),
|
||||
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top)),
|
||||
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom, s.margin_bottom)),
|
||||
_ => None,
|
||||
@@ -117,8 +112,20 @@ 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,
|
||||
}
|
||||
|
||||
/// 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 +217,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 +232,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 +240,8 @@ 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,
|
||||
})
|
||||
// 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 +438,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 +514,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 +571,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 };
|
||||
|
||||
@@ -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,39 @@ 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);
|
||||
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || !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 +786,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 +1113,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 +1192,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 +1262,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
|
||||
@@ -1332,7 +1386,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");
|
||||
|
||||
@@ -218,7 +218,8 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
let Some(part) = ctx.doc.parts.get(&id) else { return Vec::new() };
|
||||
let blocks = part.blocks.clone();
|
||||
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);
|
||||
@@ -471,11 +472,37 @@ 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))))
|
||||
})
|
||||
};
|
||||
// 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 (mut laid, mut behind, mut front) = lay_header(ctx, frame);
|
||||
// The body top was measured with the declared margins (`body_top_for`). If the rendered
|
||||
// area moves a wrapping Margin-anchored object into the header's text and the header
|
||||
// grows past that body top, keep the measured layout: its text can't run into the body.
|
||||
if sect.header + laid.height > page.body.y + 0.01 {
|
||||
let rendered = (std::mem::replace(&mut ctx.counters, before.0), ctx.eq_count);
|
||||
ctx.eq_count = before.1;
|
||||
let measured = lay_header(ctx, PageFrame { margin_area: None, ..frame });
|
||||
if measured.0.height < laid.height - 0.01 {
|
||||
(laid, behind, front) = measured;
|
||||
} else {
|
||||
(ctx.counters, ctx.eq_count) = rendered;
|
||||
}
|
||||
}
|
||||
let mut items = laid.items;
|
||||
for it in &mut items {
|
||||
it.translate(x, sect.header);
|
||||
}
|
||||
@@ -491,8 +518,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 {
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::{DocLayout, Page, Placed};
|
||||
|
||||
/// Caret geometry on a page: a bar from (`x`, `top`) to (`x + width`, `top + height`). It is
|
||||
/// upright (`width` 0) except in turned text (a table cell's text direction), where it lies
|
||||
/// across the page (`height` 0).
|
||||
/// across the page (`height` 0), and `turn` is the direction its line reads in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Caret {
|
||||
pub page: usize,
|
||||
@@ -20,6 +20,7 @@ pub struct Caret {
|
||||
pub top: f32,
|
||||
pub height: f32,
|
||||
pub width: f32,
|
||||
pub turn: TextDirection,
|
||||
}
|
||||
|
||||
/// An equation as [`DocLayout::equation_box`] finds it, in page coordinates: its left edge
|
||||
@@ -141,7 +142,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,
|
||||
@@ -757,7 +759,7 @@ impl DocLayout {
|
||||
let base = top + (l.baseline - l.top);
|
||||
let ctop = (base - asc).max(top);
|
||||
let r = crate::turn_rect(*turn, *x, *y, Rect::new(cx, ctop, 0.0, (base + desc - ctop).max(4.0)));
|
||||
return Some(Caret { page: pi, x: r.x, top: r.y, height: r.h, width: r.w });
|
||||
return Some(Caret { page: pi, x: r.x, top: r.y, height: r.h, width: r.w, turn: *turn });
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -765,18 +767,15 @@ impl DocLayout {
|
||||
/// The style run text typed at `pos` would take (the character's before it, or at the start
|
||||
/// of a paragraph the first character's) and the baseline it sits on, on the page: `pos`'s
|
||||
/// line's, raised or lowered by the run's shift (superscript, `w:position`). An input method's
|
||||
/// composition is drawn with them, as Word draws it in the text's own font and size. `None` in
|
||||
/// turned text, whose lines aren't horizontal.
|
||||
/// composition is drawn with them, as Word draws it in the text's own font and size. In turned
|
||||
/// text the baseline is meaningless (the lines aren't horizontal); use the run only.
|
||||
pub fn typing_style(&self, pos: &Pos, page_hint: usize) -> Option<(StyleRun, f32)> {
|
||||
for (_, it) in self.pieces(pos.story, &pos.path, page_hint) {
|
||||
let Placed::Lines { para, l0, l1, y, turn, .. } = it else { continue };
|
||||
let Placed::Lines { para, l0, l1, y, .. } = it else { continue };
|
||||
let li = para.line_of(pos.off);
|
||||
if li < *l0 || li >= *l1 {
|
||||
continue;
|
||||
}
|
||||
if *turn != TextDirection::Horizontal {
|
||||
return None;
|
||||
}
|
||||
let first = para.lines.get(*l0)?;
|
||||
let line = para.lines.get(li)?;
|
||||
let at = |off: usize| para.clusters.iter().find(|c| c.start <= off && off < c.end).and_then(|c| para.styles.get(c.style as usize));
|
||||
@@ -786,6 +785,42 @@ 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), so `None` at the first/last line of the
|
||||
/// caret's flow on the page.
|
||||
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
let c = self.caret_on(pos, page_hint)?;
|
||||
let lines: Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> = items_of(self.pages.get(c.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 here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
|
||||
let (path, para, li) = lines.get(if next { here + 1 } else { here.checked_sub(1)? })?;
|
||||
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)?;
|
||||
|
||||
@@ -575,7 +575,7 @@ pub(crate) fn body_top_for(ctx: &mut Ctx, sect: &SectionProps, header: Option<u3
|
||||
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 +637,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 +673,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, 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,9 @@ 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,
|
||||
}
|
||||
|
||||
impl Exclusion {
|
||||
|
||||
+118
-18
@@ -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 };
|
||||
@@ -1190,10 +1196,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.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 +1248,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 +1267,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 +1287,96 @@ 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 }
|
||||
}
|
||||
|
||||
/// 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(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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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))));
|
||||
}
|
||||
|
||||
+158
-5
@@ -28,6 +28,18 @@ 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>,
|
||||
}
|
||||
|
||||
/// A cell of a [`RowLayout`].
|
||||
@@ -336,8 +348,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 +915,16 @@ fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember the fill (or none) each restart cell gives its merge's continuation.
|
||||
fn note_restart_fills(merge_fill: &mut std::collections::HashMap<usize, Rgb>, cells: &[CellBox]) {
|
||||
for c in cells.iter().filter(|c| c.vmerge == VMerge::Restart) {
|
||||
match c.fill {
|
||||
Some(f) => merge_fill.insert(c.g, f),
|
||||
None => merge_fill.remove(&c.g),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
struct TableRows<'a> {
|
||||
story: StoryRef,
|
||||
table: &'a Table,
|
||||
@@ -938,13 +964,17 @@ 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();
|
||||
for (ri, cells) in rows.into_iter().enumerate() {
|
||||
if only.is_some_and(|(row, _)| row != ri) {
|
||||
// The restart fills of earlier rows still shade the continuation of a merge.
|
||||
note_restart_fills(&mut merge_fill, &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();
|
||||
@@ -1049,6 +1079,29 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
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),
|
||||
};
|
||||
}
|
||||
if !last_of_merge && let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
merge.end.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
}
|
||||
if c.vmerge == VMerge::Continue {
|
||||
let mut left = rh;
|
||||
let mut k = ri + 1;
|
||||
while cont.get(k).is_some_and(|v| v.contains(&c.g)) {
|
||||
left += heights.get(k).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
if let Some(color) = merge_fill.get(&c.g) {
|
||||
merge.top.push(Placed::Fill { rect: Rect::new(c.x, 0.0, c.w, left), color: *color });
|
||||
}
|
||||
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 +1128,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 +1428,52 @@ 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(),
|
||||
merge: MergeEdges { top: row.merge.top.clone(), end: at_y(&row.merge.end, cut) },
|
||||
},
|
||||
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) },
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// The fills of a merge's top edge for a continuation `by` points shorter than its row.
|
||||
fn shorter(items: &[Placed], by: f32) -> Vec<Placed> {
|
||||
items
|
||||
.iter()
|
||||
.map(|it| match it {
|
||||
Placed::Fill { rect, color } => Placed::Fill { rect: Rect::new(rect.x, rect.y, rect.w, (rect.h - by).max(0.0)), color: *color },
|
||||
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
|
||||
@@ -1775,7 +1870,10 @@ fn apply_cell_widths(t: &Table, grid: &mut [f32]) {
|
||||
grid.copy_from_slice(&widths);
|
||||
}
|
||||
|
||||
// An autofit table whose width matches its complete point-width rows but not its grid takes the rows.
|
||||
/// An autofit table whose width matches its complete point-width rows but not its grid takes the
|
||||
/// rows. Because `preferred_grid` fills in equal shares of `avail` when `tblGrid` is missing or
|
||||
/// has the wrong column count, this also covers tables with no usable grid whose width differs
|
||||
/// from `avail`: they take their column widths from the cells instead of equal shares.
|
||||
fn stale_grid_widths(t: &Table, grid: &[f32]) -> Option<Vec<f32>> {
|
||||
const WIDTH_EPSILON: f32 = 0.5;
|
||||
const EDGE_EPSILON: f32 = 0.01;
|
||||
@@ -2035,6 +2133,61 @@ mod width_tests {
|
||||
assert_eq!(grid, [100.0, 200.0, 250.0, 100.0], "a fixed table keeps its grid");
|
||||
}
|
||||
|
||||
#[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_after = 1;
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
let mut grid = table.grid.clone();
|
||||
|
||||
apply_cell_widths(&table, &mut grid);
|
||||
assert_eq!(grid, [150.0, 150.0, 150.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disagreeing_row_edges_keep_grid() {
|
||||
let mut table = Table::new(2, 3, 300.0);
|
||||
for (cell, width) in table.rows[0].cells.iter_mut().zip([100.0, 100.0, 100.0]) {
|
||||
cell.props.width = Some(width);
|
||||
}
|
||||
for (cell, width) in table.rows[1].cells.iter_mut().zip([120.0, 80.0, 100.0]) {
|
||||
cell.props.width = Some(width);
|
||||
}
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
let mut grid = table.grid.clone();
|
||||
|
||||
apply_cell_widths(&table, &mut grid);
|
||||
assert_eq!(grid, [150.0, 150.0, 150.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_keeps_fitting_widths() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -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,70 @@ 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 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();
|
||||
}
|
||||
if let Some(pg) = pb.page() {
|
||||
for it in &row.items {
|
||||
if starts_page {
|
||||
page_from.set(Some(pg.items.len()));
|
||||
}
|
||||
// The continuing fill goes under the row's items (their borders), its top rules over them.
|
||||
let top = if starts_page { row.merge.top.as_slice() } else { &[] };
|
||||
let (fills, rules) = (top.iter().filter(|i| matches!(i, Placed::Fill { .. })), top.iter().filter(|i| !matches!(i, Placed::Fill { .. })));
|
||||
for it in fills.chain(&row.items).chain(rules) {
|
||||
let mut it = it.clone();
|
||||
it.translate(x, y);
|
||||
// The area ends at this page's bottom, #8872.
|
||||
if 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 bottom = pb.y;
|
||||
if let Some(pg) = pb.page() {
|
||||
// The merged cells' areas end with the last row on the page.
|
||||
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
|
||||
&& 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 +402,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 +411,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).
|
||||
@@ -435,7 +488,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;
|
||||
}
|
||||
|
||||
+449
-5
@@ -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,59 @@ 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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertical_merge_aligns_its_text_with_the_first_page() {
|
||||
crate::test_fonts();
|
||||
@@ -6472,6 +6528,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}");
|
||||
@@ -11977,6 +12034,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 +12632,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 +13251,211 @@ 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:?}");
|
||||
}
|
||||
|
||||
/// #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();
|
||||
@@ -16240,6 +16565,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 +19490,124 @@ 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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_boundary_obstacle() {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,46 @@ 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
+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];
|
||||
|
||||
+358
-3
@@ -265,7 +265,7 @@ fn stem_darkening_follows_the_macos_curve() {
|
||||
assert_eq!(stem_darkening(f64::NAN), 0.0);
|
||||
assert_eq!(stem_darkening(-5.0), 0.0);
|
||||
// Small text grows in proportion to its pixel size...
|
||||
assert!((stem_darkening(10.0) - 10.0 * 0.0121 * 2.25 / 2.0).abs() < 1e-9);
|
||||
assert!((stem_darkening(10.0) - 10.0 * 0.0121).abs() < 1e-9);
|
||||
// ...body text on a Retina screen hits the 0.3 px cap...
|
||||
assert_eq!(stem_darkening(30.0), 0.3);
|
||||
assert_eq!(stem_darkening(72.0), 0.3);
|
||||
@@ -283,12 +283,29 @@ fn text_darkening_adds_ink_on_screen_only() {
|
||||
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let plain = render_page(&d, &l.pages[0], 2.0, &RenderOptions::default());
|
||||
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: true, ..Default::default() });
|
||||
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: 1.0, ..Default::default() });
|
||||
let (a, b) = (ink(&plain), ink(&dark));
|
||||
// About 0.3 px more on every edge of an 11 pt line at 2x: clearly more ink, not bold.
|
||||
assert!(b as f64 > a as f64 * 1.08 && (b as f64) < a as f64 * 1.6, "plain {a}, darkened {b}");
|
||||
// Off by default: exports and thumbnails are untouched.
|
||||
assert!(!RenderOptions::default().text_darkening);
|
||||
assert_eq!(RenderOptions::default().text_darkening, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_darkening_is_a_strength() {
|
||||
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let at = |strength: f32| ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: strength, ..Default::default() }));
|
||||
// The system's lighter, default and stronger steps each add ink.
|
||||
let (none, light, default, strong) = (at(0.0), at(0.5), at(1.0), at(1.5));
|
||||
assert!(none < light && light < default && default < strong, "{none} {light} {default} {strong}");
|
||||
assert_eq!(none, ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions::default())));
|
||||
// No more than twice the default, and junk is no darkening at all.
|
||||
assert_eq!(at(2.0), at(50.0));
|
||||
assert_eq!(at(2.0), at(f32::INFINITY.min(f32::MAX)));
|
||||
for junk in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] {
|
||||
assert_eq!(at(junk), none, "{junk}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Inked pixels that are only partly covered (grey): an edge between two pixel rows.
|
||||
@@ -303,6 +320,315 @@ fn ink_columns(img: &Rendered) -> (usize, usize) {
|
||||
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// The first and last pixel rows with any ink.
|
||||
fn ink_row_span(img: &Rendered) -> (usize, usize) {
|
||||
let w = img.width as usize;
|
||||
let inked: Vec<usize> = img.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[0] < 250).map(|(i, _)| i / w.max(1)).collect();
|
||||
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// One line of flat-footed capitals in a bundled face: no letter dips under the baseline.
|
||||
fn flat_capitals() -> (Document, wordcraft_layout::DocLayout) {
|
||||
let mut d = Document::from_text("THE FELT HILT FILE LIFT HEFT TILT");
|
||||
let styles = std::sync::Arc::make_mut(&mut d.styles);
|
||||
styles.default_chr.font = Some("Source Sans 3".into());
|
||||
styles.default_chr.size = Some(12.0);
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
(d, l)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapped_baseline_ends_the_letters_on_a_whole_pixel_row() {
|
||||
let (d, l) = flat_capitals();
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
// Scales that put the baseline at different places between two pixel rows.
|
||||
let mut sharper = 0;
|
||||
for scale in [1.0, 1.25, 1.45, 96.0 / 72.0 * 1.45, 2.0, 2.3] {
|
||||
let plain = render_page(&d, &l.pages[0], scale, &RenderOptions::default());
|
||||
let snapped = render_page(&d, &l.pages[0], scale, &snap);
|
||||
// The row under the letters' feet: all of it white once the baseline is on a pixel
|
||||
// boundary, where the unsnapped feet leave a grey row or end a row early.
|
||||
let (_, foot) = ink_row_span(&snapped);
|
||||
let w = snapped.width as usize;
|
||||
let foot_row = &snapped.pixels[foot * w * 4..(foot + 1) * w * 4];
|
||||
let darkest = foot_row.as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255);
|
||||
assert!(darkest < 16, "scale {scale}: the feet fill their last row (darkest pixel {darkest})");
|
||||
let (g0, g1) = (grey(&plain), grey(&snapped));
|
||||
assert!(g1 <= g0, "scale {scale}: grey pixels: plain {g0}, snapped {g1}");
|
||||
sharper += usize::from(g1 < g0);
|
||||
// The same weight, and nothing moves sideways.
|
||||
let (a, b) = (ink(&plain), ink(&snapped));
|
||||
assert!((b as f64 - a as f64).abs() < a as f64 * 0.02, "scale {scale}: ink: plain {a}, snapped {b}");
|
||||
assert_eq!(ink_columns(&plain), ink_columns(&snapped), "scale {scale}");
|
||||
// No more than half a pixel up or down.
|
||||
let ((t0, b0), (t1, b1)) = (ink_row_span(&plain), ink_row_span(&snapped));
|
||||
assert!(t0.abs_diff(t1) <= 1 && b0.abs_diff(b1) <= 1, "scale {scale}: plain {t0}..{b0}, snapped {t1}..{b1}");
|
||||
}
|
||||
assert!(sharper >= 3, "snapping sharpened {sharper} of 6 scales");
|
||||
// Off by default: exports and thumbnails are untouched.
|
||||
assert!(!RenderOptions::default().baseline_snap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_views_keep_their_baselines() {
|
||||
let (d, l) = flat_capitals();
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
let view = Affine::translate((300.0, -50.0)) * Affine::rotate(0.3) * Affine::scale(1.9);
|
||||
let plain = render_region(&d, &l.pages[0], 600, 300, view, &RenderOptions::default());
|
||||
assert!(ink(&plain) > 0);
|
||||
assert_eq!(plain.pixels, render_region(&d, &l.pages[0], 600, 300, view, &snap).pixels);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darkening_thickens_stems_and_leaves_the_tops_and_feet_of_letters_alone() {
|
||||
let (d, l) = flat_capitals();
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
let dark = RenderOptions { text_darkening: 1.0, ..snap.clone() };
|
||||
for scale in [1.0, 1.45, 2.0] {
|
||||
let plain = render_page(&d, &l.pages[0], scale, &snap);
|
||||
let darkened = render_page(&d, &l.pages[0], scale, &dark);
|
||||
// More ink, in the same pixel rows: nothing is added above the letters or under them
|
||||
// (the stroke this replaces put a third of a pixel of grey on both).
|
||||
assert!(ink(&darkened) as f64 > ink(&plain) as f64 * 1.05, "scale {scale}");
|
||||
assert_eq!(ink_row_span(&plain), ink_row_span(&darkened), "scale {scale}");
|
||||
// Sideways, less than a pixel each way.
|
||||
let ((l0, r0), (l1, r1)) = (ink_columns(&plain), ink_columns(&darkened));
|
||||
assert!(l1 <= l0 && l0 - l1 <= 1 && r1 >= r0 && r1 - r0 <= 1, "scale {scale}: plain {l0}..{r0}, darkened {l1}..{r1}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_moves_edges_sideways_away_from_the_ink() {
|
||||
// A 10 x 10 square with a 4 x 4 hole, the hole running the other way round.
|
||||
let mut ring = kurbo::Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.1);
|
||||
ring.move_to((3.0, 3.0));
|
||||
for p in [(3.0, 7.0), (7.0, 7.0), (7.0, 3.0)] {
|
||||
ring.line_to(p);
|
||||
}
|
||||
ring.close_path();
|
||||
for path in [ring.clone(), ring.reverse_subpaths()] {
|
||||
let wide = widened(&path, 0.5);
|
||||
// The square is 1 wider and the hole 1 narrower; neither is any taller.
|
||||
let b = wide.bounding_box();
|
||||
assert_eq!((b.x0, b.x1, b.y0, b.y1), (-0.5, 10.5, 0.0, 10.0));
|
||||
assert!((wide.area().abs() - (11.0 * 10.0 - 3.0 * 4.0)).abs() < 1e-9, "{}", wide.area());
|
||||
assert_eq!(wide.elements().len(), path.elements().len());
|
||||
}
|
||||
// A round shape: wider, no taller, and its top and bottom points stay put.
|
||||
let disc = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3);
|
||||
let b = widened(&disc, 0.25).bounding_box();
|
||||
assert!((b.width() - 10.5).abs() < 0.02 && (b.height() - 10.0).abs() < 0.02, "{b:?}");
|
||||
// Nothing to widen, or nothing to widen by: the path comes back as it was.
|
||||
let line = BezPath::from_vec(vec![kurbo::PathEl::MoveTo((0.0, 0.0).into()), kurbo::PathEl::LineTo((5.0, 5.0).into())]);
|
||||
for (path, d) in [(&line, 0.5), (&ring, 0.0), (&ring, -1.0), (&ring, f64::NAN), (&ring, f64::INFINITY), (&BezPath::new(), 0.5)] {
|
||||
assert_eq!(widened(path, d).elements(), path.elements(), "{d}");
|
||||
}
|
||||
// Hostile outlines don't panic: points that aren't numbers, and one point repeated.
|
||||
let mut odd = BezPath::new();
|
||||
odd.move_to((f64::NAN, 0.0));
|
||||
odd.line_to((1.0, f64::INFINITY));
|
||||
odd.quad_to((2.0, 2.0), (0.0, 0.0));
|
||||
let _ = widened(&odd, 0.5);
|
||||
let mut same = BezPath::new();
|
||||
same.move_to((1.0, 1.0));
|
||||
for _ in 0..50 {
|
||||
same.line_to((1.0, 1.0));
|
||||
}
|
||||
same.line_to((4.0, 1.0));
|
||||
same.line_to((4.0, 5.0));
|
||||
same.close_path();
|
||||
assert_eq!(widened(&same, 0.5).elements().len(), same.elements().len());
|
||||
}
|
||||
|
||||
/// The sum of one colour channel's distance from white.
|
||||
fn channel_ink(img: &Rendered, channel: usize) -> u64 {
|
||||
img.pixels.as_chunks::<4>().0.iter().map(|p| 255 - p[channel] as u64).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lcd_text_takes_each_channel_from_around_its_own_stripe() {
|
||||
let d = Document::from_text("Nobody has assembled this board yet. Italic and round strokes gain the most.");
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let (w, h) = (700, 200);
|
||||
let view = Affine::scale(1.25);
|
||||
let lcd = |order| RenderOptions { lcd: Some(order), ..Default::default() };
|
||||
let grey = render_region(&d, &l.pages[0], w, h, view, &RenderOptions::default());
|
||||
let rgb = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Rgb));
|
||||
let bgr = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Bgr));
|
||||
assert!(ink(&grey) > 0);
|
||||
// The page a third of a pixel to the right and to the left, in greyscale.
|
||||
let moved = |dx: f64| render_region(&d, &l.pages[0], w, h, Affine::translate((dx, 0.0)) * view, &RenderOptions::default());
|
||||
let (right, left) = (moved(1.0 / 3.0), moved(-1.0 / 3.0));
|
||||
let mut coloured = 0;
|
||||
let rasters = [&grey, &rgb, &bgr, &right, &left].map(|r| r.pixels.as_chunks::<4>().0);
|
||||
for i in 0..rasters[0].len() {
|
||||
let [g, c, m, r, l] = rasters.map(|px| px[i]);
|
||||
// Green sits in the middle of the pixel: it and the alpha are the greyscale raster's.
|
||||
assert_eq!((c[1], c[3]), (g[1], g[3]));
|
||||
// Red is what a pixel a third to the left would see, blue a third to the right.
|
||||
assert_eq!((c[0], c[2]), (r[0], l[2]), "pixel {i}");
|
||||
// BGR stripes are the mirror image.
|
||||
assert_eq!((m[0], m[1], m[2], m[3]), (c[2], c[1], c[0], c[3]));
|
||||
coloured += usize::from(c[0] != c[2]);
|
||||
}
|
||||
assert!(coloured > 200, "{coloured} pixels have red and blue apart");
|
||||
// No colour cast: each channel carries the same ink, to within a hundredth.
|
||||
let [r, g, b] = [0, 1, 2].map(|c| channel_ink(&rgb, c) as f64);
|
||||
assert!((r - g).abs() < g * 0.01 && (b - g).abs() < g * 0.01, "{r} {g} {b}");
|
||||
// Off by default: exports and thumbnails are untouched.
|
||||
assert_eq!(RenderOptions::default().lcd, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lcd_changes_nothing_but_text() {
|
||||
let lcd = RenderOptions { lcd: Some(LcdOrder::Rgb), ..Default::default() };
|
||||
// A page with no text: the same raster, from one pass.
|
||||
let mut blank = Document::from_text("");
|
||||
blank.settings.page_color = Some(Rgb(0x20, 0x60, 0xA0));
|
||||
let l = layout(&blank, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
assert_eq!(render_page(&blank, &l.pages[0], 0.5, &lcd).pixels, render_page(&blank, &l.pages[0], 0.5, &RenderOptions::default()).pixels);
|
||||
// A page with text on a page colour: pixels differ only where the text is.
|
||||
let mut d = Document::from_text("Coloured paper under one line of text.");
|
||||
d.settings.page_color = Some(Rgb(0xFF, 0xF0, 0xC0));
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let (grey, sub) = (render_page(&d, &l.pages[0], 1.25, &RenderOptions::default()), render_page(&d, &l.pages[0], 1.25, &lcd));
|
||||
let w = grey.width as usize;
|
||||
let paper = grey.pixels[..4].to_vec();
|
||||
let inked: Vec<usize> = grey.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[..] != paper[..]).map(|(i, _)| i).collect();
|
||||
let (top, bottom) = (inked.iter().map(|i| i / w).min().unwrap(), inked.iter().map(|i| i / w).max().unwrap());
|
||||
let (first, last) = (inked.iter().map(|i| i % w).min().unwrap(), inked.iter().map(|i| i % w).max().unwrap());
|
||||
let mut changed = 0;
|
||||
for (i, (a, b)) in grey.pixels.as_chunks::<4>().0.iter().zip(sub.pixels.as_chunks::<4>().0).enumerate() {
|
||||
if a != b {
|
||||
changed += 1;
|
||||
let (x, y) = (i % w, i / w);
|
||||
assert!((top..=bottom).contains(&y) && x + 1 >= first && x <= last + 1, "pixel {x},{y} is outside the text");
|
||||
}
|
||||
}
|
||||
assert!(changed > 50, "{changed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lcd_channels_never_exceed_the_alpha() {
|
||||
// Premultiplied pixels: a colour above its alpha would be brighter than white.
|
||||
let mut px = vec![10, 20, 30, 40, 200, 200, 200, 255];
|
||||
take_lcd_channels(&mut px, &[90, 0, 0, 255, 7, 0, 0, 255], &[0, 0, 80, 255, 0, 0, 9, 255]);
|
||||
assert_eq!(px, [40, 20, 40, 40, 7, 200, 9, 255]);
|
||||
// Rasters of other sizes leave the rest alone and don't panic.
|
||||
let mut px = vec![1, 2, 3, 255, 4, 5, 6, 255, 9];
|
||||
take_lcd_channels(&mut px, &[50, 0, 0, 255], &[]);
|
||||
assert_eq!(px, [1, 2, 3, 255, 4, 5, 6, 255, 9]);
|
||||
}
|
||||
|
||||
/// The glyph runs of `text` in a bundled face at 12 pt, as the page draws them, each changed by
|
||||
/// `change`; and the area they are in.
|
||||
fn glyph_runs(text: &str, change: impl Fn(&mut Draw)) -> (Document, Vec<Draw>, wordcraft_geom::Rect) {
|
||||
let mut d = Document::from_text(text);
|
||||
let styles = std::sync::Arc::make_mut(&mut d.styles);
|
||||
styles.default_chr.font = Some("Source Sans 3".into());
|
||||
styles.default_chr.size = Some(12.0);
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let page = &l.pages[0];
|
||||
let mut runs: Vec<Draw> = page_layers(&d, page, &DisplayOptions::default())
|
||||
.into_iter()
|
||||
.flat_map(|(_, items)| items)
|
||||
.filter(|it| matches!(it, Draw::Glyphs { .. }))
|
||||
.collect();
|
||||
assert!(!runs.is_empty());
|
||||
runs.iter_mut().for_each(change);
|
||||
(d, runs, wordcraft_geom::Rect::new(0.0, 0.0, page.w, 200.0))
|
||||
}
|
||||
|
||||
/// How much is drawn on nothing: the sum of the pixels' opacity.
|
||||
fn opacity(img: &Rendered) -> u64 {
|
||||
img.pixels.as_chunks::<4>().0.iter().map(|p| p[3] as u64).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_bold_is_darkened_too() {
|
||||
// A face with no bold of its own is made bold by stroking its outlines. The stroke reaches
|
||||
// further than the darkening does, so it has to stroke the darkened outline: the darkening
|
||||
// then moves the bold text's edges as far as the regular text's, and adds about as much ink.
|
||||
let added = |bold: bool, scale: f32| {
|
||||
let (d, runs, area) = glyph_runs("Bold made by stroking the outline", |run| {
|
||||
if let Draw::Glyphs { synth_bold, .. } = run {
|
||||
*synth_bold = bold;
|
||||
}
|
||||
});
|
||||
let dark = RenderOptions { text_darkening: 1.0, ..Default::default() };
|
||||
let (plain, darkened) =
|
||||
(opacity(&render_items(&d, &runs, area, scale, &RenderOptions::default())), opacity(&render_items(&d, &runs, area, scale, &dark)));
|
||||
assert!(plain > 0 && darkened > plain, "bold {bold}: plain {plain}, darkened {darkened}");
|
||||
(darkened - plain) as f64
|
||||
};
|
||||
for scale in [1.0, 2.0] {
|
||||
let (regular, bold) = (added(false, scale), added(true, scale));
|
||||
assert!(bold > regular * 0.75, "scale {scale}: ink added: {regular} regular, {bold} bold");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stretched_hinted_text_is_darkened_as_far_as_unstretched() {
|
||||
// One letter, hinted, at its own width and scaled to 400 % (`w:w`): the darkening moves each
|
||||
// edge the same distance on screen, so it adds about the same ink to both.
|
||||
let added = |stretch: f32| {
|
||||
let (d, runs, area) = glyph_runs("H", |run| {
|
||||
if let Draw::Glyphs { x_scale, .. } = run {
|
||||
*x_scale = stretch;
|
||||
}
|
||||
});
|
||||
let hint = RenderOptions { hinting: true, ..Default::default() };
|
||||
let dark = RenderOptions { text_darkening: 1.0, ..hint.clone() };
|
||||
let (plain, darkened) = (opacity(&render_items(&d, &runs, area, 2.0, &hint)), opacity(&render_items(&d, &runs, area, 2.0, &dark)));
|
||||
assert!(darkened > plain, "stretch {stretch}: plain {plain}, darkened {darkened}");
|
||||
(darkened - plain) as f64
|
||||
};
|
||||
let (own, stretched) = (added(1.0), added(4.0));
|
||||
assert!(stretched < own * 1.5 && stretched > own * 0.6, "ink added: {own} unstretched, {stretched} stretched");
|
||||
// The conversion itself: a widening of `px` device pixels, in outline units, is `px` again
|
||||
// once the outline is on screen.
|
||||
for (hinted, font_px, stretch) in [(true, 0.02, 1.0), (true, 0.02, 4.0), (false, 0.02, 1.0), (false, 0.02, 4.0)] {
|
||||
let on_screen = if hinted { stretch } else { font_px * stretch };
|
||||
assert!((0.25 / widen_unit(hinted, font_px, stretch) * on_screen - 0.25).abs() < 1e-12, "{hinted} {stretch}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_area_rendered_to_a_pixel_size_fills_it_and_keeps_its_text_on_the_grid() {
|
||||
let (d, l) = flat_capitals();
|
||||
let page = &l.pages[0];
|
||||
let area = wordcraft_geom::Rect::new(0.0, 0.0, page.w, page.h);
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
// A page 1746.155 × 2469.544 pixels at its scale, made 1746 × 2470: a pixel in two thousand off each way.
|
||||
let scale = 1746.155 / page.w;
|
||||
let (w, h) = (1746, (page.h * scale).round() as u32 + 1);
|
||||
let exact = render_area_to(&d, page, area, w, h, &snap);
|
||||
assert_eq!((exact.width, exact.height), (w, h));
|
||||
// One scale gives the next whole pixel up each way: not the size asked for.
|
||||
let up = render_area(&d, page, area, scale, &snap);
|
||||
assert_eq!(up.width, 1747);
|
||||
// The text is as it is at the page's own scale, feet on a whole pixel row: scaled that little differently
|
||||
// across and down, the page is still upright.
|
||||
let foot_is_dark = |img: &Rendered| {
|
||||
let (_, foot) = ink_row_span(img);
|
||||
let w = img.width as usize;
|
||||
img.pixels[foot * w * 4..(foot + 1) * w * 4].as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255) < 16
|
||||
};
|
||||
assert!(foot_is_dark(&exact) && foot_is_dark(&up));
|
||||
assert!(is_upright(Affine::scale_non_uniform(2.0, 2.002)) && is_upright(Affine::scale_non_uniform(2.933, 2.9334)));
|
||||
assert!(!is_upright(Affine::scale_non_uniform(2.0, 2.01)));
|
||||
// Hostile sizes and areas: clamped, never a panic.
|
||||
for (area, w, h) in [
|
||||
(wordcraft_geom::Rect::new(0.0, 0.0, 0.0, 0.0), 10, 10),
|
||||
(wordcraft_geom::Rect::new(f32::NAN, f32::INFINITY, f32::NAN, -5.0), 10, 10),
|
||||
(area, 0, 0),
|
||||
(area, u32::MAX, 3),
|
||||
] {
|
||||
let img = render_area_to(&d, page, area, w, h, &snap);
|
||||
assert!(img.width >= 1 && img.height >= 1 && img.pixels.len() == img.width as usize * img.height as usize * 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hinting_sharpens_screen_text_without_making_it_bolder_or_moving_it() {
|
||||
let mut d =
|
||||
@@ -2053,6 +2379,35 @@ fn rules_of_one_width_cover_the_same_whole_pixels_at_every_zoom() {
|
||||
assert!(snap_rule(Affine::scale(2.0), (0.0, 0.0, 9.0, 4.0), 0.5).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_snap_by_the_scale_across_them_on_a_page_scaled_a_little_differently_each_way() {
|
||||
// A page raster made to fill a whole number of pixels is scaled a pixel in a thousand or two
|
||||
// differently across and down. A level rule lies where the scale down the page puts it, and
|
||||
// an upright one where the scale across does.
|
||||
for (kx, ky) in [(2.0, 2.002), (2.002, 2.0), (2.933, 2.9334), (1.3333, 1.3329)] {
|
||||
let view = Affine::new([kx, 0.0, 0.0, ky, 37.3, 12.9]);
|
||||
assert!(is_upright(view));
|
||||
for i in 0..40 {
|
||||
let pos = 10.0 + f64::from(i) * 17.37;
|
||||
let (w_h, (_, oy)) = snap_rule(view, (5.0, pos, 400.0, pos), 0.5).unwrap();
|
||||
let (w_v, (ox, _)) = snap_rule(view, (pos, 5.0, pos, 400.0), 0.5).unwrap();
|
||||
for (w, centre, lies) in [(w_h, (pos + oy) * ky + 12.9, pos * ky + 12.9), (w_v, (pos + ox) * kx + 37.3, pos * kx + 37.3)] {
|
||||
let edge = centre - w / 2.0;
|
||||
assert!((edge - edge.round()).abs() < 1e-9, "scales {kx} {ky}: edge {edge} is off the pixel grid");
|
||||
// Snapped onto the grid from where it lies: never further than its own width and half a pixel.
|
||||
assert!((centre - lies).abs() <= w / 2.0 + 0.5 + 1e-9, "scales {kx} {ky}: moved {} px", centre - lies);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The case from review: a level rule at 250 pt, half a point wide, at 2.0 across and 2.002 down, is a pixel
|
||||
// wide and centred on 500.5 already. It stays there.
|
||||
let view = Affine::scale_non_uniform(2.0, 2.002);
|
||||
let (w, (_, oy)) = snap_rule(view, (5.0, 250.0, 400.0, 250.0), 0.5).unwrap();
|
||||
assert_eq!(w, 1.0);
|
||||
assert!(((250.0 + oy) * 2.002 - 500.5).abs() < 1e-9, "centre {}", (250.0 + oy) * 2.002);
|
||||
assert_eq!((rule_scale(view, true), rule_scale(view, false)), (2.002, 2.0));
|
||||
}
|
||||
|
||||
/// The same three pictures that don't draw as in the PDF test: each stays a grey box, and the page's
|
||||
/// pixels are what they were before strict export existed (#6005).
|
||||
#[test]
|
||||
|
||||
@@ -12,12 +12,12 @@ workspace = true
|
||||
# The craft libraries through their one facade (`craft::ui`, `craft::i18n`, `craft::window`, `craft::update`, ...),
|
||||
# at the workspace's one craft-libs pin.
|
||||
craft = { workspace = true, features = [
|
||||
"ui", "automation", "codepage", "keymap", "platform", "quit", "settings",
|
||||
"ui", "automation", "automation-agents", "codepage", "keymap", "platform", "quit", "settings",
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-html = { workspace = true }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -77,7 +77,7 @@ craft-ui-test-kit = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Agents in the open window, as in every Craft app: while the ArtCraft Launcher's switch
|
||||
//! (Settings › AI agents › Let AI agents use Craft apps) names WordCraft, the agent link serves the
|
||||
//! control channel on loopback with a token and publishes where in the settings folder, so
|
||||
//! `wordcraft-cli mcp` finds the window by itself. Turning the switch off stops it, with no
|
||||
//! restart. The link, the switch and the Agents page are the framework's
|
||||
//! (`craft::automation::agents`, `craft::automation::ui::agents`); WordCraft supplies the folders
|
||||
//! agent requests are confined to ([`Agents::roots`]) and the settings they come from
|
||||
//! ([`crate::prefs::Prefs::integrations`]), which only the person changes, in File › Options ›
|
||||
//! Agents.
|
||||
//!
|
||||
//! What agents do in the window reads and writes only inside those folders
|
||||
//! (`wordcraft_engine::file_access`): their requests, the screenshots they save, and the frames
|
||||
//! that play the input they send (a Ctrl+S an agent sends must not save outside them). The
|
||||
//! person's own work in the window is not confined. A server the launch options started
|
||||
//! (`--control`) is not the agent link's and stays as it was.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
|
||||
use craft::automation::control::ControlChannel;
|
||||
use craft::automation::ui::agents::AgentsPage;
|
||||
use craft::ui::patterns::preferences::SettingsDraft;
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use wordcraft_engine::file_access::AutomationRoots;
|
||||
|
||||
use crate::{WordApp, i18n};
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names WordCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "wordcraft";
|
||||
/// WordCraft's name in its default agent folder, `Documents/ArtCraft/Agents/WordCraft`.
|
||||
pub const AGENT_APP_NAME: &str = "WordCraft";
|
||||
/// The settings section and Options page the agent settings live in.
|
||||
pub const PAGE: &str = "integrations";
|
||||
|
||||
/// The agent link, the launcher's switch and the folders agent requests are confined to.
|
||||
pub struct Agents {
|
||||
link: AgentLink,
|
||||
switch: AgentSwitch,
|
||||
/// The folder agents use when the person chose none ([`craft::control::agents::default_folder`]).
|
||||
default_folder: Option<PathBuf>,
|
||||
/// While the agent link serves: what its requests may read and write. Never `None` then.
|
||||
roots: Option<Arc<AutomationRoots>>,
|
||||
}
|
||||
|
||||
impl Agents {
|
||||
/// Agents through `link` while `switch` lets them in. A link the launch options started
|
||||
/// (`AgentLink::from_launch`) keeps serving whatever the switch says.
|
||||
pub fn new(link: AgentLink, switch: AgentSwitch) -> Self {
|
||||
Self { link, switch, default_folder: craft::control::agents::default_folder(AGENT_APP_NAME), roots: None }
|
||||
}
|
||||
|
||||
/// `folder` replaces the default agent folder, so a test doesn't touch the person's Documents.
|
||||
#[doc(hidden)]
|
||||
#[must_use]
|
||||
pub fn with_default_folder(mut self, folder: Option<PathBuf>) -> Self {
|
||||
self.default_folder = folder;
|
||||
self
|
||||
}
|
||||
|
||||
/// Where the link stands: its port, whether the launch options run it, what went wrong.
|
||||
pub fn status(&self) -> &AgentLinkStatus {
|
||||
self.link.status()
|
||||
}
|
||||
|
||||
/// The launcher's switch.
|
||||
pub fn switch(&self) -> &AgentSwitch {
|
||||
&self.switch
|
||||
}
|
||||
|
||||
/// What the agent link's requests may read and write, while it serves.
|
||||
pub fn roots(&self) -> Option<&Arc<AutomationRoots>> {
|
||||
self.roots.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// The roots for agents with `settings`: their folders, the default agent folder for an empty one
|
||||
/// ([`AgentSettings::folders_with`]). Folders that can't be used grant nothing, with the reason,
|
||||
/// so agents are refused rather than left unconfined.
|
||||
fn roots_for(settings: &AgentSettings, default: Option<&Path>) -> (Arc<AutomationRoots>, Option<String>) {
|
||||
let folders = settings.folders_with(default);
|
||||
match AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref()) {
|
||||
Ok(Some(roots)) => (roots, None),
|
||||
Ok(None) => (AutomationRoots::none(), Some(tl!("Agents can't open or save files: there is no agent folder. Choose one below.").to_string())),
|
||||
Err(error) => (AutomationRoots::none(), Some(i18n::fmt(tl!("Agents can't open or save files: {error}"), &[("error", &error)]))),
|
||||
}
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
/// Lets agents into this window through `agents` ([`crate::agents`]).
|
||||
#[must_use]
|
||||
pub fn with_agents(mut self, agents: Agents) -> Self {
|
||||
self.agents = Some(agents);
|
||||
self
|
||||
}
|
||||
|
||||
/// Brings the agent link in line with the launcher's switch and the agent settings: it starts,
|
||||
/// moves or stops its control server, and does nothing while neither changed. WordCraft had no
|
||||
/// consent of its own before the switch, so without the suite's `AI-MCP` flag agents stay out
|
||||
/// (only `--control` serves then).
|
||||
pub(crate) fn sync_agents(&mut self, ctx: &egui::Context) {
|
||||
let Some(agents) = self.agents.as_mut() else { return };
|
||||
let allowed = agents.switch.allows(false);
|
||||
let update = agents.link.sync(allowed.then_some(&self.ui.integrations), &WindowHost::of(ctx));
|
||||
if update.stopped {
|
||||
self.control = None;
|
||||
}
|
||||
if let Some(requests) = update.requests {
|
||||
self.control = Some(ControlChannel::new(requests));
|
||||
}
|
||||
if !update.changed {
|
||||
return;
|
||||
}
|
||||
agents.roots = None;
|
||||
if agents.link.status().port.is_some() && !agents.link.status().launch_flags {
|
||||
let (roots, problem) = roots_for(&self.ui.integrations, agents.default_folder.as_deref());
|
||||
agents.roots = Some(roots);
|
||||
if let Some(problem) = problem {
|
||||
agents.link.note(LinkProblem::App(problem));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the agent link's requests may read and write; `None` without the link (the launch
|
||||
/// options' server is not confined).
|
||||
pub(crate) fn agent_roots(&self) -> Option<Arc<AutomationRoots>> {
|
||||
self.agents.as_ref().and_then(|agents| agents.roots.clone())
|
||||
}
|
||||
|
||||
/// The roots for this frame: the agent link's while the frame plays input it sent. A click or a
|
||||
/// key from the channel acts for the agent, not the person; a click of the person's in the same
|
||||
/// frame is confined too, which errs the safe way.
|
||||
pub(crate) fn frame_roots(&self, ctx: &egui::Context) -> Option<Arc<AutomationRoots>> {
|
||||
self.agent_roots().filter(|_| !WindowHost::of(ctx).injected_idle())
|
||||
}
|
||||
|
||||
/// The link's state for `ui.inspect`: `port`, `launchFlags`, `error`, the suite's `AI-MCP` flag
|
||||
/// (`mcpFlag`) and the launcher's switch (`launcher`).
|
||||
pub(crate) fn agent_link_json(&self) -> serde_json::Value {
|
||||
let Some(agents) = &self.agents else { return serde_json::Value::Null };
|
||||
let mut v = serde_json::json!(agents.link.status());
|
||||
if let Some(m) = v.as_object_mut() {
|
||||
m.insert("mcpFlag".into(), agents.switch.mcp_flag().into());
|
||||
m.insert("launcher".into(), agents.switch.launcher().into());
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// File › Options › Agents: the framework's Agents page over the agent settings. A change applies
|
||||
/// at once, as every other Options row does, and the agent link follows on the next frame. The
|
||||
/// page writes the settings directly, not through a command: agents must not widen their own
|
||||
/// folders.
|
||||
pub(crate) fn page(app: &mut WordApp, ui: &mut egui::Ui) -> bool {
|
||||
let status = app.agents.as_ref().map(|agents| agents.link.status().clone()).unwrap_or_default();
|
||||
let mcp_flag = app.agents.as_ref().is_some_and(|agents| agents.switch.mcp_flag());
|
||||
let mut draft = SettingsDraft::default();
|
||||
if draft.replace(&serde_json::json!({ PAGE: app.ui.integrations })).is_err() {
|
||||
return false;
|
||||
}
|
||||
let out = AgentsPage::new(PAGE, &mut draft, &status).mcp_flag(mcp_flag).show(ui);
|
||||
if !out.changed {
|
||||
return false;
|
||||
}
|
||||
match draft.get::<AgentSettings>(PAGE) {
|
||||
Some(settings) => {
|
||||
app.ui.integrations = settings;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "agents/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Agents in the open window (`agents.rs`): the agent link follows the launcher's switch, and what
|
||||
//! agents do reads and writes only inside their folders. The link, the switch and the Agents page
|
||||
//! have their own tests in craft-automation.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft::automation::agents::{AgentLink, AgentSwitch, CONNECTION_FILE, find_window};
|
||||
use craft::automation::client::ControlClient;
|
||||
use craft::automation::control::{ControlRequest, Reply};
|
||||
use serde_json::json;
|
||||
|
||||
use super::Agents;
|
||||
use crate::{Services, WordApp, control};
|
||||
|
||||
/// 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-agents-{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 settings(&self) -> PathBuf {
|
||||
self.0.join("settings")
|
||||
}
|
||||
|
||||
fn agent_folder(&self) -> PathBuf {
|
||||
self.0.join("Agents").join("WordCraft")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// An app whose agent link keeps its files in `dir`'s settings folder and whose default agent
|
||||
/// folder is in `dir`, with `switch` as the launcher's switch.
|
||||
fn linked(dir: &Folder, switch: AgentSwitch) -> WordApp {
|
||||
let link = AgentLink::new(Some(dir.settings()), "WordCraft test");
|
||||
let agents = Agents::new(link, switch).with_default_folder(Some(dir.agent_folder()));
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default()).with_agents(agents);
|
||||
app.fonts_frames = 2;
|
||||
app
|
||||
}
|
||||
|
||||
fn port(app: &WordApp) -> Option<u16> {
|
||||
app.agents.as_ref().and_then(|agents| agents.status().port)
|
||||
}
|
||||
|
||||
fn set_switch(app: &mut WordApp, switch: AgentSwitch) {
|
||||
if let Some(agents) = app.agents.as_mut() {
|
||||
agents.switch = switch;
|
||||
}
|
||||
}
|
||||
|
||||
/// With the AI-MCP flag the launcher's switch alone starts the agent link and publishes where it
|
||||
/// listens; turning it off there stops it and removes the file, with no restart.
|
||||
#[test]
|
||||
fn the_launcher_switch_starts_and_stops_the_agent_link() {
|
||||
let dir = Folder::new("switch");
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut app = linked(&dir, AgentSwitch::fixed(true, false));
|
||||
app.sync_agents(&ctx);
|
||||
assert!(port(&app).is_none() && app.control.is_none(), "off in the launcher: nothing listens");
|
||||
assert!(!dir.settings().join(CONNECTION_FILE).exists());
|
||||
|
||||
set_switch(&mut app, AgentSwitch::fixed(true, true));
|
||||
app.sync_agents(&ctx);
|
||||
let on = port(&app);
|
||||
assert!(on.is_some() && app.control.is_some(), "on in the launcher: the link serves");
|
||||
assert!(dir.settings().join(CONNECTION_FILE).is_file(), "and says where");
|
||||
let roots = app.agent_roots().expect("agent requests are confined");
|
||||
assert!(roots.write_root().is_some_and(|root| root.ends_with("WordCraft")), "to the agent folder");
|
||||
app.sync_agents(&ctx);
|
||||
assert_eq!(port(&app), on, "no change, no restart");
|
||||
assert_eq!(app.agent_link_json()["port"], json!(on));
|
||||
|
||||
set_switch(&mut app, AgentSwitch::fixed(true, false));
|
||||
app.sync_agents(&ctx);
|
||||
assert!(port(&app).is_none() && app.control.is_none() && app.agent_roots().is_none(), "off again: it stops");
|
||||
assert!(!dir.settings().join(CONNECTION_FILE).exists(), "and the file goes");
|
||||
}
|
||||
|
||||
/// Without the AI-MCP flag the launcher's list means nothing, and WordCraft had no consent of its
|
||||
/// own before the switch: agents stay out.
|
||||
#[test]
|
||||
fn without_the_flag_agents_stay_out() {
|
||||
let dir = Folder::new("flag");
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut app = linked(&dir, AgentSwitch::fixed(false, true));
|
||||
app.sync_agents(&ctx);
|
||||
assert!(port(&app).is_none() && app.control.is_none());
|
||||
}
|
||||
|
||||
/// End to end over the agent link's port, token file and challenge handshake: an agent's save goes
|
||||
/// into the agent folder and is refused outside it.
|
||||
#[test]
|
||||
fn an_agent_saves_inside_its_folder_and_is_refused_outside() {
|
||||
let dir = Folder::new("save");
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut app = linked(&dir, AgentSwitch::fixed(true, true));
|
||||
app.sync_agents(&ctx);
|
||||
let window = find_window(&dir.settings(), "WordCraft").unwrap().expect("the window accepts agents");
|
||||
let addr = window.addr().parse().unwrap();
|
||||
let token = window.token.clone();
|
||||
let inside = dir.agent_folder().join("inside.docx");
|
||||
let outside = dir.0.join("outside.docx");
|
||||
let (to_inside, to_outside) = (inside.clone(), outside.clone());
|
||||
let agent = std::thread::spawn(move || {
|
||||
let mut client = ControlClient::connect_challenged(addr, &token).unwrap();
|
||||
let save = |client: &mut ControlClient, path: &Path| client.call("engine.execute", json!({"command": "file.save", "params": {"path": path}}));
|
||||
(save(&mut client, &to_inside), save(&mut client, &to_outside))
|
||||
});
|
||||
while !agent.is_finished() {
|
||||
app.control_logic(&ctx);
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let (saved, refused) = agent.join().unwrap();
|
||||
assert!(saved.is_ok(), "{saved:?}");
|
||||
assert!(inside.is_file());
|
||||
assert!(refused.is_err_and(|e| e.contains("outside")), "refused outside the agent folder");
|
||||
assert!(!outside.exists());
|
||||
}
|
||||
|
||||
/// A key an agent sends acts for the agent: its Ctrl+S doesn't save a document outside the agent
|
||||
/// folder. The person's own save of the same document does.
|
||||
#[test]
|
||||
fn an_agents_shortcut_saves_only_inside_its_folder() {
|
||||
let dir = Folder::new("keys");
|
||||
let outside = dir.0.join("person.docx");
|
||||
let mut app = linked(&dir, AgentSwitch::fixed(true, true));
|
||||
app.run("document.setText", json!({"text": "Seed"})).unwrap();
|
||||
app.session.path = Some(outside.clone());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, a: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::logic(&ctx, a);
|
||||
a.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let frames = |h: &mut egui_kittest::Harness<'_, WordApp>, n: usize| {
|
||||
for _ in 0..n {
|
||||
let ctx = h.ctx.clone();
|
||||
craft::ui::shell::embed::before_input(&ctx, |out| h.state_mut().frame_input(out));
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
frames(&mut h, 6);
|
||||
assert!(h.state().agent_roots().is_some(), "the agent link serves");
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().canvas.focus_page(&ctx);
|
||||
frames(&mut h, 4);
|
||||
let (req, _reply) = ControlRequest::new("ui.key", json!({"key": "S", "command": true}));
|
||||
let queued = control::handle(h.state_mut(), &ctx, &req);
|
||||
if let Reply::Done(v) = &queued {
|
||||
panic!("the key is queued, not answered: {v}");
|
||||
}
|
||||
frames(&mut h, 8);
|
||||
assert!(!outside.exists(), "the agent's Ctrl+S saved nothing outside its folder");
|
||||
|
||||
h.state_mut().run("file.save", json!({})).unwrap();
|
||||
assert!(outside.is_file(), "the person's own save writes it");
|
||||
}
|
||||
@@ -118,6 +118,9 @@ impl WordApp {
|
||||
font_notices: false,
|
||||
packs_rt: Default::default(),
|
||||
control: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: None,
|
||||
pass_roots: None,
|
||||
capture_token: 0,
|
||||
native_scale: 1.0,
|
||||
software_drawing: false,
|
||||
@@ -126,6 +129,7 @@ impl WordApp {
|
||||
applied_editing: None,
|
||||
frame_ms: 0.0,
|
||||
quit_requested: false,
|
||||
quit_recheck: false,
|
||||
autosave: true,
|
||||
zotero: zotero::ZoteroLink::default(),
|
||||
ctx: None,
|
||||
@@ -262,10 +266,17 @@ impl WordApp {
|
||||
/// (a late paste, the control channel) is in `logic`.
|
||||
pub fn frame_input(&mut self, out: FrameOutput) -> FrameInput {
|
||||
if let Some(ctx) = self.ctx.clone() {
|
||||
self.run_fired(&ctx, &out);
|
||||
// The commands the last pass's keys fired act for whoever pressed them: an agent's
|
||||
// run inside its folders, as that pass did.
|
||||
let roots = self.pass_roots.take();
|
||||
wordcraft_engine::file_access::confine(roots.as_ref(), || self.run_fired(&ctx, &out));
|
||||
self.canvas.take_focus_after_pass(&ctx);
|
||||
self.native_scale = theme::usable_scale(ctx.native_pixels_per_point().unwrap_or(1.0));
|
||||
if let Some(native) = ctx.native_pixels_per_point()
|
||||
// The zoom is context-wide but the display scale is per window: read it from the active
|
||||
// document window. The windowless root has no window, so it reports none (#8853).
|
||||
let active = self.active_viewport();
|
||||
let native_now = ctx.input_for(active, |i| i.viewport().native_pixels_per_point).or_else(|| ctx.native_pixels_per_point());
|
||||
self.native_scale = theme::usable_scale(native_now.unwrap_or(1.0));
|
||||
if let Some(native) = native_now
|
||||
&& let Some(old) = self.legacy_interface_size.take()
|
||||
{
|
||||
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
|
||||
@@ -328,8 +339,16 @@ impl WordApp {
|
||||
self.print_feedback();
|
||||
}
|
||||
|
||||
/// Per-frame logic before layout: background work, the control channel, file results.
|
||||
/// Per-frame logic before layout: background work, the control channel, file results. A frame
|
||||
/// that plays input an agent sent runs inside the agent's folders ([`crate::agents`]).
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
let roots = self.frame_roots(ctx);
|
||||
self.pass_roots = roots.clone();
|
||||
wordcraft_engine::file_access::confine(roots.as_ref(), || self.frame_logic(ctx));
|
||||
}
|
||||
|
||||
/// [`WordApp::logic`] inside the frame's roots, if any.
|
||||
fn frame_logic(&mut self, ctx: &egui::Context) {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
if self.ctx.is_none() {
|
||||
theme::set_dark_text_curve(ctx);
|
||||
@@ -375,6 +394,8 @@ impl WordApp {
|
||||
self.chrome.search = false;
|
||||
}
|
||||
self.pump_close_prompt();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.sync_agents(ctx);
|
||||
self.control_logic(ctx);
|
||||
self.watch_fonts(ctx);
|
||||
// A script, an agent or a later result may have made another document the active one.
|
||||
@@ -422,7 +443,15 @@ impl WordApp {
|
||||
|
||||
/// Lay out the windows: on the desktop each open document's in its own native window
|
||||
/// ([`windows`]), on the web the one window.
|
||||
/// A frame that plays input an agent sent runs inside the agent's folders ([`crate::agents`]).
|
||||
pub fn ui(&mut self, ui: &mut egui::Ui) {
|
||||
let roots = self.frame_roots(ui.ctx()).or_else(|| self.pass_roots.clone());
|
||||
self.pass_roots = roots.clone();
|
||||
wordcraft_engine::file_access::confine(roots.as_ref(), || self.frame_ui(ui));
|
||||
}
|
||||
|
||||
/// [`WordApp::ui`] inside the frame's roots, if any.
|
||||
fn frame_ui(&mut self, ui: &mut egui::Ui) {
|
||||
if self.windows.native() {
|
||||
self.windows_ui(ui);
|
||||
} else {
|
||||
|
||||
@@ -1318,6 +1318,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
|
||||
| "tools.customizeRibbon"
|
||||
| "view.darkMode"
|
||||
| "view.paperColor"
|
||||
| "view.textSmoothing"
|
||||
| "view.marks"
|
||||
| "view.ruler"
|
||||
| "view.numeral"
|
||||
|
||||
@@ -2,6 +2,7 @@ use craft::automation::control::ControlChannel;
|
||||
use craft::automation::screenshot::DocumentId;
|
||||
use craft::ui::runtime::motion::now;
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use wordcraft_engine::file_access::confine;
|
||||
|
||||
use super::WordApp;
|
||||
use crate::control;
|
||||
@@ -19,8 +20,14 @@ impl WordApp {
|
||||
}
|
||||
|
||||
/// The control channel's logic phase: finishes captures and input waiters, then, once the
|
||||
/// fonts are warm, runs the queued requests and answers them.
|
||||
/// fonts are warm, runs the queued requests and answers them. The agent link's requests, and
|
||||
/// the screenshots they save, read and write only inside the agent's folders.
|
||||
pub(crate) fn control_logic(&mut self, ctx: &egui::Context) {
|
||||
let roots = self.agent_roots();
|
||||
confine(roots.as_ref(), || self.control_logic_in(ctx));
|
||||
}
|
||||
|
||||
fn control_logic_in(&mut self, ctx: &egui::Context) {
|
||||
let Some(mut channel) = self.control.take() else { return };
|
||||
let host = WindowHost::of(ctx);
|
||||
let document = self.capture_document();
|
||||
@@ -51,6 +58,11 @@ impl WordApp {
|
||||
if ctx.will_discard() {
|
||||
return;
|
||||
}
|
||||
let roots = self.agent_roots();
|
||||
confine(roots.as_ref(), || self.control_ui_in(ctx));
|
||||
}
|
||||
|
||||
fn control_ui_in(&mut self, ctx: &egui::Context) {
|
||||
let Some(mut channel) = self.control.take() else { return };
|
||||
let host = WindowHost::of(ctx);
|
||||
let document = self.capture_document();
|
||||
@@ -60,3 +72,15 @@ impl WordApp {
|
||||
self.control = Some(channel);
|
||||
}
|
||||
}
|
||||
|
||||
/// The web build has no agent link: nothing is confined.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
impl WordApp {
|
||||
pub(crate) fn agent_roots(&self) -> Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn frame_roots(&self, _: &egui::Context) -> Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -519,7 +519,12 @@ impl WordApp {
|
||||
return false;
|
||||
}
|
||||
if self.quit_requested {
|
||||
return true;
|
||||
// A quit that found nothing unsaved: the close that ends it has committed the focused field's typed text,
|
||||
// which is asked about like any other change (#8790). Once only, so an answered prompt is not asked again.
|
||||
if !(std::mem::take(&mut self.quit_recheck) && self.has_unsaved_documents()) {
|
||||
return true;
|
||||
}
|
||||
self.quit_requested = false;
|
||||
}
|
||||
// Nothing to save, also with no document open in this window (#1129) and none elsewhere.
|
||||
if !self.has_unsaved_documents() {
|
||||
|
||||
@@ -60,7 +60,7 @@ impl ThumbSource<ThumbKey> for TemplateThumbs {
|
||||
let Some(page) = layout.pages.first() else { return ThumbRender::Blank };
|
||||
// The longest side of the page is `request.side` pixels; the store never asks for zero.
|
||||
let scale = request.side as f32 / page.w.max(page.h).max(1.0);
|
||||
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::screen_render_options());
|
||||
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::thumbnail_render_options());
|
||||
let pixels = image.to_straight();
|
||||
ThumbRender::Ready(egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &pixels))
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ pub(crate) use links::follow_link;
|
||||
use links::{field_link, is_followable_link, is_generated_bookmark_link};
|
||||
pub use navigation::page_to_screen;
|
||||
use navigation::viewed_page;
|
||||
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options};
|
||||
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options, thumbnail_render_options};
|
||||
use pages::{page_render_options, shown_layout};
|
||||
use reading::{reading_anchor_page, reading_page_start, web_layout_width};
|
||||
use story::dims_body;
|
||||
@@ -112,6 +112,11 @@ pub struct CanvasState {
|
||||
/// The page asks for the keyboard between this pass and the next ([`CanvasState::focus_page_after_pass`]): always
|
||||
/// (no ids), or only while focus is still on one of the ids.
|
||||
focus_after_pass: Option<Vec<egui::Id>>,
|
||||
/// Where the page view put its pages (page, place in screen points) the last time two passes running put
|
||||
/// them in the same places: the view at rest. Page pictures are made to fill these places exactly
|
||||
/// (`source::WordPages`); while the view moves they stay as they were, so a scroll or a zoom under way makes
|
||||
/// no picture again for a place it is only passing through.
|
||||
pub(crate) settled_pages: Vec<(usize, Rect)>,
|
||||
/// How many page pictures the page view kept resident after the last pass (S-L352).
|
||||
pub(crate) resident_pictures: usize,
|
||||
/// The caret's glide and blink.
|
||||
@@ -422,6 +427,7 @@ impl Default for CanvasState {
|
||||
shown: ShownPages::default(),
|
||||
focus_pending: true,
|
||||
focus_after_pass: None,
|
||||
settled_pages: Vec::new(),
|
||||
resident_pictures: 0,
|
||||
glide: crate::caret_glide::CaretGlide::default(),
|
||||
comments: Default::default(),
|
||||
@@ -653,13 +659,20 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
|
||||
areas
|
||||
}
|
||||
|
||||
/// The navigation options of WordCraft's canvas: the document wheel scheme, and middle-click autoscroll where the
|
||||
/// platform has the gesture (not macOS, iOS or the web, whose middle button has its own meaning).
|
||||
fn navigation_options() -> NavigationOptions {
|
||||
/// The navigation options of WordCraft's canvas: the document wheel scheme, the document wheel notch
|
||||
/// ([`crate::scroll::NOTCH_PX`]), eased wheel scrolling when animations are enabled, and middle-click autoscroll
|
||||
/// where the platform has the gesture (not macOS, iOS or the web, whose middle button has its own meaning).
|
||||
fn navigation_options(animations: bool) -> NavigationOptions {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.middle_button =
|
||||
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::AutoScroll };
|
||||
options.wheel = WheelScheme::Document;
|
||||
// Browsers report three lines per notch where native platforms report one.
|
||||
options.wheel_line = if cfg!(target_arch = "wasm32") { crate::scroll::NOTCH_PX / 3.0 } else { crate::scroll::NOTCH_PX };
|
||||
options.eased_wheel = animations;
|
||||
// macOS, Windows and the web send their own touchpad momentum; elsewhere (Wayland, X11) the lift ends the scroll
|
||||
// and the app glides on (#8855).
|
||||
options.touchpad_glide = !cfg!(any(target_os = "macos", target_os = "ios", target_os = "windows", target_arch = "wasm32"));
|
||||
options
|
||||
}
|
||||
|
||||
@@ -752,7 +765,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
|
||||
let columns = Rect::from_min_max(full.min, pos2(full.max.x, (full.max.y - metrics.nav_bar).max(full.min.y)));
|
||||
let footer = Rect::from_min_max(pos2(full.min.x, columns.max.y), full.max);
|
||||
let mut state = std::mem::take(&mut app.canvas.reading);
|
||||
let source = source::WordPages::new(app, layout, false, None);
|
||||
// Read Mode sizes its columns itself: no view scale to rasterise at.
|
||||
let source = source::WordPages::new(app, layout, false, None, None);
|
||||
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
|
||||
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
|
||||
// the page view's side margin in from the edge.
|
||||
@@ -841,7 +855,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
let options =
|
||||
LayoutOptions { markup: f64::from(markup_width(app)), min_columns: if app.session.view.multi_page { 2 } else { 1 }, ..LayoutOptions::WORD };
|
||||
let paper = DataColor::new(paper_color(app));
|
||||
let source = source::WordPages::new(app, layout, dim_body, hidden);
|
||||
let source = source::WordPages::new(app, layout, dim_body, hidden, Some(scale as f32));
|
||||
// The describer owns its snapshot, as the source does, so the page view can hold it while the body edits the app.
|
||||
let described = preview_sel(app).unwrap_or(app.session.sel_ends()).clone();
|
||||
let describer = crate::a11y::DocumentDescriber::new(source.doc(), layout.clone(), (described.anchor.clone(), described.focus.clone()));
|
||||
@@ -862,11 +876,12 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
.into_iter()
|
||||
.filter(|(_, id)| !crate::app::command_board::command_enabled(app, id))
|
||||
.fold(EditSet::NONE, |set, (command, _)| set.with(command));
|
||||
let animations = app.animations_on();
|
||||
let out = PageView::new(tl!("Document"), &source, &mut state, paper)
|
||||
.options(options)
|
||||
// Hide White Space cuts each page to its text area: without the bodies the pages show whole.
|
||||
.bodies(&bodies)
|
||||
.navigation(navigation_options())
|
||||
.navigation(navigation_options(animations))
|
||||
.editor(craft::ui::primitives::EditorPurpose::Text)
|
||||
.inactive_edits(inactive_edits)
|
||||
.rulers(show_rulers)
|
||||
@@ -1034,6 +1049,14 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
// A window's page has the keyboard from its first pass (production's `want_focus` started on), so typing lands
|
||||
// without a click; a modal dialog keeps the keyboard until it closes.
|
||||
let view_rect = body_view.map_or(body_rect, |v| v.rect);
|
||||
// The same places two passes running: the view is at rest, and these are the places pictures are made for.
|
||||
let placed = |pages: &[PlacedPage]| pages.iter().map(|p| (p.page, p.rect)).collect::<Vec<_>>();
|
||||
let now = placed(&out.pages);
|
||||
if now == placed(&app.canvas.shown.pages) && now != app.canvas.settled_pages {
|
||||
app.canvas.settled_pages = now;
|
||||
// The pictures of the places just settled are made on the next pass.
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
app.canvas.shown =
|
||||
ShownPages { rect: body_rect, pages: out.pages.clone(), laid: laid_rects(&out), view: view_rect, canvas: Some(out.canvas.response.id) };
|
||||
if app.canvas.focus_pending && !app.modal_open() {
|
||||
@@ -1054,7 +1077,12 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
app.canvas.mini_dismissed = None;
|
||||
}
|
||||
balloons::balloons(app, ui, &out, layout);
|
||||
rulers::page_rulers(app, ui, &out, layout);
|
||||
if show_rulers {
|
||||
rulers::page_rulers(app, ui, &out, layout);
|
||||
} else if app.canvas.table_resize.as_ref().is_some_and(crate::table_resize::ResizeDrag::on_ruler) {
|
||||
// Hidden rulers can't finish a border drag they started: drop it with its preview.
|
||||
app.canvas.table_resize = None;
|
||||
}
|
||||
// The one context-menu ask of the pass: Shift+F10 or `ui.contextMenu` (below the caret), a click on the equation
|
||||
// frame's options strip, then the tool host's own request by how it was asked for.
|
||||
let ask = app.canvas.context_request.take().or_else(|| strip_click.map(ContextAsk::AtPointer));
|
||||
|
||||
@@ -13,6 +13,7 @@ use craft::ui::primitives::{FaceRun, PaintShape, StrokeWidth, TextRun};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2};
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_layout::DocLayout;
|
||||
|
||||
use super::cursor::{caret_color_at, preedit_cursor_chars};
|
||||
@@ -39,8 +40,13 @@ struct Placement {
|
||||
/// The selection is collapsed, so a caret is drawn.
|
||||
collapsed: bool,
|
||||
/// The face, size and baseline on screen text typed at the caret takes, which a composition is drawn in. `None`
|
||||
/// in an equation, in turned text and without a style run.
|
||||
/// in an equation and without a style run. In turned text the baseline is unused.
|
||||
typing: Option<TypingFace>,
|
||||
/// The direction the caret's line reads in; turned text has a composition running down or up the page.
|
||||
turn: TextDirection,
|
||||
/// Turned text: the caret's top on screen, where the composition starts, and the line's width across the page.
|
||||
y0: f32,
|
||||
across: f32,
|
||||
}
|
||||
|
||||
/// The face text typed at the caret asks for, its size and its baseline on screen (`DocLayout::typing_style`).
|
||||
@@ -76,6 +82,9 @@ fn place(app: &WordApp, doc: &DocLayout, pages: &[PlacedPage]) -> Option<Placeme
|
||||
in_equation: true,
|
||||
collapsed: true,
|
||||
typing: None,
|
||||
turn: TextDirection::Horizontal,
|
||||
y0,
|
||||
across: 0.0,
|
||||
});
|
||||
}
|
||||
let sel = preview_sel(app).unwrap_or(&app.session.sel);
|
||||
@@ -105,15 +114,17 @@ fn place(app: &WordApp, doc: &DocLayout, pages: &[PlacedPage]) -> Option<Placeme
|
||||
} else {
|
||||
[pos2(x.round() + 0.5, y0), pos2(x.round() + 0.5, y1)]
|
||||
};
|
||||
// Word draws a composition in the font and size of the text it goes into; not in turned text, whose lines aren't
|
||||
// horizontal.
|
||||
let typing = if c.width > 0.0 {
|
||||
None
|
||||
} else {
|
||||
doc.typing_style(&sel.focus, app.session.page_hint)
|
||||
.filter(|(run, base)| run.size.is_finite() && run.size > 0.0 && base.is_finite())
|
||||
.map(|(run, base)| TypingFace { face: run.requested_face, size: run.size * scale, baseline: pr.rect.min.y + base * scale })
|
||||
};
|
||||
// Word draws a composition in the font and size of the text it goes into, along the line (turned text: down or up
|
||||
// the page).
|
||||
let turned = c.width > 0.0;
|
||||
let typing = doc
|
||||
.typing_style(&sel.focus, app.session.page_hint)
|
||||
.filter(|(run, base)| run.size.is_finite() && run.size > 0.0 && (turned || base.is_finite()))
|
||||
.map(|(run, base)| TypingFace {
|
||||
face: run.requested_face,
|
||||
size: run.size * scale,
|
||||
baseline: if turned { 0.0 } else { pr.rect.min.y + base * scale },
|
||||
});
|
||||
Some(Placement {
|
||||
bar,
|
||||
page: c.page,
|
||||
@@ -124,6 +135,9 @@ fn place(app: &WordApp, doc: &DocLayout, pages: &[PlacedPage]) -> Option<Placeme
|
||||
in_equation: false,
|
||||
collapsed: sel.is_collapsed(),
|
||||
typing,
|
||||
turn: c.turn,
|
||||
y0,
|
||||
across: c.width * scale,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -204,6 +218,9 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
cursor,
|
||||
color: ink(app),
|
||||
typing: pl.typing,
|
||||
turn: pl.turn,
|
||||
y0: pl.y0,
|
||||
across: pl.across,
|
||||
});
|
||||
} else {
|
||||
let look = step(app, request(pl.bar, shown));
|
||||
@@ -224,8 +241,8 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
// them an empty rect that clips their strokes away.
|
||||
let out = CaretMarks::new(tl!("Text cursor").to_string(), bars, composition).show_at(ui, pass.rect);
|
||||
// The candidate window sits at the input method's cursor inside the composition, as production placed it.
|
||||
if let Some(x) = out.composition_caret {
|
||||
report = Rect::from_min_max(pos2(x, report.min.y), pos2(x + 1.0, report.max.y));
|
||||
if let Some(r) = out.composition_caret {
|
||||
report = if pl.turn.is_turned() { r } else { Rect::from_min_max(pos2(r.min.x, report.min.y), pos2(r.min.x + 1.0, report.max.y)) };
|
||||
}
|
||||
}
|
||||
// Reported after the marks, which lay the composition out: this pass's final caret for the input method.
|
||||
@@ -245,6 +262,11 @@ struct Composition {
|
||||
color: Color32,
|
||||
/// The face, size and baseline it is drawn in; without them, the interface font from the caret's bottom.
|
||||
typing: Option<TypingFace>,
|
||||
/// The line's direction; turned, the composition's characters stack upright down or up from `y0`, in a column
|
||||
/// `across` wide starting at `left`.
|
||||
turn: TextDirection,
|
||||
y0: f32,
|
||||
across: f32,
|
||||
}
|
||||
|
||||
/// The style of the caret marks: the composition's ink.
|
||||
@@ -265,8 +287,9 @@ pub(crate) struct CaretMarks {
|
||||
common: Common,
|
||||
bars: Vec<(Bar, Color32)>,
|
||||
composition: Option<Composition>,
|
||||
/// Where the paint put the caret inside the composition (screen x), measured from the laid-out text.
|
||||
composition_caret: Option<f32>,
|
||||
/// Where the paint put the caret inside the composition (a bar in screen points; turned text: the rect the
|
||||
/// composition fills), measured from the laid-out text.
|
||||
composition_caret: Option<Rect>,
|
||||
}
|
||||
|
||||
impl CaretMarks {
|
||||
@@ -279,7 +302,7 @@ impl CaretMarks {
|
||||
/// What the marks report: the caret's place inside the composition they drew, for the candidate window.
|
||||
pub(crate) struct CaretMarksOutput {
|
||||
response: Response,
|
||||
composition_caret: Option<f32>,
|
||||
composition_caret: Option<Rect>,
|
||||
}
|
||||
|
||||
impl Outcome for CaretMarksOutput {
|
||||
@@ -330,6 +353,12 @@ impl Component for CaretMarks {
|
||||
}
|
||||
let Some(c) = &self.composition else { return };
|
||||
let color = DataColor::new(c.color);
|
||||
if c.turn.is_turned()
|
||||
&& let Some(t) = &c.typing
|
||||
{
|
||||
self.composition_caret = Some(paint_turned(&draw, c, t, color));
|
||||
return;
|
||||
}
|
||||
let (layout, top, bottom) = match &c.typing {
|
||||
// In the text's own face and size, its first baseline on the line's, as typed text would sit. Characters the
|
||||
// face lacks (CJK in a Latin font) come from the interface fonts; a size past the font atlas is capped.
|
||||
@@ -350,7 +379,7 @@ impl Component for CaretMarks {
|
||||
draw.stroke(&PaintShape::Path(underline), StrokeWidth::Thin, color);
|
||||
let x = (c.left + layout.char_x(c.cursor)).round() + 0.5;
|
||||
draw.stroke(&PaintShape::Path(vec![pos2(x, top), pos2(x, bottom)]), StrokeWidth::Medium, color);
|
||||
self.composition_caret = Some(x);
|
||||
self.composition_caret = Some(Rect::from_min_max(pos2(x, top), pos2(x, bottom)));
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
@@ -361,3 +390,27 @@ impl Component for CaretMarks {
|
||||
CaretMarksOutput { response: cx.response.clone(), composition_caret: self.composition_caret }
|
||||
}
|
||||
}
|
||||
|
||||
/// A composition in turned text: its characters upright, each in a cell of the run's size, stacked from the caret down
|
||||
/// the page (`Down`) or up it (`Up`) in a column across the line, with the underline along the column's left edge and
|
||||
/// the input method's cursor across it. Returns the rect the composition fills, which the candidate window avoids.
|
||||
fn paint_turned(draw: &craft::ui::primitives::Draw<'_>, c: &Composition, t: &TypingFace, color: DataColor) -> Rect {
|
||||
let key = face_key(t.face);
|
||||
let sign = if c.turn == TextDirection::Up { -1.0 } else { 1.0 };
|
||||
// The cell's edge `i` characters from the start.
|
||||
let edge = |i: usize| c.y0 + sign * t.size * i as f32;
|
||||
let n = c.text.chars().count();
|
||||
for (i, ch) in c.text.chars().enumerate() {
|
||||
let mut buf = [0; 4];
|
||||
let s: &str = ch.encode_utf8(&mut buf);
|
||||
// Centred in the column as an em-wide ideograph; the baseline sits at 0.86 em in the cell, where its body lies.
|
||||
let top = edge(i).min(edge(i + 1));
|
||||
let at = pos2(c.left + (c.across - t.size) / 2.0, top + 0.86 * t.size);
|
||||
draw.face_run(at, &FaceRun::new(s, &key, t.size, color), || face_bytes(t.face));
|
||||
}
|
||||
let end = edge(n);
|
||||
draw.stroke(&PaintShape::Path(vec![pos2(c.left, c.y0), pos2(c.left, end)]), StrokeWidth::Thin, color);
|
||||
let at = edge(c.cursor.min(n)).round() + 0.5;
|
||||
draw.stroke(&PaintShape::Path(vec![pos2(c.left, at), pos2(c.left + c.across, at)]), StrokeWidth::Medium, color);
|
||||
Rect::from_two_pos(pos2(c.left, c.y0), pos2(c.left + c.across, end))
|
||||
}
|
||||
|
||||
@@ -104,6 +104,27 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// A menu row for `edit.paste` that runs `WordApp::run("edit.paste", ...)` directly instead of
|
||||
/// `MenuItem::command`: `edit.paste` is linked to the framework's `EditCommands::Paste`, which
|
||||
/// routes through `ViewportCommand::RequestPaste` when the page canvas has focus and silently does
|
||||
/// nothing if the platform paste event never arrives or carries no text (#8849).
|
||||
pub(crate) fn paste_menu_item(app: &mut WordApp, ui: &mut Ui) {
|
||||
let resolved = craft::ui::runtime::commands::resolve(ui.ctx(), CommandRef::new("edit.paste"));
|
||||
let mut row = MenuItem::new(tl!("Paste").to_string()).enabled(resolved.enabled);
|
||||
if let Some(chord) = &resolved.chord {
|
||||
row = row.shortcut(chord.display(craft::ui::runtime::windows::os_of(ui.ctx())));
|
||||
}
|
||||
if !resolved.enabled
|
||||
&& let Some(hint) = &resolved.hint
|
||||
{
|
||||
row = row.tooltip(craft::ui::contract::TooltipSpec::new(hint.clone()).disabled_text(hint.clone()));
|
||||
}
|
||||
if row.show(ui).ran {
|
||||
let _ = app.run("edit.paste", json!({}));
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
}
|
||||
|
||||
/// A row labelled `label` that runs command `id` with `params`; its chord, enabled state and
|
||||
/// action come from the command, its wording from the menu (one command id serves several rows).
|
||||
fn item(ui: &mut Ui, label: &str, id: &str, params: Value) {
|
||||
@@ -142,7 +163,7 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
|
||||
item(ui, "Copy", "edit.copy", json!({}));
|
||||
// How to paste, chosen before pasting (#2583): the ribbon's Paste menu, item for item. Paste
|
||||
// keeps the clipboard's formatting (Word's Keep Source Formatting).
|
||||
item(ui, "Paste", "edit.paste", json!({}));
|
||||
paste_menu_item(app, ui);
|
||||
item(ui, "Keep Text Only", "edit.pasteText", json!({}));
|
||||
item(ui, "Merge Formatting", "edit.pasteMerge", json!({}));
|
||||
item(ui, "Paste Special…", "edit.pasteSpecial", json!({}));
|
||||
|
||||
@@ -66,6 +66,8 @@ pub(crate) struct EquationFrameStyle {
|
||||
line: StyleColor,
|
||||
accent: StyleColor,
|
||||
soft: StyleColor,
|
||||
/// Painted over the equation's text (so must stay translucent): the argument the caret is in.
|
||||
shade: StyleColor,
|
||||
handle_fill: StyleColor,
|
||||
handle_stroke: StyleColor,
|
||||
}
|
||||
@@ -121,6 +123,7 @@ impl Component for EquationFrameControl<'_> {
|
||||
line: cx.color(t.color.overlay.line),
|
||||
accent: cx.color(t.color.accent.solid),
|
||||
soft: cx.color(t.color.accent.soft),
|
||||
shade: cx.color(t.color.accent.solid.with_alpha(40)),
|
||||
handle_fill: cx.color(t.color.overlay.handle_fill),
|
||||
handle_stroke: cx.color(t.color.overlay.handle_stroke),
|
||||
}
|
||||
@@ -160,7 +163,7 @@ impl Component for EquationFrameControl<'_> {
|
||||
let EquationFrame { outline, grip, strip } = equation_frame(self.page, self.bx, &style.sizes);
|
||||
let corner = CornerRadius::from(style.radius);
|
||||
if let Some(arg) = self.argument {
|
||||
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.soft);
|
||||
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.shade);
|
||||
}
|
||||
draw.fill(&PaintShape::Rect(strip, CornerRadius::ZERO), style.soft);
|
||||
let (c, w) = (strip.center(), style.chevron / 2.0);
|
||||
|
||||
@@ -158,16 +158,21 @@ impl<'a> PageTextTool<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tip for the link under `pos`: where it goes and how to follow it.
|
||||
fn link_tip(&self, pos: Pos2) -> Option<String> {
|
||||
/// The hyperlink under `pos`: an object or text-box link when `allow_object` is true, or a text link.
|
||||
fn link_at(&self, pos: Pos2, allow_object: bool) -> Option<String> {
|
||||
let app = &*self.app;
|
||||
let (page, x, y) = page_of(self.body.pages, pos)?;
|
||||
let layout = &*self.layout;
|
||||
// A linked picture or shape under the pointer comes first: it lies over the text (#5267).
|
||||
// The text is the story under the pointer, as for the tracked change tip that follows.
|
||||
let story = pointer_story(app, layout, page, x, y, app.session.sel.focus.story);
|
||||
let link = crate::objects::link_at(app, layout, self.body, pos)
|
||||
.or_else(|| layout.hit(page, x, y, story).and_then(|at| link_under(app, layout, page, x, y, &at)))?;
|
||||
let object = allow_object.then(|| crate::objects::link_at(app, layout, self.body, pos)).flatten();
|
||||
object.or_else(|| layout.hit(page, x, y, story).and_then(|at| link_under(app, layout, page, x, y, &at)))
|
||||
}
|
||||
|
||||
/// The tip for the link under `pos`: where it goes and how to follow it.
|
||||
fn link_tip(&self, pos: Pos2) -> Option<String> {
|
||||
let link = self.link_at(pos, true)?;
|
||||
let target = if is_generated_bookmark_link(&link) { tl!("Current Document").to_string() } else { link };
|
||||
Some(format!("{target}\n{}", crate::i18n::fmt(tl!("{key}+Click to follow link"), &[("key", self.link_key)])))
|
||||
}
|
||||
@@ -300,6 +305,11 @@ impl CanvasTool for PageTextTool<'_> {
|
||||
if self.app.session.painter.is_some() {
|
||||
return Cursor::System(CursorIcon::Copy);
|
||||
}
|
||||
// Word: Ctrl/⌘ held over a link shows the hand, as a click there follows it.
|
||||
// A text box's own link only follows when Shift is not held; inner text links follow either way.
|
||||
if pointer.mods.cmd && self.link_at(pointer.pos, !pointer.mods.shift).is_some() {
|
||||
return Cursor::System(CursorIcon::PointingHand);
|
||||
}
|
||||
text()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use craft::ui::primitives::textures::MAX_TEXTURE;
|
||||
|
||||
use super::{DocLayout, Hash, Hasher, Page, Placed, Pos, Rect, WordApp, json};
|
||||
|
||||
/// Streams `Debug` formatting directly into a [`Hasher`] without intermediate `String` allocations.
|
||||
@@ -20,6 +22,9 @@ impl std::fmt::Write for HashFmt<'_> {
|
||||
// revision that the pages' pictures key on directly.
|
||||
pub(super) fn view_key(app: &WordApp, dim_body: bool, hidden: Option<&Pos>) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
// A page drawn under the system's earlier text settings, or the user's earlier smoothing choice, must not pass
|
||||
// for one drawn under these.
|
||||
(crate::screen_text::current().key(), app.session.prefs.text_smoothing).hash(&mut h);
|
||||
let v = &app.session.view;
|
||||
(v.marks, app.session.prefs.marks, v.show_markup, v.dark_mode, wordcraft_render::DARK_PAPER, v.hide_ink, v.draw.replay).hash(&mut h);
|
||||
(v.read_mode, v.read_page_color, app.session.prefs.paper_color).hash(&mut h);
|
||||
@@ -180,6 +185,9 @@ pub(crate) fn dark_page(app: &WordApp) -> bool {
|
||||
/// Render options for this view's page rasters: marks, markup, dark page, header/body dimming.
|
||||
pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_render::RenderOptions {
|
||||
let mut opts = screen_render_options();
|
||||
// Pages, and only pages, follow the system's own text settings once they are known ([`crate::screen_text`]);
|
||||
// `view_key` has them, so a change redraws the pages.
|
||||
crate::screen_text::current().apply(&mut opts);
|
||||
opts.display.marks = app.session.view.marks;
|
||||
opts.display.always = app.session.prefs.marks;
|
||||
opts.display.placeholders = true;
|
||||
@@ -208,15 +216,107 @@ pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_re
|
||||
opts
|
||||
}
|
||||
|
||||
/// Render options for page rasters shown on screen, so a page looks as text does in the
|
||||
/// platform's other apps (exports never change): on macOS, text is darkened the way the system
|
||||
/// draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight` draws it
|
||||
/// there (not darkened: hinted text already has FreeType's weight, and darkening made it
|
||||
/// look semi-bold).
|
||||
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
|
||||
wordcraft_render::RenderOptions {
|
||||
text_darkening: cfg!(target_os = "macos"),
|
||||
hinting: cfg!(all(unix, not(target_os = "macos"))),
|
||||
..Default::default()
|
||||
/// Subpixel (LCD) text for the page rasters of a screen with `ppp` device pixels per point, as File › Options ›
|
||||
/// General › Screen text smoothing says. "Use system setting" draws it where the system asks for it
|
||||
/// ([`crate::screen_text`]) and the screen is below two device pixels per point: on a denser screen the stripes are
|
||||
/// too fine to gain from, and a page has four times the pixels to rasterise three times. "Subpixel (LCD)" draws it
|
||||
/// on any screen, in the system's stripe order, RGB when it names none (macOS never does).
|
||||
pub(super) fn lcd_for(
|
||||
choice: wordcraft_engine::cmd::view::TextSmoothing,
|
||||
asked: Option<crate::screen_text::SubpixelOrder>,
|
||||
stripes: Option<crate::screen_text::SubpixelOrder>,
|
||||
ppp: f32,
|
||||
) -> Option<wordcraft_render::LcdOrder> {
|
||||
use crate::screen_text::SubpixelOrder;
|
||||
use wordcraft_engine::cmd::view::TextSmoothing;
|
||||
use wordcraft_render::LcdOrder;
|
||||
let order = |stripes: SubpixelOrder| match stripes {
|
||||
SubpixelOrder::Rgb => LcdOrder::Rgb,
|
||||
SubpixelOrder::Bgr => LcdOrder::Bgr,
|
||||
};
|
||||
match choice {
|
||||
TextSmoothing::Grayscale => None,
|
||||
// The user's own choice, in the order of their screen even where the system has smoothing off (a BGR panel
|
||||
// with ClearType off must not get RGB edges).
|
||||
TextSmoothing::Subpixel => Some(asked.or(stripes).map(order).unwrap_or(LcdOrder::Rgb)),
|
||||
// Written so a density that isn't a number is greyscale too.
|
||||
TextSmoothing::System => asked.map(order).filter(|_| ppp < 2.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scale (pixels per document point) to rasterise a page picture at, and whether that is the screen's own.
|
||||
///
|
||||
/// The page view asks for a picture by its longest side in pixels, `side`, rounded up to a multiple of `step`, and
|
||||
/// scales what it gets to the page's place on screen. Rasterised at `side`, a page is up to `step` pixels larger
|
||||
/// than it shows and every glyph is resampled on the way to the screen, which undoes baselines put on whole pixels
|
||||
/// and makes subpixel text wrong (each colour's edge off its stripe). `native` is the view's own scale, device
|
||||
/// pixels per document point, when it is known: where it accounts for the side asked for (the page's `longest`
|
||||
/// side, in points, at that scale rounds up to `side`), the picture is rasterised at exactly that scale, one raster
|
||||
/// pixel per device pixel. Otherwise (another view's request, a fit zoom not settled yet, a part of a page shown
|
||||
/// reduced) it is rasterised at the side asked for, as before, and is not the screen's own.
|
||||
pub(super) fn raster_scale(side: u32, step: u32, longest: f32, native: Option<f32>) -> (f32, bool) {
|
||||
let largest = MAX_TEXTURE as f32;
|
||||
// `side / longest * longest` can come out a hair over `side`, which rounds up to a pixel too many for a texture.
|
||||
let mut asked = side as f32 / longest;
|
||||
if side <= MAX_TEXTURE && (longest * asked).ceil() > largest {
|
||||
asked = asked.next_down().next_down();
|
||||
}
|
||||
let fits = |scale: f32| {
|
||||
let pixels = longest * scale;
|
||||
scale.is_finite() && scale > 0.0 && pixels.is_finite() && pixels <= side as f32 + 0.5 && pixels > side as f32 - step as f32 - 0.5
|
||||
// A pixel over the largest texture and the store halves the whole picture.
|
||||
&& pixels.ceil() <= largest
|
||||
};
|
||||
match native.filter(|scale| longest.is_finite() && longest > 0.0 && step > 0 && fits(*scale)) {
|
||||
Some(scale) => (scale, true),
|
||||
None => (asked, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The size in device pixels of the place on screen a page's picture is drawn in, when a picture of about
|
||||
/// `expected` pixels (its size at the view's scale) is that place's own.
|
||||
///
|
||||
/// The page view draws a picture as its painter does every picture: the place (`page`, in screen points, or the
|
||||
/// part `region` of it, in fractions) is rounded to whole pixels, and the picture is fitted inside it by its own
|
||||
/// proportions. A picture of exactly the rounded place's size is drawn one pixel for one. Any other is scaled:
|
||||
/// rasterised a whole pixel up each way, as a single scale gives, a 2016 × 2851 pixel place gets a 2017 × 2852
|
||||
/// picture squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page.
|
||||
/// The rounded size depends on where the place starts, so it comes from where the view last put the page, not
|
||||
/// from the page's size. `None` where the place is not within a pixel and a half of `expected` each way: a
|
||||
/// place left over from another zoom, or numbers that aren't.
|
||||
pub(super) fn picture_pixels(page: egui::Rect, region: Option<egui::Rect>, ppp: f32, expected: (f32, f32)) -> Option<(u32, u32)> {
|
||||
let place = match region {
|
||||
Some(part) => {
|
||||
let at = |f: egui::Pos2| egui::pos2(page.min.x + f.x * page.width(), page.min.y + f.y * page.height());
|
||||
egui::Rect::from_min_max(at(part.min), at(part.max))
|
||||
}
|
||||
None => page,
|
||||
};
|
||||
let side = |lo: f32, hi: f32, expected: f32| {
|
||||
let pixels = (hi * ppp).round() - (lo * ppp).round();
|
||||
(pixels.is_finite() && expected.is_finite() && pixels >= 1.0 && (pixels - expected).abs() <= 1.5).then_some(pixels as u32)
|
||||
};
|
||||
Some((side(place.min.x, place.max.x, expected.0)?, side(place.min.y, place.max.y, expected.1)?))
|
||||
}
|
||||
|
||||
/// Render options for rasters shown on screen other than the pages themselves (style and font previews, a dragged
|
||||
/// object), so their text looks as it does in the platform's other apps (exports never change): on macOS it is
|
||||
/// darkened the way the system draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight`
|
||||
/// draws it there (not darkened: hinted text already has FreeType's weight, and darkening made it look semi-bold).
|
||||
/// Baselines sit on whole device pixels (hinting does that; unhinted text is moved there). These are fixed per
|
||||
/// platform: such rasters are cached without the system's text settings in their keys, so they must not follow
|
||||
/// them. Pages do ([`page_render_options`]).
|
||||
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
|
||||
let mut opts = wordcraft_render::RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
|
||||
opts
|
||||
}
|
||||
|
||||
/// Render options for the template thumbnails of File › New: the platform's text, as [`screen_render_options`],
|
||||
/// without the baseline snapping. A thumbnail is a page shrunk to a tile, drawn as it was before pages were
|
||||
/// sharpened.
|
||||
pub(crate) fn thumbnail_render_options() -> wordcraft_render::RenderOptions {
|
||||
let mut opts = wordcraft_render::RenderOptions::default();
|
||||
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
|
||||
opts
|
||||
}
|
||||
|
||||
@@ -8,12 +8,12 @@ use std::sync::Arc;
|
||||
|
||||
use craft::behavior::kurbo::Size;
|
||||
use craft::pages::ui::PageSource;
|
||||
use craft::ui::primitives::textures::{LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource};
|
||||
use craft::ui::primitives::textures::{LoadedPicture, MAX_TEXTURE, Revision, ThumbRender, ThumbRequest, ThumbSource};
|
||||
use wordcraft_doc::{Document, Pos};
|
||||
use wordcraft_layout::DocLayout;
|
||||
|
||||
use super::WordApp;
|
||||
use super::pages::{PageKeys, page_render_options, page_shows, view_key};
|
||||
use super::pages::{PageKeys, lcd_for, page_render_options, page_shows, picture_pixels, raster_scale, view_key};
|
||||
|
||||
/// A page dimension (points) safe to lay out: finite, at least 1 pt, at most `cap`.
|
||||
fn dim(v: f32, cap: f32) -> f64 {
|
||||
@@ -30,13 +30,38 @@ pub(super) struct WordPages {
|
||||
options: wordcraft_render::RenderOptions,
|
||||
/// The page a drag took an object off, and the object: rendered without it.
|
||||
hidden: Option<(usize, Pos)>,
|
||||
/// Screen points per document point in the view these pages show in, when it is one whose pages are drawn at
|
||||
/// that scale (the page view); `None` where the view sizes its pages itself (Read Mode's columns). With the
|
||||
/// screen's density it gives the scale at which a picture is the screen's own ([`raster_scale`]).
|
||||
view_scale: Option<f32>,
|
||||
/// Where the page view put each page (page, its place in screen points) the last time the view was at rest;
|
||||
/// empty for a view that sizes its pages itself. A picture is made exactly as many pixels each way as its
|
||||
/// place is ([`picture_pixels`]).
|
||||
placed: Vec<(usize, egui::Rect)>,
|
||||
/// File › Options › General › Screen text smoothing, and what the system says of the screen's text.
|
||||
smoothing: wordcraft_engine::cmd::view::TextSmoothing,
|
||||
screen_text: crate::screen_text::ScreenText,
|
||||
}
|
||||
|
||||
/// The page view asks for pictures whose longest side is a multiple of this many pixels
|
||||
/// (`ThumbRequest::side`).
|
||||
const SIDE_STEP: u32 = 16;
|
||||
|
||||
impl WordPages {
|
||||
/// The source of `layout` for this pass. The page fingerprints move out of the app for the pass; give them back
|
||||
/// with [`WordPages::into_keys`].
|
||||
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>) -> Self {
|
||||
let view = view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p));
|
||||
/// `view_scale` is the view's screen points per document point where its pages are drawn at exactly that scale,
|
||||
/// so that their pictures can be rasterised one pixel per device pixel.
|
||||
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>, view_scale: Option<f32>) -> Self {
|
||||
let view_scale = view_scale.filter(|scale| scale.is_finite() && *scale > 0.0);
|
||||
let placed = if view_scale.is_some() { app.canvas.settled_pages.clone() } else { Vec::new() };
|
||||
let view = {
|
||||
// A picture rasterised for another zoom is not this zoom's, even where the side asked for is the same.
|
||||
let mut h = DefaultHasher::new();
|
||||
(view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p)), view_scale.map(f32::to_bits)).hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
let (smoothing, screen_text) = (app.session.prefs.text_smoothing, crate::screen_text::current());
|
||||
let options = page_render_options(app, dim_body);
|
||||
let doc = if let Some((_, preview, _, _)) = &app.canvas.table_preview_layout {
|
||||
Arc::new(preview.clone())
|
||||
@@ -51,7 +76,8 @@ impl WordPages {
|
||||
}
|
||||
}
|
||||
};
|
||||
WordPages { doc, layout: layout.clone(), keys: RefCell::new(std::mem::take(&mut app.canvas.page_keys)), view, options, hidden }
|
||||
let keys = RefCell::new(std::mem::take(&mut app.canvas.page_keys));
|
||||
WordPages { doc, layout: layout.clone(), keys, view, options, hidden, view_scale, placed, smoothing, screen_text }
|
||||
}
|
||||
|
||||
/// The pass's document snapshot, shared with the accessibility describer so the pass holds one copy.
|
||||
@@ -65,16 +91,26 @@ impl WordPages {
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<usize> for WordPages {
|
||||
fn revision(&self, page: &usize, _request: &ThumbRequest) -> Revision {
|
||||
let mut h = DefaultHasher::new();
|
||||
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
|
||||
Revision::new(h.finish())
|
||||
}
|
||||
/// What a request for a page's picture is rasterised as.
|
||||
pub(super) struct RasterPlan {
|
||||
/// The whole page, or only `area` of it.
|
||||
pub(super) whole: bool,
|
||||
/// The part of the page to rasterise, in document points.
|
||||
pub(super) area: wordcraft_geom::Rect,
|
||||
/// Pixels per document point.
|
||||
pub(super) scale: f32,
|
||||
/// The picture's size in pixels where it is made to fill its place on screen exactly; `None` for one made at
|
||||
/// `scale`, a whole pixel up each way.
|
||||
pub(super) pixels: Option<(u32, u32)>,
|
||||
pub(super) options: wordcraft_render::RenderOptions,
|
||||
}
|
||||
|
||||
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
|
||||
let index = *page;
|
||||
let Some(p) = self.layout.pages.get(index) else { return ThumbRender::Blank };
|
||||
impl WordPages {
|
||||
/// What of page `index` a picture for `request` shows and how large it is made: whether it is the whole page,
|
||||
/// the area in document points, the pixels per point, whether that is the screen's own scale, and the picture's
|
||||
/// size in pixels where it is made to fill its place exactly. `None` for a page the layout doesn't have.
|
||||
fn geometry(&self, index: usize, request: &ThumbRequest) -> Option<(bool, wordcraft_geom::Rect, f32, bool, Option<(u32, u32)>)> {
|
||||
let p = self.layout.pages.get(index)?;
|
||||
let (pw, ph) = (dim(p.w, 1e5) as f32, dim(p.h, 1e6) as f32);
|
||||
let whole = request.region.is_none();
|
||||
let (x0, y0, x1, y1) = match request.region {
|
||||
@@ -84,14 +120,51 @@ impl ThumbSource<usize> for WordPages {
|
||||
let area = wordcraft_geom::Rect::new(x0 * pw, y0 * ph, ((x1 - x0) * pw).max(0.01), ((y1 - y0) * ph).max(0.01));
|
||||
let longest = area.w.max(area.h);
|
||||
let cap = wordcraft_render::MAX_SIDE as f32 / longest;
|
||||
let scale = request.side as f32 / longest;
|
||||
// At the screen's own scale where the view's zoom accounts for the side asked for, so no glyph is resampled
|
||||
// on its way to the screen; else at the side asked for.
|
||||
let (scale, own) = raster_scale(request.side, SIDE_STEP, longest, self.view_scale.map(|s| s * request.pixels_per_point));
|
||||
let own = own && scale <= cap;
|
||||
let scale = if scale.is_finite() { scale.clamp(0.01, cap.max(0.01)) } else { 1.0 };
|
||||
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
|
||||
// Exactly as many pixels each way as the picture's place on screen has, where that is known and is this
|
||||
// scale's: a pixel more and the page view scales the picture into its place.
|
||||
let place = self.placed.iter().find(|(page, _)| *page == index).map(|(_, rect)| *rect);
|
||||
let pixels = place
|
||||
.filter(|_| own)
|
||||
.and_then(|place| picture_pixels(place, request.region, request.pixels_per_point, (area.w * scale, area.h * scale)))
|
||||
// A place can round to a pixel more than the largest texture, and a larger picture is halved.
|
||||
.filter(|(w, h)| *w.max(h) <= MAX_TEXTURE);
|
||||
Some((whole, area, scale, own, pixels))
|
||||
}
|
||||
|
||||
/// How page `index` is rasterised for `request`; `None` for a page the layout doesn't have.
|
||||
pub(super) fn plan(&self, index: usize, request: &ThumbRequest) -> Option<RasterPlan> {
|
||||
let (whole, area, scale, own, pixels) = self.geometry(index, request)?;
|
||||
let mut options = self.options.clone();
|
||||
options.display.hide_object = self.hidden.as_ref().filter(|(hidden, _)| *hidden == index).map(|(_, pos)| pos.clone());
|
||||
// Subpixel text only on a picture that is the screen's own: scaled, each colour's edge would miss its stripe.
|
||||
options.lcd = lcd_for(self.smoothing, self.screen_text.subpixel, self.screen_text.stripes, request.pixels_per_point).filter(|_| own);
|
||||
Some(RasterPlan { whole, area, scale, pixels, options })
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<usize> for WordPages {
|
||||
fn revision(&self, page: &usize, request: &ThumbRequest) -> Revision {
|
||||
let mut h = DefaultHasher::new();
|
||||
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
|
||||
// A picture made for another place's pixel size is not this place's.
|
||||
self.geometry(*page, request).and_then(|(.., pixels)| pixels).hash(&mut h);
|
||||
Revision::new(h.finish())
|
||||
}
|
||||
|
||||
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
|
||||
let index = *page;
|
||||
let Some(RasterPlan { whole, area, scale, pixels, options }) = self.plan(index, request) else { return ThumbRender::Blank };
|
||||
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
|
||||
ThumbRender::Later(Box::new(move |_cancel| {
|
||||
let Some(page) = layout.pages.get(index) else { return Ok(LoadedPicture::Blank) };
|
||||
let img = if whole {
|
||||
let img = if let Some((w, h)) = pixels {
|
||||
wordcraft_render::render_area_to(&doc, page, area, w, h, &options)
|
||||
} else if whole {
|
||||
wordcraft_render::render_page(&doc, page, scale, &options)
|
||||
} else {
|
||||
wordcraft_render::render_area(&doc, page, area, scale, &options)
|
||||
|
||||
@@ -8,9 +8,11 @@ use crate::test_harness::AppFrames as _;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Rests the pointer for as long as the framework's tooltip waits before it shows a tool's tip
|
||||
/// (`tooltip::DELAY`, the framework's look), at the harness's default step of a quarter second.
|
||||
/// (`tooltip::DELAY`, the framework's look), at the harness's configured step time (`predicted_dt`).
|
||||
fn rest_for_tip(h: &mut H) {
|
||||
let frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
|
||||
let step_dt = f64::from(h.ctx.input(|i| i.predicted_dt));
|
||||
assert!(step_dt > 0.0, "harness step_dt must be positive, got {step_dt}");
|
||||
let frames = (craft::ui::contract::tooltip::DELAY / step_dt).ceil() as usize + 3;
|
||||
steps(h, frames);
|
||||
}
|
||||
|
||||
@@ -1247,6 +1249,54 @@ fn a_handled_press_skips_the_link_tooltip() {
|
||||
assert!(tips(&h) > 0, "hovering again shows the tooltip");
|
||||
}
|
||||
|
||||
/// Hovering a link with Ctrl/⌘ held shows the pointing hand cursor (while plain hover keeps
|
||||
/// the text cursor, plain text with Ctrl/⌘ keeps the text cursor, and Format Painter still takes
|
||||
/// precedence).
|
||||
#[test]
|
||||
fn holding_command_over_a_link_shows_the_hand_cursor() {
|
||||
use craft::behavior::cursor::{Cursor, CursorIcon, PaintedCursor};
|
||||
use egui::{Event, Modifiers};
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("See here")), Default::default());
|
||||
a.run("select.text", json!({"text": "here"})).unwrap();
|
||||
a.run("insert.link", json!({"url": "https://example.com/"})).unwrap();
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
let caret_at = |h: &mut H, off: usize| {
|
||||
let c = h.state_mut().session.layout().caret(&Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off }).expect("caret");
|
||||
screen(h, c.x, c.top + c.height / 2.0)
|
||||
};
|
||||
let over_plain = caret_at(&mut h, 1);
|
||||
let over_link = caret_at(&mut h, 5);
|
||||
let painted = {
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let shell = env.view().shell();
|
||||
shell.os == craft::host::target::Os::Windows && shell.runtime == craft::host::target::Runtime::Native
|
||||
};
|
||||
let text = if painted { Cursor::Painted(PaintedCursor::IBeam) } else { Cursor::System(CursorIcon::Text) };
|
||||
let cursor_at = |h: &mut H, at: Pos2, mods: Modifiers| -> Option<Cursor> {
|
||||
h.event(Event::ModifiersChanged(mods));
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.app_frame();
|
||||
craft::ui::runtime::cursor::current(&h.ctx)
|
||||
};
|
||||
assert_eq!(cursor_at(&mut h, over_link, Modifiers::NONE), Some(text.clone()), "plain hover over link keeps text cursor");
|
||||
assert_eq!(cursor_at(&mut h, over_link, Modifiers::COMMAND), Some(Cursor::System(CursorIcon::PointingHand)), "Ctrl/Cmd over link shows hand");
|
||||
h.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.app_frame();
|
||||
assert_eq!(craft::ui::runtime::cursor::current(&h.ctx), Some(text.clone()), "releasing Ctrl/Cmd over link restores text cursor");
|
||||
assert_eq!(cursor_at(&mut h, over_plain, Modifiers::COMMAND), Some(text), "Ctrl/Cmd over plain text keeps text cursor");
|
||||
h.state_mut().run("edit.formatPainter", json!({})).unwrap();
|
||||
assert_eq!(cursor_at(&mut h, over_link, Modifiers::COMMAND), Some(Cursor::System(CursorIcon::Copy)), "Format Painter still wins over link");
|
||||
}
|
||||
|
||||
/// With Hide White Space on, a click in a page's band puts the caret on that page, and a click
|
||||
/// on the cut margins either side of the seam lands on the page whose band it is nearest to.
|
||||
#[test]
|
||||
@@ -2309,6 +2359,209 @@ fn the_view_key_changes_when_a_drag_takes_an_object_off_the_page() {
|
||||
assert_eq!(hidden, view_key(&app, false, Some(&object)), "the same drag keeps the key: no re-render every frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_pages_follow_the_systems_text_settings() {
|
||||
use crate::screen_text::ScreenText;
|
||||
// Previews and thumbnails are cached without the system's settings in their keys: they are
|
||||
// drawn the platform's fixed way. Thumbnails are not baseline-snapped either.
|
||||
let (screen, thumb) = (screen_render_options(), thumbnail_render_options());
|
||||
for opts in [&screen, &thumb] {
|
||||
assert_eq!((opts.text_darkening, opts.hinting, opts.lcd), (ScreenText::PLATFORM.darkening, ScreenText::PLATFORM.hinting, None));
|
||||
}
|
||||
assert!(screen.baseline_snap && !thumb.baseline_snap);
|
||||
// A page takes the same until the app has asked the system (tests never do).
|
||||
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let page = page_render_options(&a, false);
|
||||
assert_eq!((page.text_darkening, page.hinting, page.baseline_snap), (screen.text_darkening, screen.hinting, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subpixel_text_follows_the_choice_the_system_and_the_screen() {
|
||||
use super::pages::lcd_for;
|
||||
use crate::screen_text::SubpixelOrder::{Bgr, Rgb};
|
||||
use wordcraft_engine::cmd::view::TextSmoothing::{Grayscale, Subpixel, System};
|
||||
use wordcraft_render::LcdOrder;
|
||||
// Use system setting: where the system asks for it, in its order, below 2x only.
|
||||
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 1.0), Some(LcdOrder::Rgb));
|
||||
assert_eq!(lcd_for(System, Some(Bgr), Some(Bgr), 1.5), Some(LcdOrder::Bgr));
|
||||
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 2.0), None, "a high-density screen");
|
||||
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), f32::NAN), None);
|
||||
assert_eq!(lcd_for(System, None, None, 1.0), None, "the system asks for greyscale, or says nothing");
|
||||
assert_eq!(lcd_for(System, None, Some(Bgr), 1.0), None, "a known stripe order is not a request");
|
||||
// The user's own choice wins on any screen; RGB when the system names no order.
|
||||
assert_eq!(lcd_for(Subpixel, None, None, 2.0), Some(LcdOrder::Rgb));
|
||||
assert_eq!(lcd_for(Subpixel, Some(Bgr), Some(Bgr), 3.0), Some(LcdOrder::Bgr));
|
||||
// A BGR panel whose system has smoothing off (ClearType off on Windows, greyscale on a
|
||||
// Linux desktop) still gets BGR edges, not RGB ones.
|
||||
assert_eq!(lcd_for(Subpixel, None, Some(Bgr), 1.0), Some(LcdOrder::Bgr));
|
||||
let cleartype_off = crate::screen_text::ScreenText::from_windows(Some("0"), Some(2), Some(0));
|
||||
assert_eq!(lcd_for(Subpixel, cleartype_off.subpixel, cleartype_off.stripes, 1.0), Some(LcdOrder::Bgr));
|
||||
assert_eq!(lcd_for(System, cleartype_off.subpixel, cleartype_off.stripes, 1.0), None);
|
||||
for (asked, stripes) in [(None, None), (Some(Rgb), Some(Rgb)), (None, Some(Bgr))] {
|
||||
assert_eq!(lcd_for(Grayscale, asked, stripes, 1.0), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_picture_is_rasterised_at_the_screens_own_scale_where_the_view_accounts_for_it() {
|
||||
use super::pages::raster_scale;
|
||||
// An A4 page (841.89 pt) at 100 % on a 2x screen: 2245.04 device pixels, asked for as 2256 (the next multiple
|
||||
// of 16). At 2256 every glyph would be shrunk by half a percent on its way to the screen.
|
||||
let longest = 841.89_f32;
|
||||
let native = 96.0 / 72.0 * 2.0;
|
||||
assert_eq!(raster_scale(2256, 16, longest, Some(native)), (native, true));
|
||||
assert_eq!(raster_scale(2256, 16, longest, None), (2256.0 / longest, false), "a view with no scale of its own");
|
||||
// US Letter (792 pt) at the same zoom is 2112 pixels, a multiple of 16: the same either way.
|
||||
let (scale, own) = raster_scale(2112, 16, 792.0, Some(native));
|
||||
assert!(own && (scale - 2112.0 / 792.0).abs() < 1e-6);
|
||||
// A side the view's scale doesn't account for: another zoom's request, a side lowered to the largest texture,
|
||||
// a part of the page shown reduced. Rasterised as asked for, and not the screen's own.
|
||||
for side in [2240, 2272, 1024, 16] {
|
||||
assert_eq!(raster_scale(side, 16, longest, Some(native)), (side as f32 / longest, false), "{side}");
|
||||
}
|
||||
// Numbers that aren't: as asked for.
|
||||
for (longest, native, step) in
|
||||
[(longest, f32::NAN, 16), (longest, f32::INFINITY, 16), (longest, -1.0, 16), (longest, 0.0, 16), (longest, native, 0)]
|
||||
{
|
||||
assert!(!raster_scale(2256, step, longest, Some(native)).1, "{longest} {native} {step}");
|
||||
}
|
||||
assert!(!raster_scale(2256, 16, f32::NAN, Some(native)).1 && !raster_scale(2256, 16, 0.0, Some(native)).1);
|
||||
}
|
||||
|
||||
/// A page a fraction of a pixel longer than the largest texture is made no larger than it: a picture one pixel over
|
||||
/// is halved on upload, and the page stays blurry at rest.
|
||||
#[test]
|
||||
fn a_page_picture_never_outgrows_the_largest_texture() {
|
||||
use super::source::WordPages;
|
||||
use craft::ui::primitives::textures::{MAX_TEXTURE, ThumbRequest};
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let layout = a.session.layout();
|
||||
let (w, h) = (layout.pages[0].w, layout.pages[0].h);
|
||||
let longest = w.max(h);
|
||||
for over in [-0.6, -0.1, 0.0, 0.1, 0.3, 0.5] {
|
||||
for y in [0.0, 0.3, 0.49, 0.6] {
|
||||
let scale = (MAX_TEXTURE as f32 + over) / longest;
|
||||
a.canvas.settled_pages = vec![(0, Rect::from_min_size(egui::pos2(10.0, y), egui::vec2(w * scale, h * scale)))];
|
||||
let pages = WordPages::new(&mut a, &layout, false, None, Some(scale));
|
||||
let plan = pages.plan(0, &ThumbRequest::for_cell(longest * scale, 1.0)).unwrap();
|
||||
let side = plan.pixels.map_or((longest * plan.scale).ceil() as u32, |(w, h)| w.max(h));
|
||||
assert!(side <= MAX_TEXTURE, "{over} at {y}: {side}");
|
||||
assert!(side + 2 >= MAX_TEXTURE, "not reduced either: {over} at {y}: {side}");
|
||||
if over < -0.5 {
|
||||
assert!(plan.pixels.is_some(), "a page below the limit keeps its own pixels: {over} at {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_picture_is_made_as_many_pixels_as_its_place_on_screen() {
|
||||
use super::pages::picture_pixels;
|
||||
use egui::{pos2, vec2};
|
||||
// An A4 page at 110 % on a 2x screen, centred in a window: 1746.155 × 2469.544 pixels starting at 642.923.
|
||||
// Its place rounds to 643..2389 across and 356..2826 down.
|
||||
let page = Rect::from_min_size(pos2(321.4615, 178.0), vec2(873.0775, 1234.772));
|
||||
let expected = (1746.155, 2469.544);
|
||||
assert_eq!(picture_pixels(page, None, 2.0, expected), Some((1746, 2470)));
|
||||
// The same page half a pixel further right ends on the next pixel and starts on the same one: 1747 across.
|
||||
assert_eq!(picture_pixels(page.translate(vec2(0.25, 0.0)), None, 2.0, expected), Some((1747, 2470)));
|
||||
// The upper half of it, as the page view asks for a part: the part's own place, rounded the same way.
|
||||
let half = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 0.5));
|
||||
assert_eq!(picture_pixels(page, Some(half), 2.0, (1746.155, 1234.772)), Some((1746, 1235)));
|
||||
// A place left from another zoom, or a part shown reduced, is not this picture's: no size.
|
||||
assert_eq!(picture_pixels(page, None, 2.0, (1587.4, 2245.0)), None);
|
||||
assert_eq!(picture_pixels(page, Some(half), 2.0, (873.0, 617.0)), None);
|
||||
// Numbers that aren't.
|
||||
for (page, ppp, expected) in [
|
||||
(Rect::from_min_size(pos2(f32::NAN, 0.0), vec2(800.0, 1100.0)), 2.0, expected),
|
||||
(Rect::from_min_size(pos2(0.0, 0.0), vec2(f32::INFINITY, 1100.0)), 2.0, expected),
|
||||
(page, f32::NAN, expected),
|
||||
(page, 0.0, expected),
|
||||
(page, 2.0, (f32::NAN, 2469.5)),
|
||||
(Rect::NOTHING, 2.0, expected),
|
||||
] {
|
||||
assert_eq!(picture_pixels(page, None, ppp, expected), None, "{page:?} {ppp} {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_pictures_fill_the_place_the_view_last_rested_at() {
|
||||
use super::source::WordPages;
|
||||
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
|
||||
use egui::{pos2, vec2};
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let layout = a.session.layout();
|
||||
let (pw, ph) = (layout.pages[0].w, layout.pages[0].h);
|
||||
let view_scale = 96.0 / 72.0 * 1.1;
|
||||
let request = ThumbRequest::for_cell(pw.max(ph) * view_scale, 2.0);
|
||||
// Before the view has rested anywhere: one scale, a whole pixel up each way.
|
||||
let fresh = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
|
||||
let plan = fresh.plan(0, &request).unwrap();
|
||||
assert_eq!((plan.pixels, plan.scale), (None, view_scale * 2.0));
|
||||
let fresh_revision = fresh.revision(&0, &request);
|
||||
a.canvas.page_keys = fresh.into_keys();
|
||||
// At rest, a third of a pixel into a pixel: the picture is its place's size, and another picture than before.
|
||||
let place = Rect::from_min_size(pos2(321.4615, 178.0), vec2(pw * view_scale, ph * view_scale));
|
||||
a.canvas.settled_pages = vec![(0, place)];
|
||||
let rested = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
|
||||
let plan = rested.plan(0, &request).unwrap();
|
||||
let (w, h) = plan.pixels.expect("a place to fill");
|
||||
assert_eq!(w as f32, (place.max.x * 2.0).round() - (place.min.x * 2.0).round());
|
||||
assert_eq!(h as f32, (place.max.y * 2.0).round() - (place.min.y * 2.0).round());
|
||||
assert_ne!(rested.revision(&0, &request), fresh_revision);
|
||||
assert!(rested.plan(1, &request).is_none_or(|plan| plan.pixels.is_none()), "a page with no place");
|
||||
a.canvas.page_keys = rested.into_keys();
|
||||
// A place from another zoom is not this zoom's; Read Mode's columns use none.
|
||||
let zoomed = WordPages::new(&mut a, &layout, false, None, Some(view_scale * 1.3));
|
||||
assert_eq!(zoomed.plan(0, &ThumbRequest::for_cell(pw.max(ph) * view_scale * 1.3, 2.0)).unwrap().pixels, None);
|
||||
a.canvas.page_keys = zoomed.into_keys();
|
||||
let reading = WordPages::new(&mut a, &layout, false, None, None);
|
||||
assert_eq!(reading.plan(0, &request).unwrap().pixels, None);
|
||||
a.canvas.page_keys = reading.into_keys();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_pictures_take_subpixel_text_only_at_the_screens_own_scale() {
|
||||
use super::source::WordPages;
|
||||
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
|
||||
use wordcraft_render::LcdOrder;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let layout = a.session.layout();
|
||||
let longest = layout.pages[0].w.max(layout.pages[0].h);
|
||||
let view_scale = 96.0 / 72.0 * 1.1;
|
||||
let request = |ppp: f32| ThumbRequest::for_cell(longest * view_scale, ppp);
|
||||
let pages = |a: &mut WordApp, scale: Option<f32>| WordPages::new(a, &layout, false, None, scale);
|
||||
// Greyscale until chosen (tests never ask the system), at the screen's own scale.
|
||||
let grey = pages(&mut a, Some(view_scale));
|
||||
let plan = grey.plan(0, &request(2.0)).unwrap();
|
||||
assert_eq!((plan.scale, plan.options.lcd), (view_scale * 2.0, None));
|
||||
assert!(plan.options.baseline_snap);
|
||||
let grey_revision = grey.revision(&0, &request(2.0));
|
||||
a.canvas.page_keys = grey.into_keys();
|
||||
// The user's choice, a command: subpixel text on the picture that is the screen's own...
|
||||
a.run("view.textSmoothing", json!({"value": "subpixel"})).unwrap();
|
||||
let sub = pages(&mut a, Some(view_scale));
|
||||
assert_eq!(sub.plan(0, &request(2.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
|
||||
assert_eq!(sub.plan(0, &request(1.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
|
||||
assert_ne!(sub.revision(&0, &request(2.0)), grey_revision, "a page drawn the other way is another picture");
|
||||
let sub_revision = sub.revision(&0, &request(2.0));
|
||||
// ...and not on one that will be scaled: a request the view's zoom doesn't account for, a part shown reduced.
|
||||
let other = ThumbRequest::for_cell(longest * view_scale * 1.3, 2.0);
|
||||
let plan = sub.plan(0, &other).unwrap();
|
||||
assert_eq!((plan.scale, plan.options.lcd), (other.side as f32 / longest, None));
|
||||
a.canvas.page_keys = sub.into_keys();
|
||||
// Read Mode's columns size their pages themselves: as asked for, greyscale.
|
||||
let reading = pages(&mut a, None);
|
||||
let plan = reading.plan(0, &request(2.0)).unwrap();
|
||||
assert_eq!((plan.scale, plan.options.lcd), (request(2.0).side as f32 / longest, None));
|
||||
a.canvas.page_keys = reading.into_keys();
|
||||
// Another zoom is another picture, even where the side asked for is the same.
|
||||
let nudged = pages(&mut a, Some(view_scale * 1.0005));
|
||||
assert_eq!(ThumbRequest::for_cell(longest * view_scale * 1.0005, 2.0).side, request(2.0).side);
|
||||
assert_ne!(nudged.revision(&0, &request(2.0)), sub_revision);
|
||||
assert!(nudged.plan(99, &request(2.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_paper_color_changes_raster_and_cache_without_changing_export_paper() {
|
||||
use wordcraft_doc::props::Rgb;
|
||||
@@ -2469,6 +2722,75 @@ fn a_picture_linked_from_its_context_menu_shows_and_follows_its_link() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9145: Ctrl/⌘ over a linked picture or shape shows the pointing hand (even when selected),
|
||||
/// while Ctrl/⌘+Shift keeps the object drag/copy cursor since Shift suppresses link following.
|
||||
#[test]
|
||||
fn ctrl_over_linked_object_shows_pointing_hand() {
|
||||
use craft::behavior::cursor::{Cursor, CursorIcon};
|
||||
|
||||
for case in ["inline-picture", "floating-picture", "shape"] {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
if case == "shape" {
|
||||
a.run("insert.shape", json!({"kind": "rectangle", "width": 160, "height": 80})).unwrap();
|
||||
} else {
|
||||
let img = image::RgbaImage::from_pixel(40, 20, image::Rgba([200, 30, 30, 255]));
|
||||
let png = wordcraft_geom::picture::encode_format(&image::DynamicImage::ImageRgba8(img), image::ImageFormat::Png).unwrap();
|
||||
a.run("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png), "width": 160})).unwrap();
|
||||
if case == "floating-picture" {
|
||||
a.run("arrange.wrap", json!({"wrap": "inFrontOfText"})).unwrap();
|
||||
}
|
||||
}
|
||||
let pos = wordcraft_engine::cmd::objects::selected(&a.session).unwrap().0;
|
||||
let end = Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() };
|
||||
a.run("insert.link", json!({"url": "https://example.com/obj"})).unwrap();
|
||||
// Also test when unselected (caret back in body text).
|
||||
a.session.sel = wordcraft_engine::Selection::caret(Pos::body(0, 0));
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
let rect = h.state_mut().session.layout().object(&pos, 0).expect("the object is laid out").rect;
|
||||
let at = page_to_screen(h.state_mut(), 0, rect.x + rect.w / 2.0, rect.y + rect.h / 2.0).expect("on screen");
|
||||
let cursor_at = |h: &mut H, mods: egui::Modifiers| {
|
||||
h.event(egui::Event::ModifiersChanged(mods));
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.app_frame();
|
||||
craft::ui::runtime::cursor::current(&h.ctx)
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, egui::Modifiers::COMMAND),
|
||||
Some(Cursor::System(CursorIcon::PointingHand)),
|
||||
"{case} unselected: Ctrl/Cmd shows hand"
|
||||
);
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT),
|
||||
Some(Cursor::System(CursorIcon::Move)),
|
||||
"{case} unselected: Ctrl/Cmd+Shift keeps move cursor"
|
||||
);
|
||||
|
||||
// Now select the object and verify Ctrl/Cmd still shows the hand, while Ctrl/Cmd+Shift shows Copy.
|
||||
h.state_mut().run("select.range", json!({"anchor": pos, "focus": end})).unwrap();
|
||||
steps(&mut h, 2);
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, egui::Modifiers::COMMAND),
|
||||
Some(Cursor::System(CursorIcon::PointingHand)),
|
||||
"{case} selected: Ctrl/Cmd shows hand"
|
||||
);
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT),
|
||||
Some(Cursor::System(CursorIcon::Copy)),
|
||||
"{case} selected: Ctrl/Cmd+Shift keeps copy cursor"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// #5267: inside a linked text box, hovering shows the box's link and Ctrl/⌘+click follows it,
|
||||
/// although a click there reaches the box's text rather than the box.
|
||||
#[test]
|
||||
@@ -2517,6 +2839,72 @@ fn a_linked_text_box_shows_and_follows_its_link_from_inside() {
|
||||
assert!(s.sel.is_collapsed() && s.sel.focus == start, "the caret went to the bookmark: {:?}", s.sel);
|
||||
}
|
||||
|
||||
/// #9146: Ctrl/⌘+Shift inside a linked text box does not follow the box's link on click, so it
|
||||
/// shows the text cursor over plain text inside the box while still showing the hand over inner
|
||||
/// text links (which Ctrl/⌘+Shift+click follows) and on plain Ctrl/⌘.
|
||||
#[test]
|
||||
fn ctrl_shift_inside_linked_text_box_shows_text_cursor() {
|
||||
use craft::behavior::cursor::{Cursor, CursorIcon, PaintedCursor};
|
||||
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("insert.textBox", json!({"text": "Plain inner"})).unwrap();
|
||||
let bx = a.session.layout().find_object(0, |o| o.text_box.is_some()).expect("the box");
|
||||
let box_story = StoryRef::Part(bx.text_box.expect("text box id"));
|
||||
let end = Pos { off: bx.off + wordcraft_doc::para::OBJ.len_utf8(), ..bx.pos() };
|
||||
a.run("select.range", json!({"anchor": bx.pos(), "focus": end})).unwrap();
|
||||
a.run("insert.link", json!({"url": "https://example.com/box"})).unwrap();
|
||||
a.run("select.range", json!({"anchor": Pos::new(box_story, wordcraft_doc::Path::top(0), "Plain ".len()), "focus": Pos::new(box_story, wordcraft_doc::Path::top(0), "Plain inner".len())})).unwrap();
|
||||
a.run("insert.link", json!({"url": "https://example.com/inner"})).unwrap();
|
||||
a.session.sel = wordcraft_engine::Selection::caret(Pos::body(0, 0));
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
|
||||
let plain_caret = h.state_mut().session.layout().caret(&Pos::new(box_story, wordcraft_doc::Path::top(0), 2)).expect("plain text caret");
|
||||
let over_plain =
|
||||
page_to_screen(h.state_mut(), plain_caret.page, plain_caret.x, plain_caret.top + plain_caret.height / 2.0).expect("plain on screen");
|
||||
let inner_caret =
|
||||
h.state_mut().session.layout().caret(&Pos::new(box_story, wordcraft_doc::Path::top(0), "Plain in".len())).expect("inner link caret");
|
||||
let over_inner =
|
||||
page_to_screen(h.state_mut(), inner_caret.page, inner_caret.x, inner_caret.top + inner_caret.height / 2.0).expect("inner on screen");
|
||||
|
||||
let painted = {
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let shell = env.view().shell();
|
||||
shell.os == craft::host::target::Os::Windows && shell.runtime == craft::host::target::Runtime::Native
|
||||
};
|
||||
let text = if painted { Cursor::Painted(PaintedCursor::IBeam) } else { Cursor::System(CursorIcon::Text) };
|
||||
let cursor_at = |h: &mut H, pos: Pos2, mods: egui::Modifiers| {
|
||||
h.event(egui::Event::ModifiersChanged(mods));
|
||||
h.event(egui::Event::PointerMoved(pos));
|
||||
h.app_frame();
|
||||
craft::ui::runtime::cursor::current(&h.ctx)
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, over_plain, egui::Modifiers::COMMAND),
|
||||
Some(Cursor::System(CursorIcon::PointingHand)),
|
||||
"Ctrl/Cmd over plain text inside linked text box shows hand"
|
||||
);
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, over_plain, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT),
|
||||
Some(text),
|
||||
"Ctrl/Cmd+Shift over plain text inside linked text box shows text cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
cursor_at(&mut h, over_inner, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT),
|
||||
Some(Cursor::System(CursorIcon::PointingHand)),
|
||||
"Ctrl/Cmd+Shift over inner hyperlink still shows hand"
|
||||
);
|
||||
}
|
||||
|
||||
/// Unit-level checks for #7742 (`hostile_numbers_are_ignored` logic): invalid `ScrollSpeed`
|
||||
/// codes, non-finite framework wheel/ease inputs, out-of-range `view.zoom` commands, and
|
||||
/// `sync_view_state` recovery from non-finite `session.view.zoom`.
|
||||
@@ -2770,18 +3158,18 @@ fn the_caret_blinks_only_while_the_window_is_active() {
|
||||
fn word_pages_reuses_doc_snapshot_across_unchanged_frames_and_invalidates_on_edit() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("hello")), Default::default());
|
||||
let layout = app.session.layout();
|
||||
let first = super::source::WordPages::new(&mut app, &layout, false, None);
|
||||
let first = super::source::WordPages::new(&mut app, &layout, false, None, None);
|
||||
let doc1 = first.doc();
|
||||
app.canvas.page_keys = first.into_keys();
|
||||
|
||||
let second = super::source::WordPages::new(&mut app, &layout, false, None);
|
||||
let second = super::source::WordPages::new(&mut app, &layout, false, None, None);
|
||||
let doc2 = second.doc();
|
||||
app.canvas.page_keys = second.into_keys();
|
||||
assert!(std::sync::Arc::ptr_eq(&doc1, &doc2), "unchanged frame reuses cached Arc<Document> snapshot");
|
||||
|
||||
app.run("text.insert", json!({"text": " world"})).unwrap();
|
||||
let layout2 = app.session.layout();
|
||||
let third = super::source::WordPages::new(&mut app, &layout2, false, None);
|
||||
let third = super::source::WordPages::new(&mut app, &layout2, false, None, None);
|
||||
let doc3 = third.doc();
|
||||
app.canvas.page_keys = third.into_keys();
|
||||
assert!(!std::sync::Arc::ptr_eq(&doc1, &doc3), "editing document invalidates cached snapshot");
|
||||
@@ -2899,3 +3287,184 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
|
||||
assert!(picked.contains(&first) && picked.contains(&second), "both pictures are selected: {picked:?} {:?} at {at:?}", h.state().session.sel);
|
||||
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
|
||||
}
|
||||
|
||||
/// Mouse-wheel notches scroll by WordCraft's document line distance (`NOTCH_PX`, 56 pt) rather than the framework's
|
||||
/// 16 pt default, and rapid flick notches accelerate when animations are enabled (#8840).
|
||||
#[test]
|
||||
fn mouse_wheel_notch_scrolls_document_line_distance_and_accelerates_on_flick() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "lorem ipsum dolor sit amet consectetur ".repeat(2000)})).unwrap();
|
||||
a.run("caret.docStart", json!({})).unwrap();
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 4);
|
||||
let center = h.state().canvas.view_rect().expect("the canvas laid out").center();
|
||||
let wheel = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
|
||||
// With animations off, one notch jumps the full document line distance in a single frame.
|
||||
let start_y = h.state().canvas.view.offset.1;
|
||||
h.event(egui::Event::PointerMoved(center));
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
let one_notch = h.state().canvas.view.offset.1 - start_y;
|
||||
assert!(
|
||||
(one_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"one mouse-wheel notch should scroll ~{} pt, got {one_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
// With animations on, a single notch eases to the same distance, and a rapid flick accelerates past it.
|
||||
h.state_mut().ui.animations = crate::theme::Animations::On;
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 4);
|
||||
let eased_start = h.state().canvas.view.offset.1;
|
||||
h.event(wheel());
|
||||
steps(&mut h, 30);
|
||||
let eased_notch = h.state().canvas.view.offset.1 - eased_start;
|
||||
assert!(
|
||||
(eased_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"an eased notch should settle at ~{} pt, got {eased_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 30);
|
||||
let flick_start = h.state().canvas.view.offset.1;
|
||||
for _ in 0..5 {
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
}
|
||||
steps(&mut h, 40);
|
||||
let flicked = h.state().canvas.view.offset.1 - flick_start;
|
||||
assert!(flicked > 5.0 * eased_notch, "a rapid 5-notch flick ({flicked}) should accelerate past 5 single notches ({})", 5.0 * eased_notch);
|
||||
}
|
||||
|
||||
/// In vertical text the composition runs down the line, upright and at the text's size, and the candidate window
|
||||
/// reports the column it fills, not a horizontal strip (#8980).
|
||||
#[test]
|
||||
fn a_composition_in_vertical_text_runs_down_the_line() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.run("document.setText", json!({"text": "Hello"})).unwrap();
|
||||
app.run("layout.textDirection", json!({"value": "tbRl"})).unwrap();
|
||||
app.run("caret.docEnd", json!({})).unwrap();
|
||||
let mut h = composing_harness(app);
|
||||
kana_test_glyphs(&h.ctx);
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほん".into(), active_range_chars: None }));
|
||||
for _ in 0..4 {
|
||||
h.app_frame();
|
||||
}
|
||||
let kana: Vec<_> = ["に", "ほ", "ん"].iter().filter_map(|k| drawn_composition(&h, k)).collect();
|
||||
assert_eq!(kana.len(), 3, "each kana is drawn on its own");
|
||||
let at = |i: usize| kana[i].pos;
|
||||
assert!(at(0).y < at(1).y && at(1).y < at(2).y, "the kana stack down the page");
|
||||
assert!((at(0).x - at(2).x).abs() < 1.0, "in one column");
|
||||
let ime = h.output().platform_output.ime.clone().expect("the canvas places the candidate window").cursor_rect;
|
||||
assert!(ime.height() > ime.width(), "the candidate window sits by the column: {ime:?}");
|
||||
}
|
||||
|
||||
/// The pictures drawn in the last pass that are at least 300 texels wide (a page's, not an icon's or the font
|
||||
/// atlas's glyphs): how many device pixels each is drawn across and down, and how many texels it shows.
|
||||
fn drawn_pictures(
|
||||
shapes: &[egui::epaint::ClippedShape],
|
||||
sizes: &std::collections::HashMap<egui::TextureId, [usize; 2]>,
|
||||
ppp: f32,
|
||||
) -> Vec<([f32; 2], [f32; 2])> {
|
||||
fn walk(shape: &egui::Shape, found: &mut Vec<(egui::TextureId, Rect, Rect)>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, found)),
|
||||
egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => {
|
||||
let (mut at, mut uv) = (Rect::NOTHING, Rect::NOTHING);
|
||||
for v in &mesh.vertices {
|
||||
at.extend_with(v.pos);
|
||||
uv.extend_with(v.uv);
|
||||
}
|
||||
found.push((mesh.texture_id, at, uv));
|
||||
}
|
||||
egui::Shape::Rect(rect) => {
|
||||
if let Some(brush) = &rect.brush
|
||||
&& brush.fill_texture_id != egui::TextureId::default()
|
||||
{
|
||||
found.push((brush.fill_texture_id, rect.rect, brush.uv));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut found));
|
||||
found
|
||||
.into_iter()
|
||||
.filter_map(|(id, at, uv)| {
|
||||
let size = sizes.get(&id).filter(|size| size[0] >= 300)?;
|
||||
let texels = [uv.width() * size[0] as f32, uv.height() * size[1] as f32];
|
||||
(texels[0] >= 300.0).then_some(([at.width() * ppp, at.height() * ppp], texels))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The page view scales a picture into its place, so a page's picture has to be exactly as many pixels each way
|
||||
/// as that place: a pixel more (what one scale and rounding up give) squeezes it by a twentieth of a percent and
|
||||
/// the text slides off the pixel grid and back down the page, which reads as blur. Run through the real page view
|
||||
/// and its picture store, at several zooms and screen densities, on the passes a renderer would draw.
|
||||
#[test]
|
||||
fn a_page_at_rest_is_drawn_one_texel_per_device_pixel() {
|
||||
for ppp in [1.0_f32, 2.0] {
|
||||
let ctx = crate::test_harness::context();
|
||||
crate::test_harness::cjk_stand_in(&ctx);
|
||||
ctx.set_pixels_per_point(ppp);
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.run("document.setText", json!({"text": "The quick brown fox jumps over the lazy dog."})).unwrap();
|
||||
app.run("layout.size", json!({"name": "A4"})).unwrap();
|
||||
let mut sizes = std::collections::HashMap::new();
|
||||
for (step, zoom) in [100, 110, 137].into_iter().enumerate() {
|
||||
app.run("view.zoom", json!({"value": zoom})).unwrap();
|
||||
// Until the view has come to rest and the worker has made the picture for where it rests.
|
||||
let mut seen = Vec::new();
|
||||
let exact = |pictures: &[([f32; 2], [f32; 2])]| {
|
||||
!pictures.is_empty()
|
||||
&& pictures.iter().all(|(drawn, texels)| (drawn[0] - texels[0]).abs() < 0.01 && (drawn[1] - texels[1]).abs() < 0.01)
|
||||
};
|
||||
for frame in 0..600 {
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1500.0, 950.0))),
|
||||
time: Some(step as f64 * 100.0 + frame as f64 * 0.05),
|
||||
max_texture_side: Some(8192),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(viewport) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
|
||||
viewport.native_pixels_per_point = Some(ppp);
|
||||
}
|
||||
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
crate::test_harness::logic(ui.ctx(), &mut app);
|
||||
app.ui(ui);
|
||||
});
|
||||
for (id, deltas) in &out.textures_delta.set {
|
||||
for delta in deltas.iter().filter(|delta| delta.pos.is_none()) {
|
||||
sizes.insert(*id, delta.image.size());
|
||||
}
|
||||
}
|
||||
seen = drawn_pictures(&out.shapes, &sizes, ppp);
|
||||
out.textures_delta.clear();
|
||||
if frame > 3 && exact(&seen) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(exact(&seen), "{zoom} % at {ppp}x: (pixels drawn, texels shown) {seen:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,18 @@ fn window(a: WordApp) -> H {
|
||||
/// [`window`] with a chosen step time (the time one frame adds), for gestures whose outcome
|
||||
/// depends on how long frames last.
|
||||
fn window_dt(a: WordApp, dt: Option<f32>) -> H {
|
||||
let mut b = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0));
|
||||
sized_window(a, egui::vec2(1440.0, 900.0), dt, 6)
|
||||
}
|
||||
|
||||
/// A harness around `a` in a window of `size`, with step time `dt` (the default when `None`),
|
||||
/// after `settle` frames: a smaller window and fewer frames keep a test that needs little of
|
||||
/// the window fast.
|
||||
fn sized_window(a: WordApp, size: egui::Vec2, dt: Option<f32>, settle: usize) -> H {
|
||||
let mut b = crate::test_harness::builder().with_size(size);
|
||||
if settle == 0 {
|
||||
// Stop kittest's build-time settle loop after one step when the caller wants zero settle frames.
|
||||
b = b.with_max_steps(0);
|
||||
}
|
||||
if let Some(dt) = dt {
|
||||
b = b.with_step_dt(dt);
|
||||
}
|
||||
@@ -26,9 +37,7 @@ fn window_dt(a: WordApp, dt: Option<f32>) -> H {
|
||||
},
|
||||
a,
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.app_frame();
|
||||
}
|
||||
steps(&mut h, settle);
|
||||
h
|
||||
}
|
||||
|
||||
@@ -37,27 +46,31 @@ fn button(at: Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event {
|
||||
egui::Event::PointerButton { pos: at, button, pressed, modifiers: Default::default() }
|
||||
}
|
||||
|
||||
/// A primary click at `at`, press and release a frame apart, then three frames to settle.
|
||||
/// A primary click at `at` (press and release a frame apart).
|
||||
fn click_at(h: &mut H, at: Pos2) {
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.event(button(at, egui::PointerButton::Primary, true));
|
||||
h.app_frame();
|
||||
h.event(button(at, egui::PointerButton::Primary, false));
|
||||
steps(h, 3);
|
||||
h.app_frame();
|
||||
}
|
||||
|
||||
/// A primary double click at `at`: two clicks a few frames apart, inside egui's double click delay.
|
||||
/// A primary double click at `at`: lets any prior click age past egui's double click delay, sends two clicks inside it,
|
||||
/// then one frame for the resulting UI change to draw.
|
||||
fn double_click_at(h: &mut H, at: Pos2) {
|
||||
// Let the click before it age out, or the pair would count as a triple click.
|
||||
steps(h, 40);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
let delay = h.ctx.options(|o| o.input_options.max_double_click_delay);
|
||||
let dt = f64::from(h.ctx.input(|i| i.predicted_dt)).max(1e-3);
|
||||
// Let any prior click clear `delay` by Click 1's release (at least 2*dt later).
|
||||
let since = f64::from(h.ctx.input(|i| i.pointer.time_since_last_click()));
|
||||
if since + 2.0 * dt <= delay + 1e-3 {
|
||||
steps(h, ((delay + 1e-3 - since - 2.0 * dt) / dt).ceil() as usize);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
h.event(button(at, egui::PointerButton::Primary, true));
|
||||
h.app_frame();
|
||||
h.event(button(at, egui::PointerButton::Primary, false));
|
||||
h.app_frame();
|
||||
}
|
||||
steps(h, 3);
|
||||
h.app_frame();
|
||||
}
|
||||
|
||||
/// A primary drag from `from` to `to` in six moves.
|
||||
@@ -262,12 +275,17 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
|
||||
/// #1348: an app with one comment ("Original") on some text, its balloon on screen.
|
||||
fn comment_harness() -> (H, u32) {
|
||||
comment_harness_in(egui::vec2(1440.0, 900.0), 6)
|
||||
}
|
||||
|
||||
/// [`comment_harness`] in a window of `size`, after `settle` frames.
|
||||
fn comment_harness_in(size: egui::Vec2, settle: usize) -> (H, u32) {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "Some text here"})).unwrap();
|
||||
a.run("select.text", json!({"text": "text"})).unwrap();
|
||||
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
(window_dt(a, Some(1.0 / 60.0)), id)
|
||||
(sized_window(a, size, Some(0.08), settle), id)
|
||||
}
|
||||
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
|
||||
@@ -278,33 +296,38 @@ fn click_balloon(h: &mut H, id: u32) {
|
||||
}
|
||||
|
||||
/// Double-clicks comment `id`'s card to open message 0 for editing, unless a draft is already open (a refused one
|
||||
/// is kept), and clicks into its field. Nothing opens where comments can't change.
|
||||
/// is kept), and ensures its field has the keyboard. Nothing opens where comments can't change.
|
||||
fn open_edit(h: &mut H, id: u32) {
|
||||
if crate::app::command_board::command_enabled(h.state(), "review.editComment") {
|
||||
if h.state().canvas.comments.editing.is_none() {
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
double_click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert!(h.state().canvas.comments.editing.is_some(), "a double click on the card opens its edit");
|
||||
}
|
||||
steps(h, 2);
|
||||
if crate::app::command_board::command_enabled(h.state(), "review.editComment") && h.state().canvas.comments.editing.is_none() {
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
double_click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert!(h.state().canvas.comments.editing.is_some(), "a double click on the card opens its edit");
|
||||
}
|
||||
use egui::accesskit::Role;
|
||||
let field = h
|
||||
.query_by_role_and_label(Role::MultilineTextInput, "Edit")
|
||||
.or_else(|| h.query_by_role_and_label(Role::TextInput, "Edit"))
|
||||
.map(|n| n.rect().center());
|
||||
if let Some(at) = field {
|
||||
let field = edit_field(h);
|
||||
if let Some(n) = field
|
||||
&& !n.is_focused()
|
||||
{
|
||||
let at = n.rect().center();
|
||||
click_at(h, at);
|
||||
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the card stays selected");
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the inline comment `Edit` text field node from the accessibility tree, if open.
|
||||
fn edit_field(h: &H) -> Option<egui_kittest::Node<'_>> {
|
||||
use egui::accesskit::Role;
|
||||
h.query_by_role_and_label(Role::MultilineTextInput, "Edit").or_else(|| h.query_by_role_and_label(Role::TextInput, "Edit"))
|
||||
}
|
||||
|
||||
/// Clicks comment `id`'s card (from no selected balloon): it is selected with no edit open, so Reply shows.
|
||||
fn select_balloon_card(h: &mut H, id: u32) {
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
steps(h, 2);
|
||||
if h.state().canvas.selected_balloon().is_some() {
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
h.app_frame();
|
||||
}
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
h.app_frame();
|
||||
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
|
||||
}
|
||||
|
||||
@@ -317,12 +340,7 @@ fn type_in(h: &mut H, text: &str) {
|
||||
/// Leave the comment field by clicking on the page (which also leaves the balloon).
|
||||
fn leave_field(h: &mut H) {
|
||||
let at = h.state().canvas.page_rects().next().map(|(_, r)| r.center()).expect("a page is shown");
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
for pressed in [true, false] {
|
||||
h.event(button(at, egui::PointerButton::Primary, pressed));
|
||||
h.app_frame();
|
||||
}
|
||||
steps(h, 3);
|
||||
click_at(h, at);
|
||||
}
|
||||
|
||||
/// The text of comment `id` in the document.
|
||||
@@ -358,7 +376,7 @@ fn an_empty_comment_balloon_deletes() {
|
||||
}
|
||||
let id = a.run("review.newComment", json!({})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
let mut h = window_dt(a, Some(1.0 / 60.0));
|
||||
let mut h = window_dt(a, Some(0.08));
|
||||
click_balloon(&mut h, id);
|
||||
let resolve = h.get_by_label("Resolve").rect().center();
|
||||
click_at(&mut h, resolve);
|
||||
@@ -408,6 +426,29 @@ fn a_refused_comment_edit_keeps_the_draft() {
|
||||
assert!(text.contains("Edited"), "the typed text survived the refusal: {text:?}");
|
||||
}
|
||||
|
||||
/// #1348: Escape in a balloon throws the draft away and shows the comment's text again, and leaving the field writes nothing.
|
||||
#[test]
|
||||
fn escape_reverts_a_comment_draft() {
|
||||
// Zero post-build settle frames keep the test fast (`sized_window` with `with_max_steps(0)` still runs kittest's
|
||||
// initial build frame, which populates `balloon_rects` before `click_balloon` clicks). The window stays wide enough
|
||||
// for the click on the page's centre to land on the page, not on a balloon.
|
||||
let (mut h, id) = comment_harness_in(egui::vec2(1440.0, 900.0), 0);
|
||||
click_balloon(&mut h, id);
|
||||
type_in(&mut h, "Discarded ");
|
||||
assert!(draft_text(h.state()).is_some_and(|d| d.contains("Discarded")), "the draft was recorded before Escape");
|
||||
assert!(edit_field(&h).and_then(|n| n.value()).is_some_and(|v| v.contains("Discarded")), "the Edit field showed the typed draft before Escape");
|
||||
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
|
||||
h.app_frame();
|
||||
assert_eq!(draft_text(h.state()), None, "the draft is gone");
|
||||
assert_eq!(comment_text(h.state(), id), "Original", "nothing was written");
|
||||
assert!(edit_field(&h).is_none(), "Escape closes the inline Edit field");
|
||||
assert!(h.query_by_label_contains("Original").is_some(), "the balloon shows the comment's original text again");
|
||||
assert!(h.query_by_label_contains("Discarded").is_none(), "no discarded draft remains shown in the balloon");
|
||||
leave_field(&mut h);
|
||||
assert_eq!(h.state().canvas.selected_balloon(), None, "the click on the page left the balloon");
|
||||
assert_eq!(comment_text(h.state(), id), "Original", "and nothing is written later");
|
||||
}
|
||||
|
||||
/// #3268: clicking a balloon's Reply button, typing a reply and clicking away posts it as a
|
||||
/// reply comment under the original, not a draft that silently disappears.
|
||||
#[test]
|
||||
@@ -977,3 +1018,29 @@ fn a_footnote_link_shows_its_tip_with_the_caret_in_the_body() {
|
||||
assert!(h.query_all_by_label_contains("https://example.com/note").count() > 0, "the footnote's link shows its tip (pointer at {at:?})");
|
||||
assert_eq!(h.query_all_by_label_contains("Inserted ").count(), 0, "not the tracked insertion's tip");
|
||||
}
|
||||
|
||||
/// #8849: choosing Paste in the right-click context menu pastes from the system clipboard
|
||||
/// directly without relying on a platform `RequestPaste` round-trip.
|
||||
#[test]
|
||||
fn context_menu_paste_inserts_system_clipboard_text() {
|
||||
use craft::platform::clipboard::{Clipboard, Flavor, MemoryClipboard};
|
||||
let mut clipboard = Clipboard::new(MemoryClipboard::default());
|
||||
let _ = clipboard.write(&[Flavor::text("pasted text")]).unwrap();
|
||||
let mut h = crate::test_harness::builder_with(move || crate::test_harness::install_spec().clipboard(clipboard))
|
||||
.with_size(egui::vec2(1440.0, 900.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello ")), Default::default()),
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
let at = caret_point(&mut h, &Pos::body(0, 6));
|
||||
right_click(&mut h, at);
|
||||
assert!(h.state().canvas.context_menu_open, "menu open");
|
||||
pick(&mut h, &["Paste"]);
|
||||
steps(&mut h, 3);
|
||||
assert_eq!(h.state().session.doc.body[0].as_para().unwrap().plain_text(), "Hello pasted text");
|
||||
}
|
||||
|
||||
@@ -51,8 +51,11 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
|
||||
.iter()
|
||||
.filter(|c| !crate::dialogs::NOT_IN_SEARCH.contains(&c.id))
|
||||
.map(|c| {
|
||||
let command =
|
||||
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
|
||||
let command = if c.id == "view.paperColor" || c.id == "view.textSmoothing" {
|
||||
CommandRef::with_params("file.options", json!({"pane": "general"}))
|
||||
} else {
|
||||
CommandRef::new(c.id)
|
||||
};
|
||||
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
|
||||
match crate::app::command_board::location_path(c.location) {
|
||||
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
|
||||
|
||||
@@ -9,10 +9,11 @@ use craft::theme::ControlSize;
|
||||
use craft::theme::variant::Variant;
|
||||
use craft::ui::bars::{Bar, BarKind};
|
||||
use craft::ui::buttons::{Button, ButtonOutput, IconButton, ToggleButton};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{AfterInk, Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::display::{Divider, Text};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::runtime::env::with_env;
|
||||
use craft::ui::value_drag::{Slider, SliderScale};
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
@@ -45,7 +46,16 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
if let Ok(mut a) = app.try_borrow_mut() {
|
||||
page.set(Some(readouts(&mut a, ui)));
|
||||
// The readouts are secondary text, as v0.19.1 drew them (#8811): craft's ghost button takes the muted ink
|
||||
// where it passes text contrast.
|
||||
let rect = with_env(
|
||||
ui,
|
||||
|o| {
|
||||
o.values.set(AfterInk::Muted);
|
||||
},
|
||||
|ui| readouts(&mut a, ui),
|
||||
);
|
||||
page.set(Some(rect));
|
||||
}
|
||||
});
|
||||
if let (Some(page), Some(group), Ok(mut a)) = (page.get(), group.get(), app.try_borrow_mut()) {
|
||||
|
||||
@@ -252,10 +252,14 @@ fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (u
|
||||
agree(cells.into_iter().filter_map(|(r, c)| table.rows.get(r)?.cells.get(c).map(|cell| cell.props.shading)))
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch), read from what its command changes:
|
||||
/// `para.shading` reads the selected text's shading when the selection is text within one paragraph,
|
||||
/// else the paragraphs'; `shape.effects` reads shapes only. `None` when it has none, is Automatic,
|
||||
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
|
||||
/// The colour a target has now (the dialog's Current swatch).
|
||||
///
|
||||
/// Returns the colour already stored in `params` at the JSON pointer `at` first (used for targets
|
||||
/// such as gradient stops, so a non-null colour at `at` overrides reading the document). Otherwise
|
||||
/// reads from what its command changes: `para.shading` reads the selected text's shading when the
|
||||
/// selection is text within one paragraph, else the paragraphs'; `shape.effects` reads shapes only.
|
||||
/// `None` when it has none, is Automatic, differs across the selection, or cannot be read (a
|
||||
/// picture's icon colour is not stored).
|
||||
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
use wordcraft_doc::InlineObject;
|
||||
let Target::Run { cmd, params, at, .. } = target else { return None };
|
||||
|
||||
@@ -70,9 +70,21 @@ pub fn inspect(app: &mut WordApp, ctx: &egui::Context) -> Value {
|
||||
"document": app.session.document_id(),
|
||||
"documents": app.session.documents(),
|
||||
"perf": {"frameMs": app.frame_ms, "layoutMs": app.session.layout().ms},
|
||||
"agentLink": agent_link(app),
|
||||
})
|
||||
}
|
||||
|
||||
/// The agent link for `ui.inspect` ([`crate::agents`]); `null` without one.
|
||||
fn agent_link(app: &WordApp) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
return app.agent_link_json();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = app;
|
||||
Value::Null
|
||||
}
|
||||
}
|
||||
|
||||
/// Programmatic calls never open the Save prompt, so closing unsaved work must be explicit:
|
||||
/// save first, or pass `"force": true` (only a real boolean true counts) to discard it (#1268).
|
||||
pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&'static str> {
|
||||
|
||||
@@ -425,3 +425,61 @@ fn inspect_lists_recent_documents_as_full_paths() {
|
||||
let Reply::Done(r) = control::handle(&mut a, &installed(), &req) else { panic!("ui.inspect answers at once") };
|
||||
assert_eq!(r["result"]["ui"]["recent"], json!([full]), "{r}");
|
||||
}
|
||||
|
||||
/// Quit with a table title still typed in the focused Alt Text field: the root window's close (the built-in Quit)
|
||||
/// commits the draft and asks Save Changes; `ui.quit` (the app menu's Quit, ⌘Q, the Dock) must do the same (#8790),
|
||||
/// and asks only once: Don't Save quits.
|
||||
#[test]
|
||||
fn quit_commits_the_focused_fields_draft_before_asking() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
fn caption(a: &WordApp) -> Option<String> {
|
||||
let focus = &a.session.sel.focus;
|
||||
let (path, _, _) = focus.path.cell()?;
|
||||
a.session.doc.table(focus.story, &path)?.props.caption.clone()
|
||||
}
|
||||
fn typed_title() -> egui_kittest::Harness<'static, WordApp> {
|
||||
let mut a = app();
|
||||
a.run("insert.table", json!({"rows": 1, "cols": 1})).unwrap();
|
||||
a.session.dirty = false;
|
||||
a.session.view.alt_text_pane = true;
|
||||
let mut h = harness(a);
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").click();
|
||||
frames(&mut h, 2);
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").type_text("Prices");
|
||||
frames(&mut h, 2);
|
||||
assert!(!h.state().session.dirty && caption(h.state()).is_none(), "the title is still a draft in the focused field");
|
||||
h
|
||||
}
|
||||
fn host_close(h: &mut egui_kittest::Harness<'static, WordApp>) {
|
||||
h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
|
||||
frames(h, 6);
|
||||
}
|
||||
|
||||
// The root window's close, as the built-in Quit sent it.
|
||||
let mut h = typed_title();
|
||||
host_close(&mut h);
|
||||
let a = h.state();
|
||||
assert_eq!(prompt(a), Some("saveChanges"), "root close asks about the committed title");
|
||||
|
||||
// The app menu's Quit (⌘Q), then the close the host sends once `quit_requested` is set.
|
||||
let mut h = typed_title();
|
||||
h.state_mut().run("ui.quit", json!({})).unwrap();
|
||||
frames(&mut h, 2);
|
||||
host_close(&mut h);
|
||||
let a = h.state();
|
||||
assert!(
|
||||
prompt(a) == Some("saveChanges") && !a.quit_requested,
|
||||
"ui.quit lost the typed title: caption={:?} dirty={} quit_requested={}",
|
||||
caption(a),
|
||||
a.session.dirty,
|
||||
a.quit_requested
|
||||
);
|
||||
assert_eq!(caption(a).as_deref(), Some("Prices"), "the prompt is about the committed title");
|
||||
|
||||
// Don't Save answers the quit: it is not asked again, though the last document stays open and modified.
|
||||
h.state_mut().run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert!(h.state().quit_requested, "Don't Save quits");
|
||||
host_close(&mut h);
|
||||
assert!(h.state().quit_requested && prompt(h.state()).is_none(), "the answered quit is not asked about again");
|
||||
}
|
||||
|
||||
@@ -52,7 +52,15 @@ fn assignable(binding: &Binding) -> bool {
|
||||
|
||||
/// The ribbon tab a command lives on, in English (the first part of its path).
|
||||
fn tab(def: &CommandDef) -> &str {
|
||||
def.paths.first().and_then(|path| path.first()).map_or("", String::as_str)
|
||||
if let Some(tab) = def.paths.first().and_then(|path| path.first()) {
|
||||
return tab;
|
||||
}
|
||||
// The runtime owns these definitions and their bindings. Use the engine's ribbon location
|
||||
// for classification when the linked definition has no path of its own.
|
||||
match def.command.id.as_str() {
|
||||
"edit.cut" | "edit.copy" | "edit.paste" => wordcraft_engine::cmd::edit::LINKED_CLIPBOARD_LOCATION.split(" › ").next().unwrap_or_default(),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
|
||||
@@ -367,4 +375,28 @@ mod tests {
|
||||
let bold = catalog.defs().iter().find(|def| def.command == CommandRef::new("format.bold")).expect("format.bold");
|
||||
assert_eq!(bold.paths.first().and_then(|p| p.first()).map(String::as_str), Some("Home"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_clipboard_commands_are_listed_once_under_home() {
|
||||
let mut a = app();
|
||||
let app_catalog = a.catalog().expect("app catalog");
|
||||
let mut h = crate::test_harness::builder().build_eframe(|_| a);
|
||||
h.run_steps(2);
|
||||
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board installs a keymap");
|
||||
let areas = super::areas();
|
||||
|
||||
for (id, category, shortcut) in
|
||||
[("edit.cut", "Home", "Mod+X"), ("edit.copy", "Home", "Mod+C"), ("edit.paste", "Home", "Mod+V"), ("edit.undo", "Other", "Mod+Z")]
|
||||
{
|
||||
let command = CommandRef::new(id);
|
||||
assert!(app_catalog.defs().iter().all(|def| def.command != command), "{id} is owned by the linked set");
|
||||
let mut rows = keymap.catalog().iter().filter(|def| def.command == command);
|
||||
let row = rows.next().unwrap_or_else(|| panic!("{id} is listed"));
|
||||
assert!(rows.next().is_none(), "{id} is listed once");
|
||||
let categories: Vec<_> = areas.iter().filter(|area| (area.rows)(row)).map(|area| area.id).collect();
|
||||
assert_eq!(categories, [category, "All Commands"], "{id} is filed under the expected tab");
|
||||
let shortcut = Binding::parse(shortcut).unwrap();
|
||||
assert!(keymap.bindings(&command).iter().any(|binding| binding.trigger == shortcut.trigger), "{id} retains its shortcut");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn field_kind(name: &str) -> FieldKind {
|
||||
pub struct FieldForm {
|
||||
pub category: String,
|
||||
pub name: String,
|
||||
/// `\@` picture for date fields.
|
||||
/// `\@` picture for date fields. Empty uses the field language's default.
|
||||
pub date_format: String,
|
||||
/// `\*` value for number fields (empty = none).
|
||||
pub number_format: String,
|
||||
@@ -206,7 +206,7 @@ impl FieldForm {
|
||||
let mut f = FieldForm {
|
||||
category: FIELD_CATEGORIES.first().copied().unwrap_or("(All)").to_string(),
|
||||
name: "DATE".into(),
|
||||
date_format: DATE_FORMATS.first().copied().unwrap_or("M/d/yyyy").to_string(),
|
||||
date_format: String::new(),
|
||||
number_format: String::new(),
|
||||
text_format: String::new(),
|
||||
typed_text_formats: Vec::new(),
|
||||
@@ -257,7 +257,7 @@ impl FieldForm {
|
||||
};
|
||||
self.style_switches.clear();
|
||||
if field_kind(name) == FieldKind::Date {
|
||||
self.date_format = if name == "TIME" { "h:mm am/pm" } else { "M/d/yyyy" }.into();
|
||||
self.date_format.clear();
|
||||
}
|
||||
self.code = self.instruction();
|
||||
}
|
||||
@@ -377,10 +377,14 @@ impl FieldForm {
|
||||
match field_kind(&self.name) {
|
||||
FieldKind::Date => {
|
||||
text_field(ui, "field_date", &word("Date formats:"), &mut self.date_format);
|
||||
let samples: Vec<String> = DATE_FORMATS.iter().map(|p| wordcraft_engine::cmd::insert::format_date(p)).collect();
|
||||
let current = DATE_FORMATS.iter().position(|p| *p == self.date_format);
|
||||
let formats: Vec<_> = std::iter::once("").chain(DATE_FORMATS.iter().copied()).collect();
|
||||
let samples = formats
|
||||
.iter()
|
||||
.map(|p| if p.is_empty() { tl!("Default (field language)").to_string() } else { wordcraft_engine::cmd::insert::format_date(p) })
|
||||
.collect::<Vec<_>>();
|
||||
let current = formats.iter().position(|p| *p == self.date_format.trim());
|
||||
if let Some(at) = list_index(ui, &word("Date formats:"), &samples, current).selected
|
||||
&& let Some(p) = DATE_FORMATS.get(at)
|
||||
&& let Some(p) = formats.get(at)
|
||||
{
|
||||
self.date_format = (*p).to_string();
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ use crate::widgets::font_box::font_picker;
|
||||
|
||||
/// A symbol inserted from the Symbol dialog, kept for its Recently used row and the ribbon's
|
||||
/// Symbol gallery (`font` empty = the text's own font).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RecentSymbol {
|
||||
pub ch: String,
|
||||
@@ -650,11 +650,9 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
Text::new(word("Recently used symbols:")).show(ui);
|
||||
return false;
|
||||
}
|
||||
let positions: Vec<usize> = (0..form.recent.len()).collect();
|
||||
let source = keyed(&positions, |at: &usize| *at);
|
||||
let mut events = Vec::new();
|
||||
Field::new(word("Recently used symbols:")).show(ui, |ui, _| {
|
||||
let recent = &form.recent;
|
||||
let source = keyed(&form.recent, |r: &RecentSymbol| r.clone());
|
||||
events = TileGrid::new(word("Recently used symbols:"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
@@ -662,11 +660,10 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
.card_columns(RECENT_SYMBOLS)
|
||||
.natural_height(true)
|
||||
.selection(Bind::given(Selection::default()))
|
||||
.show_items(ui, &source, &mut |at, _| {
|
||||
let r = recent.get(*at).cloned().unwrap_or_default();
|
||||
.show_items(ui, &source, &mut |r, _| {
|
||||
let ch = r.ch.chars().next().unwrap_or(' ');
|
||||
let font = r.font;
|
||||
Tile::new(r.ch).thumb(ThumbAspect::SQUARE, move |cx, rect| paint_glyph(cx, rect, ch, &font, dark))
|
||||
let font = r.font.clone();
|
||||
Tile::new(r.ch.clone()).thumb(ThumbAspect::SQUARE, move |cx, rect| paint_glyph(cx, rect, ch, &font, dark))
|
||||
})
|
||||
.response
|
||||
.events;
|
||||
@@ -674,7 +671,7 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
let (mut picked, mut activated) = (None, false);
|
||||
for event in events {
|
||||
match event {
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(rows), .. } => picked = rows.last().copied().or(picked),
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(rows), .. } => picked = rows.last().cloned().or(picked),
|
||||
CollectionEvent::Activate(row) => {
|
||||
picked = Some(row);
|
||||
activated = true;
|
||||
@@ -682,7 +679,7 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(r) = picked.and_then(|i| form.recent.get(i)).cloned()
|
||||
if let Some(r) = picked
|
||||
&& let Some(c) = r.ch.chars().next()
|
||||
{
|
||||
form.font = r.font;
|
||||
|
||||
@@ -242,12 +242,56 @@ fn cross_font_recent_symbol_inserts_clicked_character() {
|
||||
assert!(h.state().dialog_host.get_dyn(id).is_some(), "insert mode keeps the Symbol dialog open");
|
||||
}
|
||||
|
||||
/// #9004: Pressing Enter twice on a focused recent symbol tile inserts the same symbol (and its
|
||||
/// font) both times even after `remember_symbol` moves it to the front of the row.
|
||||
#[test]
|
||||
fn enter_twice_on_recent_symbol_tile_inserts_same_symbol_and_font() {
|
||||
use egui::{Event, Key, Modifiers, PointerButton};
|
||||
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
// Put © with Source Sans 3 at index 1 behind © with DejaVu Sans at index 0 so both character
|
||||
// identity and font identity are tested when the second tile moves to the front.
|
||||
remember_symbol(&mut a, "©", "Source Sans 3");
|
||||
remember_symbol(&mut a, "©", "DejaVu Sans");
|
||||
let mut h = testing::harness(a);
|
||||
let id = crate::dialogs::open(h.state_mut(), "symbol", &json!({})).expect("symbol dialog opens");
|
||||
h.run_steps(3);
|
||||
|
||||
// Click the second recent tile (index 1: © in Source Sans 3) to focus it without activating.
|
||||
let recent_rect = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Recently used symbols:").rect();
|
||||
let mut tiles: Vec<egui::Rect> = h.query_all_by_label("©").map(|n| n.rect()).filter(|r| recent_rect.contains_rect(*r)).collect();
|
||||
tiles.sort_by(|a, b| a.min.x.total_cmp(&b.min.x));
|
||||
assert_eq!(tiles.len(), 2, "both recent tiles render");
|
||||
let second = tiles[1].center();
|
||||
h.event(Event::PointerMoved(second));
|
||||
h.event(Event::PointerButton { pos: second, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(Event::PointerButton { pos: second, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(3);
|
||||
|
||||
for press in 1..=2 {
|
||||
h.event(Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: false, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(3);
|
||||
let text = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(text.chars().count(), press, "Enter #{press} inserts one symbol: {text:?}");
|
||||
}
|
||||
|
||||
let text = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert!(text.starts_with("©©"), "both Enters insert ©: {text:?}");
|
||||
let para = h.state().session.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(para.props_of_char(0).font.as_deref(), Some("Source Sans 3"), "first insert uses Source Sans 3");
|
||||
assert_eq!(para.props_of_char("©".len()).font.as_deref(), Some("Source Sans 3"), "second insert keeps focus on Source Sans 3 tile");
|
||||
assert!(h.state().dialog_host.get_dyn(id).is_some(), "insert mode keeps the Symbol dialog open");
|
||||
}
|
||||
|
||||
/// The Field dialog builds the field code from its options.
|
||||
#[test]
|
||||
fn field_dialog_builds_the_instruction() {
|
||||
let a = app();
|
||||
let mut f = FieldForm::new(&a);
|
||||
assert_eq!(f.instruction(), r#"DATE \@ "M/d/yyyy" \* MERGEFORMAT"#);
|
||||
assert_eq!(f.instruction(), r"DATE \* MERGEFORMAT");
|
||||
f.date_format = "yyyy-MM-dd".into();
|
||||
f.preserve = false;
|
||||
assert_eq!(f.instruction(), r#"DATE \@ "yyyy-MM-dd""#);
|
||||
@@ -275,6 +319,73 @@ fn field_dialog_builds_the_instruction() {
|
||||
assert!(f.params().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_dialog_date_and_time_defaults_follow_the_field_language_on_update() {
|
||||
use crate::dialogs::host::WordForm;
|
||||
use wordcraft_doc::InlineObject;
|
||||
use wordcraft_engine::cmd::{insert::format_date_at_in, local_offset_secs, now_unix};
|
||||
|
||||
let locales = [("de-DE", "HH:mm", "dd.MM.yyyy", "04.12.2026"), ("en-US", "h:mm am/pm", "M/d/yyyy", "12/4/2026")];
|
||||
for (lang, time, date, created) in locales {
|
||||
let mut a = app();
|
||||
a.session.doc.core.created = "2026-12-04".into();
|
||||
a.session.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
|
||||
let mut form = FieldForm::new(&a);
|
||||
let mut expected = Vec::new();
|
||||
let start = now_unix();
|
||||
for name in ["TIME", "DATE", "CREATEDATE", "SAVEDATE", "PRINTDATE"] {
|
||||
let picture = if name == "TIME" { time } else { date };
|
||||
a.run("insert.field", json!({"instr": name})).unwrap();
|
||||
expected.push((name.to_string(), picture));
|
||||
|
||||
form.select(name);
|
||||
assert!(form.date_format.is_empty(), "{name} starts from the field-language default");
|
||||
let instruction = format!(r"{name} \* MERGEFORMAT");
|
||||
assert_eq!(form.final_code(), instruction);
|
||||
let (command, params) = form.commands().pop().expect("the dialog inserts a field");
|
||||
a.run(&command, params).unwrap();
|
||||
expected.push((instruction, picture));
|
||||
}
|
||||
|
||||
for (name, picture) in [("TIME", "HH:mm:ss"), ("DATE", "yyyy-MM-dd")] {
|
||||
form.select(name);
|
||||
form.date_format = picture.into();
|
||||
let (command, params) = form.commands().pop().unwrap();
|
||||
a.run(&command, params).unwrap();
|
||||
expected.push((format!(r#"{name} \@ "{picture}" \* MERGEFORMAT"#), picture));
|
||||
}
|
||||
|
||||
let check = |a: &WordApp, from, to| {
|
||||
let p = a.session.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.objects.len(), expected.len());
|
||||
for (object, (instruction, picture)) in p.objects.iter().zip(&expected) {
|
||||
let InlineObject::Field { instr, result, .. } = object else { panic!("expected {instruction}") };
|
||||
assert_eq!(instr, instruction);
|
||||
if instr.starts_with("CREATEDATE") {
|
||||
assert_eq!(result, created);
|
||||
} else {
|
||||
// The clock can roll over while the command is running.
|
||||
assert!(
|
||||
(from..=to).any(|t| *result == format_date_at_in(picture, Some(lang), t, local_offset_secs(t))),
|
||||
"{lang}: {instr} showed {result:?}, expected {picture}"
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
check(&a, start, now_unix());
|
||||
|
||||
let p = a.session.doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
for o in &mut p.objects {
|
||||
if let InlineObject::Field { result, .. } = o {
|
||||
*result = "stale".into();
|
||||
}
|
||||
}
|
||||
let start = now_unix();
|
||||
a.run("references.updateFields", json!({"all": true})).unwrap();
|
||||
check(&a, start, now_unix());
|
||||
}
|
||||
}
|
||||
|
||||
/// Text fields take a capitalization Format: each choice writes its `\*` switch before
|
||||
/// `\* MERGEFORMAT`, after the field's own arguments and switches, and (none) writes none.
|
||||
#[test]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user