mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-21 20:39:42 +00:00
Compare commits
290
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba145e9405 | ||
|
|
f7d7c0288c | ||
|
|
e65d188747 | ||
|
|
e05b7fe86f | ||
|
|
e3bb06a298 | ||
|
|
cd709ea0a9 | ||
|
|
d1b0bfc3f9 | ||
|
|
fd24c1ab3f | ||
|
|
2e6db0bd88 | ||
|
|
9b4b948c6e | ||
|
|
e6c5a701dd | ||
|
|
4e2568e2da | ||
|
|
b8debb3050 | ||
|
|
f1b4be8a04 | ||
|
|
2304bf6ac6 | ||
|
|
e8866ea58b | ||
|
|
74ab8d2819 | ||
|
|
517ba09250 | ||
|
|
49a934fba7 | ||
|
|
117aea31a8 | ||
|
|
fdf791a8b2 | ||
|
|
dbc5c3407b | ||
|
|
3f9c19d9f3 | ||
|
|
435be0a4cb | ||
|
|
6950c22d73 | ||
|
|
e0ff4b0c3d | ||
|
|
ebabb57e5e | ||
|
|
25ad07f868 | ||
|
|
e1e6c31571 | ||
|
|
396344c31e | ||
|
|
6e3f800a8b | ||
|
|
83014016c6 | ||
|
|
570b992947 | ||
|
|
76d8347f77 | ||
|
|
19e5bb48cf | ||
|
|
ab968b072d | ||
|
|
d26b8dcae7 | ||
|
|
68bc118a68 | ||
|
|
18c7c1d114 | ||
|
|
60ad86acb3 | ||
|
|
d588e0b873 | ||
|
|
61e565cd1c | ||
|
|
2d0169e718 | ||
|
|
384d5ef307 | ||
|
|
99ff497180 | ||
|
|
4b18b307be | ||
|
|
972252d0b4 | ||
|
|
100dfb37c8 | ||
|
|
00abb59a85 | ||
|
|
72328ab521 | ||
|
|
652a1596aa | ||
|
|
d82f17ac58 | ||
|
|
0b3733749d | ||
|
|
3af927501b | ||
|
|
c266e5a751 | ||
|
|
e85fc75808 | ||
|
|
12428df221 | ||
|
|
8b789b87d1 | ||
|
|
528da1f6a2 | ||
|
|
b7579bfe34 | ||
|
|
b8b1ec6141 | ||
|
|
914e92b163 | ||
|
|
8b0f1762a1 | ||
|
|
de8a81c1e4 | ||
|
|
2646700ca0 | ||
|
|
9b9eeb8c61 | ||
|
|
72467d037b | ||
|
|
ca6faa8c1d | ||
|
|
0786b2eae5 | ||
|
|
ae5da324ad | ||
|
|
69302481ad | ||
|
|
03a992a46a | ||
|
|
9ce4553899 | ||
|
|
fad83fd876 | ||
|
|
8bde3b3c25 | ||
|
|
fe4faca3f0 | ||
|
|
596176c794 | ||
|
|
c91c1793a3 | ||
|
|
00cd3f3368 | ||
|
|
cff4cd35b8 | ||
|
|
5909ab642a | ||
|
|
60617d9a71 | ||
|
|
e7cd8679ad | ||
|
|
4495e2be53 | ||
|
|
833f5b64d9 | ||
|
|
866b48ac55 | ||
|
|
6e30349bbb | ||
|
|
8c812bf1d6 | ||
|
|
dec24458cf | ||
|
|
473df388f3 | ||
|
|
beedd1b30d | ||
|
|
87cab84e4a | ||
|
|
5fdd0a0e89 | ||
|
|
a7abd346e7 | ||
|
|
bdb7672c0f | ||
|
|
b5759bcd99 | ||
|
|
5b211d6dc5 | ||
|
|
6dd7c3bc3a | ||
|
|
1005c59bfc | ||
|
|
11f8881cd2 | ||
|
|
913621c1c4 | ||
|
|
8c328386fa | ||
|
|
63ee34c557 | ||
|
|
e04dd0e785 | ||
|
|
9cd34ebc80 | ||
|
|
d9ca2573a6 | ||
|
|
a114a79a69 | ||
|
|
61a626820e | ||
|
|
545673d644 | ||
|
|
973e6e12f5 | ||
|
|
94e3dda6af | ||
|
|
3031033790 | ||
|
|
95b5c71f80 | ||
|
|
6cf7159a71 | ||
|
|
65127c2727 | ||
|
|
874e5a76a0 | ||
|
|
720f8acd2c | ||
|
|
2054f8fd88 | ||
|
|
4c8508cd93 | ||
|
|
e7babf364e | ||
|
|
c9468a13cb | ||
|
|
e2d9224996 | ||
|
|
eedf9c9740 | ||
|
|
5977112a0d | ||
|
|
872b2bc99d | ||
|
|
aed0b71786 | ||
|
|
0f5e945a69 | ||
|
|
e50850d4dd | ||
|
|
166b95feba | ||
|
|
072acce71b | ||
|
|
70fc00c80f | ||
|
|
20188e4610 | ||
|
|
1b45615940 | ||
|
|
ac76375d74 | ||
|
|
f4c109a0ab | ||
|
|
715f491d29 | ||
|
|
7333a302f5 | ||
|
|
c9a5191b70 | ||
|
|
492aceb960 | ||
|
|
ff39a5c357 | ||
|
|
1595343fa0 | ||
|
|
a5d817a9ef | ||
|
|
09b822fdbe | ||
|
|
8107581df2 | ||
|
|
ca45f97ace | ||
|
|
9726d6f1cb | ||
|
|
57dfacfc07 | ||
|
|
4cb4b2d231 | ||
|
|
a14948a23d | ||
|
|
4deb654862 | ||
|
|
d7bd5bcd3c | ||
|
|
28d6260a81 | ||
|
|
a492189a84 | ||
|
|
5c4408f341 | ||
|
|
8f0000de63 | ||
|
|
9bed0156df | ||
|
|
f7de98a711 | ||
|
|
d6f20f93fd | ||
|
|
3348e93140 | ||
|
|
11f1d0aee6 | ||
|
|
b8279c4da5 | ||
|
|
2caa9db109 | ||
|
|
4dcd4749ca | ||
|
|
d4a3292834 | ||
|
|
7f4b649f6f | ||
|
|
0c8399896f | ||
|
|
69c2414615 | ||
|
|
879e688fec | ||
|
|
f5b3c5d069 | ||
|
|
f8ffab72e2 | ||
|
|
0b1c957233 | ||
|
|
999e2ae896 | ||
|
|
438dec0d61 | ||
|
|
1cea0f7e11 | ||
|
|
d04d756c4e | ||
|
|
85c7d1214b | ||
|
|
5e751c848b | ||
|
|
2707ac403f | ||
|
|
3bede06646 | ||
|
|
da607a00ee | ||
|
|
4a251d4b9c | ||
|
|
4362e6624d | ||
|
|
c92d120098 | ||
|
|
86ad3ddb63 | ||
|
|
fc08b0e4f6 | ||
|
|
455e1f419f | ||
|
|
56d0a162b3 | ||
|
|
3a2cea6ca4 | ||
|
|
5a82eafa5a | ||
|
|
1880f6162c | ||
|
|
61ad110e9f | ||
|
|
fa755e9de4 | ||
|
|
d2321d05d9 | ||
|
|
7c95f02050 | ||
|
|
2db55b5498 | ||
|
|
341f370368 | ||
|
|
09f14d5a5e | ||
|
|
088156d4ca | ||
|
|
e1b39cd41d | ||
|
|
d32119c377 | ||
|
|
6b3de1c4dc | ||
|
|
5e2b63b710 | ||
|
|
a3aab66bfa | ||
|
|
8fcaa66e19 | ||
|
|
559f16601d | ||
|
|
0254f3afc7 | ||
|
|
da8b7b7feb | ||
|
|
3787af0a67 | ||
|
|
c9f3da2fc5 | ||
|
|
82bf806118 | ||
|
|
6b192f58ce | ||
|
|
eff1444f08 | ||
|
|
228a3eae3e | ||
|
|
db9d9d488a | ||
|
|
af90833305 | ||
|
|
31cb2c8714 | ||
|
|
bcdad07d00 | ||
|
|
0c4558cd08 | ||
|
|
6d83d13257 | ||
|
|
c5a9c954f7 | ||
|
|
1f0aeb4626 | ||
|
|
211d6c0c06 | ||
|
|
9acc34f22c | ||
|
|
c2b97f1180 | ||
|
|
47c2eda22c | ||
|
|
8701f4e28d | ||
|
|
6fefeb72e6 | ||
|
|
6311f9d411 | ||
|
|
963df12a11 | ||
|
|
e7f5d32c35 | ||
|
|
8cdd85f7e7 | ||
|
|
1d37043128 | ||
|
|
35cbdb8002 | ||
|
|
498d9aaa9b | ||
|
|
72cea2daf4 | ||
|
|
ab57696ba7 | ||
|
|
a30a1866e2 | ||
|
|
04eadcb2ca | ||
|
|
f354e7fc9b | ||
|
|
1c8c352cf5 | ||
|
|
7fc2bbf248 | ||
|
|
540692515b | ||
|
|
986d7e2a5a | ||
|
|
cdb13144b3 | ||
|
|
8812fe068d | ||
|
|
7bd3eb8ca7 | ||
|
|
357deba3c2 | ||
|
|
ecd94e0f8a | ||
|
|
1cc3d190a7 | ||
|
|
35fb78f0cc | ||
|
|
a93932d491 | ||
|
|
6670b9c867 | ||
|
|
d8b11c69d3 | ||
|
|
7f94643154 | ||
|
|
edee285c36 | ||
|
|
2e062168f0 | ||
|
|
8fb4d44d2c | ||
|
|
abb36aceb2 | ||
|
|
da11d6634b | ||
|
|
ce38b0c372 | ||
|
|
81098c52f6 | ||
|
|
a3fcb9ed47 | ||
|
|
ff61b32177 | ||
|
|
da84f48040 | ||
|
|
795cad3326 | ||
|
|
ba8dc7bf1c | ||
|
|
f6115ea7fa | ||
|
|
ace1adc624 | ||
|
|
4d8204c2f2 | ||
|
|
5b322e1530 | ||
|
|
70c5c44f01 | ||
|
|
33f00e8dfe | ||
|
|
4950690479 | ||
|
|
4442390213 | ||
|
|
bd0521d476 | ||
|
|
55bef52d38 | ||
|
|
df9c29f673 | ||
|
|
03e713b72f | ||
|
|
b2b8ad8f52 | ||
|
|
fc15682fb0 | ||
|
|
aa665b16a9 | ||
|
|
8c1a39ba95 | ||
|
|
16622f0853 | ||
|
|
75122c1178 | ||
|
|
ad820dce6c | ||
|
|
3507a34430 | ||
|
|
db0affc0d3 | ||
|
|
74c1f26c4e | ||
|
|
72453d9def | ||
|
|
76f5d4b817 |
@@ -0,0 +1,6 @@
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
reviews:
|
||||
auto_review:
|
||||
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
|
||||
ignore_usernames:
|
||||
- "dependabot[bot]"
|
||||
@@ -0,0 +1,30 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Maintain Rust / Cargo dependencies
|
||||
- package-ecosystem: "cargo"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
# Consolidate updates into a single PR rather than one PR per crate
|
||||
groups:
|
||||
cargo-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: "chore(deps)"
|
||||
|
||||
# Maintain GitHub Actions workflows
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
groups:
|
||||
actions:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: "ci(deps)"
|
||||
@@ -0,0 +1,62 @@
|
||||
# The CLAUDE.md quality gate (`cargo xtask ci`: fmt, clippy -D warnings, tests, assets, layers,
|
||||
# wasm) on every pull request and every push to main, so a merge burst can't land a red tree that
|
||||
# only the next contributor's local run discovers.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# Same craft-fonts commit as release.yml and freebsd.yml, so layout tests see the fonts a
|
||||
# release build embeds (the checkout is an optional build input, see crates/fonts/build.rs).
|
||||
CRAFT_FONTS_REF: 8dcdacd5153e64560d109541a47d806f26f048c0
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
name: cargo xtask ci
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: "0"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: ${{ env.CRAFT_FONTS_REF }}
|
||||
path: craft-fonts
|
||||
|
||||
- name: Install Linux build dependencies (winit, wgpu, rfd)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev \
|
||||
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
|
||||
- name: Install Rust (stable + clippy, rustfmt, wasm32)
|
||||
run: |
|
||||
rustup toolchain install stable --profile minimal --component clippy,rustfmt \
|
||||
--target wasm32-unknown-unknown
|
||||
rustup default stable
|
||||
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: Quality gate
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
run: cargo xtask ci
|
||||
@@ -18,16 +18,6 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
eval:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1
|
||||
- name: nix flake check --no-build
|
||||
run: |
|
||||
if [ -f flake.nix ]; then
|
||||
nix flake check --no-build --all-systems
|
||||
else
|
||||
echo "No flake.nix present in this repository; skipping check."
|
||||
fi
|
||||
nix:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
secrets: inherit
|
||||
+1
-1
@@ -67,7 +67,7 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| craft-fonts (optional build input, not files in this repo): BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic | see https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | embedded only when built with `CRAFT_FONTS_DIR` (all official releases) | OFL-1.1 | Japanese and Chinese UI, Japanese document fallback |
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk with Codex | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Ukrainian interface catalog; spelling checked with external VESUM and ULIF dictionaries, neither bundled |
|
||||
| `crates/ui-egui/src/i18n/et.tsv` | @henno with Codex | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Estonian interface catalog |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | Konrad Witkowski with Claude (AI agent) | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Polish interface catalog; not yet reviewed by a second native speaker |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | Konrad Witkowski with Claude (AI agent); Aleksander Kutycki (@olekkut) with Gemini 3.8 Flash | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Polish interface catalog; not yet reviewed by a second native speaker |
|
||||
| `crates/ui-egui/src/i18n/pt-br.tsv` | @edurbs with ZCode | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Brazilian Portuguese interface catalog; spelling checked with the external pt_BR Hunspell dictionary, not bundled |
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | @DanielKnourek with Antigravity for VS Code | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | Czech interface catalog; review suggestions by @Losminek |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | @arekown with Kimi | Original translation from the English interface labels in this repository; no other product localisation copied | MIT OR Apache-2.0 | German interface catalog |
|
||||
|
||||
Generated
+23
-20
@@ -5131,7 +5131,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"clipboard-win",
|
||||
@@ -5144,6 +5144,7 @@ dependencies = [
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"open",
|
||||
"pollster 0.4.0",
|
||||
"rfd",
|
||||
@@ -5163,7 +5164,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-cli"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
@@ -5176,11 +5177,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-control-key"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-doc"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -5192,7 +5193,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-docbin"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"image",
|
||||
@@ -5208,7 +5209,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-docx"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64",
|
||||
@@ -5222,6 +5223,7 @@ dependencies = [
|
||||
"sha1",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-geom",
|
||||
"zeroize",
|
||||
@@ -5230,7 +5232,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-engine"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"encoding_rs",
|
||||
@@ -5259,7 +5261,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-fonts"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
@@ -5272,7 +5274,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-formats"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"chardetng",
|
||||
@@ -5289,14 +5291,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-geom"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-layout"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"js-sys",
|
||||
@@ -5315,7 +5317,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-mcp"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde_json",
|
||||
@@ -5327,7 +5329,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-metafile"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5335,7 +5337,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-pdf"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"hayro-cmap",
|
||||
@@ -5355,7 +5357,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-proof"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.8.9",
|
||||
@@ -5364,7 +5366,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-render"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -5378,8 +5380,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-ui-egui"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
@@ -5404,7 +5407,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-web"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5423,7 +5426,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-zotero"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -5536,7 +5539,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/wordcraft", "apps/wordcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -10,11 +10,11 @@
|
||||
<h1 align="center">WordCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
<b>Writing and document design; an open-source, clean-room reimplementation of Microsoft Word, rebuilt in pure Rust.</b>
|
||||
<b>Writing and document design; an open-source, modern word processor, built in pure Rust.</b>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
A fast, open-source word processor with the Word workflow you already know: the ribbon, styles,
|
||||
A fast, open-source word processor with a familiar workflow: the ribbon, styles,
|
||||
tables, track changes, references and mail merge. It reads and writes .docx, runs natively on
|
||||
macOS, Windows, Linux and BSD, and in the browser via WebAssembly.<br>
|
||||
<i>By the ArtCraft team.</i>
|
||||
@@ -25,6 +25,9 @@
|
||||
<img alt="Runs on macOS, Windows, Linux, BSD and the web" src="https://img.shields.io/badge/runs%20on-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20BSD%20%C2%B7%20Web-3b5bdb?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-2b47b5?style=flat-square">
|
||||
<img alt="Agent-drivable over MCP" src="https://img.shields.io/badge/agents-MCP%20%C2%B7%20CLI-3b5bdb?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_wordcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/wordcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -86,10 +89,10 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
|
||||
|
||||
## Why WordCraft
|
||||
|
||||
- **Familiar.** Word's ribbon tabs, groups, shortcuts and behaviour: Enter continues a list,
|
||||
- **Familiar.** Ribbon tabs, groups, shortcuts and behaviour: Enter continues a list,
|
||||
Tab demotes it, Ctrl/⌘+B bolds the word under the caret, the Styles gallery previews styles live,
|
||||
F4 repeats, F7 checks spelling, F8 extends the selection.
|
||||
- **Your files.** Opens and saves .docx (OOXML), and also .odt, .rtf, .html, .md, .tex (LaTeX), .txt; opens Word 97-2003 .doc; exports PDF
|
||||
- **Your files.** Opens and saves .docx (OOXML), and also .odt, .rtf, .html, .md, .tex (LaTeX), .txt; opens legacy 97-2003 .doc; exports PDF
|
||||
with real, selectable text, links and bookmarks.
|
||||
- **Fast.** Paragraph layout is cached, so typing in a 188-page document re-lays it out in about
|
||||
1.4 ms; pages render on demand.
|
||||
@@ -118,7 +121,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
|
||||
| **Review** | Spelling and grammar with suggestions (English and Polish, by each run's language), thesaurus, word count, comments in margin balloons or a pane, track changes, accept/reject, compare documents, restrict editing, accessibility checker, document inspector |
|
||||
| **Mailings** | Mail merge from CSV, merge fields, address block, greeting line, rules, preview, finish to a document; envelopes and labels |
|
||||
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어 or Svenska (follows the system language by default) |
|
||||
| **Files** | .docx read/write (opens in Word), Word 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
|
||||
| **Files** | .docx read/write, legacy 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
|
||||
|
||||
The honest picture, area by area, is in [ROADMAP.md](ROADMAP.md), the
|
||||
[parity assessment](docs/target-app-parity.md) and the generated
|
||||
@@ -141,6 +144,7 @@ wordcraft-cli text report.docx # plain text
|
||||
wordcraft-cli inspect report.docx # structure as JSON
|
||||
wordcraft-cli run --template sample \
|
||||
--cmd 'select.text={"text":"Membership"}' --cmd format.bold --save out.docx
|
||||
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
|
||||
```
|
||||
|
||||
Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?sample>.
|
||||
@@ -189,9 +193,9 @@ covers every target starting with it (`wordcraft*=debug`). The logger is
|
||||
| L1 | `wordcraft-doc`, `wordcraft-fonts`, `wordcraft-proof` | document model and editing; fonts and shaping; spelling, grammar, hyphenation |
|
||||
| L2 | `wordcraft-layout`, `wordcraft-docx`, `wordcraft-formats` | line breaking, pagination, tables, notes, hit testing; OOXML; ODT/RTF/HTML/Markdown/TXT |
|
||||
| L3 | `wordcraft-render`, `wordcraft-pdf` | rasteriser (vello_cpu); PDF ([craft-pdf](docs/shared-pdf.md), Krilla) |
|
||||
| L4 | `wordcraft-engine` | session, undo, 422 commands, Word feature catalog |
|
||||
| L4 | `wordcraft-engine` | session, undo, 422 commands, document feature catalog |
|
||||
| L5 | `wordcraft-mcp` | MCP server |
|
||||
| L6 | `wordcraft-ui-egui` | the Word-style front end (swappable) |
|
||||
| L6 | `wordcraft-ui-egui` | the word processor front end (swappable) |
|
||||
| apps | `wordcraft`, `wordcraft-cli`, `wordcraft-web` | desktop, command line, browser |
|
||||
|
||||
`cargo xtask ci` runs formatting, clippy, ~800 tests, the asset-attribution check, the layering
|
||||
@@ -199,12 +203,13 @@ check and the wasm build. Contributor and agent instructions: [AGENTS.md](AGENTS
|
||||
|
||||
## Roadmap
|
||||
|
||||
WordCraft is in **alpha**. It covers 88% of Word's ribbon features with commands today; counting
|
||||
depth, file fidelity, stability and the rest, we estimate it is about 60% of the way to replacing
|
||||
all of Word for real work, about 55% for a typical professional's weekly work and about 63% for
|
||||
everyday essentials. Beta needs testing against real-world .docx files, keeping charts and SmartArt
|
||||
through a round trip, pagination closer to Word's, a stability sweep and native printing. Details
|
||||
and estimates: [ROADMAP.md](ROADMAP.md) and [where we fall short](docs/gaps.md).
|
||||
WordCraft is in **alpha**. It has commands for 97% of the ribbon and menu features in its feature catalog
|
||||
([`docs/parity-checklist.md`](docs/parity-checklist.md)) today; counting
|
||||
depth, file fidelity, stability and the rest, we estimate it is about 60% ready for real work,
|
||||
about 55% for a typical professional's weekly work and about 63% for everyday essentials. Beta
|
||||
needs testing against real-world .docx files, keeping charts and SmartArt through a round trip,
|
||||
closer pagination fidelity, a stability sweep and native printing. Details and estimates:
|
||||
[ROADMAP.md](ROADMAP.md) and [where we fall short](docs/gaps.md).
|
||||
|
||||
## Downloads
|
||||
|
||||
@@ -247,9 +252,10 @@ WordCraft compiles DirectX 12 shaders with FXC, the compiler built into Windows,
|
||||
also avoids DirectX 12 altogether.
|
||||
|
||||
**If the app is slow on an older Windows PC:** when DirectX 12 finds no graphics card with a
|
||||
driver for it (for example Intel 4th-generation graphics on Windows 11), it only offers Microsoft's
|
||||
software renderer, which draws every frame on the processor. In that case WordCraft uses OpenGL
|
||||
instead, without setting anything. The log file records the choice (lines starting with
|
||||
driver for it (for example Intel 4th-generation graphics on Windows 11), it only offers the built-in
|
||||
software renderer, which draws every frame on the processor. WordCraft normally uses OpenGL instead,
|
||||
without setting anything. If OpenGL has no usable adapter, it can use DirectX 12's WARP software
|
||||
adapter. The log file records the choice (lines starting with
|
||||
`graphics:`). `WGPU_BACKEND` still overrides it, e.g. `$env:WGPU_BACKEND = "gl"` or `"dx12"`.
|
||||
|
||||
### macOS
|
||||
@@ -366,7 +372,9 @@ Bundled fonts, icons, images and other assets keep their own open licenses; each
|
||||
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
The English spelling dictionary and hyphenation come from Grady Ward's public-domain Moby
|
||||
Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled) and
|
||||
Hyphenator II word list. Polish spelling reads the Hunspell `pl_PL` dictionary installed on the system (not bundled), as
|
||||
do Russian, Portuguese, Czech, Italian, Croatian and Turkish spelling (how to install them:
|
||||
[docs/spelling-dictionaries.md](docs/spelling-dictionaries.md)), and
|
||||
Polish hyphenation the TeX patterns by Hanna Kołodziejska, Bogusław Jackowski and Marek Ryćko (MIT
|
||||
option). The sample documents and templates are original text written for WordCraft.
|
||||
|
||||
@@ -375,8 +383,6 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif
|
||||
part of this repository and WordCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
Forks and modified versions must remove them.
|
||||
|
||||
<sub>Microsoft and Microsoft Word are trademarks of the Microsoft group of companies. Adobe, Photoshop, Illustrator, Premiere Pro, Lightroom, Acrobat, After Effects and InDesign are trademarks or registered trademarks of Adobe Inc. in the United States and/or other countries. WordCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Microsoft Corporation or Adobe Inc.; these names are used only to describe the workflows it is compatible with.</sub>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
|
||||
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
|
||||
|
||||
+190
-6
@@ -2,8 +2,8 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** trivial (Language dialog keeps inherited proofing language and no-proof choices (#2717)); previously trivial (table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** trivial (progress log: print-area strings translated in every catalog; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** trivial (progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** trivial (long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
|
||||
> **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below.
|
||||
|
||||
WordCraft aims for complete parity with Microsoft Word, then goes further on speed, openness and
|
||||
@@ -15,7 +15,7 @@ agent control. This page is the summary; the assessment is
|
||||
## Headline numbers (2026-10-10)
|
||||
|
||||
| Number | Value | Kind |
|
||||
| 2026-10-12 | Table formulas: cell references and ranges (`=B2+B3`, `=SUM(B2:C3)`), arithmetic and comparisons, IF, AND, OR, NOT, TRUE, FALSE, DEFINED and the `\#` number format; ABOVE and LEFT sum the run of numbers next to the cell as Word does; an unknown function or a syntax error is an error instead of a sum; Update Field (F9) recalculates formula fields |
|
||||
| --- | --- | --- |
|
||||
| Ribbon/menu catalog coverage | **487 / 502 (97.0%)** | measured (`cargo xtask parity` → [`docs/parity-checklist.md`](docs/parity-checklist.md)) |
|
||||
| **Feature breadth** (weighted, incl. dialog options, styles, languages beyond the ribbon) | **~80%** | estimated |
|
||||
| **Ready for real work** (full target) | **~60%** (55–63%) | estimated, additive weighted sum over the dimensions |
|
||||
@@ -104,7 +104,7 @@ Weights and evidence per area: [docs/target-app-parity.md](docs/target-app-parit
|
||||
| Spanish | es | partial | ~95% |
|
||||
| Hindi | hi | none | 0% |
|
||||
| Arabic | ar | none (document shaping and bidi work; no mirrored UI) | 0% |
|
||||
| French | fr | partial (interface) | ~95% |
|
||||
| French | fr | partial (interface complete, native-speaker reviewed; no proofing) | 100% (2,615 entries) |
|
||||
| Portuguese | pt-br (pt-PT none) | partial | ~95% |
|
||||
| Indonesian | id | none | 0% |
|
||||
| Japanese | ja | partial | ~95% |
|
||||
@@ -116,7 +116,7 @@ Also shipped: Traditional Chinese (`zh-hant`), Ukrainian (`uk`), Serbian (`sr`,
|
||||
system-locale selection and a saved language choice (Italian also has 51 strings none of the others had yet); Estonian, Turkish and Italian proofing are not included. Hungarian (`hu`) has a
|
||||
complete 2,419-entry catalog, also without proofing. Vietnamese (`vi`, #1434) has a complete
|
||||
2,448-entry catalog, also without proofing.
|
||||
Proofing: English, Polish, Portuguese and Russian (spelling, grammar, hyphenation), plus Czech (system Hunspell spelling, generic checks), chosen per run from its language. Word ships
|
||||
Proofing: English, Polish, Portuguese and Russian (spelling, grammar, hyphenation), plus Czech and Indonesian (system Hunspell spelling, generic checks), chosen per run from its language. Word ships
|
||||
30 interface languages and proofing for ~50. Detail: [docs/localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
@@ -134,20 +134,115 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
## Progress log
|
||||
|
||||
Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target on interactive Save (#2445). Save before Close waits for that write; cancel or failure keeps the draft and original file. This does not add binary Word output. Late Save As answers are rejected before writing if automation has replaced the document.
|
||||
|
||||
- 2026-10-19: Restrict Editing: with Filling in forms enforced, inserting content controls, their Properties and Remove Content Control are refused, as in Word (it greys them out), so a form's fields stay as they are and only their content is filled in.
|
||||
- 2026-10-19: Content controls: text typed over a placeholder takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 §17.5.2.27), as in Word, and the placeholder style is recognised by its built-in name "Placeholder Text" whatever its localized id (German Word: `Platzhaltertext`), so entries in forms from localized Word no longer stay grey.
|
||||
- 2026-10-15: Find opens Navigation on Results; editing the query restores Results after manual Headings/Pages navigation. Typed and selected-text searches retain document contents (#2096).
|
||||
|
||||
| Date | What landed |
|
||||
| 2026-10-19 | Save As, Export and Open no longer do nothing on Linux desktops whose file chooser portal fails to show its dialog (#2999): a "cancel" quicker than anyone could make one asks again without the parent window, then opens the built-in file browser. |
|
||||
| 2026-10-18 | Long navigation headings wrap onto further lines inside the resizable pane instead of ending in an ellipsis: the row grows with the text and the pane keeps its width (#759, #3015). |
|
||||
| 2026-10-18 | Clearing a font query with no matches keeps Recently Used Fonts visible at the top of a scrollable list. The initial scroll position no longer skips its heading; measured keyboard scrolling is unchanged (#2068). |
|
||||
| 2026-10-17 | Edit Recipient List finds records (#1576): a Find in list box hides rows with no cell containing the text (any case) and counts the matches, and "Show only records that will be merged" hides the rows the filter leaves out; both only change the view. Rows are striped, and edits and removes go to the right record however the grid is narrowed |
|
||||
| 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. |
|
||||
| 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture |
|
||||
| 2026-10-12 | Fields keep `w:dirty` through DOCX saves (#877): a begin marker flagged by a generator that couldn't compute a result (pandoc-style TOC placeholders) keeps the flag on open/save — as a buffered field or a range field — so Word still refreshes it on open; computing a result (Update Field, Update Table) clears it, like Word's F9 |
|
||||
| 2026-10-18 | Symbols keep their font (#2036): a `w:sym` or Insert › Symbol character in Wingdings, Symbol or Webdings remembers its symbol font apart from the text's font, so selecting all and changing the font (or Clear Formatting) no longer turns the symbols into boxes; saved back to DOCX as `w:sym`, so Word shows them too. Typed text and the Format Painter don't pick up the symbol font. |
|
||||
| 2026-10-16 | `wordcraft-cli run --script FILE.json` (`-` for stdin) runs a JSON list of commands, then saves to one or more outputs (docx and pdf in one run); errors name the command number and id and nothing is saved, #1963 |
|
||||
| 2026-10-17 | Restrict Editing holds for structure too (#1327): an exception inside a table cell no longer lets table, row or cell formatting change the protected rest of the table; formatting limited to styles refuses Paste Formatting, table shading, borders, cell alignment, cell margins, text direction, table-style edits and locked table styles; loading, filtering or sorting recipients no longer rewrites merge-field results in a protected document. |
|
||||
| 2026-10-18 | Manage Sources › Import… (#2640) reads a Word bibliography file (`b:Sources`: Word's own `Sources.xml` master list) into the document: the tags, names, kinds and fields Word saves are read by the same code that reads the bibliography custom XML part of a `.docx`, a tag already in the document is left alone (an import never overwrites an edited source), an untagged source gets a tag the way a new one does, the whole import is one undo step, and a file that isn't `b:Sources` is refused. |
|
||||
| 2026-10-14 | RTF export writes every section (gap 19): `\sect` ends each section and `\sectd` carries its break type, page size and orientation, margins, columns, page numbering and title page, so multi-section documents survive an RTF round trip |
|
||||
| 2026-10-14 | `ASK` and `SET` fields no longer show their stored result on the page or in PDFs (#1765): like Word, they only assign text to a bookmark and draw nothing; the stored result is kept and saved |
|
||||
| 2026-10-15 | Table rows with an at-least height start the next page whole when less than their minimum is left on a page that already holds something, so one-row-per-page booklets keep their pages; rows taller than a page split from the top of the next page and repeated header rows go with the row (#1742) |
|
||||
| 2026-10-16 | Strict OOXML line heights render as Word renders them (#2329): `w:line="13.90pt"` under `lineRule="auto"` is a height read through twips (13.90 × 20 = 278; the 1.1583 multiple Word shows), not the 13.9 multiple the bare transitional number counts, so a Word 2024 file with 13.9 lines of line spacing opens at Word's 1 page with matching baselines instead of 10 |
|
||||
| 2026-10-15 | RTF keeps more tracked changes (gap 19): tracked paragraph marks (a `\par` inside a `\revised`/`\deleted` group) and character and paragraph formatting changes (`\crauth`/`\crdate` with `\oldcprops`, `\prauth`/`\prdate` with `\oldpprops`) are read and written, so their balloons and Accept/Reject survive an RTF round trip |
|
||||
| 2026-10-14 | ODT export writes sections (gap 19): every new-page section gets its own page layout and master page (the first stays "Standard"), named by its first paragraph or table with the page-numbering restart; a continuous section with columns is written as a columned `text:section`, so a landscape, two-column or restarted part survives a save as .odt |
|
||||
| 2026-10-14 | A bulleted or numbered list item that starts with a lower-case word no longer gets the grammar squiggle for a missing sentence capital (#1741): list items are often fragments, so the sentence-capital rule (every proofed language) skips the first word of a list paragraph (own or style numbering); later sentences in the item are still checked |
|
||||
| 2026-10-15 | The caret, clicks and selection edges fall between the letters of a ligature (fi, ffi, lam-alef), as in Word: the glyph's advance is shared evenly among its letters, mirrored in right-to-left text (#1974) |
|
||||
| 2026-10-16 | The Spike, as in Word: Ctrl+F3 (⌘F3 on macOS) cuts the selection and adds it to the end of the Spike, each piece followed by a paragraph mark; Ctrl+Shift+F3 (⌘⇧F3) inserts everything collected, in order and with its formatting, and empties the Spike. The clipboard is left alone; each is one undo step. The Spike is the AutoText entry "Spike", so Insert › Quick Parts inserts it without emptying it. It lasts for the session (Word keeps it in Normal.dotm) |
|
||||
| 2026-10-16 | Update Field is offered on a table of contents after a save and reopen, and repeated save and update adds no blank line (#2182; the flow in that report already worked since #1197) |
|
||||
| 2026-10-16 | DOCX two lines in one and horizontal in vertical (`w:eastAsianLayout`: id, combine, brackets, vert, vertCompress) are read and kept on save, in runs and character styles, instead of being dropped. Layout doesn't apply them yet. |
|
||||
| 2026-10-16 | Read Aloud speaks Russian, Ukrainian, Greek, Arabic, Hebrew, CJK and Thai text with a voice for its language instead of spelling out letters (#1843): the sentence's language comes from its run's tag (`w:bidi` for right-to-left text) or, when that disagrees with the script, from its letters, even when English letters outnumber them; Windows reads the text as UTF-8 and picks an installed voice of that language, macOS `say -v` and Linux `espeak -v` get the same language. The user's own voice stays whenever it already speaks the language (English documents read exactly as before), and a voice espeak lacks falls back to the default voice instead of silence. Not run on Windows or macOS here. |
|
||||
| 2026-10-16 | Hint-reliant CJK fonts execute TrueType contour assembly; Windows DFKai-SB no longer loses strokes. Synthetic local-font regression; no font binaries bundled. |
|
||||
| 2026-10-16 | Ctrl/⌘+wheel only zooms: a coast or wheel notch still gliding no longer scrolls the page on top of the zoom, which keeps the page point under the pointer (#1743). |
|
||||
| 2026-10-15 | AutoCorrect follows Turkish and Azerbaijani case mapping: `istanbul` → `İstanbul`, `ılık` → `Ilık`, `İNgilizce` → `İngilizce` with no combining dot (#1923) |
|
||||
| 2026-10-16 | Releasing a table drag with the mouse (column or row border, move handle, selection areas) leaves the view where it is instead of scrolling back to the caret (#1738) |
|
||||
| 2026-10-16 | Hebrew in fields and quotes (#1670): a STYLEREF (or any field) showing right-to-left text such as "פרק א" reads right to left in headers and the body instead of reversed; smart quotes in Hebrew pinned to Word's logical-order result (“ before, ” after, ” in acronyms like צה"ל) |
|
||||
| 2026-10-15 | Backspace with a whole table selected removes it, as in Word, and selected whole rows or columns go the same way; Delete clears them and keeps the table. A selection that covers a table and the paragraph before or after it removes the table, also when it starts inside the table or the table is nested (#1844) |
|
||||
| 2026-10-15 | Image size limits are checked before allocating (#1321): a picture whose header declares more RGBA bytes than the 512 MiB budget is refused before decoding (render and PDF share one helper in `wordcraft-geom`), and page rasters are capped at 100 million pixels in total, scaled down rather than only per side. |
|
||||
| 2026-10-15 | Saved DOCX files keep the order of mixed right-to-left and left-to-right text in Word: Hebrew around a Latin name, numbers, brackets or an e-mail address no longer changes places, and Word reports the Hebrew as Hebrew rather than Arabic (#1543). |
|
||||
| 2026-10-15 | Web: typing in Cyrillic or another non-Latin script no longer repeats text. WordCraft now honours the input method's request to erase around the caret before retyping (#1480). Chrome can still move the hidden text field's caret, so later letters may still land out of order. That cause is still open |
|
||||
| 2026-10-15 | Equations: typing `V_dd` or `x^ab` and pressing Space keeps `dd` and `ab` whole in the subscript or superscript, like `V_(dd)`, as Word for Mac does; Linear format shows the bare form |
|
||||
| 2026-10-15 | Plain text pasted from another program keeps the formatting of the paragraph it lands in: Paste inserts it as Keep Text Only does, so every pasted line, empty lines too, becomes a paragraph with that paragraph's direction, style, alignment, indents and list, and the text after the caret keeps them. The lines after the first had default formatting, so pasting several lines into a right-to-left paragraph turned all but the first left-to-right |
|
||||
| 2026-10-14 | Add Font… imports every file selected in the file chooser (#1789), not just the first: the desktop dialog and the web picker are multi-select, each file is added, a bad file is reported ("Added 11 fonts; 1 couldn't be read: X.ttf") without stopping the rest, and one pick adds at most 2,000 (the status line counts the skipped). On the web each font is added and reported on its own, with no single summary line. The built-in file browser still picks one file. |
|
||||
| 2026-10-15 | Additive paragraph spacing retains the full before-space after a section page break; ordinary overlapping spacing is unchanged. |
|
||||
| 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. |
|
||||
| 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture |
|
||||
| 2026-10-12 | Fields keep `w:dirty` through DOCX saves (#877): a begin marker flagged by a generator that couldn't compute a result (pandoc-style TOC placeholders) keeps the flag on open/save — as a buffered field or a range field — so Word still refreshes it on open; computing a result (Update Field, Update Table) clears it, like Word's F9 |
|
||||
| 2026-10-15 | Exact line spacing keeps the run font baseline around tall equations; automatic and minimum spacing still grow for math. |
|
||||
| 2026-10-16 | Zero-extent drawing anchors contribute no inline font height. |
|
||||
| 2026-10-16 | Control-channel keyboard and text input reaches the focused widget while the native window is inactive, without activating it; normal widget targets, dialogs and document protection remain in force (#2420) |
|
||||
| 2026-10-15 | Hide Quick Access Toolbar (#1945): the toolbar's menu ends with Hide Quick Access Toolbar, as Word's does; the ribbon's right-click menu and Customize Ribbon › Quick Access Toolbar offer Show Quick Access Toolbar; kept between runs; `ui.quickAccessToolbar {"value"?}` for scripts and MCP |
|
||||
| 2026-10-15 | Rulers: the numbers thin out as the page shrinks on screen (every 1, 2, 4… units, at least 30 px apart, the small ticks at least 4 px apart), give way to the indent, tab and column markers, and the margins get ticks only; both rulers span the caret's page at its own scale in One Page and Multiple Pages and follow the caret to another page (#1878) |
|
||||
| 2026-10-15 | Spelling as you type no longer flags the word being typed; the squiggle comes when the word ends or the caret leaves it, as in Word (#1552) |
|
||||
| 2026-10-15 | Text Highlight Color: No Color becomes the Highlight button's choice, as in Word, so the next click on the button removes highlighting instead of applying the colour picked before; the ribbon and the mini toolbar share one menu (#2105) |
|
||||
| 2026-10-16 | Footnote and endnote editing keeps the body and active note text at normal opacity (#2545), without changing document colours or print/PDF output. |
|
||||
| 2026-10-16 | A picture watermark in a header that starts with a table is drawn centred on the page behind the body text, on every page, instead of in the header's cell at the top of the page (#1775); `layoutInCell="0"` and VML `o:allowincell="f"` survive save and reopen |
|
||||
| 2026-10-17 | Ribbon hover hints: a disabled control says why (the command's own reason), split-button arrows, menu buttons and the font, size and outline boxes have hints, and hints show on keyboard focus (#1086). |
|
||||
| 2026-10-17 | Insert › Drop Cap is a menu (None, Dropped, In margin, Drop Cap Options…); the dialog sets position, font, lines to drop and distance; letters in the margin; DOCX keeps them (#2601). |
|
||||
| 2026-10-16 | An otherwise empty section starting a new page retains its paragraph line before a continuous section, matching an original native Word control. |
|
||||
| 2026-10-16 | Equations from Word files keep all their content (#1273): math straight in the body or a table cell, math behind `mc:AlternateContent Requires="m"`, runs inside hyperlinks, simple fields and markup-compatibility blocks within an equation, and `w:sym`/Symbol-font characters in math; operators, delimiters and accents the math font lacks come from a fallback font. Every ECMA-376 §22.1 element is pinned by a coverage test. |
|
||||
| 2026-10-16 | Captions and title pages (#1230): Insert Caption… on the right-click menu of pictures, shapes, text boxes and charts, the caption going under (or over) the object in its own cell or text box; Page Setup's Different First Page and Different Odd & Even Pages check boxes, so a title page can go without its page number |
|
||||
| 2026-10-17 | SECTIONPAGES includes shared continuous-section pages. A native original control confirms a section starting on page 1 and continuing on page 2 reports 2. |
|
||||
| 2026-10-17 | File › Print's Scale to paper size (#2108): pick Letter, Legal, A4 or any Layout › Size paper and every page is scaled to it and centred, the paper turned to each page's orientation, in the preview, the print job (with the spooler's media) and Save these pages as PDF; the document keeps its page size. `paper` param on `ui.print`/`file.printPdf` |
|
||||
| 2026-10-17 | Non-overlapping body floating tables clear header tables. Original native controls distinguish never-overlap from allowed overlap. |
|
||||
| 2026-10-14 | Comment text being typed is no longer lost or misplaced (#1348): an edit or reply the document refuses (for example read-only protection) keeps the typed text in its field and says why on the status line; drafts belong to their document, so after New or Open a comment with the same number shows its own text; Save, Export, Print, Close, New and Open write pending comment text first; if the document refuses it, Save, Export and Print carry on with the stored comments and show why on the status line (a refused draft is dropped when Save is the only change), while Close, New and Open show the Save Changes prompt (Don't Save drops text the document refuses); Escape discards what was typed; in a document protected as read only or for forms the comment fields can't be typed in |
|
||||
|---|---|
|
||||
| 2026-10-18 | Picture Format › Size (#2573): width and height in the interface unit, and a size typed in any unit works, pixels too (`300 px` keeps the picture's proportions, #1901), applied once typed (Enter, Tab or a click elsewhere; Esc cancels) in one undo step. The group's launcher opens a Size dialog: height and width, scale of the original size (or of the size it opened with), Lock aspect ratio, the original size with its pixels, and Reset. `picture.size {"original": true, "scale"?}` sizes from the original; sizes past 4000 pt that keep the proportions shrink as a whole. |
|
||||
| 2026-10-16 | Save Changes gives assistive technology a named alert dialog with the loss warning and any save failure; visual layout and save policy unchanged (#1015). Native screen-reader verification remains pending. |
|
||||
| 2026-10-15 | The font family caches are bounded (4096 families for text, 1024 for math, names over 256 bytes aren't remembered), so a document naming thousands of missing fonts can't grow memory; equation fonts are looked up again after a font is added or removed instead of keeping the old choice (#1354) |
|
||||
| 2026-10-15 | AutoCorrect recognizes `-->` as `→` (#2223), respecting replacement settings and undo without changing paragraph-start arrow bullets. |
|
||||
| 2026-10-15 | Numbered headings (#1793): the Multilevel List gallery offers four lists linked to Heading 1–9 (1 / 1.1 / 1.1.1, Article I. / Section 1.01 / (a), I. / A. / 1., Chapter 1; `list.multilevelPreset`). The heading styles carry the numbers, so paragraphs already in a Heading style keep their style and level, any other selected paragraph (Normal, Quote, Title) becomes Heading 1 (checked in Word), a new Heading 2 is numbered 2.1 by itself and body text stays unnumbered; Numbering or typing `1. ` keeps a heading a heading |
|
||||
| 2026-10-15 | Reversing an automatic sentence capital (Undo, or Backspace and retype) adds the word before it to AutoCorrect's First Letter exceptions, as Word does; "Automatically add words to list" switches for First Letter and INitial CAps (#1857). |
|
||||
| 2026-10-15 | Dialog close control: a Windows-style box at the title bar's right end, the whole box clickable, red on hover, in both themes (#1885) |
|
||||
| 2026-10-15 | Font box: a Recently Used Fonts section at the top of the list (the fonts applied lately, most recent first, ten at most, kept between runs), then All Fonts, as in Word (#2068) |
|
||||
| 2026-10-15 | A missing Thai document font (TH Sarabun New, Angsana New, Cordia New, the UPC families…) is substituted by one Thai face for the whole run, Latin letters and digits included, as Word substitutes Cordia New; Thai no longer sits in one font next to larger Latin in another (#1549) |
|
||||
|---|---|
|
||||
| 2026-10-17 | Paste from LibreOffice: a paragraph indented on both sides (HTML `<blockquote>` on the clipboard) pastes as an indented Normal paragraph with LibreOffice's margins, not centred and italic in the Quote style (#1270). |
|
||||
| 2026-10-17 | DrawingML shape outlines retain explicit preset/custom dashes on screen and in PDF, including zero-width path strokes. |
|
||||
| 2026-10-17 | Missing Arial Unicode MS tries Arial and its proportional substitutes before code-font heuristics. |
|
||||
| 2026-10-16 | Web Layout text fills the window width and re-wraps once a resize settles, or at once on a zoom, instead of a fixed 800 pt column; Draft and Outline keep their 800 pt column (#1876). |
|
||||
| 2026-10-16 | Create Source: the automatic Tag is three letters of the first author and the last two digits of the year (`Smi20`), with 1, 2… added when taken, as Word for Mac 16.113.4 does (user-checked). Editing Author or Year keeps the Tag, as in Word, and the citations in the text show the new author and year (#2094; the reporter expected the Tag to follow). |
|
||||
| 2026-10-18 | Split Cells and Convert Text to Table dialogs (#2592), matched to Word: Split Cells starts from the selection (twice its columns, its rows; Merge cells before split offered for several cells or one cell merged across columns); `table.split` gains `rows` and `mergeFirst`, a merged cell splits into 1 to its height rows (its height cuts it into rows, 1 × 1 changes nothing, a number that doesn't divide the height or more than it is refused with Word's messages) and column splits make equal parts without moving other rows' grid lines. Convert Text to Table guesses columns live, shows the row count, and offers Initial column width (Auto or up to 22 in, kept as each column's preferred width), AutoFit to contents/window and Paragraphs/Commas/Tabs/Other separators; `table.fromText` gains `paragraph`/`other` + `char`, `columns`, `autofit` and `width`. |
|
||||
| 2026-10-16 | Font list entries of fonts with a very tall ascent (Amiri, Amiri Quran) sit in their row like the others instead of low or cut in half (#2570) |
|
||||
| 2026-10-16 | Read Mode draws documents cleanly (#1772): the arrows, Page Up/Down and Escape work as soon as it opens (the canvas kept a stable widget id, so it no longer lost the keyboard), only whole columns show, centred, at any column width, text size or window size, and the columns end above the page-turn bar instead of under it. |
|
||||
| 2026-10-16 | Comment and revision balloons are readable in the dark theme (#2045): they were drawn on a fixed white card under light text; the card, markup area and author colours are now theme tokens with a contrast test. |
|
||||
| 2026-10-17 | DOCX glossary documents (building blocks) open into the model: Insert › Quick Parts and AutoText list and insert the document's own entries, and saving an entry with `"in": "document"` keeps it in the file (undoable). An untouched glossary is saved back byte for byte; an edited one is written from the model |
|
||||
| 2026-10-16 | Indonesian proofing (#498): id-ID spelling reads the installed Hunspell `id_ID` dictionary (`hunspell-id` on Debian/Ubuntu, LibreOffice's `dict-id`, or the Dictionaries folder), suggestions use its MAP/REP/TRY/KEY tables, generic repeated-word (offering `anak-anak`) and spacing checks explain in Indonesian; Review › Language, Set Proofing Language and File › Options › Proofing offer Indonesian. No dictionary data bundled; hyphenation keeps the English fallback; parity estimates unchanged |
|
||||
| 2026-10-17 | A table inserted in a right-to-left paragraph is a right-to-left table, like Word, so Tab moves right to left through its cells (#2634) |
|
||||
| 2026-10-16 | French interface catalog completed: 402 entries added (equation gallery, built-in style and table-style names, citation styles, paper sizes, watermarks, Bookmark / Go To / Print dialogs), 2,615 in all, with a native-speaker review of the terminology; no French proofing yet |
|
||||
| 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. |
|
||||
| 2026-10-15 | Layout › Columns with text selected puts only that text in columns, as in Word (#2024): a continuous section break goes where the selection starts and one where it ends (splitting a paragraph there; none at the document's start or end, or where a section already begins or ends), and the columns go on the section between, one undo step; More Columns… offers "Selected text" and picks it. Before, the whole section took the columns |
|
||||
| 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture |
|
||||
| 2026-10-12 | Table formulas: cell references and ranges (`=B2+B3`, `=SUM(B2:C3)`), arithmetic and comparisons, IF, AND, OR, NOT, TRUE, FALSE, DEFINED and the `\#` number format; ABOVE and LEFT sum the run of numbers next to the cell as Word does; an unknown function or a syntax error is an error instead of a sum; Update Field (F9) recalculates formula fields |
|
||||
| 2026-10-12 | Fields keep `w:dirty` through DOCX saves (#877): a begin marker flagged by a generator that couldn't compute a result (pandoc-style TOC placeholders) keeps the flag on open/save — as a buffered field or a range field — so Word still refreshes it on open; computing a result (Update Field, Update Table) clears it, like Word's F9 |
|
||||
| 2026-10-18 | Different First Page works from page 1 (#2826): Insert › Header and Edit Header with the caret on page 1, and a double-click there while another header is being edited, go into page 1's own header instead of the default one page 1 no longer shows. |
|
||||
| 2026-10-15 | Track Changes Options › Moves (gap #5): Moved from and Moved to each have a mark and a colour (by default green double strikethrough and double underline, as before and as in Word for Mac), saved per user; `review.trackingOptions` takes `moveFromMark`, `moveFromColor`, `moveToMark`, `moveToColor`, and `trackMoves`, the document's Track moves setting: off, a tracked cut and paste is an ordinary deletion and insertion. DOCX `w:doNotTrackMoves` round-trips |
|
||||
| 2026-10-17 | Language dialog keeps inherited proofing language and no-proof choices (#2717). Opening and accepting unchanged no longer replaces style-derived values with English US and proofing enabled. |
|
||||
| 2026-10-16 | Text with the legacy Outline, Shadow, Emboss or Engrave font effects (`w:outline`, `w:shadow`, `w:emboss`, `w:imprint`) is drawn with them on screen and in PDFs, no longer as plain text: hollow outlined letters, or a grey copy behind the letters; the PDF keeps the text (#2534) |
|
||||
| 2026-10-15 | Table Layout › Cell Margins opens an editable dialog initialized from the table defaults; confirming an unchanged dialog preserves imported margins, and changing one side retains the others (#1960) |
|
||||
| 2026-10-15 | Word's native ink inside groups and drawing canvases survives DOCX saves (gap 2): the ink member keeps its InkML part, relationship, content type and picture fallback, stays in its place among the members, moves with the group and is drawn from its fallback picture; deleting the group drops its part |
|
||||
| 2026-10-14 | Consistent preferred cell widths override a stale table grid when both totals agree, for fixed and AutoFit tables. Conflicting widths, spans and percentages remain unchanged. |
|
||||
| 2026-10-14 | Legacy VML freeforms (`v:shape` with its own `path`), such as the rule lines in many older headers, are read as freeform shapes: they show on screen and in PDFs and are saved back as DrawingML custom geometry instead of vanishing |
|
||||
| 2026-10-14 | Field instructions spanning paragraphs no longer add blank lines during pagination; empty result paragraphs still take a line. |
|
||||
| 2026-10-16 | Opening a DOCX no longer copies its pictures: each picture, and each embedded object or macro part kept for saving, was copied out of the unzipped package, so a document with pictures held them twice while it opened and left the package's copies behind as freed memory. The document now shares the package's bytes: a 92 MB document with 20 pictures opens in about 90 MB less (866 → 772 MB in the app on macOS; the command line's peak, 319 → 231 MB) |
|
||||
| 2026-10-14 | Page-break-only list paragraphs no longer print stray bullets or numbers. The next item keeps its number, matching the reference export. |
|
||||
| 2026-10-12 | Backspace at the start of the paragraph after a table nested in a cell moves into the nested table's last cell, no longer into the last cell of the table around it |
|
||||
| 2026-10-14 | Grouped `flowChartOr` shapes draw their circle and crossing spokes, as in Word |
|
||||
| 2026-10-14 | Deleting a comment removes its anchors from headers, footers, notes and text boxes too, not just the body, and deletes the whole thread below it, replies to replies included; no anchor or reply is left pointing at a deleted comment (#1345) |
|
||||
| 2026-10-14 | Legacy DOC DIB conversion checks the BMP header and copy before allocation, uses the caller's decode allowance, and caps PNG output while encoding; a BMP fallback is kept when it fits. A generated 1-pixel regression covers 57/58/512-byte limits. Resource-exhaustion consequences remain unmeasured. Related: #1334 and #1554 |
|
||||
| 2026-10-15 | Draw: Ink to Shape makes two-stroke arrows and arrows with a closed triangle head. A line plus a separate head stroke (an open V or a small closed triangle, drawn after the line or before it) whose apex sits at one of the line's ends becomes one straight arrow connector, and the head stroke goes, in one undo step; this works while drawing with Ink to Shape on and on lasso-selected strokes with Convert to Shapes. A shaft with a small triangle drawn round its tip in the same stroke is an arrow too; a triangle without a shaft stays a triangle. Our own design (Word for Mac has no Ink to Shape). |
|
||||
| 2026-10-13 | Justified vertical page alignment (#1320): a section set to Justified spreads each page's paragraphs and tables from the top margin to the bottom one, as Word does, including the last page and pages ending in a manual page break. DOCX `w:vAlign="both"` opens as Justified (it showed centred) and saves back; `layout.verticalAlign` takes `justify`, and Page Setup has a Vertical alignment box |
|
||||
| 2026-10-13 | macOS shortcuts as in Word for Mac: ⌘⇧S Save As, ⌘⌥E Insert Endnote, ⌘⌥A New Comment, ⌃H Replace, ⌘⌥R collapse the ribbon |
|
||||
| 2026-10-13 | The status bar flags a proofing language whose Hunspell dictionary isn't installed (Polish, Portuguese): "Polish (no dictionary)", with a tooltip naming the dictionary and where it is looked up (#1167) |
|
||||
@@ -159,6 +254,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-13 | Cut copies to the system clipboard however it is run (#1265): the ribbon, the context menu and the native menu cut deleted the words without copying them (only the Cmd+X event wrote the clipboard, so Paste re-inserted the previous copy); Copy/Cut publication is centralised in one sink and every entry point is tested |
|
||||
| 2026-10-13 | Insert › Bookmark deletes bookmarks (#1236): the dialog is laid out as Word's, with Add, Delete and Go To beside the list, Sort by Name or Location and Hidden bookmarks; it opens on the bookmark around the caret, Delete and Go To keep it open, and Go To selects the bookmark's text. `insert.deleteBookmark {name}` removes both ends of a bookmark, also one across paragraphs (adding a bookmark under a name in use left such a one's end behind) |
|
||||
| 2026-10-12 | Password-protected Word 97-2003 `.doc` files open after a password prompt (XOR obfuscation, RC4, RC4 CryptoAPI; wrong passwords are rejected by the stored verifier, #1079); written from the public specs and tested on synthetic files only, AES-encrypted `.doc` files are still refused |
|
||||
| 2026-10-14 | Update Field works inside headers, footers, notes and text boxes, on the part being edited, as in Word (#1706); with the caret in the body it still leaves them alone, and printing updates every field in the document |
|
||||
| 2026-10-12 | Comments can show only for the selected text (#1055): Track Changes Options › Comments › "Only for the selected text" drops the margin column, and the comment under the caret, or the clicked one, floats beside the page (over its edge in a narrow window). The default stays "In the margin", as in Word; `review.trackingOptions {"commentDisplay"}` for agents |
|
||||
| 2026-10-12 | Clicking inside a selected comment's balloon moves the caret in its text (#1013); the click used to leave the balloon, so the caret could only be moved with the arrow keys. A press on any balloon now belongs to the balloon, not the page behind it |
|
||||
| 2026-10-12 | Page background pictures and textures (Design › Page Color › Fill Effects) are drawn (tiled or stretched) and kept on save instead of being dropped from the package (#999); PDF export paints them too |
|
||||
@@ -191,6 +287,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-13 | Interface size means what it says (#822): a chosen size is absolute, as in PhotoCraft and PdfCraft, so "100%" is one screen pixel per point even where the system reports 200 % (a bare window manager on X11, where winit guesses the scale from the monitor's DPI). The new default, Auto, keeps the system's display scale and its menu entry shows the size it draws at; sizes run 75–300 %. A saved size from before stays the same if it was the default (now Auto) and becomes absolute otherwise |
|
||||
| 2026-10-14 | Copied text keeps its formatting in other programs (#1523): Copy and Cut put HTML beside the plain text on the system clipboard for every selection, not only one holding an equation, so a browser, mail client or another word processor pastes bold, italic, fonts and sizes. RTF on the clipboard is not written yet |
|
||||
| 2026-10-13 | Copying an equation also puts MathML in HTML on the clipboard beside the linear text like `y=2x_s` (#816; Word/LibreOffice paste not yet verified; OMML is #1297). HTML export writes equations as MathML too, and opening or pasting HTML with MathML gives equations back |
|
||||
| 2026-10-16 | Copying one equation on its own also puts it in the clipboard's MathML formats, which Microsoft documents Word reading first when it pastes math. Whether it pastes into Word as an editable equation hasn't been confirmed yet; testers welcome (#1297) |
|
||||
| 2026-10-13 | The Equation tab's galleries, structure buttons and symbols keep the theme's colours on Windows: their pictures share a few textures written in place (no wipe of pictures already on screen, room for the built-ins at high display scales), instead of hundreds of small textures freed in bulk, which on DirectX 12 showed inverted, red or teal tiles (#1002) |
|
||||
| 2026-10-13 | `file.close` over the control channel or MCP bridge no longer quits and discards unsaved changes (#1268): it returns an error unless the document is saved or `{"force": true}` is passed; the user's Save / Don't Save / Cancel prompt is unchanged |
|
||||
| 2026-10-14 | Text copied out of an exported PDF reads as shown (#1473): All Caps and Small Caps text comes out in capitals, as from Word's PDFs, and plain text after it keeps its own case (before, a capital first drawn for a lowercase letter made later capitals extract lowercase) |
|
||||
@@ -204,6 +301,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-14 | Hebrew and Arabic in exported PDFs copy and search as whole words (#1383): right-to-left glyphs are written left to right as they appear, the order Chrome and Edge (PDFium) and poppler read text back from (checked by hand), instead of in reading order, which they reversed (`שלום` came back as `םולש`, Arabic in pieces). Lam-alef stays whole and vowel marks follow their letters, though Chrome and poppler can still break a fully vowelled word with spaces. The page looks the same. Readers that take glyphs strictly in file order get only plain Hebrew runs right, through `/ReversedChars`; screen readers are unverified |
|
||||
| 2026-10-14 | HTML import (#1381): header cells (`<th>`) are bold unless their own CSS says otherwise, and `text-align` on a cell, its row, row group or table aligns the cell's paragraphs (a paragraph's own alignment wins), so `wordcraft-cli convert page.html out.docx` writes the bold header and `w:jc` right-aligned cells. HTML, Markdown and plain text, which give no page size, open on the region's paper (A4 in Italy, Letter in the US) like a new blank document, in the app and in `wordcraft-cli`; documents with their own page size keep it |
|
||||
| 2026-10-14 | Custom page sizes (#1433): Layout › Size ends with More Paper Sizes…, which opens Page Setup's new Paper group — a Paper size list (the named sizes, or Custom size) and Width and Height in the measurement unit; OK sets the size only when it changed, and a wider-than-tall size comes out landscape. `layout.size` now clamps each side to Word's 0.1"–22" and refuses a page the margins don't fit (the margins rule: 36 pt of text room), and Page Setup checks the size and margins together before applying either |
|
||||
| 2026-10-14 | Bold text in Arial Black and other Black or Heavy fonts looks as in Word: older copies of these fonts (Arial Black in the core fonts) call themselves regular weight, so bold was drawn with an extra synthetic bold; a family named Black/Heavy now counts as that heavy |
|
||||
| 2026-10-13 | Highlighted text reads on a dark page (View › Switch Modes, #1252): highlights and character shading are dimmed, keeping their hue (yellow turns a dim olive, as in Word), and the text on them is drawn light (coloured text below 4.5:1 is drawn white, and underlines and strikethroughs follow the same rule), instead of white text on bright yellow; light page, print and exports unchanged |
|
||||
| 2026-10-13 | Full screen (#980): F11, or View › Window › Full Screen, fills the screen with the window (⌃⌘F on macOS); F11 again or Escape gives back the window as it was. Next Field, which Word puts on F11, keeps Word's Alt+F1 and Alt+Shift+F1 (and Shift+F11). The web app leaves full screen to the browser's own F11 |
|
||||
| 2026-10-13 | Double-clicking the top or bottom margin of a page creates its header or footer when it has none and puts the caret in it, as in Word (#960): the one that page shows (different first page, odd and even pages), only in Print Layout; one left empty is taken away again when you leave it, so nothing empty is saved. `insert.editHeader`/`insert.editFooter` take `{"page"}` for agents |
|
||||
@@ -284,7 +382,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-12 | Symbol fonts (#776): text in Wingdings, Wingdings 2, Wingdings 3, Webdings and Symbol (proprietary, never bundled) shows its intended symbols — full code tables from Unicode's published correspondence, both storage forms (`w:sym` private-use codes and plain codes); PDF text, copy and TXT export use the Unicode characters; the saved text is unchanged |
|
||||
| 2026-10-11 | Hide White Space (#645): `view.hideWhiteSpace` (View › Show checkbox, or double-click the gap between pages) collapses margins, headers and footers between pages to a thin line in Print Layout; screen only, page count unchanged |
|
||||
| 2026-10-11 | Fonts: Palatino Linotype and Book Antiqua fall back to Palatino (macOS) or TeX Gyre Pagella / P052 / URW Palladio (Linux) before generic serif (#670) |
|
||||
|---|---|
|
||||
| 2026-10-12 | Czech proofing: cs-CZ spelling reads the installed Hunspell dictionary (`hunspell-cs` on Debian/Ubuntu), suggestions use runtime MAP/REP/TRY/KEY tables, generic repeated-word and spacing checks explain in Czech; Review › Language offers Czech/Čeština; the Czech interface writes new documents and opened TXT/Markdown in cs-CZ. Affix headers accept trailing comments. No system dictionary data or Czech hyphenation patterns bundled; parity estimates unchanged |
|
||||
| 2026-10-12 | Tables: dragging the border of one selected cell (Select Cell, or a click along its left edge) moves it in that cell's row only, as in Word, like the border of cells selected across (#962) |
|
||||
| 2026-10-13 | Korean interface catalog completed: all 2,463 entries translated; the ko-KR system locale and saved language choice select the interface. The UI prefers Korean embedded/system font faces so Hangul renders instead of boxes, and print settings and printer feedback are translated. Korean proofing remains unavailable; macOS Korean IME fixes are still pending (#163, #164) |
|
||||
@@ -399,16 +496,98 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-05 | M0–M12 first versions: model, layout, render, engine with 200+ commands, Word-style UI, DOCX I/O, PDF and other formats, references, review, mailings, CLI, MCP, web |
|
||||
| 2026-10-12 | Mail-merge recipients (#778): legacy Excel .xls workbooks; CSV/TXT lists in GBK, Big5, Shift_JIS, UTF-16 and other encodings read correctly (plain-text import too); Edit Recipient List filters (equal, not equal, less, greater, blank, contains… joined by And/Or) and sorts, and preview, Finish & Merge and labels use only the matching records in that order (`mailings.filterRecipients`, `mailings.sortRecipients`) |
|
||||
| 2026-10-13 | The interface-translation audit runs in CI again (#1128): the size labels of Envelopes, Labels and Layout › Size are translated (`4,13 × 9,5 дюйма`) and use the region's decimal separator, and status-bar messages (table split and merge, ink replay, citations, SmartArt, Researcher, Design defaults), the Reading Mode toolbar, Go To and Search's Suggested heading are translated in every interface language, and the Read Aloud player no longer shows a speech error a frame before the status bar does, the race behind the audit's rare failure under load |
|
||||
| 2026-10-15 | Lists (#1683): a bullet stored as a private-use character its font can't draw (the font isn't installed) shows the level's default bullet (• ○ ▪); it used to be whatever an installed icon font has at that code, such as Font Awesome's Twitter logo |
|
||||
| 2026-10-15 | The web app keeps its preferences between visits (#2132): theme (dark mode), interface size, editing options and the rest of what the desktop app saves in `ui.json` are kept in the browser's `localStorage`, written as soon as they change |
|
||||
| 2026-10-17 | Saving into a folder that refuses a temporary file (macOS privacy protection, read-only folders, #2138) never overwrites an existing document in place: it is left untouched and the error says to use Save As to another folder or allow WordCraft access to the folder (System Settings › Privacy & Security › Files and Folders on macOS). A new file is created directly. Unit tests on Linux; not yet confirmed on a Mac |
|
||||
|
||||
Footer page-table height and body wrapping are corrected. Other pagination gaps remain open.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-19 | trivial | Progress log: forms protection keeps its content controls: no inserting, Properties or Remove Content Control |
|
||||
| 2026-10-19 | trivial | Progress log: text typed into a content control takes the control's formatting; localized placeholder styles recognised |
|
||||
| 2026-10-18 | trivial | Progress log: long navigation headings wrap within the pane instead of ending in an ellipsis (#3015) |
|
||||
| 2026-10-18 | trivial | Font list starts at its first row after clearing a no-match query; recent heading remains visible (#2068) |
|
||||
| 2026-10-18 | trivial | A word after a slash wraps whole, like Word (#2963) |
|
||||
| 2026-10-17 | trivial | Progress log: recipient list search and merged-only view (#1576) |
|
||||
| 2026-10-18 | trivial | Progress log: symbols keep their font when the text font changes (#2036) |
|
||||
| 2026-10-17 | trivial | Progress log: Restrict Editing guards tables, Paste Formatting and merge fields (#1327) |
|
||||
| 2026-10-18 | trivial | Progress log: Picture Format › Size, sizes typed in any unit and the Size dialog (#2573); readiness estimates unchanged |
|
||||
| 2026-10-18 | trivial | Progress log: Manage Sources imports Word's `Sources.xml` (#2640) |
|
||||
| 2026-10-14 | trivial | Progress log: a list item's first word is not flagged for a missing capital (#1741) |
|
||||
| 2026-10-18 | trivial | #2445: pending Save As answers keep their originating document identity, so a replacement document is never written to an old picker destination; real Save-button and focused-editor shortcut controls verified |
|
||||
| 2026-10-16 | trivial | #2445: interactive Save on import-only .doc/.dot paths uses the existing DOCX Save As flow; cancel and failed writes keep the draft, and Close waits for a successful save. Explicit/script saves still report unsupported legacy output |
|
||||
| 2026-10-16 | trivial | Save Changes exposes an alert-dialog role, the document-specific question and loss/failure context to accessibility; full-app focus/ancestry regression. Native screen-reader verification remains pending. |
|
||||
| 2026-10-16 | trivial | Progress log: the Spike |
|
||||
| 2026-10-16 | trivial | Progress log: `w:eastAsianLayout` kept on save |
|
||||
| 2026-10-15 | trivial | Progress log: undrawable private-use list bullets show the level's default bullet (#1683) |
|
||||
| 2026-10-15 | trivial | Progress log: web preferences kept between visits (#2132) |
|
||||
| 2026-10-15 | trivial | Progress log: Recently Used Fonts in the font box (#2068) |
|
||||
| 2026-10-15 | trivial | Progress log: one Thai face for a run in a missing Thai font (#1549) |
|
||||
| 2026-10-18 | trivial | Progress log: Different First Page headers reachable from page 1 (#2826) |
|
||||
| 2026-10-18 | trivial | Progress log: bold Black/Heavy fonts are not emboldened again |
|
||||
| 2026-10-16 | trivial | Progress log: Web Layout fills the window width (#1876) |
|
||||
| 2026-10-17 | trivial | Progress log: DOCX glossary documents (building blocks) |
|
||||
| 2026-10-15 | trivial | Progress log: move options in Track Changes Options (gap #5) |
|
||||
| 2026-10-15 | trivial | Progress log: image size limits checked before allocation (#1321) |
|
||||
| 2026-10-17 | trivial | Progress log: Read Aloud speaks each sentence in its own language, #1843 |
|
||||
| 2026-10-18 | trivial | Progress log: `wordcraft-cli run --script` (#1963) |
|
||||
| 2026-10-18 | trivial | Progress log: header-cell picture watermarks drawn behind the text (#1775); readiness estimates unchanged |
|
||||
| 2026-10-14 | trivial | Progress log: comment drafts kept and written before saving or closing (#1348) |
|
||||
| 2026-10-17 | trivial | Language dialog keeps inherited proofing language and no-proof choices (#2717); readiness estimates unchanged |
|
||||
| 2026-10-14 | trivial | Progress log: ASK and SET fields show nothing (#1765) |
|
||||
| 2026-10-15 | trivial | Progress log: at-least table rows start the next page whole (#1742) |
|
||||
| 2026-10-14 | trivial | Progress log: ODT sections on export (gap 19) |
|
||||
| 2026-10-17 | trivial | Explicit DrawingML preset/custom outline dashes survive import/save and paint in raster/PDF, scaled to the effective stroke width even for zero-width paths. Synthetic controls; theme-inherited dashes and line caps remain unverified. |
|
||||
| 2026-10-15 | trivial | `wordcraft-cli convert --update-fields` explicitly refreshes unlocked fields before conversion; ordinary conversion keeps cached results. Field refresh can change pagination |
|
||||
| 2026-10-17 | trivial | Arial Unicode MS uses Arial and its proportional substitutes; glyph coverage and exact Word line height remain font-dependent. |
|
||||
| 2026-10-18 | trivial | Progress log: Split Cells and Convert Text to Table dialogs, matched to the Word check (#2592) |
|
||||
| 2026-10-16 | trivial | Progress log: tall-ascent font list entries no longer cut off (#2570) |
|
||||
| 2026-10-16 | trivial | Progress log: Read Mode keeps the keyboard, whole columns, page-turn bar clear (#1772) |
|
||||
| 2026-10-16 | trivial | Progress log: comments readable in the dark theme (#2045) |
|
||||
| 2026-10-16 | trivial | Progress log: Indonesian proofing (#498) |
|
||||
| 2026-10-16 | trivial | Progress log: legacy outline, shadow, emboss and imprint text effects drawn (#2534) |
|
||||
| 2026-10-15 | trivial | Progress log: Columns on selected text (#2024) |
|
||||
| 2026-10-15 | trivial | Navigation Find and query edits expose Results (#2096) |
|
||||
| 2026-10-15 | trivial | Progress log: numbered headings (#1793) |
|
||||
| 2026-10-15 | trivial | Add the missing `-->` → `→` AutoCorrect entry (#2223), with typing, undo and preference regression coverage; existing arrow bullets unchanged |
|
||||
| 2026-10-15 | trivial | Progress log: Update Field updates the part being edited, as in Word (#1706) |
|
||||
| 2026-10-14 | trivial | Progress log: Update Fields reaches headers, footers and text boxes (#1706) |
|
||||
| 2026-10-15 | trivial | Progress log: font family caches bounded; math font resolution follows font changes (#1354) |
|
||||
| 2026-10-15 | trivial | Progress log: web typing in non-Latin text no longer repeats (#1480) |
|
||||
| 2026-10-15 | trivial | Progress log: Backspace removes a selected table, rows or columns (#1844) |
|
||||
| 2026-10-16 | trivial | Progress log: Hebrew field results and smart quotes (#1670) |
|
||||
| 2026-10-16 | trivial | Progress log: Ctrl+wheel zoom no longer scrolls the document (#1743) |
|
||||
| 2026-10-16 | trivial | Hint-reliant CJK fonts execute TrueType contour assembly; Windows DFKai-SB no longer loses strokes. Synthetic local-font regression; no font binaries bundled. |
|
||||
| 2026-10-14 | trivial | Progress log: RTF export writes sections (gap 19) |
|
||||
| 2026-10-15 | trivial | Progress log: multi-letter equation scripts (#1609) |
|
||||
| 2026-10-15 | trivial | Progress log: plain-text paste keeps the paragraph formatting where it lands |
|
||||
| 2026-10-14 | trivial | Progress log: Add Font imports every selected font file (#1789) |
|
||||
| 2026-10-15 | trivial | Additive paragraph spacing retains the full before-space after a section page break; ordinary overlapping spacing is unchanged. |
|
||||
| 2026-10-15 | trivial | Exact line spacing keeps the run font baseline around tall equations; automatic and minimum spacing still grow for math. |
|
||||
| 2026-10-16 | trivial | Zero-extent drawing anchors contribute no inline font height. Synthetic regressions. |
|
||||
| 2026-10-16 | trivial | Control keyboard/text input works in the inactive native window (#2420) |
|
||||
| 2026-10-15 | trivial | Progress log: Hide Quick Access Toolbar (#1945) |
|
||||
| 2026-10-15 | trivial | Progress log: native ink nested in groups and drawing canvases kept on save |
|
||||
| 2026-10-15 | trivial | Progress log: the word being typed gets no squiggle until the caret leaves it (#1552) |
|
||||
| 2026-10-15 | trivial | Progress log: Highlight No Color sticks to the button (#2105) |
|
||||
| 2026-10-16 | trivial | Body and active note text keep normal opacity while editing footnotes or endnotes (#2545); header/footer dimming is unchanged |
|
||||
| 2026-10-17 | minor | Progress log: Drop Cap Options (#2601) |
|
||||
| 2026-10-16 | trivial | An otherwise empty section at page start retains its line before continuous content; later closing marks stay quiet |
|
||||
| 2026-10-16 | trivial | Progress log: equations from Word files keep their content (#1273) |
|
||||
| 2026-10-16 | trivial | Progress log: Insert Caption… on objects and Page Setup header and footer options (#1230) |
|
||||
| 2026-10-17 | trivial | SECTIONPAGES includes shared continuous-section pages in body and header/footer fields |
|
||||
| 2026-10-17 | trivial | Footer page tables no longer inflate footer text height; body lines wrap at their physical bounds |
|
||||
| 2026-10-17 | minor | Progress log: Scale to paper size on File › Print, #2108 |
|
||||
| 2026-10-17 | trivial | Non-overlapping body floating tables clear header tables; overlapping tables keep their requested position |
|
||||
| 2026-10-15 | trivial | Progress log: caret inside ligatures (#1974) |
|
||||
| 2026-10-14 | trivial | Progress log: row table border exceptions |
|
||||
| 2026-10-12 | minor | Czech proofing review: short-word splits rank after deletion, NOSUGGEST excludes suggestions while accepting typed forms, affix comments apply only to headers, ratios keep spaces and repeated-word messages use Czech quotes; synthetic engine end-to-end and latency checks |
|
||||
| 2026-10-12 | minor | Czech spelling from the installed Hunspell dictionary, runtime-table suggestions and generic checks; Czech interface writes cs-CZ documents; no Czech hyphenation patterns bundled; estimates unchanged |
|
||||
| 2026-10-12 | trivial | Progress log: one selected cell's border drags in its row only (#962) |
|
||||
| 2026-10-16 | trivial | Progress log: opening a DOCX no longer copies its pictures |
|
||||
| 2026-10-12 | minor | Progress log: Word default shortcuts expanded to 140 commands on macOS (169 combinations) and 158 on Linux/Windows (188 combinations), addressing gap #24 |
|
||||
| 2026-10-13 | trivial | Web/Draft long-page blur fixed with visible full-resolution raster tiles |
|
||||
| 2026-10-14 | trivial | Progress log: VML freeforms read and kept on save |
|
||||
@@ -418,6 +597,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-14 | trivial | Floating-table overlap checks use visible line content; empty line-break lines no longer move a table |
|
||||
| 2026-10-14 | trivial | Progress log: deleting a comment leaves no dangling anchors or replies (#1345) |
|
||||
| 2026-10-14 | minor | Legacy DOC DIB conversion byte limits only; related #1334/#1554, stage and readiness estimates unchanged |
|
||||
| 2026-10-15 | trivial | Progress log: Ink to Shape two-stroke and closed-head arrows |
|
||||
| 2026-10-13 | trivial | Progress log: justified vertical page alignment (#1320) |
|
||||
| 2026-10-14 | trivial | Progress log: file names that aren't valid Unicode (#1440) |
|
||||
| 2026-10-13 | trivial | Behind Text pictures and shapes drag over overlapping text in the body and headers, selected or not, while ordinary clicks keep editing text; In Front of Text drag covered too |
|
||||
@@ -592,3 +772,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
| 2026-10-09 | minor | Recently landed: RTL, Ukrainian and Brazilian Portuguese |
|
||||
| 2026-10-06 | major | First honest estimate: 88% catalog, ~62% real parity, alpha ~85% of the way |
|
||||
| 2026-10-12 | trivial | Progress log: recipient filter and sort, .xls and legacy-encoding recipient lists (#778) |
|
||||
| 2026-10-15 | trivial | Progress log: dialog close box (#1885) |
|
||||
| 2026-10-15 | trivial | Progress log: mixed Hebrew/Latin text keeps its order in Word (#1543) |
|
||||
| 2026-10-15 | trivial | Progress log: ruler numbers by zoom, rulers follow the caret's page (#1878) |
|
||||
| 2026-10-17 | trivial | Progress log: saving into a folder that refuses a temporary file (#2138) |
|
||||
|
||||
+369
-41
@@ -2,6 +2,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod automation_args;
|
||||
mod script;
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fmt;
|
||||
@@ -16,9 +17,10 @@ const USAGE: &str = "\
|
||||
wordcraft-cli — WordCraft from the command line
|
||||
|
||||
USAGE:
|
||||
wordcraft-cli convert <in> <out> [--markup] [--format wordml2003|flatopc]
|
||||
wordcraft-cli convert <in> <out> [--markup] [--update-fields] [--format wordml2003|flatopc]
|
||||
convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png,
|
||||
xml); an .xml file is a Word XML Document (Flat OPC), or with
|
||||
xml); --update-fields refreshes unlocked fields before saving;
|
||||
an .xml file is a Word XML Document (Flat OPC), or with
|
||||
--format wordml2003 a Word 2003 XML Document;
|
||||
--markup (Print Markup): comments beside each page and
|
||||
tracked changes in pdf/png, a comment list in html/md/txt
|
||||
@@ -26,9 +28,15 @@ USAGE:
|
||||
wordcraft-cli text <file> plain text
|
||||
wordcraft-cli inspect <file> document structure (JSON)
|
||||
wordcraft-cli render <file> <out.png> [--page N] [--scale S]
|
||||
wordcraft-cli run [--file F | --template T] --cmd 'id={json}' [--cmd …] [--save OUT] [--print]
|
||||
[--author NAME] run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] --cmd 'id={json}' [--cmd …]
|
||||
[--save OUT] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
|
||||
formats follow the extension (docx and pdf in one run);
|
||||
relative paths resolve against the script's folder
|
||||
wordcraft-cli commands [--json] list every command
|
||||
wordcraft-cli parity [--markdown] feature-catalog parity
|
||||
wordcraft-cli mcp [--connect HOST:PORT | --author NAME] [--automation-read-root DIR] [--automation-write-root DIR]
|
||||
@@ -47,6 +55,11 @@ USAGE:
|
||||
wordcraft-cli [<command>] -h | --help this help
|
||||
wordcraft-cli --version
|
||||
|
||||
A password-protected Word file is opened with --password PASS, --password-file PATH or the
|
||||
WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by
|
||||
every other process, so the other two are better. A file opened with a password is written with
|
||||
it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.
|
||||
|
||||
Paper: documents created here, and HTML, Markdown and text files (which give no page size), use
|
||||
the system region's paper (A4, or Letter in the US and other Letter regions), read from
|
||||
LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the
|
||||
@@ -60,13 +73,24 @@ fn wants_help(cmd: &str, rest: &[String]) -> bool {
|
||||
SUBCOMMANDS.contains(&cmd) && rest.iter().any(|a| a == "--help" || a == "-h")
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> Result<Session, String> {
|
||||
/// The error every subcommand gives when a required path is not there.
|
||||
fn missing_argument() -> Failure {
|
||||
format!("missing argument\n\n{USAGE}").into()
|
||||
}
|
||||
|
||||
/// Open a document for a subcommand. A password-protected Word file needs its password
|
||||
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
|
||||
/// `convert` does not quietly write a copy the password no longer protects.
|
||||
fn open(path: &Path, password: Option<&str>) -> Result<Session, String> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, _) = wordcraft_engine::io::open_path_in(path, None, ®ion)?;
|
||||
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, ®ion)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
@@ -85,18 +109,57 @@ fn text_args<S: AsRef<OsStr>>(raw: &[S]) -> Result<(Vec<String>, Option<PathBuf>
|
||||
None if cmd == "run" => args.iter().position(|a| a == "--file").map(|i| i + 1),
|
||||
None => None,
|
||||
};
|
||||
// `run --script FILE` may also name its script with such a file name.
|
||||
let script_at = if cmd == "run" { args.iter().position(|a| a == "--script").map(|i| i + 1) } else { None };
|
||||
let mut file = None;
|
||||
for (i, a) in raw.iter().map(AsRef::as_ref).enumerate() {
|
||||
if a.to_str().is_none() {
|
||||
if Some(i) != file_at {
|
||||
if Some(i) != file_at && Some(i) != script_at {
|
||||
return Err(format!("argument {} is not valid Unicode: {}", i + 1, a.to_string_lossy()));
|
||||
}
|
||||
file = Some(PathBuf::from(a));
|
||||
if Some(i) == file_at {
|
||||
file = Some(PathBuf::from(a));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((args, file))
|
||||
}
|
||||
|
||||
/// The password for a protected Word file: `--password`, `--password-file`, or
|
||||
/// `WORDCRAFT_PASSWORD`, in that order. The file form exists because a password on a command line
|
||||
/// is readable by every other process on the machine; a trailing newline is dropped so a file
|
||||
/// written by `echo` works. Never logged, and never named in an error.
|
||||
fn password_from(args: &[String]) -> Result<Option<String>, String> {
|
||||
if let Some(password) = arg_value(args, "--password") {
|
||||
return Ok(Some(password));
|
||||
}
|
||||
if let Some(path) = arg_value(args, "--password-file") {
|
||||
let raw = std::fs::read_to_string(&path).map_err(|e| format!("--password-file {path}: {e}"))?;
|
||||
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
|
||||
}
|
||||
Ok(std::env::var("WORDCRAFT_PASSWORD").ok().filter(|p| !p.is_empty()))
|
||||
}
|
||||
|
||||
/// The positional arguments, skipping every option's value so an option value is never read as a
|
||||
/// path. Mirrors [`validate_options`], which has already checked the options are known.
|
||||
fn positionals<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'a String> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some(arg) = args.get(i) {
|
||||
let takes_value =
|
||||
arg.starts_with("--") && specs.iter().any(|s| s.name == arg && s.takes_value) && args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
|
||||
if takes_value {
|
||||
i += 2;
|
||||
} else {
|
||||
if !arg.starts_with("--") {
|
||||
out.push(arg);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
@@ -222,13 +285,30 @@ fn automation_roots(
|
||||
Ok((roots, left))
|
||||
}
|
||||
|
||||
const NO_OPTIONS: &[OptionSpec] = &[];
|
||||
const CONVERT_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--markup", takes_value: false }, OptionSpec { name: "--format", takes_value: true }];
|
||||
const RENDER_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--page", takes_value: true }, OptionSpec { name: "--scale", takes_value: true }];
|
||||
/// The password a protected Word file is opened with: `--password` (which any other process on
|
||||
/// the machine can read from the command line), `--password-file`, or `WORDCRAFT_PASSWORD`.
|
||||
const PASSWORD_OPTIONS: &[OptionSpec] =
|
||||
&[OptionSpec { name: "--password", takes_value: true }, OptionSpec { name: "--password-file", takes_value: true }];
|
||||
const CONVERT_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--markup", takes_value: false },
|
||||
OptionSpec { name: "--format", takes_value: true },
|
||||
OptionSpec { name: "--update-fields", takes_value: false },
|
||||
OptionSpec { name: "--password", takes_value: true },
|
||||
OptionSpec { name: "--password-file", takes_value: true },
|
||||
];
|
||||
const RENDER_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--page", takes_value: true },
|
||||
OptionSpec { name: "--scale", takes_value: true },
|
||||
OptionSpec { name: "--password", takes_value: true },
|
||||
OptionSpec { name: "--password-file", takes_value: true },
|
||||
];
|
||||
const RUN_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--file", takes_value: true },
|
||||
OptionSpec { name: "--password", takes_value: true },
|
||||
OptionSpec { name: "--password-file", takes_value: true },
|
||||
OptionSpec { name: "--template", takes_value: true },
|
||||
OptionSpec { name: "--cmd", takes_value: true },
|
||||
OptionSpec { name: "--script", takes_value: true },
|
||||
OptionSpec { name: "--save", takes_value: true },
|
||||
OptionSpec { name: "--page", takes_value: true },
|
||||
OptionSpec { name: "--scale", takes_value: true },
|
||||
@@ -291,32 +371,37 @@ fn write_stdout(write: impl FnOnce(&mut std::io::StdoutLock<'static>) -> std::io
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The operand after `--script`, by its real name (it may not be valid Unicode).
|
||||
fn script_operand<S: AsRef<OsStr>>(raw: &[S]) -> Option<PathBuf> {
|
||||
let at = raw.iter().position(|a| a.as_ref() == OsStr::new("--script"))?;
|
||||
raw.get(at + 1).map(|a| PathBuf::from(a.as_ref()))
|
||||
}
|
||||
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
let script_path = script_operand(args);
|
||||
let (args, file) = text_args(args)?;
|
||||
// Opens the file by its real name, which its text in `args` may have lost.
|
||||
let open = |text: &str| open(file.as_deref().unwrap_or(Path::new(text)));
|
||||
// Opens the file by its real name, which its text in `args` may have lost, and with the
|
||||
// password of a protected document (`password_from`).
|
||||
let open = |text: &str, password: Option<&str>| open(file.as_deref().unwrap_or(Path::new(text)), password);
|
||||
let cmd = args.first().map(String::as_str).unwrap_or("");
|
||||
let rest: Vec<String> = args.iter().skip(1).cloned().collect();
|
||||
// Before options are checked or files and folders opened.
|
||||
if wants_help(cmd, &rest) {
|
||||
return write_stdout(|o| write!(o, "{USAGE}"));
|
||||
}
|
||||
let pos = |i: usize| rest.iter().filter(|a| !a.starts_with("--")).nth(i).cloned().ok_or_else(|| format!("missing argument\n\n{USAGE}"));
|
||||
match cmd {
|
||||
"convert" => {
|
||||
validate_options("convert", &rest, CONVERT_OPTIONS)?;
|
||||
// `--format wordml2003` (or `flatopc`) picks the kind of `.xml` file; its value isn't a path.
|
||||
let format = arg_value(&rest, "--format");
|
||||
let paths: Vec<&String> = rest
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(n, a)| !a.starts_with("--") && !(*n > 0 && rest.get(n - 1).is_some_and(|p| p == "--format")))
|
||||
.map(|(_, a)| a)
|
||||
.collect();
|
||||
let missing = || format!("missing argument\n\n{USAGE}");
|
||||
let (i, o) = (paths.first().ok_or_else(missing)?.to_string(), paths.get(1).ok_or_else(missing)?.to_string());
|
||||
let paths = positionals(&rest, CONVERT_OPTIONS);
|
||||
let (i, o) = (paths.first().ok_or_else(missing_argument)?.to_string(), paths.get(1).ok_or_else(missing_argument)?.to_string());
|
||||
let markup = rest.iter().any(|a| a == "--markup");
|
||||
let mut s = open(&i)?;
|
||||
let password = password_from(&rest)?;
|
||||
let mut s = open(&i, password.as_deref())?;
|
||||
if rest.iter().any(|a| a == "--update-fields") {
|
||||
s.run("references.updateFields", &json!({})).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let r = if o.to_ascii_lowercase().ends_with(".png") {
|
||||
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": markup}))
|
||||
} else {
|
||||
@@ -331,29 +416,40 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
Ok(())
|
||||
}
|
||||
"info" => {
|
||||
validate_options("info", &rest, NO_OPTIONS)?;
|
||||
let mut s = open(&pos(0)?)?;
|
||||
validate_options("info", &rest, PASSWORD_OPTIONS)?;
|
||||
let paths = positionals(&rest, PASSWORD_OPTIONS);
|
||||
let password = password_from(&rest)?;
|
||||
let mut s = open(paths.first().ok_or_else(missing_argument)?, password.as_deref())?;
|
||||
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(|e| e.to_string())?).unwrap_or_default();
|
||||
write_stdout(|o| writeln!(o, "{info}"))
|
||||
}
|
||||
"text" => {
|
||||
validate_options("text", &rest, NO_OPTIONS)?;
|
||||
let s = open(&pos(0)?)?;
|
||||
validate_options("text", &rest, PASSWORD_OPTIONS)?;
|
||||
let paths = positionals(&rest, PASSWORD_OPTIONS);
|
||||
let password = password_from(&rest)?;
|
||||
let s = open(paths.first().ok_or_else(missing_argument)?, password.as_deref())?;
|
||||
let text = listed_text(&s.doc)?;
|
||||
write_stdout(|o| writeln!(o, "{text}"))
|
||||
}
|
||||
"inspect" => {
|
||||
validate_options("inspect", &rest, NO_OPTIONS)?;
|
||||
let mut s = open(&pos(0)?)?;
|
||||
validate_options("inspect", &rest, PASSWORD_OPTIONS)?;
|
||||
let paths = positionals(&rest, PASSWORD_OPTIONS);
|
||||
let password = password_from(&rest)?;
|
||||
let mut s = open(paths.first().ok_or_else(missing_argument)?, password.as_deref())?;
|
||||
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(|e| e.to_string())?).unwrap_or_default();
|
||||
write_stdout(|o| writeln!(o, "{tree}"))
|
||||
}
|
||||
"render" => {
|
||||
validate_options("render", &rest, RENDER_OPTIONS)?;
|
||||
let (i, o) = (pos(0)?, pos(1)?);
|
||||
let paths = positionals(&rest, RENDER_OPTIONS);
|
||||
let password = password_from(&rest)?;
|
||||
let (Some(i), Some(o)) = (paths.first(), paths.get(1)) else {
|
||||
return Err(missing_argument());
|
||||
};
|
||||
let (i, o) = (i.to_string(), o.to_string());
|
||||
let page = parse_page_arg("render", &rest)?.unwrap_or(1);
|
||||
let scale = parse_scale_arg("render", &rest)?.unwrap_or(2.0);
|
||||
let mut s = open(&i)?;
|
||||
let mut s = open(&i, password.as_deref())?;
|
||||
let r = s.run("file.exportPng", &json!({"path": o, "page": page, "scale": scale})).map_err(|e| e.to_string())?;
|
||||
write_stdout(|o| writeln!(o, "{r}"))
|
||||
}
|
||||
@@ -361,8 +457,20 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
let mut s = match (arg_value(&rest, "--file"), arg_value(&rest, "--template")) {
|
||||
(Some(f), _) => open(&f)?,
|
||||
let password = password_from(&rest)?;
|
||||
let script = match arg_value(&rest, "--script") {
|
||||
Some(path) if !path.starts_with("--") => Some(script::load(script_path.as_deref().unwrap_or(Path::new(&path)))?),
|
||||
_ if rest.iter().any(|a| a == "--script") => return Err("run: --script requires a value".into()),
|
||||
_ => None,
|
||||
};
|
||||
// A source named on the command line wins over both of the script's.
|
||||
let (mut from_file, mut from_template) = (arg_value(&rest, "--file"), arg_value(&rest, "--template"));
|
||||
if from_file.is_none() && from_template.is_none() {
|
||||
from_file = script.as_ref().and_then(|c| c.file.clone());
|
||||
from_template = script.as_ref().and_then(|c| c.template.clone());
|
||||
}
|
||||
let mut s = match (from_file, from_template) {
|
||||
(Some(f), _) => open(&f, password.as_deref())?,
|
||||
(None, Some(t)) => {
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
s.run("file.new", &json!({"template": t})).map_err(|e| e.to_string())?;
|
||||
@@ -373,6 +481,13 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
if let Some(name) = arg_value(&rest, "--author") {
|
||||
set_author(&mut s, &name)?;
|
||||
}
|
||||
let print = rest.iter().any(|a| a == "--print");
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| format!("command {} ({id}): {e}", n + 1))?;
|
||||
if print {
|
||||
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
let mut i = 0;
|
||||
while i < rest.len() {
|
||||
if rest.get(i).map(String::as_str) == Some("--cmd") {
|
||||
@@ -382,7 +497,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
None => (spec.clone(), json!({})),
|
||||
};
|
||||
let r = s.run(&id, ¶ms).map_err(|e| format!("{id}: {e}"))?;
|
||||
if rest.iter().any(|a| a == "--print") {
|
||||
if print {
|
||||
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
i += 2;
|
||||
@@ -390,7 +505,21 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if let Some(out) = arg_value(&rest, "--save") {
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
if let Some(p) = parent.filter(|p| !p.is_dir()) {
|
||||
return Err(format!("{out}: folder {} does not exist", p.display()).into());
|
||||
}
|
||||
if Path::new(out).is_dir() {
|
||||
return Err(format!("{out}: is a folder, not a file").into());
|
||||
}
|
||||
if !out.to_ascii_lowercase().ends_with(".png") {
|
||||
wordcraft_engine::io::save_bytes(out, &s.doc)?;
|
||||
}
|
||||
}
|
||||
for out in outputs {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = page {
|
||||
@@ -478,10 +607,12 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
"zotero" => {
|
||||
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
|
||||
let name = pos(0)?;
|
||||
let command = wordcraft_zotero::Command::from_name(&name).ok_or_else(|| format!("unknown Zotero command `{name}`\n\n{USAGE}"))?;
|
||||
let file = pos(1)?;
|
||||
let mut s = open(&file)?;
|
||||
let paths = positionals(&rest, ZOTERO_OPTIONS);
|
||||
let (Some(name), Some(file)) = (paths.first(), paths.get(1)) else {
|
||||
return Err(missing_argument());
|
||||
};
|
||||
let command = wordcraft_zotero::Command::from_name(name).ok_or_else(|| format!("unknown Zotero command `{name}`\n\n{USAGE}"))?;
|
||||
let mut s = open(file, None)?;
|
||||
for spec in rest.iter().zip(rest.iter().skip(1)).filter(|(a, _)| *a == "--cmd").map(|(_, v)| v) {
|
||||
let (id, params) = match spec.split_once('=') {
|
||||
Some((id, p)) => (id.to_string(), serde_json::from_str::<Value>(p).map_err(|e| format!("{id}: bad JSON params: {e}"))?),
|
||||
@@ -569,6 +700,7 @@ fn main() -> ExitCode {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
@@ -576,7 +708,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("info", &args(&["file.docx"]), NO_OPTIONS).is_ok());
|
||||
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
@@ -593,6 +725,41 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_value_is_never_read_as_a_path() {
|
||||
// `--password`'s value sits between the paths and would be taken for one without
|
||||
// `positionals`, so `render` would write its picture over a file called after the password.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
// A bare flag takes no value, so the next argument stays a path.
|
||||
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
|
||||
// `convert` is the one with a value-taking flag between the two paths.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_a_file_or_the_environment() {
|
||||
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
|
||||
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the other two sources.
|
||||
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_file_loses_only_its_trailing_newline() {
|
||||
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_password_file_is_named_without_the_password() {
|
||||
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_are_rejected_before_file_access() {
|
||||
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
|
||||
@@ -893,4 +1060,165 @@ mod tests {
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
/// A scratch folder that removes itself, even when the test fails.
|
||||
struct ScriptDir(PathBuf);
|
||||
|
||||
impl std::ops::Deref for ScriptDir {
|
||||
type Target = Path;
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ScriptDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn script_dir(tag: &str) -> ScriptDir {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-script-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
ScriptDir(dir)
|
||||
}
|
||||
|
||||
fn write_script(dir: &Path, text: &str) -> String {
|
||||
let p = dir.join("job.json");
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
|
||||
let dir = script_dir("two");
|
||||
let script = write_script(
|
||||
&dir,
|
||||
r#"{"template":"blank","commands":[{"command":"text.insert","params":{"text":"Hello script"}},{"command":"format.bold"}],"save":["out.docx","out.pdf"]}"#,
|
||||
);
|
||||
run(&args(&["run", "--script", &script])).unwrap();
|
||||
assert!(std::fs::read(dir.join("out.pdf")).unwrap().starts_with(b"%PDF"));
|
||||
let doc = open(&dir.join("out.docx"), None).unwrap().doc;
|
||||
let json = serde_json::to_string(&doc).unwrap();
|
||||
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_bad_output_writes_no_output() {
|
||||
let dir = script_dir("badout");
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["a.docx","b.xyz"]}"#);
|
||||
let e = run(&args(&["run", "--script", &script])).unwrap_err().to_string();
|
||||
assert_eq!(e.matches("b.xyz").count(), 1, "{e}");
|
||||
assert!(!dir.join("a.docx").exists());
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["a.docx","nope/b.docx"]}"#);
|
||||
assert!(run(&args(&["run", "--script", &script])).is_err());
|
||||
assert!(!dir.join("a.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_folder_as_output_writes_no_output() {
|
||||
let dir = script_dir("folderout");
|
||||
std::fs::create_dir(dir.join("b.pdf")).unwrap();
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["a.docx","b.pdf"]}"#);
|
||||
let e = run(&args(&["run", "--script", &script])).unwrap_err().to_string();
|
||||
assert!(e.contains("b.pdf"), "{e}");
|
||||
assert!(!dir.join("a.docx").exists());
|
||||
}
|
||||
|
||||
/// APFS refuses file names that aren't valid UTF-8, so the fixture can't be made on macOS
|
||||
/// (as in `tests/non_utf8_args.rs`).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn script_file_name_need_not_be_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let dir = script_dir("latin1");
|
||||
let mut name = dir.as_os_str().to_os_string().into_vec();
|
||||
name.extend_from_slice(b"/caf\xe9.json");
|
||||
let path = PathBuf::from(OsString::from_vec(name));
|
||||
std::fs::write(&path, r#"{"commands":["caret.docEnd"],"save":["o.txt"]}"#).unwrap();
|
||||
let raw = vec![OsString::from("run"), OsString::from("--script"), path.into_os_string()];
|
||||
run(&raw).unwrap();
|
||||
assert!(dir.join("o.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_line_template_wins_over_the_scripts_file() {
|
||||
let dir = script_dir("source");
|
||||
let input = dir.join("in.docx");
|
||||
run(&args(&["run", "--template", "blank", "--cmd", "text.insert={\"text\":\"FROM FILE\"}", "--save", &input.to_string_lossy()])).unwrap();
|
||||
let script = write_script(&dir, r#"{"file":"in.docx","commands":["caret.docEnd"]}"#);
|
||||
let (a, b) = (dir.join("a.txt"), dir.join("b.txt"));
|
||||
run(&args(&["run", "--script", &script, "--template", "blank", "--save", &a.to_string_lossy()])).unwrap();
|
||||
assert!(!std::fs::read_to_string(&a).unwrap().contains("FROM FILE"));
|
||||
run(&args(&["run", "--script", &script, "--save", &b.to_string_lossy()])).unwrap();
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
assert!(e.contains("--script requires a value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
|
||||
assert_eq!((s.commands.len(), s.save), (1, vec!["o.docx".to_string()]));
|
||||
let big = std::io::repeat(b' ').take(script::MAX_SCRIPT_BYTES + 10);
|
||||
let e = script::load_from(big, "-", None).unwrap_err();
|
||||
assert!(e.contains("too large"), "{e}");
|
||||
assert!(script::load_from(&b"{"[..], "-", None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_commands_run_before_cmd_flags() {
|
||||
let dir = script_dir("order");
|
||||
let script = write_script(&dir, r#"{"commands":[{"command":"text.insert","params":{"text":"first"}}]}"#);
|
||||
let out = dir.join("o.txt");
|
||||
run(&args(&["run", "--script", &script, "--cmd", "text.insert={\"text\":\" second\"}", "--save", &out.to_string_lossy()])).unwrap();
|
||||
assert!(std::fs::read_to_string(&out).unwrap().contains("first second"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_failure_names_the_command_and_writes_nothing() {
|
||||
let dir = script_dir("fail");
|
||||
let script =
|
||||
write_script(&dir, r#"{"commands":[{"command":"text.insert","params":{"text":"x"}},{"command":"no.such.command"}],"save":["out.docx"]}"#);
|
||||
let e = run(&args(&["run", "--script", &script])).unwrap_err().to_string();
|
||||
assert!(e.contains("command 2") && e.contains("no.such.command"), "{e}");
|
||||
assert!(!dir.join("out.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_rejects_junk_empty_missing_and_huge_input() {
|
||||
let dir = script_dir("junk");
|
||||
for text in [
|
||||
"not json",
|
||||
"[]",
|
||||
"{}",
|
||||
r#"{"commands":[]}"#,
|
||||
r#"{"commands":[{"params":{}}]}"#,
|
||||
r#"{"commands":[1]}"#,
|
||||
r#"{"commands":[{"command":"a"}],"save":[1]}"#,
|
||||
] {
|
||||
let script = write_script(&dir, text);
|
||||
assert!(run(&args(&["run", "--script", &script])).is_err(), "{text}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--script", &dir.join("missing.json").to_string_lossy()])).is_err());
|
||||
let huge = write_script(&dir, &" ".repeat(5 * 1024 * 1024));
|
||||
let e = run(&args(&["run", "--script", &huge])).unwrap_err().to_string();
|
||||
assert!(e.contains("too large"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_parse_resolves_paths_against_the_base() {
|
||||
let s = script::parse(r#"{"file":"in.docx","commands":[{"command":"edit.undo"}],"save":["/abs/o.pdf","o.docx"]}"#, Some(Path::new("/base")))
|
||||
.unwrap();
|
||||
let joined = |name: &str| Path::new("/base").join(name).to_string_lossy().into_owned();
|
||||
assert_eq!(s.file, Some(joined("in.docx")));
|
||||
assert_eq!(s.save, vec!["/abs/o.pdf".to_string(), joined("o.docx")]);
|
||||
let s = script::parse(r#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#, None).unwrap();
|
||||
assert_eq!(s.save, vec!["o.docx".to_string()]);
|
||||
assert_eq!(s.commands.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
//! `run --script FILE`: commands read from a JSON file (`-` is stdin), so a job can be kept in a
|
||||
//! file instead of a long chain of `--cmd` flags (#1963).
|
||||
//!
|
||||
//! ```json
|
||||
//! {"file": "in.docx", "template": "sample",
|
||||
//! "commands": [{"command": "text.insert", "params": {"text": "Hi"}}, "caret.docEnd"],
|
||||
//! "save": ["out.docx", "out.pdf"]}
|
||||
//! ```
|
||||
//!
|
||||
//! `file` and `template` are optional (`--file` / `--template` on the command line win), and a
|
||||
//! command is an object with `command` and optional `params`, or just the id as a string. Relative
|
||||
//! `file` and `save` paths resolve against the script's folder (the working folder for stdin).
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// The largest script read. A job is a list of commands; anything bigger is a mistake.
|
||||
pub const MAX_SCRIPT_BYTES: u64 = 4 * 1024 * 1024;
|
||||
/// The most commands a script may hold.
|
||||
const MAX_COMMANDS: usize = 100_000;
|
||||
/// The most outputs a script may save to.
|
||||
const MAX_SAVES: usize = 64;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Script {
|
||||
pub file: Option<String>,
|
||||
pub template: Option<String>,
|
||||
pub commands: Vec<(String, Value)>,
|
||||
pub save: Vec<String>,
|
||||
}
|
||||
|
||||
/// Read the script at `arg` (`-` for stdin) and parse it.
|
||||
pub fn load(arg: &Path) -> Result<Script, String> {
|
||||
let name = arg.display().to_string();
|
||||
if arg == Path::new("-") {
|
||||
return load_from(std::io::stdin().lock(), &name, None);
|
||||
}
|
||||
let f = std::fs::File::open(arg).map_err(|e| format!("--script {name}: {e}"))?;
|
||||
load_from(f, &name, arg.parent().filter(|p| !p.as_os_str().is_empty()))
|
||||
}
|
||||
|
||||
/// Read and parse a script from `r`, called `name` in errors; relative paths resolve against `base`.
|
||||
pub fn load_from(r: impl Read, name: &str, base: Option<&Path>) -> Result<Script, String> {
|
||||
let text = read_capped(r, name)?;
|
||||
parse(&text, base).map_err(|e| format!("--script {name}: {e}"))
|
||||
}
|
||||
|
||||
fn read_capped(r: impl Read, name: &str) -> Result<String, String> {
|
||||
let mut bytes = Vec::new();
|
||||
r.take(MAX_SCRIPT_BYTES + 1).read_to_end(&mut bytes).map_err(|e| format!("--script {name}: {e}"))?;
|
||||
if bytes.len() as u64 > MAX_SCRIPT_BYTES {
|
||||
return Err(format!("--script {name}: script too large (over {} MiB)", MAX_SCRIPT_BYTES / 1024 / 1024));
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|_| format!("--script {name}: not valid UTF-8"))
|
||||
}
|
||||
|
||||
fn resolve(path: &str, base: Option<&Path>) -> String {
|
||||
match base {
|
||||
Some(b) if Path::new(path).is_relative() => b.join(path).to_string_lossy().into_owned(),
|
||||
_ => path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_string(obj: &serde_json::Map<String, Value>, key: &str) -> Result<Option<String>, String> {
|
||||
match obj.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(s)) => Ok(Some(s.clone())),
|
||||
Some(_) => Err(format!("`{key}` must be a string")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str, base: Option<&Path>) -> Result<Script, String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("bad JSON: {e}"))?;
|
||||
let obj = v.as_object().ok_or("a script is a JSON object with a `commands` list")?;
|
||||
let list = match obj.get("commands") {
|
||||
Some(Value::Array(a)) => a,
|
||||
_ => return Err("`commands` must be a list".into()),
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Err("`commands` is empty".into());
|
||||
}
|
||||
if list.len() > MAX_COMMANDS {
|
||||
return Err(format!("too many commands (over {MAX_COMMANDS})"));
|
||||
}
|
||||
let mut commands = Vec::with_capacity(list.len());
|
||||
for (i, c) in list.iter().enumerate() {
|
||||
let n = i + 1;
|
||||
let entry = match c {
|
||||
Value::String(id) => Some((id.clone(), Value::Object(Default::default()))),
|
||||
Value::Object(o) => match o.get("command") {
|
||||
Some(Value::String(id)) => Some((id.clone(), o.get("params").cloned().unwrap_or_else(|| Value::Object(Default::default())))),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
match entry {
|
||||
Some((id, _)) if id.is_empty() => return Err(format!("command {n}: empty command id")),
|
||||
Some(e) => commands.push(e),
|
||||
None => return Err(format!("command {n}: expected a command id or {{\"command\": id, \"params\": {{…}}}}")),
|
||||
}
|
||||
}
|
||||
let save = match obj.get("save") {
|
||||
None | Some(Value::Null) => Vec::new(),
|
||||
Some(Value::String(s)) => vec![resolve(s, base)],
|
||||
Some(Value::Array(a)) if a.len() <= MAX_SAVES => {
|
||||
a.iter().map(|s| s.as_str().map(|s| resolve(s, base)).ok_or("`save` entries must be strings")).collect::<Result<_, _>>()?
|
||||
}
|
||||
Some(_) => return Err(format!("`save` must be a path or a list of at most {MAX_SAVES} paths")),
|
||||
};
|
||||
Ok(Script { file: opt_string(obj, "file")?.map(|f| resolve(&f, base)), template: opt_string(obj, "template")?, commands, save })
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Explicit field refresh for headless conversions; ordinary conversion keeps cached results.
|
||||
use std::process::Command;
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
use wordcraft_doc::{Document, Path, Pos, StoryRef};
|
||||
|
||||
#[test]
|
||||
fn convert_refresh_is_opt_in() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-convert-fields-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut doc = Document::from_text("Contents\nTarget");
|
||||
doc.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.page_break_before = Some(true);
|
||||
doc.insert_object(&Pos::body(1, 0), InlineObject::BookmarkStart { name: "target".into() }, &Default::default()).unwrap();
|
||||
for locked in [true, false] {
|
||||
doc.insert_object(
|
||||
&Pos::body(0, 0),
|
||||
InlineObject::Field { instr: "PAGEREF target".into(), result: "104".into(), locked, dirty: true, code: false, form: String::new() },
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let input = dir.join("in.json");
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let docx = dir.join("in.docx");
|
||||
let make = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&docx).output().unwrap();
|
||||
assert!(make.status.success(), "{}", String::from_utf8_lossy(&make.stderr));
|
||||
for refresh in [false, true] {
|
||||
let output = dir.join(if refresh { "refreshed.json" } else { "cached.json" });
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cmd.arg("convert").arg(&docx).arg(&output);
|
||||
if refresh {
|
||||
cmd.arg("--update-fields");
|
||||
}
|
||||
let run = cmd.output().unwrap();
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
let out: Document = serde_json::from_slice(&std::fs::read(output).unwrap()).unwrap();
|
||||
let results: Vec<_> = out
|
||||
.para(StoryRef::Body, &Path::top(0))
|
||||
.unwrap()
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Field { result, .. } => Some(result.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(results, if refresh { vec!["2", "104"] } else { vec!["104", "104"] });
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -29,4 +29,4 @@ rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "ClipboardEvent", "DataTransfer", "FileList", "File", "DomStringList", "IdbFactory", "IdbOpenDbRequest", "IdbRequest", "IdbDatabase", "IdbObjectStore", "IdbTransaction", "IdbTransactionMode", "MediaQueryList"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "ClipboardEvent", "DataTransfer", "FileList", "File", "DomStringList", "IdbFactory", "IdbOpenDbRequest", "IdbRequest", "IdbDatabase", "IdbObjectStore", "IdbTransaction", "IdbTransactionMode", "MediaQueryList", "Storage"] }
|
||||
|
||||
@@ -6,9 +6,15 @@
|
||||
//!
|
||||
//! Differences from the desktop app: no TCP control channel; Open and Insert › Pictures use the
|
||||
//! browser file picker (bytes arrive through `Services::inbox`); Save and Export download.
|
||||
//! Preferences (theme, interface size, editing options…) are kept in `localStorage` (`prefs`).
|
||||
//! URL flags: `?webgl` forces WebGL2; `?sample` opens the sample document.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod prefs;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod save_fallback;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Preferences between visits (#2132): the same [`UiState`] the desktop app keeps in `ui.json`
|
||||
//! (theme, interface size, recent symbols, editing options…), kept in the browser's
|
||||
//! `localStorage` under [`KEY`]. Restored at startup; written back whenever it changes, so a
|
||||
//! reload or a closed tab keeps the last setting (browsers don't reliably run exit code).
|
||||
|
||||
use wordcraft_ui_egui::{UiState, WordApp};
|
||||
|
||||
/// The `localStorage` key.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
pub const KEY: &str = "wordcraft.ui";
|
||||
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
|
||||
const MAX_STORED: usize = 4 << 20;
|
||||
|
||||
/// Apply preferences stored on an earlier visit. Missing, oversized or unreadable values leave
|
||||
/// the defaults.
|
||||
pub fn restore(app: &mut WordApp, stored: Option<&str>) {
|
||||
if let Some(s) = stored.filter(|s| s.len() <= MAX_STORED)
|
||||
&& let Some(ui) = UiState::from_json(s.as_bytes())
|
||||
{
|
||||
app.apply_prefs(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks what was last written, so the store is written only when a preference changed.
|
||||
#[derive(Default)]
|
||||
pub struct PrefsSync {
|
||||
last: Option<String>,
|
||||
}
|
||||
|
||||
impl PrefsSync {
|
||||
/// Starts from what is already stored, so restoring doesn't write it straight back.
|
||||
pub fn new(stored: Option<String>) -> Self {
|
||||
Self { last: stored }
|
||||
}
|
||||
|
||||
/// The JSON to store when the app's preferences differ from what was last written.
|
||||
pub fn changed(&mut self, app: &WordApp) -> Option<String> {
|
||||
let json = match serde_json::to_string(&app.prefs()) {
|
||||
Ok(j) => j,
|
||||
Err(e) => {
|
||||
log::warn!("preferences: cannot serialize: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if self.last.as_deref() == Some(json.as_str()) {
|
||||
return None;
|
||||
}
|
||||
self.last = Some(json.clone());
|
||||
Some(json)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use wordcraft_ui_egui::Services;
|
||||
|
||||
fn app() -> WordApp {
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_engine::sample::sample_document()), Services::default())
|
||||
}
|
||||
|
||||
/// #2132: dark mode chosen on one visit is there after a reload.
|
||||
#[test]
|
||||
fn dark_mode_survives_reload() {
|
||||
let mut first = app();
|
||||
let mut sync = PrefsSync::new(None);
|
||||
let initial = sync.changed(&first);
|
||||
assert!(initial.is_some(), "first frame stores the preferences");
|
||||
assert_eq!(sync.changed(&first), None, "unchanged preferences are not rewritten");
|
||||
first.run("ui.theme", json!({"value": "dark"})).unwrap();
|
||||
let stored = sync.changed(&first).expect("the theme change is stored");
|
||||
|
||||
let mut reloaded = app();
|
||||
restore(&mut reloaded, Some(&stored));
|
||||
assert_eq!(reloaded.ui.theme, wordcraft_ui_egui::theme::Appearance::Dark);
|
||||
assert_eq!(PrefsSync::new(Some(stored)).changed(&reloaded), None, "restoring doesn't write back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_storage_keeps_defaults() {
|
||||
for junk in [None, Some(""), Some("not json"), Some("[1,2]"), Some("{\"theme\":42}")] {
|
||||
let mut a = app();
|
||||
restore(&mut a, junk);
|
||||
assert_eq!(a.ui.theme, wordcraft_ui_egui::theme::Appearance::System, "junk keeps the default appearance");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Save-picker rejection policy, shared with native tests of the browser fallback.
|
||||
|
||||
use wordcraft_ui_egui::async_saves::SaveOutcome;
|
||||
|
||||
/// A cancelled picker ends the save. Other picker failures try the browser download path.
|
||||
/// Write/close errors do not pass through this function: they retain their own failure.
|
||||
pub(crate) fn picker_rejected(name: &str, download: impl FnOnce() -> Result<(), String>) -> SaveOutcome {
|
||||
if name == "AbortError" {
|
||||
SaveOutcome::Cancelled
|
||||
} else {
|
||||
match download() {
|
||||
Ok(()) => SaveOutcome::Saved,
|
||||
Err(error) => SaveOutcome::Failed(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unavailable_picker_downloads_once() {
|
||||
for name in ["SecurityError", "NotSupportedError", "TypeError", ""] {
|
||||
let mut calls = 0;
|
||||
let outcome = picker_rejected(name, || {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(outcome, SaveOutcome::Saved);
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_picker_never_downloads() {
|
||||
let outcome = picker_rejected("AbortError", || panic!("cancel must not download"));
|
||||
assert_eq!(outcome, SaveOutcome::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_fallback_remains_a_failed_save() {
|
||||
let outcome = picker_rejected("SecurityError", || Err("download unavailable".into()));
|
||||
assert_eq!(outcome, SaveOutcome::Failed("download unavailable".into()));
|
||||
}
|
||||
}
|
||||
@@ -65,11 +65,21 @@ pub fn start() {
|
||||
// Pasted pictures wait apart from dropped files: the app inserts one only when the page is the edit target (#1349).
|
||||
app.services.pasted = Some(pasted);
|
||||
app.autosave = false;
|
||||
// Preferences from an earlier visit (#2132), as the desktop app reads `ui.json`.
|
||||
let stored = stored_prefs();
|
||||
crate::prefs::restore(&mut app, stored.as_deref());
|
||||
// A region chosen in File › Options replaces the browser's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.session.set_document(doc);
|
||||
}
|
||||
let prefs = crate::prefs::PrefsSync::new(stored);
|
||||
// No document to show: start on File › Home, as the desktop app does (#766).
|
||||
if !sample {
|
||||
app.start_screen();
|
||||
}
|
||||
Ok(Box::new(WebShell { app, inbox, messages }))
|
||||
Ok(Box::new(WebShell { app, inbox, messages, prefs }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -92,6 +102,16 @@ struct WebShell {
|
||||
app: WordApp,
|
||||
inbox: Inbox,
|
||||
messages: Rc<RefCell<Vec<String>>>,
|
||||
prefs: crate::prefs::PrefsSync,
|
||||
}
|
||||
|
||||
fn local_storage() -> Option<web_sys::Storage> {
|
||||
web_sys::window()?.local_storage().ok()?
|
||||
}
|
||||
|
||||
/// The preferences stored on an earlier visit, if the browser allows storage.
|
||||
fn stored_prefs() -> Option<String> {
|
||||
local_storage()?.get_item(crate::prefs::KEY).ok()?
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
@@ -116,6 +136,17 @@ impl eframe::App for WebShell {
|
||||
self.app.status(msg);
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
// Store changed preferences straight away: a reload or closed tab runs no exit code (#2132).
|
||||
if let Some(json) = self.prefs.changed(&self.app) {
|
||||
match local_storage() {
|
||||
Some(store) => {
|
||||
if let Err(e) = store.set_item(crate::prefs::KEY, &json) {
|
||||
log::warn!("preferences: cannot save: {e:?}");
|
||||
}
|
||||
}
|
||||
None => log::warn!("preferences: browser storage is unavailable"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
@@ -193,13 +224,23 @@ fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: Asyn
|
||||
} else {
|
||||
rfd::AsyncFileDialog::new().add_filter("Documents", DOC_EXTS)
|
||||
};
|
||||
let many = purpose == "font";
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let Some(file) = dialog.pick_file().await else {
|
||||
return;
|
||||
};
|
||||
let bytes = file.read().await;
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
|
||||
ctx.request_repaint();
|
||||
// Add Font takes every selected file (#1789); the others one.
|
||||
let files = if many { dialog.pick_files().await.unwrap_or_default() } else { dialog.pick_file().await.into_iter().collect() };
|
||||
for file in files.into_iter().take(MAX_PICKED_FILES) {
|
||||
let mut bytes = file.read().await;
|
||||
let mut pending = inbox.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Fonts waiting for the app to drain them stay under a byte cap. A file
|
||||
// over it is queued empty, so Add Font reports that file on its own.
|
||||
let held: usize = pending.iter().map(|(_, b)| b.len()).fold(0, usize::saturating_add);
|
||||
if many && held.saturating_add(bytes.len()) > MAX_PENDING_PICKED_BYTES {
|
||||
bytes = Vec::new();
|
||||
}
|
||||
pending.push((file.file_name(), bytes));
|
||||
drop(pending);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
})),
|
||||
// Exports ask for a name; the browser decides where the download goes.
|
||||
@@ -219,6 +260,10 @@ fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: Asyn
|
||||
}
|
||||
}
|
||||
|
||||
/// Most files one multi-select pick (Add Font) reads.
|
||||
const MAX_PICKED_FILES: usize = 2000;
|
||||
/// Most bytes of picked fonts held in the inbox before the app drains them.
|
||||
const MAX_PENDING_PICKED_BYTES: usize = 256 << 20;
|
||||
/// Most local fonts one Load System Installed Fonts installs (a designer's machine has thousands).
|
||||
const MAX_SYSTEM_FONTS: usize = 500;
|
||||
/// Most font bytes one Load System Installed Fonts reads into memory (wasm memory is small).
|
||||
@@ -408,6 +453,7 @@ fn trigger_save_file_picker(
|
||||
let prom: js_sys::Promise = prom_val.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
|
||||
let bytes_vec = bytes.to_vec();
|
||||
let window = window.clone();
|
||||
let saves = saves.clone();
|
||||
let ctx = ctx.clone();
|
||||
let name = name.to_string();
|
||||
@@ -429,13 +475,10 @@ fn trigger_save_file_picker(
|
||||
Err(e) => {
|
||||
let err_name =
|
||||
js_sys::Reflect::get(&e, &wasm_bindgen::JsValue::from_str("name")).ok().and_then(|v| v.as_string()).unwrap_or_default();
|
||||
if err_name == "AbortError" {
|
||||
log::debug!("save picker cancelled");
|
||||
SaveOutcome::Cancelled
|
||||
} else {
|
||||
log::error!("showSaveFilePicker error: {e:?}");
|
||||
SaveOutcome::Failed(format!("{e:?}"))
|
||||
}
|
||||
// A browser can expose the picker but reject its promise (for example in
|
||||
// a cross-origin iframe). Use the same download path as an absent API;
|
||||
// cancelling a picker must never start an unwanted download (#1246).
|
||||
crate::save_fallback::picker_rejected(&err_name, || trigger_anchor_download(&window, &name, &bytes_vec))
|
||||
}
|
||||
};
|
||||
saves.finish(ticket, outcome);
|
||||
|
||||
@@ -38,8 +38,12 @@ fmv-macos-events = "=0.1.0"
|
||||
# NSWorkspace: a safe call in these bindings. Already in the build through eframe, rfd and arboard,
|
||||
# at this version; this adds the `NSAccessibility` bindings and, to fit the title bar around the
|
||||
# traffic lights, the window, button and view ones.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication", "NSWindow", "NSButton", "NSControl", "NSView", "NSResponder"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication", "NSWindow", "NSButton", "NSControl", "NSView", "NSResponder", "NSPasteboard"] }
|
||||
objc2 = "0.6"
|
||||
# A copied equation's MathML goes on the pasteboard as `public.mathml.presentation` beside
|
||||
# arboard's HTML and text (#1297), through NSPasteboard's safe `setString:forType:`. Already in
|
||||
# the build through arboard, at this version; this adds only the NSString bindings.
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }
|
||||
# Closing the window must quit through NSApplication rather than by dropping the NSWindow
|
||||
# inside the AppKit run loop (see `schedule_macos_terminate`).
|
||||
dispatch2 = "0.3"
|
||||
|
||||
@@ -10,9 +10,14 @@
|
||||
//! Everything read here comes from other programs: sizes are capped as it is read.
|
||||
//!
|
||||
//! Written here: a copy puts HTML beside its text, so other programs keep its formatting (#1523),
|
||||
//! with equations as MathML (#816; pasting into Word and LibreOffice not yet verified). arboard sets HTML with a
|
||||
//! text alternative on every desktop platform; formats of other names (Word's "Office Open XML"
|
||||
//! with OMML, #1297) it can't, so they aren't offered.
|
||||
//! with equations as MathML (#816). arboard sets HTML with a text alternative on every desktop
|
||||
//! platform. A copy of one equation alone also goes in the platform's MathML formats (#1297),
|
||||
//! added beside arboard's: on Windows "MathML" and "MathML Presentation" (UTF-16LE), on macOS
|
||||
//! `public.mathml.presentation` and `public.mathml` — the names W3C MathML 3 §6.2.4 registers
|
||||
//! for transferring MathML, and the ones Microsoft documents its Office apps reading first when
|
||||
//! they paste math (learn.microsoft.com/office/math/mathml, "Clipboard support"). Pasting into
|
||||
//! Word and LibreOffice is not yet verified. Linux and the BSDs have no Word, and arboard can't
|
||||
//! add MIME types of other names, so there the HTML carries the MathML alone.
|
||||
|
||||
use wordcraft_engine::cmd::paste::MAX_PASTE_BYTES;
|
||||
use wordcraft_ui_egui::paste_picture::ClipboardPicture;
|
||||
@@ -26,13 +31,24 @@ thread_local! {
|
||||
static WRITER: std::cell::RefCell<Option<arboard::Clipboard>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Put `html` on the clipboard with `text` as its plain-text alternative. `false` when it couldn't
|
||||
/// (the caller copies the text alone), including a Wayland session without the data-control
|
||||
/// protocol, where arboard would fall back to X11 and native Wayland programs might not see it.
|
||||
pub fn set_html(html: &str, text: &str) -> bool {
|
||||
/// Put `html` on the clipboard with `text` as its plain-text alternative, and `mathml` (a copy of
|
||||
/// one equation alone; empty for any other copy) in the platform's MathML formats. `false` when
|
||||
/// the HTML and text couldn't be set (the caller copies the text alone), including a Wayland
|
||||
/// session without the data-control protocol, where arboard would fall back to X11 and native
|
||||
/// Wayland programs might not see it. MathML that can't be added is logged: the HTML still
|
||||
/// carries it.
|
||||
pub fn set_html(html: &str, text: &str, mathml: &str) -> bool {
|
||||
if !platform::can_set() {
|
||||
return false;
|
||||
}
|
||||
let set = set_html_text(html, text);
|
||||
if set && !mathml.is_empty() && mathml.len() <= MAX_PASTE_BYTES {
|
||||
platform::add_mathml(mathml);
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
fn set_html_text(html: &str, text: &str) -> bool {
|
||||
WRITER.with(|w| {
|
||||
let Ok(mut slot) = w.try_borrow_mut() else { return false };
|
||||
if slot.is_none() {
|
||||
@@ -146,6 +162,9 @@ mod platform {
|
||||
)
|
||||
}
|
||||
|
||||
/// arboard serves its own MIME types only; Word, which reads the MathML formats, isn't here.
|
||||
pub fn add_mathml(_mathml: &str) {}
|
||||
|
||||
pub fn rtf() -> Option<Vec<u8>> {
|
||||
if !wayland() {
|
||||
return None;
|
||||
@@ -193,9 +212,68 @@ mod platform {
|
||||
pub fn can_set() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Add the MathML to what arboard just set, as "MathML" and "MathML Presentation": UTF-16LE
|
||||
/// text (with its terminating NUL, as Windows text formats have).
|
||||
pub fn add_mathml(mathml: &str) {
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else {
|
||||
log::warn!("clipboard: couldn't open it to add MathML");
|
||||
return;
|
||||
};
|
||||
let bytes: Vec<u8> = mathml.encode_utf16().chain(std::iter::once(0)).flat_map(u16::to_le_bytes).collect();
|
||||
for name in super::MATHML_FORMATS {
|
||||
let Some(format) = raw::register_format(name) else { continue };
|
||||
if let Err(e) = raw::set_without_clear(format.get(), &bytes) {
|
||||
log::warn!("clipboard: {name}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "windows", all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))))))]
|
||||
/// The clipboard format names for MathML that Windows programs read (W3C MathML 3 §6.2.4; Office
|
||||
/// reads and writes both).
|
||||
#[cfg(target_os = "windows")]
|
||||
const MATHML_FORMATS: [&str; 2] = ["MathML", "MathML Presentation"];
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod platform {
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::NSString;
|
||||
|
||||
pub fn formats() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub fn rtf() -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn encoded_picture() -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn can_set() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Add the MathML to the pasteboard item arboard just wrote, as the MathML types (W3C MathML 3
|
||||
/// §6.2.4): presentation markup, and the generic type for readers that only know that one.
|
||||
pub fn add_mathml(mathml: &str) {
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
let text = NSString::from_str(mathml);
|
||||
for name in ["public.mathml.presentation", "public.mathml"] {
|
||||
if !board.setString_forType(&text, &NSString::from_str(name)) {
|
||||
log::warn!("clipboard: couldn't add {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten")))
|
||||
)))]
|
||||
mod platform {
|
||||
pub fn formats() -> Vec<String> {
|
||||
Vec::new()
|
||||
@@ -212,4 +290,6 @@ mod platform {
|
||||
pub fn can_set() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn add_mathml(_mathml: &str) {}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,12 @@
|
||||
//! thread first checks that one of them is there and otherwise answers with an error, and the app
|
||||
//! shows its built-in file browser. `WORDCRAFT_FILE_DIALOG=builtin` always uses the built-in one.
|
||||
//!
|
||||
//! On Linux and the BSDs, rfd reports a portal that failed to show its dialog as a cancel (#2999).
|
||||
//! There a cancel quicker than anyone could dismiss a dialog is taken as that failure: the dialog
|
||||
//! is asked for once more without a parent window, and if that also comes back at once the
|
||||
//! built-in browser shows. Windows and macOS always show their dialog, so a quick cancel there is
|
||||
//! the person's and is answered as one.
|
||||
//!
|
||||
//! [`Services::file_dialog`]: wordcraft_ui_egui::Services::file_dialog
|
||||
|
||||
use std::future::Future;
|
||||
@@ -27,7 +33,7 @@ type Request = (FileDialogRequest, Sender<FileDialogAnswer>);
|
||||
pub type Hook = Box<dyn Fn(FileDialogRequest) -> Receiver<FileDialogAnswer>>;
|
||||
|
||||
/// A picker's answer, waited for off the UI thread.
|
||||
type Picking = Pin<Box<dyn Future<Output = Option<rfd::FileHandle>> + Send>>;
|
||||
type Picking = Pin<Box<dyn Future<Output = Vec<rfd::FileHandle>> + Send>>;
|
||||
|
||||
/// Shows the dialogs the app queued; lives in the eframe app, which has the window.
|
||||
pub struct Launcher {
|
||||
@@ -54,23 +60,22 @@ impl Launcher {
|
||||
pub fn show(&self, parent: &eframe::Frame) {
|
||||
while let Ok((req, answer)) = self.queue.try_recv() {
|
||||
// Built here, on the UI thread: macOS shows the panel as a sheet on the window now.
|
||||
let dialog = rfd::AsyncFileDialog::new().set_parent(parent);
|
||||
let picking: Picking = match req {
|
||||
FileDialogRequest::Open { purpose } => Box::pin(open_filters(dialog, &purpose).pick_file()),
|
||||
FileDialogRequest::Save { name } => {
|
||||
let mut dialog = dialog.set_file_name(name.clone());
|
||||
for (label, exts) in save_filters(&name) {
|
||||
dialog = dialog.add_filter(label, &exts);
|
||||
}
|
||||
Box::pin(dialog.save_file())
|
||||
}
|
||||
};
|
||||
let picking = picker(rfd::AsyncFileDialog::new().set_parent(parent), &req);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let unparented = picker(rfd::AsyncFileDialog::new(), &req);
|
||||
let ctx = self.ctx.clone();
|
||||
let waiting = std::thread::Builder::new().name("file dialog".into()).spawn(move || {
|
||||
// The picker only starts when first polled: without a system dialog it never does.
|
||||
// The pickers only start when first polled: without a system dialog they never do.
|
||||
let picked = match no_system_dialog() {
|
||||
Some(reason) => Err(reason),
|
||||
None => Ok(pollster::block_on(picking).map(|f| f.path().to_string_lossy().to_string())),
|
||||
None => {
|
||||
// Only the portal folds a failure into "cancelled" (#2999).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let picked = pick(picking, unparented, TOO_QUICK);
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let picked: Result<_, String> = Ok(pollster::block_on(picking));
|
||||
picked.map(|f| f.iter().map(|f| f.path().to_string_lossy().to_string()).collect())
|
||||
}
|
||||
};
|
||||
let _ = answer.send(picked);
|
||||
ctx.request_repaint();
|
||||
@@ -83,6 +88,53 @@ impl Launcher {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker for `req` on `dialog`.
|
||||
fn picker(dialog: rfd::AsyncFileDialog, req: &FileDialogRequest) -> Picking {
|
||||
match req.clone() {
|
||||
FileDialogRequest::Open { purpose } => Box::pin(async move { open_filters(dialog, &purpose).pick_file().await.into_iter().collect() }),
|
||||
FileDialogRequest::OpenMany { purpose } => Box::pin(async move { open_filters(dialog, &purpose).pick_files().await.unwrap_or_default() }),
|
||||
FileDialogRequest::Save { name } => {
|
||||
let mut dialog = dialog.set_file_name(name.clone());
|
||||
for (label, exts) in save_filters(&name) {
|
||||
dialog = dialog.add_filter(label, &exts);
|
||||
}
|
||||
Box::pin(async move { dialog.save_file().await.into_iter().collect() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quicker than anyone can see a dialog and dismiss it.
|
||||
// ponytail: a timing heuristic, as rfd folds the portal's failure code into "cancelled". A portal
|
||||
// failing slower than this still reads as a cancel; ask rfd for the response code if it matters.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
const TOO_QUICK: std::time::Duration = std::time::Duration::from_millis(300);
|
||||
|
||||
/// Wait for `picking`. Nothing picked within `too_quick` is a portal that failed to show its
|
||||
/// dialog (#2999), not a person cancelling: try `unparented`, as a portal may fail on the parent
|
||||
/// window; if that too comes back at once, an error, so the app shows its built-in browser.
|
||||
/// Linux and the BSDs only (built everywhere for its test).
|
||||
#[cfg(any(test, all(unix, not(target_os = "macos"))))]
|
||||
fn pick<T>(
|
||||
picking: impl Future<Output = Vec<T>>,
|
||||
unparented: impl Future<Output = Vec<T>>,
|
||||
too_quick: std::time::Duration,
|
||||
) -> Result<Vec<T>, String> {
|
||||
fn timed<T>(f: impl Future<Output = Vec<T>>, too_quick: std::time::Duration) -> (Vec<T>, bool) {
|
||||
let start = std::time::Instant::now();
|
||||
let picked = pollster::block_on(f);
|
||||
let quick = picked.is_empty() && start.elapsed() < too_quick;
|
||||
(picked, quick)
|
||||
}
|
||||
match timed(picking, too_quick) {
|
||||
(_, true) => log::warn!("the system file dialog closed at once; asking again without a parent window"),
|
||||
(picked, false) => return Ok(picked),
|
||||
}
|
||||
match timed(unparented, too_quick) {
|
||||
(_, true) => Err("the system file dialog closed at once".into()),
|
||||
(picked, false) => Ok(picked),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file types Open offers (shared with the built-in browser).
|
||||
fn open_filters(mut d: rfd::AsyncFileDialog, purpose: &str) -> rfd::AsyncFileDialog {
|
||||
for (name, exts) in wordcraft_ui_egui::open_filters(purpose) {
|
||||
@@ -193,7 +245,24 @@ fn format_name(ext: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{save_exts, save_filters};
|
||||
use super::{pick, save_exts, save_filters};
|
||||
use std::time::Duration;
|
||||
|
||||
/// #2999: a dialog that "cancels" at once is a portal that failed: asked again without a
|
||||
/// parent, then the built-in browser. A pick, or a cancel after a while, is the answer.
|
||||
#[test]
|
||||
fn an_instant_cancel_retries_then_falls_back() {
|
||||
let quick = Duration::from_millis(200);
|
||||
let slow_cancel = || async {
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
Vec::<u8>::new()
|
||||
};
|
||||
assert_eq!(pick(async { vec![1u8] }, async { vec![2] }, quick), Ok(vec![1]));
|
||||
assert_eq!(pick(async { vec![] }, async { vec![2u8] }, quick), Ok(vec![2]), "asked again without a parent");
|
||||
assert!(pick(async { Vec::<u8>::new() }, async { vec![] }, quick).is_err(), "the built-in browser");
|
||||
assert_eq!(pick(slow_cancel(), async { vec![2u8] }, quick), Ok(vec![]), "a real cancel isn't asked again");
|
||||
assert_eq!(pick(async { vec![] }, slow_cancel(), quick), Ok(vec![]), "the second dialog cancelled for real");
|
||||
}
|
||||
|
||||
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
|
||||
/// every savable extension exactly once.
|
||||
|
||||
@@ -1,12 +1,37 @@
|
||||
//! Windows graphics instance configuration (backends and the DirectX 12 shader compiler), applied
|
||||
//! before wgpu can initialize any driver.
|
||||
//! Graphics instance configuration applied before wgpu can initialize any driver: Windows
|
||||
//! backends and the DirectX 12 shader compiler, and the Intel Mac indirect-validation skip.
|
||||
// On macOS only the indirect-validation items are used outside tests. Elsewhere it is the other
|
||||
// way round, so those two carry their own `allow`.
|
||||
#![cfg_attr(target_os = "macos", allow(dead_code))]
|
||||
|
||||
use eframe::{
|
||||
NativeOptions,
|
||||
egui_wgpu::WgpuSetup,
|
||||
wgpu::{Backends, DeviceType, Dx12Compiler},
|
||||
wgpu::{Backends, DeviceType, Dx12Compiler, InstanceFlags},
|
||||
};
|
||||
|
||||
/// wgpu compiles its indirect-call validation compute shaders inside `request_device`. On old
|
||||
/// Intel Macs (HD Graphics 5000 on Big Sur, #2652) Metal's Intel
|
||||
/// compiler aborts on them, the device is lost and eframe exits before the window opens. WordCraft
|
||||
/// issues no indirect draws or dispatches, so Intel Macs skip them; every other GPU keeps wgpu's
|
||||
/// default. Same fix as PhotoCraft's storytold/PhotoCraft#3171.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub fn skips_indirect_validation(macos: bool, intel: bool) -> bool {
|
||||
macos && intel
|
||||
}
|
||||
|
||||
/// Leaves wgpu's indirect-call validation out of the instance eframe creates when `skip`.
|
||||
/// `WGPU_VALIDATION_INDIRECT_CALL=1` still turns it back on.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub fn configure_indirect_validation(options: &mut NativeOptions, skip: bool) {
|
||||
if !skip {
|
||||
return;
|
||||
}
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.instance_descriptor.flags = create.instance_descriptor.flags.difference(InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
|
||||
}
|
||||
}
|
||||
|
||||
/// What the start-up probe learned about one DirectX 12 adapter.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Dx12Adapter {
|
||||
@@ -153,6 +178,33 @@ fn probe_dx12(options: &NativeOptions) -> Vec<Dx12Adapter> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn intel_macs_skip_the_indirect_validation_shaders() {
|
||||
// #2652: Metal's Intel compiler aborted on them, losing the device before the window opened.
|
||||
assert!(skips_indirect_validation(true, true));
|
||||
// Apple silicon, Windows and Linux keep wgpu's validation.
|
||||
for (macos, intel) in [(true, false), (false, true), (false, false)] {
|
||||
assert!(!skips_indirect_validation(macos, intel), "macos={macos} intel={intel}");
|
||||
}
|
||||
let mut options = NativeOptions::default();
|
||||
let WgpuSetup::CreateNew(before) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
let before = before.instance_descriptor.flags;
|
||||
configure_indirect_validation(&mut options, false);
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert_eq!(create.instance_descriptor.flags, before, "flags untouched when not skipping");
|
||||
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
|
||||
configure_indirect_validation(&mut options, true);
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(!create.instance_descriptor.flags.contains(InstanceFlags::VALIDATION_INDIRECT_CALL));
|
||||
}
|
||||
}
|
||||
|
||||
fn configured_backends(backends: Backends) -> Backends {
|
||||
let mut options = NativeOptions::default();
|
||||
configure_backends(&mut options, backends);
|
||||
|
||||
@@ -16,7 +16,7 @@ mod clipboard;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod file_dialogs;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", test))]
|
||||
mod graphics;
|
||||
mod logging;
|
||||
mod print;
|
||||
@@ -389,6 +389,9 @@ fn main() -> eframe::Result {
|
||||
// FXC, which needs no DLL of ours (#603; see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env());
|
||||
// Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (#2652).
|
||||
#[cfg(target_os = "macos")]
|
||||
graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64")));
|
||||
load_user_fonts();
|
||||
let restored = saved_window();
|
||||
if let Some(window) = restored {
|
||||
|
||||
@@ -119,6 +119,7 @@ display_name = "The Legend Of MTS Dev"
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
[people.rbr48]
|
||||
real_name = "M S Rana"
|
||||
@@ -135,3 +136,33 @@ sync_github_name = false
|
||||
real_name = "Andrej Škvorc"
|
||||
display_name = "Andrej Škvorc"
|
||||
sync_github_name = false
|
||||
|
||||
[people.olekkut]
|
||||
real_name = "Aleksander Kutycki"
|
||||
display_name = "Aleksander Kutycki"
|
||||
sync_github_name = true
|
||||
|
||||
[people.marcoarnulfo]
|
||||
real_name = "Marco Arnulfo"
|
||||
display_name = "Marco Arnulfo"
|
||||
sync_github_name = false
|
||||
|
||||
[people.rem5411]
|
||||
real_name = "Vivien Janny"
|
||||
sync_github_name = true
|
||||
|
||||
[people.C00kieMonsta]
|
||||
real_name = "Antoine Boxho"
|
||||
sync_github_name = true
|
||||
|
||||
[people.matteo-andreuzza]
|
||||
sync_github_name = true
|
||||
|
||||
[people.lucAmbr0]
|
||||
sync_github_name = true
|
||||
|
||||
[people.maxm11]
|
||||
real_name = "Max Murphy"
|
||||
|
||||
[people.SlavenDj]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -38,6 +38,9 @@ pub struct ShapeExtra {
|
||||
/// 100000ths of the shorter side, at most [`MAX_CORNER`]; `None` draws [`DEFAULT_CORNER`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub corner: Option<u32>,
|
||||
/// The outline dash pattern; absent in older saved documents means solid.
|
||||
#[serde(skip_serializing_if = "crate::line_dash::LineDash::is_solid")]
|
||||
pub dash: crate::line_dash::LineDash,
|
||||
}
|
||||
|
||||
fn is_zero(v: &u32) -> bool {
|
||||
|
||||
@@ -242,6 +242,10 @@ pub struct ContentControl {
|
||||
/// The run properties of `w:sdtPr` (`w:rPr`), kept verbatim (XML).
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub rpr_xml: String,
|
||||
/// The same run properties, read: the formatting text typed in place of the placeholder
|
||||
/// takes (ECMA-376 §17.5.2.27). `None` when the control names none.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub run_props: Option<crate::props::CharProps>,
|
||||
/// Other `w:sdtPr` children we don't model, kept verbatim (XML) in file order.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra: Vec<String>,
|
||||
|
||||
+398
-31
@@ -40,11 +40,76 @@ impl Fragment {
|
||||
}
|
||||
found
|
||||
}
|
||||
/// The equation (its linear format and whether it is a display equation) when the fragment
|
||||
/// is that one equation and nothing else but white space and empty paragraphs: a copy of it
|
||||
/// also goes on the system clipboard in the MathML formats that equation editors read (#1297).
|
||||
pub fn sole_equation(&self) -> Option<(&str, bool)> {
|
||||
let mut found = None;
|
||||
for b in &self.blocks {
|
||||
let Block::Para(p) = b else { return None };
|
||||
for c in p.text.chars().filter(|c| !c.is_whitespace()) {
|
||||
if c != crate::para::OBJ || found.is_some() {
|
||||
return None;
|
||||
}
|
||||
// The paragraph's only visible character, so its first object.
|
||||
match p.objects.first() {
|
||||
Some(InlineObject::Equation { linear, display, .. }) => found = Some((linear.as_str(), *display)),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
/// The text a copy puts on the clipboard: [`Self::plain_text`] with symbol-font characters
|
||||
/// (Wingdings…) as their Unicode equivalents.
|
||||
pub fn clipboard_text(&self) -> String {
|
||||
self.to_document().shown_text(crate::StoryRef::Body)
|
||||
}
|
||||
/// Add `piece` at the end, followed by a paragraph mark unless it already ends with one: how
|
||||
/// Word's Spike collects what it cuts. The piece's text box stories get ids after this
|
||||
/// fragment's, so pieces copied from different documents (or after an id was freed and reused)
|
||||
/// never share one.
|
||||
pub fn append_piece(&mut self, mut piece: Fragment) {
|
||||
let Some(last) = piece.blocks.last() else { return };
|
||||
let ends_with_mark = piece.blocks.len() >= 2 && matches!(last, Block::Para(p) if p.is_empty());
|
||||
if !ends_with_mark {
|
||||
let mut mark = Paragraph::new();
|
||||
if let Block::Para(p) = last {
|
||||
mark.props = p.props.clone();
|
||||
}
|
||||
piece.blocks.push(Block::Para(mark));
|
||||
}
|
||||
let next = self.parts.keys().next_back().map_or(1, |k| k.saturating_add(1));
|
||||
let ids: BTreeMap<u32, u32> = piece.parts.keys().zip(next..=u32::MAX).map(|(old, new)| (*old, new)).collect();
|
||||
let renumber = |b: &mut Block| {
|
||||
each_para_mut(b, 0, &mut |p| {
|
||||
let mut changed = false;
|
||||
for o in p.objects.iter_mut() {
|
||||
for slot in o.text_box_slots() {
|
||||
if let Some(new) = slot.and_then(|old| ids.get(&old)) {
|
||||
*slot = Some(*new);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
p.touch();
|
||||
}
|
||||
})
|
||||
};
|
||||
piece.blocks.iter_mut().for_each(renumber);
|
||||
for (old, mut part) in std::mem::take(&mut piece.parts) {
|
||||
part.blocks.iter_mut().map(Arc::make_mut).for_each(renumber);
|
||||
if let Some(new) = ids.get(&old) {
|
||||
self.parts.insert(*new, part);
|
||||
}
|
||||
}
|
||||
// The empty paragraph after the last mark is where the next piece starts.
|
||||
if self.blocks.len() >= 2 && matches!(self.blocks.last(), Some(Block::Para(p)) if p.is_empty()) {
|
||||
self.blocks.pop();
|
||||
}
|
||||
self.blocks.append(&mut piece.blocks);
|
||||
}
|
||||
pub fn from_text(s: &str) -> Fragment {
|
||||
let lines: Vec<&str> = s.split('\n').collect();
|
||||
Fragment {
|
||||
@@ -54,6 +119,19 @@ impl Fragment {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether block `b`, in a block list the paragraph walk reaches at `depth`, has cells the walk
|
||||
/// skips ([`crate::PARA_WALK_DEPTH`]). Bounded by that depth.
|
||||
fn deeper_than_walk(b: &Block, depth: usize) -> bool {
|
||||
match b {
|
||||
Block::Para(_) => false,
|
||||
Block::Table(t) => t
|
||||
.rows
|
||||
.iter()
|
||||
.flat_map(|r| &r.cells)
|
||||
.any(|c| depth + 1 > crate::PARA_WALK_DEPTH || c.blocks.iter().any(|x| deeper_than_walk(x, depth + 1))),
|
||||
}
|
||||
}
|
||||
|
||||
fn order(a: &Pos, b: &Pos) -> (Pos, Pos) {
|
||||
if a <= b { (a.clone(), b.clone()) } else { (b.clone(), a.clone()) }
|
||||
}
|
||||
@@ -314,7 +392,12 @@ impl Document {
|
||||
if a.story != b.story {
|
||||
return Vec::new();
|
||||
}
|
||||
self.para_paths(a.story).into_iter().filter(|p| *p >= a.path && *p <= b.path).collect()
|
||||
// Only the blocks the range reaches are walked (not every paragraph of the story).
|
||||
let mut out = Vec::new();
|
||||
if let Some(bl) = self.story(a.story) {
|
||||
crate::walk_between(bl, &mut Vec::new(), &mut out, 0, (&a.path.0, &b.path.0));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Delete `a..b`. Returns the position where the deletion collapsed to. On error the document
|
||||
@@ -372,18 +455,42 @@ impl Document {
|
||||
pb.clone()
|
||||
};
|
||||
let bl = self.container_mut(a.story, &a.path)?;
|
||||
// Section breaks on the marks in between go with their paragraphs.
|
||||
let between: Vec<_> = bl
|
||||
.get(ia + 1..ib)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|b| match &**b {
|
||||
Block::Para(p) => p.section.clone(),
|
||||
Block::Table(_) => None,
|
||||
})
|
||||
.collect();
|
||||
if ib < bl.len() && ia < ib {
|
||||
bl.drain(ia + 1..=ib);
|
||||
}
|
||||
tail.props = ParaProps::default();
|
||||
// The deleted marks include `a`'s, so a section break there goes too: the joined
|
||||
// paragraph ends where `b`'s mark did, and its text takes the following section's
|
||||
// setup, as in Word (#2127).
|
||||
let sect = tail.section.take();
|
||||
let pa = self.para_mut(a.story, &a.path)?;
|
||||
let keep_props = pa.props.clone();
|
||||
pa.append(tail);
|
||||
pa.props = keep_props;
|
||||
let before = std::mem::replace(&mut pa.section, sect);
|
||||
if a.story == crate::StoryRef::Body && a.path.0.len() == 1 {
|
||||
// Nearest first, as "link to previous" resolved them before the delete.
|
||||
let following = self.section_mut(a.path.last());
|
||||
for s in between.iter().rev().chain(before.iter()) {
|
||||
following.absorb(s);
|
||||
}
|
||||
}
|
||||
return Ok(a);
|
||||
}
|
||||
// Different containers (range enters or leaves a table): clear text in every paragraph
|
||||
// inside; remove whole tables that are entirely covered when at the same level as `a`.
|
||||
// inside, then remove the tables it covers whole (below).
|
||||
// Whether `b` is at its paragraph's end, before that paragraph is trimmed.
|
||||
let b_at_end = self.para(b.story, &b.path).is_some_and(|p| p.len() == b.off);
|
||||
let paths = self.paths_between(&a, &b);
|
||||
for p in paths.iter().rev() {
|
||||
let (from, to) = {
|
||||
@@ -394,41 +501,68 @@ impl Document {
|
||||
};
|
||||
self.para_mut(a.story, p)?.delete_except(from, to, &kept_in(p))?;
|
||||
}
|
||||
// Drop top-level tables strictly between a and b at a's level.
|
||||
if a.path.depth() == 0 && b.path.depth() > 0 {
|
||||
let first_b = b.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let ia = a.path.last();
|
||||
let bl = self.container_mut(a.story, &a.path)?;
|
||||
let mut i = first_b;
|
||||
while i > ia + 1 {
|
||||
i -= 1;
|
||||
// Tables the range covers whole, in the innermost container holding both ends, go (#1198,
|
||||
// #1844): those strictly between the ends, the one `a` is in when it starts at that
|
||||
// table's very start, and the one `b` is in when it ends at that table's very end. A range
|
||||
// that is one table and nothing else only empties it (Word's Delete keeps the table).
|
||||
let common = a.path.0.iter().zip(&b.path.0).take_while(|(x, y)| x == y).count();
|
||||
let level = common - common % 3;
|
||||
let (Some(&ia), Some(&ib)) = (a.path.0.get(level), b.path.0.get(level)) else { return Ok(a) };
|
||||
let (ia, ib) = (ia as usize, ib as usize);
|
||||
if ia >= ib {
|
||||
return Ok(a);
|
||||
}
|
||||
let prefix = a.path.0.get(..level).unwrap_or_default().to_vec();
|
||||
let block_path = |i: usize| {
|
||||
let mut v = prefix.clone();
|
||||
v.push(i as u32);
|
||||
Path(v)
|
||||
};
|
||||
// Paragraphs inside the block at index `i` of the container, in document order.
|
||||
let paths = self.para_paths(a.story);
|
||||
let inside = |i: usize| -> Vec<&Path> {
|
||||
let pre = block_path(i);
|
||||
paths.iter().filter(|q| q.0.len() > pre.0.len() && q.0.starts_with(&pre.0)).collect()
|
||||
};
|
||||
// A table with cells deeper than the paragraph walk goes has paragraphs `inside` never
|
||||
// lists, so where it starts or ends isn't known: it is never taken as covered.
|
||||
let walked = |i: usize| self.container(a.story, &block_path(i)).and_then(|bl| bl.get(i)).is_some_and(|b| !deeper_than_walk(b, level / 3));
|
||||
let a_covers = a.path.0.len() > level + 1 && a.off == 0 && walked(ia) && inside(ia).first() == Some(&&a.path);
|
||||
let b_covers = b.path.0.len() > level + 1 && walked(ib) && inside(ib).last() == Some(&&b.path) && b_at_end;
|
||||
let first = if a_covers { ia } else { ia + 1 };
|
||||
let last = if b_covers { ib } else { ib - 1 };
|
||||
let mut removed = 0;
|
||||
{
|
||||
let bl = self.container_mut(a.story, &block_path(ia))?;
|
||||
for i in (first..=last.min(bl.len().saturating_sub(1))).rev() {
|
||||
if matches!(bl.get(i).map(|b| &**b), Some(Block::Table(_))) {
|
||||
bl.remove(i);
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// From the very start of a top-level table to a top-level paragraph (Select All in a
|
||||
// document that starts with a table, #1198): the tables are covered whole and go too,
|
||||
// and the paragraphs left between join.
|
||||
if a.path.depth() > 0 && b.path.depth() == 0 && a.off == 0 {
|
||||
let ta = a.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let first = self.para_paths(a.story).into_iter().find(|q| q.0.first().is_some_and(|t| *t as usize == ta));
|
||||
if first.as_ref() == Some(&a.path) {
|
||||
let ib = b.path.last();
|
||||
let bl = self.container_mut(a.story, &b.path)?;
|
||||
let mut removed = 0;
|
||||
for i in (ta..ib).rev() {
|
||||
if matches!(bl.get(i).map(|b| &**b), Some(Block::Table(_))) {
|
||||
bl.remove(i);
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
let at = Pos { story: a.story, path: Path::top(ta), off: 0 };
|
||||
let end = Pos { story: a.story, path: Path::top(ib.saturating_sub(removed)), off: 0 };
|
||||
return self.delete_range(&at, &end);
|
||||
if removed == 0 {
|
||||
return Ok(a);
|
||||
}
|
||||
// A story or cell always ends with a paragraph.
|
||||
if bl.is_empty() || matches!(bl.last().map(|b| &**b), Some(Block::Table(_))) {
|
||||
bl.push(para_block(Paragraph::new()));
|
||||
}
|
||||
}
|
||||
Ok(a)
|
||||
// The paragraphs left between the ends join, as in a range within one container.
|
||||
let at = if a_covers { Pos { story: a.story, path: block_path(ia), off: 0 } } else { a.clone() };
|
||||
let end = if b_covers {
|
||||
Pos { story: a.story, path: block_path((ib + 1).saturating_sub(removed)), off: 0 }
|
||||
} else {
|
||||
Pos { story: a.story, path: block_path(ib.saturating_sub(removed)), off: 0 }
|
||||
};
|
||||
let paras = |p: &Pos| p.path.0.len() == level + 1 && self.para(p.story, &p.path).is_some();
|
||||
if paras(&at) && paras(&end) && at.path <= end.path {
|
||||
return self.delete_range(&at, &end);
|
||||
}
|
||||
if self.para(at.story, &at.path).is_some() {
|
||||
return Ok(at);
|
||||
}
|
||||
Ok(self.clamp(&at))
|
||||
}
|
||||
|
||||
/// Apply `f` to the character formatting of `a..b`. A collapsed range changes nothing (the
|
||||
@@ -694,6 +828,27 @@ mod tests {
|
||||
Document::from_text(&lines.join("\n"))
|
||||
}
|
||||
|
||||
/// Paths between two positions are those of all the story's paragraphs between them.
|
||||
#[test]
|
||||
fn paths_between_matches_every_path_filtered() {
|
||||
let mut d = doc(&["a", "b", "c", "d", "e"]);
|
||||
let mut inner = Table::new(2, 2, 100.0);
|
||||
inner.rows[1].cells[0].blocks.push(crate::para_block(crate::Paragraph::new()));
|
||||
let mut t = Table::new(3, 2, 200.0);
|
||||
t.rows[1].cells[1].blocks.insert(0, Arc::new(Block::Table(inner)));
|
||||
d.insert_block(StoryRef::Body, &Path::top(2), Block::Table(t)).unwrap();
|
||||
d.insert_block(StoryRef::Body, &Path::top(4), Block::Table(Table::new(1, 3, 200.0))).unwrap();
|
||||
let all = d.para_paths(StoryRef::Body);
|
||||
for a in &all {
|
||||
for b in &all {
|
||||
let (pa, pb) = (Pos { story: StoryRef::Body, path: a.clone(), off: 0 }, Pos { story: StoryRef::Body, path: b.clone(), off: 0 });
|
||||
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
||||
let want: Vec<Path> = all.iter().filter(|p| *p >= lo && *p <= hi).cloned().collect();
|
||||
assert_eq!(d.paths_between(&pa, &pb), want, "{a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_and_join() {
|
||||
let mut d = doc(&["Hello world"]);
|
||||
@@ -737,6 +892,29 @@ mod tests {
|
||||
assert_eq!(d.body.len(), 1);
|
||||
}
|
||||
|
||||
/// #2127: a range over two section breaks joins three sections into the last; the headers
|
||||
/// and footers it showed by linking to earlier ones stay, each from the nearest section that
|
||||
/// named it, as they resolved before the delete.
|
||||
#[test]
|
||||
fn delete_over_two_section_breaks_keeps_the_linked_headers() {
|
||||
let mut d = doc(&["A", "B", "C"]);
|
||||
let set = |default| crate::section::HeaderSet { default: Some(default), ..Default::default() };
|
||||
let s1 = crate::section::SectionProps { headers: set(1), footers: set(5), ..Default::default() };
|
||||
let s2 = crate::section::SectionProps { headers: set(2), ..Default::default() };
|
||||
let s3 = crate::section::SectionProps { margin_left: 99.0, ..Default::default() };
|
||||
for (i, s) in [(0, s1), (1, s2), (2, s3.clone())] {
|
||||
if let Some(Block::Para(p)) = d.body.get_mut(i).map(Arc::make_mut) {
|
||||
p.section = Some(Box::new(s));
|
||||
}
|
||||
}
|
||||
assert_eq!(d.sections().len(), 4);
|
||||
d.delete_range(&Pos::body(0, 1), &Pos::body(2, 0)).unwrap();
|
||||
assert_eq!(d.plain_text(StoryRef::Body), "AC");
|
||||
let sections = d.sections();
|
||||
assert_eq!(sections.len(), 2);
|
||||
assert_eq!(*sections[0].1, crate::section::SectionProps { headers: set(2), footers: set(5), ..s3 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_across() {
|
||||
let mut d = doc(&["abc", "def"]);
|
||||
@@ -914,6 +1092,42 @@ mod tests {
|
||||
assert_eq!(Path(vec![1, 0, 1, 0]).cell(), Some((Path::top(1), 0, 1)));
|
||||
}
|
||||
|
||||
fn para(text: &str) -> Block {
|
||||
Block::Para(Paragraph::with_text(text, CharProps::default()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appended_pieces_are_each_followed_by_one_paragraph_mark() {
|
||||
let mut spike = Fragment::default();
|
||||
spike.append_piece(Fragment { blocks: vec![para("a")], ..Default::default() });
|
||||
spike.append_piece(Fragment { blocks: vec![para("b")], ..Default::default() });
|
||||
assert_eq!(spike.plain_text(), "a\nb\n");
|
||||
// A piece that already ends with its paragraph mark gets no second one.
|
||||
let mut spike = Fragment::default();
|
||||
spike.append_piece(Fragment { blocks: vec![para("a"), para("")], ..Default::default() });
|
||||
assert_eq!(spike.plain_text(), "a\n");
|
||||
spike.append_piece(Fragment { blocks: vec![para("b"), para("c")], ..Default::default() });
|
||||
assert_eq!(spike.plain_text(), "a\nb\nc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appended_pieces_keep_their_own_text_boxes() {
|
||||
// Two documents give their first text box the same id.
|
||||
let mut one = doc(&["x"]);
|
||||
let id1 = text_box(&mut one, &Pos::body(0, 1), "One");
|
||||
let mut two = doc(&["y"]);
|
||||
let id2 = text_box(&mut two, &Pos::body(0, 1), "Two");
|
||||
assert_eq!(id1, id2);
|
||||
let mut spike = Fragment::default();
|
||||
spike.append_piece(one.copy_range(&Pos::body(0, 0), &Pos::body(0, 1 + 3)));
|
||||
spike.append_piece(two.copy_range(&Pos::body(0, 0), &Pos::body(0, 1 + 3)));
|
||||
let mut dst = doc(&[""]);
|
||||
dst.insert_fragment(&Pos::body(0, 0), &spike).unwrap();
|
||||
let texts: Vec<String> =
|
||||
[0, 1].iter().flat_map(|i| boxes_in(&dst, &Path::top(*i))).map(|b| dst.plain_text(StoryRef::Part(b.unwrap()))).collect();
|
||||
assert_eq!(texts, ["One", "Two"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_positions_error() {
|
||||
let mut d = doc(&["é"]);
|
||||
@@ -924,4 +1138,157 @@ mod tests {
|
||||
assert_eq!(c, Pos::body(0, 2));
|
||||
assert!(d.delete_range(&Pos { story: StoryRef::Part(3), path: Path::top(0), off: 0 }, &Pos::body(0, 0)).is_err());
|
||||
}
|
||||
|
||||
// delete_range over whole tables (#1844), in the body, a header and a footnote.
|
||||
|
||||
/// A document whose story (the body, or a header or footnote part) holds `lines`.
|
||||
fn story_doc(kind: Option<PartKind>, lines: &[&str]) -> (Document, StoryRef) {
|
||||
match kind {
|
||||
None => (doc(lines), StoryRef::Body),
|
||||
Some(k) => {
|
||||
let mut d = doc(&["body"]);
|
||||
let blocks = lines.iter().map(|l| para_block(Paragraph::with_text(l, CharProps::default()))).collect();
|
||||
let id = d.add_part(k, blocks);
|
||||
(d, StoryRef::Part(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const STORIES: [Option<PartKind>; 3] = [None, Some(PartKind::Header), Some(PartKind::Footnote)];
|
||||
|
||||
fn at(story: StoryRef, path: &[u32], off: usize) -> Pos {
|
||||
Pos { story, path: Path(path.to_vec()), off }
|
||||
}
|
||||
|
||||
/// Insert an `rows`×`cols` table at `path` whose cells hold `texts`, row by row.
|
||||
fn put_table(d: &mut Document, story: StoryRef, path: &[u32], rows: usize, cols: usize, texts: &[&str]) {
|
||||
d.insert_block(story, &Path(path.to_vec()), Block::Table(Table::new(rows, cols, 200.0))).unwrap();
|
||||
for (k, t) in texts.iter().enumerate() {
|
||||
let mut p = path.to_vec();
|
||||
p.extend([(k / cols) as u32, (k % cols) as u32, 0]);
|
||||
d.insert_text(&at(story, &p, 0), t, &CharProps::default()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The story's top-level blocks: a paragraph's text, or `[table]`.
|
||||
fn shape(d: &Document, story: StoryRef) -> Vec<String> {
|
||||
d.story(story).unwrap().iter().map(|b| b.as_para().map_or("[table]".to_string(), |p| p.text.clone())).collect()
|
||||
}
|
||||
|
||||
fn cell_text(d: &Document, story: StoryRef, table: &[u32], r: u32, c: u32) -> String {
|
||||
let mut p = table.to_vec();
|
||||
p.extend([r, c, 0]);
|
||||
d.para(story, &Path(p)).map(|p| p.text.clone()).unwrap_or_else(|| "<none>".into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_ending_at_the_end_of_a_cell_that_isnt_the_last_keeps_the_table() {
|
||||
for kind in STORIES {
|
||||
for (r, c) in [(0, 1), (1, 0)] {
|
||||
let (mut d, st) = story_doc(kind, &["before", "after"]);
|
||||
put_table(&mut d, st, &[1], 2, 2, &["a", "b", "c", "d"]);
|
||||
d.delete_range(&at(st, &[0], 0), &at(st, &[1, r, c, 0], 1)).unwrap();
|
||||
assert_eq!(shape(&d, st), ["", "[table]", "after"], "{kind:?} ({r},{c})");
|
||||
assert_eq!(cell_text(&d, st, &[1], 1, 1), "d", "{kind:?} ({r},{c})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_from_the_start_of_one_table_into_the_middle_of_the_next_removes_only_the_first() {
|
||||
for kind in STORIES {
|
||||
let (mut d, st) = story_doc(kind, &["x", "mid", "y"]);
|
||||
put_table(&mut d, st, &[2], 2, 2, &["e", "f", "g", "h"]);
|
||||
put_table(&mut d, st, &[1], 2, 2, &["a", "b", "c", "d"]);
|
||||
assert_eq!(shape(&d, st), ["x", "[table]", "mid", "[table]", "y"]);
|
||||
let to = d.delete_range(&at(st, &[1, 0, 0, 0], 0), &at(st, &[3, 0, 1, 0], 1)).unwrap();
|
||||
assert_eq!(shape(&d, st), ["x", "", "[table]", "y"], "{kind:?}");
|
||||
assert_eq!([cell_text(&d, st, &[2], 0, 0), cell_text(&d, st, &[2], 0, 1), cell_text(&d, st, &[2], 1, 0)], ["", "", "g"], "{kind:?}");
|
||||
assert!(d.para(st, &to.path).is_some(), "{kind:?}: {to:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_from_a_cell_paragraph_to_the_end_of_a_table_nested_in_that_cell_removes_only_the_nested_table() {
|
||||
for kind in STORIES {
|
||||
let (mut d, st) = story_doc(kind, &["before", "after"]);
|
||||
put_table(&mut d, st, &[1], 1, 1, &["p"]);
|
||||
put_table(&mut d, st, &[1, 0, 0, 1], 1, 1, &["n"]);
|
||||
d.insert_block(st, &Path(vec![1, 0, 0, 2]), Block::Para(Paragraph::with_text("q", CharProps::default()))).unwrap();
|
||||
let to = d.delete_range(&at(st, &[1, 0, 0, 0], 1), &at(st, &[1, 0, 0, 1, 0, 0, 0], 1)).unwrap();
|
||||
assert_eq!(shape(&d, st), ["before", "[table]", "after"], "{kind:?}");
|
||||
let cell = d.container(st, &Path(vec![1, 0, 0, 0])).unwrap();
|
||||
let cell: Vec<String> = cell.iter().map(|b| b.as_para().map_or("[table]".to_string(), |p| p.text.clone())).collect();
|
||||
assert_eq!(cell, ["pq"], "{kind:?}");
|
||||
assert_eq!(to, at(st, &[1, 0, 0, 0], 1), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_whole_tables_at_the_end_of_a_story_leave_one_empty_paragraph() {
|
||||
for kind in STORIES {
|
||||
for trailing in [true, false] {
|
||||
let (mut d, st) = story_doc(kind, &[""]);
|
||||
put_table(&mut d, st, &[0], 1, 2, &["a", "b"]);
|
||||
put_table(&mut d, st, &[1], 2, 1, &["c", "d"]);
|
||||
if !trailing {
|
||||
// A story that ends in a table (a hostile file).
|
||||
d.story_mut(st).unwrap().pop();
|
||||
}
|
||||
let to = d.delete_range(&at(st, &[0, 0, 0, 0], 0), &at(st, &[1, 1, 0, 0], 1)).unwrap();
|
||||
assert_eq!(shape(&d, st), [""], "{kind:?} trailing {trailing}");
|
||||
assert_eq!(to, at(st, &[0], 0), "{kind:?} trailing {trailing}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Content controls pair their markers within one block list (a story, or a cell), so a
|
||||
/// marker in a table never has its partner outside it: a control inside a table removed whole
|
||||
/// goes with it, and one the range only enters keeps both markers (the control is emptied).
|
||||
#[test]
|
||||
fn removing_a_whole_table_keeps_a_control_the_range_only_partly_covers() {
|
||||
use crate::control::ContentControl;
|
||||
let start = || InlineObject::ControlStart { control: Box::new(ContentControl::default()) };
|
||||
for kind in STORIES {
|
||||
let (mut d, st) = story_doc(kind, &["before", "after"]);
|
||||
put_table(&mut d, st, &[1], 1, 1, &["c"]);
|
||||
// One control around "efo" in "before", one around the cell's text.
|
||||
d.insert_object(&at(st, &[0], 4), InlineObject::ControlEnd, &CharProps::default()).unwrap();
|
||||
let in_before = d.insert_object(&at(st, &[0], 1), start(), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(st, &[1, 0, 0, 0], 1), InlineObject::ControlEnd, &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(st, &[1, 0, 0, 0], 0), start(), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.control_ranges(st).len(), 2, "setup");
|
||||
let end = d.para(st, &Path(vec![1, 0, 0, 0])).unwrap().len();
|
||||
// From inside the first control to the end of the table.
|
||||
d.delete_range(&Pos { off: in_before.off + 1, ..in_before }, &at(st, &[1, 0, 0, 0], end)).unwrap();
|
||||
assert_eq!(shape(&d, st), ["b\u{FFFC}e\u{FFFC}after"], "{kind:?}: the table goes, the paragraphs join");
|
||||
let ranges = d.control_ranges(st);
|
||||
assert_eq!(ranges.len(), 1, "{kind:?}: {ranges:?}");
|
||||
assert!(ranges.iter().all(|r| r.start.path == Path::top(0) && r.end.path == Path::top(0)), "{kind:?}");
|
||||
let objects = d.para(st, &Path::top(0)).map_or(0, |p| p.objects.len());
|
||||
assert_eq!(objects, 2, "{kind:?}: no orphan markers left");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_nested_deeper_than_the_paragraph_walk_is_never_removed_whole() {
|
||||
// 20 tables, each in the first cell of the one around it, ahead of that cell's paragraph:
|
||||
// the innermost paragraphs come first in the document but the paragraph walk stops short.
|
||||
let mut t = Table::new(1, 1, 200.0);
|
||||
if let Some(cell) = t.rows.get_mut(0).and_then(|r| r.cells.get_mut(0)) {
|
||||
cell.blocks = vec![para_block(Paragraph::with_text("deep", CharProps::default()))];
|
||||
}
|
||||
for _ in 0..20 {
|
||||
let mut outer = Table::new(1, 1, 200.0);
|
||||
if let Some(cell) = outer.rows.get_mut(0).and_then(|r| r.cells.get_mut(0)) {
|
||||
cell.blocks.insert(0, Arc::new(Block::Table(t)));
|
||||
}
|
||||
t = outer;
|
||||
}
|
||||
let mut d = doc(&["before", "after"]);
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), Block::Table(t)).unwrap();
|
||||
let first = d.para_paths(StoryRef::Body).into_iter().find(|p| p.0.first() == Some(&1)).unwrap();
|
||||
d.delete_range(&Pos { story: StoryRef::Body, path: first, off: 0 }, &Pos::body(2, 0)).unwrap();
|
||||
assert!(d.body.get(1).is_some_and(|b| b.as_table().is_some()), "a table with paragraphs the walk never saw was removed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,12 +287,12 @@ pub fn code_page_byte(code_page: u16, b: u8) -> char {
|
||||
}
|
||||
|
||||
/// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern
|
||||
/// European → 1250, 77 Mac → 10000, 254 PC → 437… `None` for the ANSI and default charsets (the
|
||||
/// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437… `None` for the ANSI and default charsets (the
|
||||
/// document's code page applies), symbol fonts and the double-byte East Asian charsets.
|
||||
pub fn charset_code_page(charset: i32) -> Option<u16> {
|
||||
Some(match charset {
|
||||
77 => MAC_ROMAN_CODE_PAGE,
|
||||
254 => 437,
|
||||
254 | 255 => 437,
|
||||
161 => 1253,
|
||||
162 => 1254,
|
||||
163 => 1258,
|
||||
@@ -323,6 +323,7 @@ mod tests {
|
||||
assert_eq!(decode(10000, &[0x80, 0x8E, 0xDB, 0xF1, 0xF2, 0xF3, 0xD2, 0xD3, 0x41]), "Äé€ÒÚÛ“”A");
|
||||
assert_eq!(charset_code_page(77), Some(10000));
|
||||
assert_eq!(charset_code_page(254), Some(437));
|
||||
assert_eq!(charset_code_page(255), Some(437));
|
||||
assert_eq!(charset_code_page(204), Some(1251));
|
||||
assert_eq!(charset_code_page(0), None);
|
||||
for cp in SINGLE_BYTE_CODE_PAGES {
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Legacy form fields (`FORMCHECKBOX`, `FORMTEXT`, `FORMDROPDOWN`): what their `w:ffData` says,
|
||||
//! read from the raw XML a [`crate::InlineObject::Field`] keeps in its `form` (ECMA-376 Part 1
|
||||
//! §17.16.17). Only what layout and PDF export need; the XML itself stays the source of truth
|
||||
//! for saving.
|
||||
|
||||
/// Most drop-down entries kept (Word allows 25).
|
||||
pub const MAX_ENTRIES: usize = 64;
|
||||
|
||||
/// A legacy form field's kind and state.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum LegacyForm {
|
||||
/// A check box: `checked` is its state (`w:checked`, else `w:default`), `size` its explicit
|
||||
/// size in points (`w:size`), `None` when it follows the text (`w:sizeAuto`).
|
||||
CheckBox { name: String, checked: bool, size: Option<f32> },
|
||||
/// A text field; its text is the field's result.
|
||||
Text { name: String, max_len: Option<u32> },
|
||||
/// A drop-down list showing entry `selected` (`w:result`, else `w:default`, else the first).
|
||||
DropDown { name: String, entries: Vec<String>, selected: usize },
|
||||
}
|
||||
|
||||
impl LegacyForm {
|
||||
/// The field's definition, or `None` when `ff_data` holds none of the three.
|
||||
pub fn parse(ff_data: &str) -> Option<LegacyForm> {
|
||||
let name = attr_of(ff_data, "w:name").unwrap_or_default();
|
||||
if let Some(cb) = element(ff_data, "w:checkBox") {
|
||||
let default = attr_of(cb, "w:default").is_some_and(|v| on(&v));
|
||||
// `<w:checked/>` with no value means checked.
|
||||
let checked = match tag(cb, "w:checked") {
|
||||
Some(t) => attr_in(t).is_none_or(|v| on(&v)),
|
||||
None => default,
|
||||
};
|
||||
let size =
|
||||
attr_of(cb, "w:size").and_then(|v| v.trim().parse::<f32>().ok()).filter(|v| v.is_finite() && *v > 0.0).map(|v| (v / 2.0).min(1584.0));
|
||||
return Some(LegacyForm::CheckBox { name, checked, size });
|
||||
}
|
||||
if let Some(dd) = element(ff_data, "w:ddList") {
|
||||
let entries: Vec<String> = tags(dd, "w:listEntry").filter_map(attr_in).take(MAX_ENTRIES).collect();
|
||||
let pick = |n: &str| attr_of(dd, n).and_then(|v| v.trim().parse::<usize>().ok());
|
||||
let selected = pick("w:result").or_else(|| pick("w:default")).filter(|i| *i < entries.len()).unwrap_or(0);
|
||||
return Some(LegacyForm::DropDown { name, entries, selected });
|
||||
}
|
||||
if ff_data.contains("<w:textInput") {
|
||||
let max_len =
|
||||
element(ff_data, "w:textInput").and_then(|t| attr_of(t, "w:maxLength")).and_then(|v| v.trim().parse::<u32>().ok()).filter(|n| *n > 0);
|
||||
return Some(LegacyForm::Text { name, max_len });
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The text a drop-down shows (its selected entry); `None` for other kinds or an empty list.
|
||||
pub fn shown_text(&self) -> Option<&str> {
|
||||
match self {
|
||||
LegacyForm::DropDown { entries, selected, .. } => entries.get(*selected).map(String::as_str),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The field's bookmark-style name (`w:name`), possibly empty.
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
LegacyForm::CheckBox { name, .. } | LegacyForm::Text { name, .. } | LegacyForm::DropDown { name, .. } => name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on(v: &str) -> bool {
|
||||
!matches!(v.trim(), "0" | "false" | "off")
|
||||
}
|
||||
|
||||
/// The element `name` in `xml` with its content: from its start tag to its end tag, or the
|
||||
/// self-closing tag alone.
|
||||
fn element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let open = tag(xml, name)?;
|
||||
let start = xml.find(open)?;
|
||||
if open.ends_with("/>") {
|
||||
return Some(open);
|
||||
}
|
||||
let close = format!("</{name}>");
|
||||
let end = xml.get(start..)?.find(&close)? + start + close.len();
|
||||
xml.get(start..end)
|
||||
}
|
||||
|
||||
/// The first start (or empty) tag `<name ...>` in `xml`.
|
||||
fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
tags(xml, name).next()
|
||||
}
|
||||
|
||||
/// Every start (or empty) tag `<name ...>` in `xml`, in order.
|
||||
fn tags<'a>(xml: &'a str, name: &str) -> impl Iterator<Item = &'a str> + use<'a> {
|
||||
let pat = format!("<{name}");
|
||||
let mut from = 0;
|
||||
std::iter::from_fn(move || {
|
||||
loop {
|
||||
let at = from + xml.get(from..)?.find(&pat)?;
|
||||
let after = at + pat.len();
|
||||
from = after;
|
||||
// `<w:checkBox` must not match `<w:checkBoxes`: the name ends at a space, `/` or `>`.
|
||||
if xml.get(after..).and_then(|s| s.chars().next()).is_some_and(|c| c == ' ' || c == '/' || c == '>') {
|
||||
let end = after + xml.get(after..)?.find('>')? + 1;
|
||||
return xml.get(at..end);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The `w:val` of the first tag `name` in `xml`.
|
||||
fn attr_of(xml: &str, name: &str) -> Option<String> {
|
||||
tag(xml, name).and_then(attr_in)
|
||||
}
|
||||
|
||||
/// The `w:val` of a single tag, XML entities resolved.
|
||||
fn attr_in(tag: &str) -> Option<String> {
|
||||
let at = tag.find("w:val=")? + "w:val=".len();
|
||||
let quote = tag.get(at..)?.chars().next()?;
|
||||
if quote != '"' && quote != '\'' {
|
||||
return None;
|
||||
}
|
||||
let rest = tag.get(at + 1..)?;
|
||||
let end = rest.find(quote)?;
|
||||
Some(unescape(rest.get(..end)?))
|
||||
}
|
||||
|
||||
fn unescape(s: &str) -> String {
|
||||
s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn check_boxes_text_fields_and_drop_downs() {
|
||||
let cb = |inner: &str| format!(r#"<w:ffData><w:name w:val="Box1"/><w:enabled/><w:checkBox>{inner}</w:checkBox></w:ffData>"#);
|
||||
assert_eq!(
|
||||
LegacyForm::parse(&cb(r#"<w:sizeAuto/><w:default w:val="0"/>"#)),
|
||||
Some(LegacyForm::CheckBox { name: "Box1".into(), checked: false, size: None })
|
||||
);
|
||||
assert_eq!(
|
||||
LegacyForm::parse(&cb(r#"<w:sizeAuto/><w:default w:val="1"/>"#)).map(|f| matches!(f, LegacyForm::CheckBox { checked: true, .. })),
|
||||
Some(true)
|
||||
);
|
||||
// `w:checked` wins over `w:default`; without a value it means checked.
|
||||
assert!(matches!(
|
||||
LegacyForm::parse(&cb(r#"<w:default w:val="1"/><w:checked w:val="0"/>"#)),
|
||||
Some(LegacyForm::CheckBox { checked: false, .. })
|
||||
));
|
||||
assert!(matches!(LegacyForm::parse(&cb(r#"<w:default w:val="0"/><w:checked/>"#)), Some(LegacyForm::CheckBox { checked: true, .. })));
|
||||
assert!(matches!(
|
||||
LegacyForm::parse(&cb(r#"<w:size w:val="30"/><w:default w:val="0"/>"#)),
|
||||
Some(LegacyForm::CheckBox { size: Some(15.0), .. })
|
||||
));
|
||||
let dd = r#"<w:ffData><w:name w:val="List1"/><w:ddList><w:result w:val="1"/><w:listEntry w:val="Alpha"/><w:listEntry w:val="B & C"/></w:ddList></w:ffData>"#;
|
||||
let f = LegacyForm::parse(dd).unwrap();
|
||||
assert_eq!(f.shown_text(), Some("B & C"));
|
||||
assert_eq!(f.name(), "List1");
|
||||
let dd0 = r#"<w:ffData><w:ddList><w:listEntry w:val="Only"/></w:ddList></w:ffData>"#;
|
||||
assert_eq!(LegacyForm::parse(dd0).and_then(|f| f.shown_text().map(str::to_string)).as_deref(), Some("Only"));
|
||||
let tx = r#"<w:ffData><w:name w:val="Name1"/><w:textInput><w:maxLength w:val="40"/></w:textInput></w:ffData>"#;
|
||||
assert_eq!(LegacyForm::parse(tx), Some(LegacyForm::Text { name: "Name1".into(), max_len: Some(40) }));
|
||||
assert_eq!(LegacyForm::parse(""), None);
|
||||
assert_eq!(LegacyForm::parse("<w:ffData><w:name w:val=\"x\"/></w:ffData>"), None);
|
||||
}
|
||||
}
|
||||
+109
-1
@@ -24,6 +24,8 @@ pub mod eq;
|
||||
pub mod fields;
|
||||
pub mod freeform;
|
||||
pub mod graphic;
|
||||
pub mod legacy_form;
|
||||
pub mod line_dash;
|
||||
pub mod link;
|
||||
pub mod locale_number;
|
||||
pub mod math;
|
||||
@@ -310,6 +312,11 @@ pub struct TextBody {
|
||||
/// Resize shape to fit text (`a:spAutoFit`, VML `mso-fit-shape-to-text`): Word grows the
|
||||
/// box to its text, so none of the text is cut.
|
||||
pub auto_fit: bool,
|
||||
/// The colour the shape's style gives its text (`wps:style/a:fontRef`): what automatic text
|
||||
/// colour means inside this box, instead of black. Text whose colour comes from its runs,
|
||||
/// styles or the document defaults keeps it (Word, observed with synthetic documents).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub auto_color: Option<props::Rgb>,
|
||||
}
|
||||
|
||||
/// Word's default text box margins (left, top, right, bottom), EMU: 0.1" and 0.05".
|
||||
@@ -387,6 +394,40 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// A building block (Insert › Quick Parts, AutoText…) kept in the document's glossary
|
||||
/// (ECMA-376 §17.12: `w:docPart`).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct BuildingBlock {
|
||||
/// The entry's name (`w:docPartPr/w:name`).
|
||||
pub name: String,
|
||||
/// Its gallery (`w:category/w:gallery`: `docParts` for Quick Parts, `autoTxt` for AutoText…).
|
||||
pub gallery: String,
|
||||
/// Its category within the gallery (`w:category/w:name`, e.g. "General").
|
||||
pub category: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub description: String,
|
||||
/// The entry's identity (`w:guid`), kept as read.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub guid: String,
|
||||
/// The paragraph style it's associated with (`w:style`), kept as read.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub style: String,
|
||||
/// Its types (`w:types/w:type`: `normal`, `bbPlcHdr` for a content control's placeholder…).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub types: Vec<String>,
|
||||
/// How it's inserted (`w:behaviors/w:behavior`: `content`, `p`, `pg`).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub behaviors: Vec<String>,
|
||||
/// The content (`w:docPartBody`).
|
||||
pub blocks: Blocks,
|
||||
}
|
||||
|
||||
/// The gallery Quick Parts saves to (`w:gallery w:val="docParts"`).
|
||||
pub const QUICK_PARTS_GALLERY: &str = "docParts";
|
||||
/// The AutoText gallery (`w:gallery w:val="autoTxt"`).
|
||||
pub const AUTO_TEXT_GALLERY: &str = "autoTxt";
|
||||
|
||||
/// A bibliography source.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -448,6 +489,10 @@ pub struct CoreProps {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Settings {
|
||||
pub track_changes: bool,
|
||||
/// Record a tracked cut and paste of a sentence or paragraph as a move (Track moves); off
|
||||
/// when the file has `w:doNotTrackMoves` (ECMA-376 §17.15.1.29), and then it is an
|
||||
/// ordinary deletion and insertion.
|
||||
pub track_moves: bool,
|
||||
/// Default tab stop interval, points.
|
||||
pub default_tab: f32,
|
||||
pub even_odd_headers: bool,
|
||||
@@ -614,6 +659,7 @@ impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Settings {
|
||||
track_changes: false,
|
||||
track_moves: true,
|
||||
default_tab: 36.0,
|
||||
even_odd_headers: false,
|
||||
mirror_margins: false,
|
||||
@@ -682,6 +728,9 @@ pub struct Document {
|
||||
/// Source-format parts we keep verbatim for round-trip (e.g. custom XML), by part name.
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub passthrough: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
/// The document's own building blocks (its glossary document), in file order.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub glossary: Vec<BuildingBlock>,
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
@@ -709,6 +758,7 @@ impl Document {
|
||||
endnote_separators: NoteSeparators::default(),
|
||||
media: BTreeMap::new(),
|
||||
passthrough: BTreeMap::new(),
|
||||
glossary: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -978,6 +1028,18 @@ impl Document {
|
||||
&mut self.last_section
|
||||
}
|
||||
|
||||
/// Remove the section break on the mark of top-level body paragraph `block`: its section
|
||||
/// joins the following one ([`SectionProps::absorb`]). False when there is no break there.
|
||||
pub fn remove_section_break(&mut self, block: usize) -> bool {
|
||||
if !matches!(self.body.get(block).map(|b| &**b), Some(Block::Para(p)) if p.section.is_some()) {
|
||||
return false;
|
||||
}
|
||||
let Some(Block::Para(p)) = self.body.get_mut(block).map(Arc::make_mut) else { return false };
|
||||
let Some(before) = p.section.take() else { return false };
|
||||
self.section_mut(block).absorb(&before);
|
||||
true
|
||||
}
|
||||
|
||||
/// Allocate a new part id and insert the part. Part ids run out only past `u32::MAX` parts, more
|
||||
/// than memory holds; then nothing is added and the id is 0, which [`free_id`] never gives a part.
|
||||
pub fn add_part(&mut self, kind: PartKind, blocks: Blocks) -> u32 {
|
||||
@@ -1387,8 +1449,11 @@ pub fn count_words(s: &str) -> usize {
|
||||
s.split(|c: char| c.is_whitespace() || c == para::OBJ).filter(|w| w.chars().any(char::is_alphanumeric)).count()
|
||||
}
|
||||
|
||||
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
|
||||
pub(crate) const PARA_WALK_DEPTH: usize = 16;
|
||||
|
||||
fn walk(bl: &Blocks, prefix: &mut Vec<u32>, out: &mut Vec<Path>, depth: usize) {
|
||||
if depth > 16 {
|
||||
if depth > PARA_WALK_DEPTH {
|
||||
return;
|
||||
}
|
||||
for (i, b) in bl.iter().enumerate() {
|
||||
@@ -1411,6 +1476,49 @@ fn walk(bl: &Blocks, prefix: &mut Vec<u32>, out: &mut Vec<Path>, depth: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`walk`] for the paragraphs from path `a` to `b` inclusive, skipping the blocks outside.
|
||||
pub(crate) fn walk_between(bl: &Blocks, prefix: &mut Vec<u32>, out: &mut Vec<Path>, depth: usize, (a, b): (&[u32], &[u32])) {
|
||||
use std::cmp::Ordering::{Greater, Less};
|
||||
if depth > PARA_WALK_DEPTH {
|
||||
return;
|
||||
}
|
||||
// Where the paths starting with `q` lie against `x`: all before, all after, or either.
|
||||
let side = |q: &[u32], x: &[u32]| {
|
||||
let m = q.len().min(x.len());
|
||||
q[..m].cmp(&x[..m])
|
||||
};
|
||||
for (i, blk) in bl.iter().enumerate() {
|
||||
prefix.push(i as u32);
|
||||
if side(prefix, b) == Greater {
|
||||
prefix.pop();
|
||||
break;
|
||||
}
|
||||
if side(prefix, a) != Less {
|
||||
match &**blk {
|
||||
Block::Para(_) => {
|
||||
if prefix.as_slice() >= a && prefix.as_slice() <= b {
|
||||
out.push(Path(prefix.clone()));
|
||||
}
|
||||
}
|
||||
Block::Table(t) => {
|
||||
for (r, row) in t.rows.iter().enumerate() {
|
||||
for (c, cell) in row.cells.iter().enumerate() {
|
||||
prefix.push(r as u32);
|
||||
prefix.push(c as u32);
|
||||
if side(prefix, a) != Less && side(prefix, b) != Greater {
|
||||
walk_between(&cell.blocks, prefix, out, depth + 1, (a, b));
|
||||
}
|
||||
prefix.pop();
|
||||
prefix.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
prefix.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Which text of a paragraph [`text_of`] collects.
|
||||
#[derive(Clone, Copy)]
|
||||
enum TextMode {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! DrawingML outline dashes, measured in multiples of the stroke width.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const DASH_PERCENT: u32 = 100_000;
|
||||
pub const MAX_DASH_STOPS: usize = 64;
|
||||
const MIN_DASH_POINTS: f32 = 0.01;
|
||||
const MAX_DASH_POINTS: f32 = 20_000.0;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LineDash {
|
||||
#[default]
|
||||
Solid,
|
||||
Dot,
|
||||
Dash,
|
||||
LongDash,
|
||||
DashDot,
|
||||
LongDashDot,
|
||||
LongDashDotDot,
|
||||
SystemDash,
|
||||
SystemDot,
|
||||
SystemDashDot,
|
||||
SystemDashDotDot,
|
||||
/// Dash/space pairs in 100000ths of the line width (`a:ds/@d`, `@sp`).
|
||||
Custom(Vec<(u32, u32)>),
|
||||
}
|
||||
|
||||
impl LineDash {
|
||||
pub fn from_ooxml(value: &str) -> Self {
|
||||
match value {
|
||||
"dot" => Self::Dot,
|
||||
"dash" => Self::Dash,
|
||||
"lgDash" => Self::LongDash,
|
||||
"dashDot" => Self::DashDot,
|
||||
"lgDashDot" => Self::LongDashDot,
|
||||
"lgDashDotDot" => Self::LongDashDotDot,
|
||||
"sysDash" => Self::SystemDash,
|
||||
"sysDot" => Self::SystemDot,
|
||||
"sysDashDot" => Self::SystemDashDot,
|
||||
"sysDashDotDot" => Self::SystemDashDotDot,
|
||||
_ => Self::Solid,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ooxml(&self) -> Option<&'static str> {
|
||||
Some(match self {
|
||||
Self::Solid => "solid",
|
||||
Self::Dot => "dot",
|
||||
Self::Dash => "dash",
|
||||
Self::LongDash => "lgDash",
|
||||
Self::DashDot => "dashDot",
|
||||
Self::LongDashDot => "lgDashDot",
|
||||
Self::LongDashDotDot => "lgDashDotDot",
|
||||
Self::SystemDash => "sysDash",
|
||||
Self::SystemDot => "sysDot",
|
||||
Self::SystemDashDot => "sysDashDot",
|
||||
Self::SystemDashDotDot => "sysDashDotDot",
|
||||
Self::Custom(_) => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_solid(&self) -> bool {
|
||||
*self == Self::Solid
|
||||
}
|
||||
|
||||
/// Page-point lengths for the painters. Bound hostile custom lists and tiny spans.
|
||||
pub fn pattern(&self, width: f32) -> Vec<f32> {
|
||||
let preset: &[f32] = match self {
|
||||
Self::Solid => return Vec::new(),
|
||||
Self::Dot => &[1.0, 3.0],
|
||||
Self::Dash => &[4.0, 3.0],
|
||||
Self::LongDash => &[8.0, 3.0],
|
||||
Self::DashDot => &[4.0, 3.0, 1.0, 3.0],
|
||||
Self::LongDashDot => &[8.0, 3.0, 1.0, 3.0],
|
||||
Self::LongDashDotDot => &[8.0, 3.0, 1.0, 3.0, 1.0, 3.0],
|
||||
Self::SystemDash => &[3.0, 1.0],
|
||||
Self::SystemDot => &[1.0, 1.0],
|
||||
Self::SystemDashDot => &[3.0, 1.0, 1.0, 1.0],
|
||||
Self::SystemDashDotDot => &[3.0, 1.0, 1.0, 1.0, 1.0, 1.0],
|
||||
Self::Custom(stops) => {
|
||||
return stops
|
||||
.iter()
|
||||
.take(MAX_DASH_STOPS)
|
||||
.flat_map(|&(d, sp)| [d, sp])
|
||||
.map(|v| dash_points(v as f32 / DASH_PERCENT as f32, width))
|
||||
.collect();
|
||||
}
|
||||
};
|
||||
preset.iter().map(|v| dash_points(*v, width)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn dash_points(ratio: f32, width: f32) -> f32 {
|
||||
let width = if width.is_finite() { width.clamp(0.25, 200.0) } else { 0.75 };
|
||||
(ratio * width).clamp(MIN_DASH_POINTS, MAX_DASH_POINTS)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dash_units_follow_line_width() {
|
||||
assert_eq!(LineDash::Dash.pattern(1.0), [4.0, 3.0]);
|
||||
assert_eq!(LineDash::Dash.pattern(2.0), [8.0, 6.0]);
|
||||
assert_eq!(LineDash::Custom(vec![(200_000, 150_000)]).pattern(2.0), [4.0, 3.0]);
|
||||
assert!(LineDash::Solid.pattern(2.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_shapes_default_to_solid() {
|
||||
let extra: crate::connector::ShapeExtra = serde_json::from_str("{}").unwrap();
|
||||
assert!(extra.dash.is_solid());
|
||||
assert!(!serde_json::to_string(&extra).unwrap().contains("dash"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dashes_are_bounded() {
|
||||
let pattern = LineDash::Custom(vec![(0, u32::MAX); MAX_DASH_STOPS + 1]).pattern(f32::NAN);
|
||||
assert_eq!(pattern.len(), MAX_DASH_STOPS * 2);
|
||||
assert!(pattern.iter().all(|v| v.is_finite() && *v >= MIN_DASH_POINTS && *v <= MAX_DASH_POINTS));
|
||||
}
|
||||
}
|
||||
@@ -111,10 +111,11 @@ pub fn format_number(v: f64, lang: Option<&str>) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
if v.fract() == 0.0 && v.abs() < 1e15 {
|
||||
if v.fract() == 0.0 && v.abs() < 9.2e18 {
|
||||
return format!("{}", v as i64);
|
||||
}
|
||||
let s = format!("{v:.2}");
|
||||
let s = if s == "-0.00" { "0.00".to_string() } else { s };
|
||||
if decimal_separator(lang) == ',' { s.replace('.', ",") } else { s }
|
||||
}
|
||||
|
||||
@@ -147,6 +148,7 @@ mod tests {
|
||||
assert_eq!(parse_number(".", pl), None);
|
||||
assert_eq!(format_number(5.75, pl), "5,75");
|
||||
assert_eq!(format_number(1350.0, pl), "1350");
|
||||
assert_eq!(format_number(-0.001, pl), "0,00", "a rounded zero has no sign");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -161,6 +163,8 @@ mod tests {
|
||||
assert_eq!(parse_number("1.", en), Some(1.0));
|
||||
assert_eq!(parse_number("0,125", en), None, "never 125");
|
||||
assert_eq!(format_number(5.75, en), "5.75");
|
||||
assert_eq!(format_number(-0.001, en), "0.00", "a rounded zero has no sign");
|
||||
assert_eq!(format_number(-0.0, None), "0");
|
||||
assert_eq!(decimal_separator(Some("de-CH")), '.');
|
||||
assert_eq!(decimal_separator(Some("de-DE")), ',');
|
||||
}
|
||||
@@ -174,4 +178,13 @@ mod tests {
|
||||
}
|
||||
assert_eq!(format_number(f64::NAN, None), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_whole_numbers_have_no_decimals() {
|
||||
assert_eq!(format_number(1e15, None), "1000000000000000");
|
||||
assert_eq!(format_number(2.5e15, None), "2500000000000000");
|
||||
assert_eq!(format_number(-1e15, None), "-1000000000000000");
|
||||
assert_eq!(format_number(9.0e18, None), "9000000000000000000");
|
||||
assert_eq!(format_number(1e15 + 0.5, None), "1000000000000000.50");
|
||||
}
|
||||
}
|
||||
|
||||
+108
-10
@@ -470,8 +470,27 @@ fn lin_arg(a: &[MNode], s: &mut String, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for n in a {
|
||||
for (i, n) in a.iter().enumerate() {
|
||||
lin_node(n, s, depth + 1);
|
||||
// A bare script or limit ends at a space: a letter, digit or period after it is its own item.
|
||||
if matches!(n, MNode::Script { kind, .. } if *kind != ScriptKind::Pre) || matches!(n, MNode::Lim { .. }) {
|
||||
let ends_bare = s.chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '.');
|
||||
if ends_bare && a.get(i + 1).and_then(first_lin_char).is_some_and(|c| c.is_alphanumeric() || c == '.') {
|
||||
s.push(' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first character `n` is written with, when that is cheap to tell (letters and digits).
|
||||
fn first_lin_char(n: &MNode) -> Option<char> {
|
||||
match n {
|
||||
MNode::Run(r) => r.text.chars().next(),
|
||||
MNode::Func { name, .. } => name.first().and_then(first_lin_char),
|
||||
MNode::Script { kind, base, .. } if *kind != ScriptKind::Pre => base.first().and_then(first_lin_char),
|
||||
MNode::Lim { e, .. } => e.first().and_then(first_lin_char),
|
||||
MNode::Frac { num, .. } => num.first().and_then(first_lin_char),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,19 +518,25 @@ fn lin_operand(a: &[MNode], s: &mut String, depth: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A script or limit operand. The parser reads a script as one letter or a number (`x_10`), so a
|
||||
/// longer run is grouped: `V_(dd)`, not `V_dd` (which reads back as V_d then d).
|
||||
/// A script or limit operand. The parser reads a run of letters and digits up to the next space or
|
||||
/// operator, so `V_dd` is written bare as Word's Linear format shows it (`V_(dd)` reads back the same).
|
||||
fn lin_script(a: &[MNode], s: &mut String, depth: usize) {
|
||||
// Bare only when the parser reads the whole run back, in the same style.
|
||||
if let [MNode::Run(r)] = a
|
||||
&& r.text.chars().nth(1).is_some()
|
||||
&& !(r.text.starts_with(|c: char| c.is_ascii_digit()) && r.text.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
{
|
||||
s.push('(');
|
||||
s.push_str(&r.text);
|
||||
s.push(')');
|
||||
} else {
|
||||
lin_operand(a, s, depth);
|
||||
let upright_name = r.sty == Some(MSty::Plain) && crate::math_linear::FUNCTION_NAMES.contains(&r.text.as_str());
|
||||
let number = r.text.starts_with(|c: char| c.is_ascii_digit()) && r.text.chars().all(|c| c.is_alphanumeric() || c == '.');
|
||||
let word = r.text.starts_with(char::is_alphabetic) && r.text.chars().all(char::is_alphanumeric);
|
||||
let upright_other = r.sty == Some(MSty::Plain) && !upright_name;
|
||||
if upright_other || (!number && !word) {
|
||||
s.push('(');
|
||||
s.push_str(&r.text);
|
||||
s.push(')');
|
||||
return;
|
||||
}
|
||||
}
|
||||
lin_operand(a, s, depth);
|
||||
}
|
||||
|
||||
fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
@@ -962,7 +987,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn multi_letter_scripts_round_trip() {
|
||||
// A script reads one letter or a number, so `V_dd` is V_d then d: longer scripts are grouped.
|
||||
// Word for Mac 16.113.4 (#1609): a script is the whole run up to a space or operator, and Word's
|
||||
// Linear format shows it bare (`V_dd`); the parenthesised form reads back identically.
|
||||
let script = |kind, sub: &str, sup: &str| MNode::Script { kind, base: vec![run("V")], sub: parse_linear(sub), sup: parse_linear(sup) };
|
||||
for n in [
|
||||
vec![script(ScriptKind::Sub, "dd", "")],
|
||||
@@ -985,6 +1011,78 @@ mod tests {
|
||||
// Numbers and single letters stay bare.
|
||||
assert_eq!(to_linear(&[script(ScriptKind::SubSup, "10", "2.5")]), "V_10^2.5");
|
||||
assert_eq!(to_linear(&[script(ScriptKind::Sub, "d", "")]), "V_d");
|
||||
assert_eq!(to_linear(&[script(ScriptKind::Sub, "dd", "")]), "V_dd");
|
||||
assert_eq!(to_linear(&[script(ScriptKind::Sup, "", "ab")]), "V^ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_letter_script_operands_follow_word() {
|
||||
// #1609, Word for Mac 16.113.4: `V_dd` and `V_(dd)` build up the same; `dd` is all subscript.
|
||||
let sub_dd = MNode::Script { kind: ScriptKind::Sub, base: vec![run("V")], sub: vec![run("dd")], sup: vec![] };
|
||||
assert_eq!(parse_linear("V_dd"), vec![sub_dd.clone()]);
|
||||
assert_eq!(parse_linear("V_(dd)"), vec![sub_dd]);
|
||||
let sup_ab = MNode::Script { kind: ScriptKind::Sup, base: vec![run("x")], sub: vec![], sup: vec![run("ab")] };
|
||||
assert_eq!(parse_linear("x^ab"), vec![sup_ab.clone()]);
|
||||
assert_eq!(parse_linear("x^(ab)"), vec![sup_ab]);
|
||||
// Delimiters still end the operand.
|
||||
let both = MNode::Script { kind: ScriptKind::SubSup, base: vec![run("x")], sub: vec![run("i")], sup: vec![run("2")] };
|
||||
assert_eq!(parse_linear("x_i^2"), vec![both]);
|
||||
let a_i = MNode::Script { kind: ScriptKind::Sub, base: vec![run("a")], sub: vec![run("i")], sup: vec![] };
|
||||
assert_eq!(parse_linear("a_i b"), vec![a_i, run("b")]);
|
||||
let both2 = MNode::Script { kind: ScriptKind::SubSup, base: vec![run("x")], sub: vec![run("ij")], sup: vec![run("kl")] };
|
||||
assert_eq!(parse_linear("x_ij^kl"), vec![both2]);
|
||||
// Round trip is Word's bare form.
|
||||
assert_eq!(to_linear(&parse_linear("V_(dd)")), "V_dd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_script_does_not_absorb_what_follows() {
|
||||
// #1609 review: `x_i` then `y` must not read back as x with subscript `iy`.
|
||||
let sc =
|
||||
|kind, base: &str, sub: &str, sup: &str| MNode::Script { kind, base: vec![run(base)], sub: parse_linear(sub), sup: parse_linear(sup) };
|
||||
let sin_x = MNode::Func { name: vec![MNode::Run(MRun::plain("sin"))], e: vec![run("x")] };
|
||||
let lim = MNode::Lim { upper: false, e: vec![run("a")], lim: vec![run("n")] };
|
||||
for n in [
|
||||
vec![sc(ScriptKind::Sub, "x", "i", ""), run("y")],
|
||||
vec![sc(ScriptKind::Sub, "a", "i", ""), sc(ScriptKind::Sub, "b", "j", "")],
|
||||
vec![sc(ScriptKind::Sup, "x", "", "2"), run("y")],
|
||||
vec![sc(ScriptKind::Sup, "x", "", "2"), run("3")],
|
||||
vec![sc(ScriptKind::Sub, "x", "i", ""), sin_x],
|
||||
vec![lim.clone(), run("y")],
|
||||
vec![sc(ScriptKind::Sub, "x", "ab", ""), run("y")],
|
||||
vec![sc(ScriptKind::Sub, "x", "i", ""), run(".5")],
|
||||
] {
|
||||
let lin = to_linear(&n);
|
||||
assert_eq!(parse_linear(&lin), n, "{lin}");
|
||||
}
|
||||
assert_eq!(to_linear(&[sc(ScriptKind::Sub, "x", "i", ""), run("y")]), "x_i y");
|
||||
// Nothing extra when the script already ends in a bracket or a symbol follows.
|
||||
assert_eq!(to_linear(&[sc(ScriptKind::Sub, "x", "i", ""), run("+")]), "x_i+");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_name_in_a_script_stays_upright() {
|
||||
// Word for Mac (#1609): `x_max` and `x_(max)` both give an upright function name.
|
||||
let up = vec![MNode::Script { kind: ScriptKind::Sub, base: vec![run("x")], sub: vec![MNode::Run(MRun::plain("max"))], sup: vec![] }];
|
||||
assert_eq!(parse_linear("x_max"), up);
|
||||
assert_eq!(parse_linear("x_(max)"), up);
|
||||
assert_eq!(parse_linear(&to_linear(&up)), up, "{}", to_linear(&up));
|
||||
// Other upright text is not a function name: it keeps its parentheses.
|
||||
let other = vec![MNode::Script { kind: ScriptKind::Sub, base: vec![run("x")], sub: vec![MNode::Run(MRun::plain("ab"))], sup: vec![] }];
|
||||
assert_eq!(to_linear(&other), "x_(ab)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digits_then_letters_continue_a_script() {
|
||||
// Word for Mac (#1609): a script runs to a space or operator, so `x_2a` is subscript "2a".
|
||||
let sub = |t: &str| vec![MNode::Script { kind: ScriptKind::Sub, base: vec![run("x")], sub: vec![run(t)], sup: vec![] }];
|
||||
assert_eq!(parse_linear("x_2a"), sub("2a"));
|
||||
assert_eq!(parse_linear("x_a2"), sub("a2"));
|
||||
assert_eq!(parse_linear("x_αβ"), sub("αβ"));
|
||||
assert_eq!(parse_linear("x_10"), sub("10"));
|
||||
assert_eq!(parse_linear("x_2.5"), sub("2.5"));
|
||||
assert_eq!(to_linear(&sub("2a")), "x_2a");
|
||||
assert_eq!(parse_linear(&to_linear(&sub("2a"))), sub("2a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+116
-13
@@ -6,7 +6,7 @@
|
||||
//! spacing and every named symbol in [`crate::math_symbols`]. Unknown commands stay as text.
|
||||
|
||||
use crate::math::{
|
||||
Arg, FracKind, MAX_DEPTH, MNode, MRun, MScr, MSty, ScriptKind, WRAP_DEPTH, any_too_deep, is_nary_char, math_class, merge_runs, too_deep,
|
||||
Arg, ColJc, FracKind, MAX_DEPTH, MNode, MRun, MScr, MSty, ScriptKind, WRAP_DEPTH, any_too_deep, is_nary_char, math_class, merge_runs, too_deep,
|
||||
};
|
||||
use crate::math_linear::{FUNCTION_NAMES, map_args};
|
||||
use crate::math_symbols::{name_of, symbol};
|
||||
@@ -380,9 +380,30 @@ impl Lp {
|
||||
one(MNode::Run(MRun { text: t, nor: true, sty: Some(MSty::Italic), ..Default::default() }))
|
||||
}
|
||||
"operatorname" => {
|
||||
let starred = self.peek() == Some(&Tok::Ch('*'));
|
||||
if starred {
|
||||
self.i += 1;
|
||||
}
|
||||
let t = self.raw_arg();
|
||||
let name = vec![MNode::Run(MRun::plain(t))];
|
||||
self.apply(name)
|
||||
if starred && self.peek() == Some(&Tok::Sub) {
|
||||
self.i += 1;
|
||||
let lim = self.arg();
|
||||
vec![MNode::Lim { upper: false, e: name, lim }]
|
||||
} else {
|
||||
self.apply(name)
|
||||
}
|
||||
}
|
||||
"tag" => {
|
||||
let starred = self.peek() == Some(&Tok::Ch('*'));
|
||||
if starred {
|
||||
self.i += 1;
|
||||
}
|
||||
let t = self.raw_arg();
|
||||
let num_str = if starred { format!("#{t}") } else { format!("# ({t})") };
|
||||
let mut r = MRun::new(num_str);
|
||||
r.lit = false;
|
||||
vec![MNode::Run(r)]
|
||||
}
|
||||
"mathrm" | "rm" => {
|
||||
let a = self.arg();
|
||||
@@ -424,13 +445,15 @@ impl Lp {
|
||||
"underline" => one(MNode::Bar { top: false, e: self.arg() }),
|
||||
"boxed" | "fbox" => one(MNode::BorderBox { hide: [false; 4], strike: [false; 4], e: self.arg() }),
|
||||
"phantom" => one(MNode::Phant { show: false, zero_wid: false, zero_asc: false, zero_desc: false, e: self.arg() }),
|
||||
"overbrace" | "underbrace" | "overparen" | "underparen" => {
|
||||
"overbrace" | "underbrace" | "overparen" | "underparen" | "overbracket" | "underbracket" => {
|
||||
let top = c.starts_with("over");
|
||||
let chr = match c {
|
||||
"overbrace" => '⏞',
|
||||
"underbrace" => '⏟',
|
||||
"overparen" => '⏜',
|
||||
_ => '⏝',
|
||||
"underparen" => '⏝',
|
||||
"overbracket" => '⎴',
|
||||
_ => '⎵',
|
||||
};
|
||||
let e = self.arg();
|
||||
let g = MNode::GroupChr { chr, top, e };
|
||||
@@ -540,6 +563,22 @@ impl Lp {
|
||||
}
|
||||
|
||||
fn environment(&mut self, env: &str) -> Arg {
|
||||
let base = env.trim_end_matches('*');
|
||||
let mut col_jc = Vec::new();
|
||||
if base == "array" || base == "tabular" {
|
||||
let _ = self.opt();
|
||||
let spec = self.raw_arg();
|
||||
for ch in spec.chars() {
|
||||
match ch {
|
||||
'l' | 'L' => col_jc.push(ColJc::Left),
|
||||
'r' | 'R' => col_jc.push(ColJc::Right),
|
||||
'c' | 'C' => col_jc.push(ColJc::Center),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else if base == "aligned" {
|
||||
let _ = self.opt();
|
||||
}
|
||||
// Rows of `&`-separated cells up to `\end{…}`.
|
||||
let mut rows: Vec<Vec<Arg>> = vec![vec![]];
|
||||
loop {
|
||||
@@ -567,7 +606,6 @@ impl Lp {
|
||||
if rows.len() > 1 && rows.last().is_some_and(|r| r.iter().all(|c| c.is_empty())) {
|
||||
rows.pop();
|
||||
}
|
||||
let base = env.trim_end_matches('*');
|
||||
let delims = match base {
|
||||
"pmatrix" => Some((Some('('), Some(')'))),
|
||||
"bmatrix" => Some((Some('['), Some(']'))),
|
||||
@@ -585,8 +623,8 @@ impl Lp {
|
||||
elems: vec![vec![inner]],
|
||||
};
|
||||
match base {
|
||||
"matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "array" => {
|
||||
let m = MNode::Matrix { rows, col_jc: Vec::new() };
|
||||
"matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "array" | "tabular" => {
|
||||
let m = MNode::Matrix { rows, col_jc };
|
||||
match delims {
|
||||
Some((b, e)) => vec![wrap(m, b, e)],
|
||||
None => vec![m],
|
||||
@@ -774,6 +812,17 @@ fn delim_tex(c: Option<char>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn group_chr_tex(chr: char, top: bool) -> &'static str {
|
||||
match chr {
|
||||
'⏜' => "\\overparen",
|
||||
'⏝' => "\\underparen",
|
||||
'⎴' => "\\overbracket",
|
||||
'⎵' => "\\underbracket",
|
||||
_ if top => "\\overbrace",
|
||||
_ => "\\underbrace",
|
||||
}
|
||||
}
|
||||
|
||||
fn node(n: &MNode, s: &mut String, depth: usize) {
|
||||
match n {
|
||||
MNode::Run(r) => {
|
||||
@@ -877,12 +926,16 @@ fn node(n: &MNode, s: &mut String, depth: usize) {
|
||||
s.push(' ');
|
||||
braced(e, s, depth);
|
||||
}
|
||||
MNode::Delim { beg, end, elems, .. } => {
|
||||
MNode::Delim { beg, end, sep, elems, .. } => {
|
||||
s.push_str("\\left");
|
||||
s.push_str(&delim_tex(*beg));
|
||||
let mid = match sep {
|
||||
Some(c) => format!("\\middle{}", delim_tex(Some(*c))),
|
||||
None => "\\middle|".to_string(),
|
||||
};
|
||||
for (i, e) in elems.iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.push_str("\\middle|");
|
||||
s.push_str(&mid);
|
||||
}
|
||||
arg(e, s, depth);
|
||||
}
|
||||
@@ -901,11 +954,10 @@ fn node(n: &MNode, s: &mut String, depth: usize) {
|
||||
s.push('_');
|
||||
braced(lim, s, depth);
|
||||
} else if let [MNode::GroupChr { chr, top, e: inner }] = e.as_slice() {
|
||||
s.push_str(if *top { "\\overbrace" } else { "\\underbrace" });
|
||||
s.push_str(group_chr_tex(*chr, *top));
|
||||
braced(inner, s, depth);
|
||||
s.push(if *upper { '^' } else { '_' });
|
||||
braced(lim, s, depth);
|
||||
let _ = chr;
|
||||
} else {
|
||||
s.push_str(if *upper { "\\overset" } else { "\\underset" });
|
||||
braced(lim, s, depth);
|
||||
@@ -941,8 +993,8 @@ fn node(n: &MNode, s: &mut String, depth: usize) {
|
||||
braced(e, s, depth);
|
||||
}
|
||||
MNode::Boxed { e } => braced(e, s, depth),
|
||||
MNode::GroupChr { top, e, .. } => {
|
||||
s.push_str(if *top { "\\overbrace" } else { "\\underbrace" });
|
||||
MNode::GroupChr { chr, top, e } => {
|
||||
s.push_str(group_chr_tex(*chr, *top));
|
||||
braced(e, s, depth);
|
||||
}
|
||||
MNode::EqArr { rows } => {
|
||||
@@ -1034,6 +1086,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_character_latex_roundtrip() {
|
||||
for cmd in ["\\overparen{a+b}", "\\underparen{a+b}", "\\overbracket{x}", "\\underbracket{x}"] {
|
||||
let n = parse_latex(cmd);
|
||||
let tex = to_latex(&n);
|
||||
assert_eq!(tex, cmd);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_latex_never_panics() {
|
||||
for s in ["", "\\", "{", "}", "^", "_", "\\frac", "\\sqrt[", "\\left(", "\\right)", "\\begin{matrix", "&&\\\\", "{{{{", "\\end{x}", "a^^b__c"]
|
||||
@@ -1049,4 +1110,46 @@ mod tests {
|
||||
let deep = "\\hat".repeat(5000) + "x";
|
||||
let _ = parse_latex(&deep);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_column_specs_and_aligned_optional_args() {
|
||||
let n = parse_latex(r"\begin{array}{lcr} a & b & c \\ d & e & f \end{array}");
|
||||
let MNode::Matrix { rows, col_jc } = &n[0] else { panic!("{n:#?}") };
|
||||
assert_eq!(col_jc, &[ColJc::Left, ColJc::Center, ColJc::Right]);
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(crate::math::to_linear(&rows[0][0]), "a");
|
||||
assert_eq!(crate::math::to_linear(&rows[0][1]), "b");
|
||||
assert_eq!(crate::math::to_linear(&rows[0][2]), "c");
|
||||
|
||||
let n = parse_latex(r"\begin{aligned}[t] x &= 1 \\ y &= 2 \end{aligned}");
|
||||
assert!(matches!(&n[0], MNode::EqArr { rows } if rows.len() == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operatorname_starred_and_tag() {
|
||||
let n = parse_latex(r"\operatorname*{argmin}_{x} f(x)");
|
||||
assert!(matches!(&n[0], MNode::Lim { upper: false, .. }));
|
||||
|
||||
let n = parse_latex(r"E=mc^2 \tag{1}");
|
||||
let MNode::EqArr { rows } = &n[0] else { panic!("{n:#?}") };
|
||||
assert!(crate::math::has_number_mark(&rows[0]));
|
||||
|
||||
let n = parse_latex(r"E=mc^2 \tag*{(A)}");
|
||||
let MNode::EqArr { rows } = &n[0] else { panic!("{n:#?}") };
|
||||
assert!(crate::math::has_number_mark(&rows[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delim_preserves_custom_separator() {
|
||||
let delim = MNode::Delim {
|
||||
beg: Some('{'),
|
||||
end: Some('}'),
|
||||
sep: Some('‖'),
|
||||
grow: true,
|
||||
shp_match: false,
|
||||
elems: vec![vec![MNode::Run(MRun::new("x"))], vec![MNode::Run(MRun::new("y"))]],
|
||||
};
|
||||
let tex = to_latex(&[delim]);
|
||||
assert!(tex.contains(r"\middle\|"), "Expected \\middle\\|, got: {tex}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -587,8 +587,8 @@ impl P {
|
||||
}
|
||||
}
|
||||
|
||||
/// A script or limit: a parenthesised group, a structure, a number, a signed operand or one
|
||||
/// character.
|
||||
/// A script or limit: a parenthesised group, a structure, a number, a signed operand, a run of
|
||||
/// letters (and digits) or one other character.
|
||||
fn script_operand(&mut self, stops: &[char]) -> Arg {
|
||||
if self.tired() {
|
||||
return self.rest();
|
||||
@@ -612,7 +612,7 @@ impl P {
|
||||
Some(c) if is_prefix(c) || closer(c).is_some() => self.atom(stops),
|
||||
Some(c) if c.is_ascii_digit() => {
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|k| k.is_ascii_digit() || k == '.') {
|
||||
while self.peek().is_some_and(|k| k.is_alphanumeric() || k == '.') {
|
||||
self.i += 1;
|
||||
}
|
||||
let t: String = self.c.get(start..self.i).unwrap_or(&[]).iter().collect();
|
||||
@@ -624,10 +624,16 @@ impl P {
|
||||
v.extend(self.script_operand(stops));
|
||||
v
|
||||
}
|
||||
Some(c) if c.is_ascii_alphabetic() => {
|
||||
// A function name as a script (`e^sin x` is rare): one letter.
|
||||
self.i += 1;
|
||||
vec![text(c)]
|
||||
Some(c) if c.is_alphabetic() => {
|
||||
// Word (#1609): the whole run of letters and digits up to a space or operator, so
|
||||
// `V_dd` is V with a subscript `dd`, exactly like `V_(dd)`.
|
||||
let start = self.i;
|
||||
while self.peek().is_some_and(|k| k.is_alphanumeric()) {
|
||||
self.i += 1;
|
||||
}
|
||||
let t: String = self.c.get(start..self.i).unwrap_or(&[]).iter().collect();
|
||||
// A known function name stays upright, as Word builds it.
|
||||
vec![MNode::Run(if FUNCTION_NAMES.contains(&t.as_str()) { MRun::plain(t) } else { MRun::new(t) })]
|
||||
}
|
||||
Some(c) if !stops.contains(&c) && c != ' ' && !is_closer(c) => {
|
||||
self.i += 1;
|
||||
|
||||
@@ -156,6 +156,11 @@ impl ListKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bullet a level of a plain bulleted list shows: • ○ ▪ repeating (`level` is zero-based).
|
||||
pub fn default_bullet(level: usize) -> char {
|
||||
['•', '○', '▪'][level % 3]
|
||||
}
|
||||
|
||||
fn bullet_level(i: usize, c: char) -> Level {
|
||||
Level {
|
||||
format: NumFormat::Bullet,
|
||||
@@ -188,8 +193,8 @@ pub fn levels_for(kind: ListKind) -> Vec<Level> {
|
||||
let lvl = |format: NumFormat, text: String| Level { format, text, indent: ind, hanging: 18.0, ..Level::default() };
|
||||
let n = i + 1;
|
||||
match kind {
|
||||
ListKind::Bullet => bullet_level(i, ['•', '○', '▪'][i % 3]),
|
||||
ListKind::BulletChar(c) => bullet_level(i, if i == 0 { c } else { ['•', '○', '▪'][i % 3] }),
|
||||
ListKind::Bullet => bullet_level(i, default_bullet(i)),
|
||||
ListKind::BulletChar(c) => bullet_level(i, if i == 0 { c } else { default_bullet(i) }),
|
||||
ListKind::Numbered => lvl(cyc(NumFormat::Decimal, NumFormat::LowerLetter, NumFormat::LowerRoman), format!("%{n}.")),
|
||||
ListKind::NumberedParen => lvl(cyc(NumFormat::Decimal, NumFormat::LowerLetter, NumFormat::LowerRoman), format!("%{n})")),
|
||||
ListKind::UpperLetter => lvl(cyc(NumFormat::UpperLetter, NumFormat::LowerLetter, NumFormat::LowerRoman), format!("%{n}.")),
|
||||
|
||||
+96
-3
@@ -216,6 +216,10 @@ pub struct Float {
|
||||
/// laid out, as Word for Windows does (Word for Mac draws hidden VML shapes).
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub hidden: bool,
|
||||
/// Anchored in a table cell but placed on the page, not in the cell (`wp:anchor/@layoutInCell`
|
||||
/// off, any VML shape in a header or footer): a picture watermark in a header that starts with a table.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub outside_cell: bool,
|
||||
}
|
||||
|
||||
/// Longest alternative text kept (characters): hostile files and commands are capped.
|
||||
@@ -316,6 +320,60 @@ pub enum NoteKind {
|
||||
Endnote,
|
||||
}
|
||||
|
||||
/// Where a positional tab ([`InlineObject::PositionalTab`]) lands on its line, and how the text
|
||||
/// after it lines up there (ECMA-376 `ST_PTabAlignment`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PTabAlign {
|
||||
#[default]
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
}
|
||||
|
||||
impl PTabAlign {
|
||||
pub const ALL: [PTabAlign; 3] = [PTabAlign::Left, PTabAlign::Center, PTabAlign::Right];
|
||||
|
||||
/// The OOXML name (`left`, `center`, `right`).
|
||||
pub fn ooxml(self) -> &'static str {
|
||||
match self {
|
||||
PTabAlign::Left => "left",
|
||||
PTabAlign::Center => "center",
|
||||
PTabAlign::Right => "right",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_ooxml(v: &str) -> Option<PTabAlign> {
|
||||
PTabAlign::ALL.into_iter().find(|a| a.ooxml() == v)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a positional tab's place is measured against (ECMA-376 `ST_PTabRelativeTo`): the text
|
||||
/// margins, or the paragraph's indents.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PTabBase {
|
||||
#[default]
|
||||
Margin,
|
||||
Indent,
|
||||
}
|
||||
|
||||
impl PTabBase {
|
||||
pub const ALL: [PTabBase; 2] = [PTabBase::Margin, PTabBase::Indent];
|
||||
|
||||
/// The OOXML name (`margin`, `indent`).
|
||||
pub fn ooxml(self) -> &'static str {
|
||||
match self {
|
||||
PTabBase::Margin => "margin",
|
||||
PTabBase::Indent => "indent",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_ooxml(v: &str) -> Option<PTabBase> {
|
||||
PTabBase::ALL.into_iter().find(|a| a.ooxml() == v)
|
||||
}
|
||||
}
|
||||
|
||||
/// How ruby (phonetic guide) text lines up over its base text (ECMA-376 `ST_RubyAlign`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -549,6 +607,17 @@ pub enum InlineObject {
|
||||
#[serde(default, skip_serializing_if = "CharProps::is_empty")]
|
||||
props: Box<CharProps>,
|
||||
},
|
||||
/// A positional tab (Word's alignment tab, `w:ptab`): it goes to the left edge, centre or
|
||||
/// right edge of the margins or of the indents, whatever the paragraph's tab stops, and the
|
||||
/// text after it lines up there. Text already past that place sends it to the next line.
|
||||
PositionalTab {
|
||||
#[serde(default)]
|
||||
align: PTabAlign,
|
||||
#[serde(default)]
|
||||
relative_to: PTabBase,
|
||||
#[serde(default)]
|
||||
leader: crate::props::TabLeader,
|
||||
},
|
||||
/// Something we don't model, kept for round-trip (raw XML of the source format).
|
||||
Opaque {
|
||||
format: String,
|
||||
@@ -678,6 +747,14 @@ impl InlineObject {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// A legacy form field's definition (`FORMCHECKBOX`, `FORMTEXT`, `FORMDROPDOWN`), read from
|
||||
/// the `w:ffData` it keeps; `None` for anything else.
|
||||
pub fn legacy_form(&self) -> Option<crate::legacy_form::LegacyForm> {
|
||||
match self {
|
||||
InlineObject::Field { form, .. } if !form.is_empty() => crate::legacy_form::LegacyForm::parse(form),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Zero-width markers don't take part in layout.
|
||||
pub fn is_marker(&self) -> bool {
|
||||
matches!(
|
||||
@@ -756,6 +833,7 @@ impl InlineObject {
|
||||
InlineObject::Field { result, .. } => result,
|
||||
InlineObject::Equation { linear, .. } => linear,
|
||||
InlineObject::Ruby { base, .. } => base,
|
||||
InlineObject::PositionalTab { .. } => "\t",
|
||||
InlineObject::Opaque { text, .. } => text,
|
||||
_ => "",
|
||||
}
|
||||
@@ -870,7 +948,7 @@ impl Paragraph {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
let font = runs.peek().filter(|(r, _)| r.contains(&i)).and_then(|(_, p)| p.font.as_deref());
|
||||
let font = runs.peek().filter(|(r, _)| r.contains(&i)).and_then(|(_, p)| p.shown_font());
|
||||
out.push(font.and_then(|f| crate::symbol_fonts::symbol_char(f, c)).unwrap_or(c));
|
||||
}
|
||||
out
|
||||
@@ -1322,7 +1400,7 @@ impl Paragraph {
|
||||
let mut a = 0;
|
||||
let mut prev_end = false;
|
||||
for (i, c) in t.char_indices() {
|
||||
if i >= off {
|
||||
if i > off {
|
||||
break;
|
||||
}
|
||||
if prev_end && c != ' ' {
|
||||
@@ -1335,7 +1413,9 @@ impl Paragraph {
|
||||
}
|
||||
}
|
||||
let mut b = t.len();
|
||||
let mut ended = false;
|
||||
// A caret on the space right after a sentence's end belongs to that sentence; a terminator
|
||||
// directly followed by text ("Hello.World") doesn't end the sentence the caret is in.
|
||||
let mut ended = t.get(..off).unwrap_or("").ends_with(['.', '!', '?']) && t.get(off..).unwrap_or("").starts_with(' ');
|
||||
for (i, c) in t.get(off..).unwrap_or("").char_indices() {
|
||||
if ended && c != ' ' {
|
||||
b = off + i;
|
||||
@@ -1353,6 +1433,19 @@ impl Paragraph {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sentence_at_sentence_start() {
|
||||
let p = Paragraph::with_text("Hello. World", CharProps::default());
|
||||
assert_eq!(p.sentence_at(0), (0, 7));
|
||||
assert_eq!(p.sentence_at(6), (0, 7));
|
||||
assert_eq!(p.sentence_at(7), (7, 12));
|
||||
assert_eq!(p.sentence_at(8), (7, 12));
|
||||
assert_eq!(p.sentence_at(99), (7, 12));
|
||||
let p = Paragraph::with_text("Hello.World", CharProps::default());
|
||||
assert_eq!(p.sentence_at(6), (6, 11));
|
||||
assert_eq!(p.sentence_at(8), (6, 11));
|
||||
}
|
||||
|
||||
fn bold() -> CharProps {
|
||||
CharProps { bold: Some(true), ..Default::default() }
|
||||
}
|
||||
|
||||
+202
-6
@@ -155,6 +155,46 @@ impl Underline {
|
||||
}
|
||||
}
|
||||
|
||||
/// The OpenType ligatures a run asks for ([MS-DOCX] `w14:ligatures`): standard (`liga`),
|
||||
/// contextual (`clig`), historical (`hlig`) and discretional (`dlig`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Ligatures {
|
||||
pub standard: bool,
|
||||
pub contextual: bool,
|
||||
pub historical: bool,
|
||||
pub discretional: bool,
|
||||
}
|
||||
|
||||
impl Ligatures {
|
||||
/// Every combination of the four flags.
|
||||
pub fn all() -> impl Iterator<Item = Ligatures> {
|
||||
(0u8..16).map(|b| Ligatures { standard: b & 1 != 0, contextual: b & 2 != 0, historical: b & 4 != 0, discretional: b & 8 != 0 })
|
||||
}
|
||||
/// The `w14:ligatures/@w14:val` name: `none`, `all`, or the set flags joined in camelCase
|
||||
/// (`standardContextual`).
|
||||
pub fn ooxml(self) -> String {
|
||||
let on: Vec<&str> =
|
||||
[(self.standard, "standard"), (self.contextual, "contextual"), (self.historical, "historical"), (self.discretional, "discretional")]
|
||||
.into_iter()
|
||||
.filter_map(|(on, n)| on.then_some(n))
|
||||
.collect();
|
||||
match on.len() {
|
||||
0 => "none".into(),
|
||||
4 => "all".into(),
|
||||
_ => on
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, n)| n.chars().enumerate().map(move |(j, c)| if i > 0 && j == 0 { c.to_ascii_uppercase() } else { c }))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
/// `None` for a name [MS-DOCX] doesn't define.
|
||||
pub fn from_ooxml(s: &str) -> Option<Ligatures> {
|
||||
Ligatures::all().find(|l| l.ooxml() == s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VertAlign {
|
||||
@@ -286,6 +326,11 @@ pub struct CharProps {
|
||||
pub style: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font: Option<String>,
|
||||
/// The symbol's own font (OOXML `w:sym/@w:font`, ECMA-376 §17.3.3.30), set on a symbol
|
||||
/// character from a `w:sym` or Insert › Symbol: it is shown in this font whatever `font` is,
|
||||
/// so changing the text's font keeps the symbol. `None` = the run's font.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sym_font: Option<String>,
|
||||
/// Points.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<f32>,
|
||||
@@ -331,6 +376,10 @@ pub struct CharProps {
|
||||
/// Kerning for fonts at or above this size (points); 0 = off.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub kern: Option<f32>,
|
||||
/// OpenType ligatures (`w14:ligatures`). `None` leaves WordCraft's default: standard and
|
||||
/// contextual ligatures.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ligatures: Option<Ligatures>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub outline: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -372,6 +421,10 @@ pub struct CharProps {
|
||||
/// BCP 47 language of complex-script text (`w:lang/@w:bidi`, e.g. `fa-IR`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub lang_bidi: Option<String>,
|
||||
/// East Asian typography: two lines in one and horizontal in vertical (`w:eastAsianLayout`).
|
||||
/// Kept for round trip; layout doesn't apply it yet.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub east_asian_layout: Option<EastAsianLayout>,
|
||||
/// Hyperlink target: a URL, or `#bookmark` for an internal link.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub link: Option<String>,
|
||||
@@ -386,6 +439,60 @@ pub struct CharProps {
|
||||
pub fmt_change: Option<Box<PropChange<CharProps>>>,
|
||||
}
|
||||
|
||||
/// East Asian typography settings of a run (ISO/IEC 29500-1 §17.3.2.10, `w:eastAsianLayout`):
|
||||
/// *two lines in one* sets the run's text on two sub-lines inside one line (warichu), *horizontal
|
||||
/// in vertical* turns it 90° to read across a vertical line (tate-chu-yoko). Each attribute is
|
||||
/// `None` when the file doesn't say.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct EastAsianLayout {
|
||||
/// East Asian typography run id (`w:id`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<i32>,
|
||||
/// Two lines in one (`w:combine`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub combine: Option<bool>,
|
||||
/// Brackets around two lines in one (`w:combineBrackets`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub combine_brackets: Option<CombineBrackets>,
|
||||
/// Horizontal in vertical (`w:vert`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vert: Option<bool>,
|
||||
/// Compress horizontal-in-vertical text to the line height (`w:vertCompress`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vert_compress: Option<bool>,
|
||||
}
|
||||
|
||||
/// Brackets around two lines in one (`ST_CombineBrackets`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum CombineBrackets {
|
||||
None,
|
||||
Round,
|
||||
Square,
|
||||
Angle,
|
||||
Curly,
|
||||
}
|
||||
|
||||
impl CombineBrackets {
|
||||
pub const ALL: [CombineBrackets; 5] =
|
||||
[CombineBrackets::None, CombineBrackets::Round, CombineBrackets::Square, CombineBrackets::Angle, CombineBrackets::Curly];
|
||||
/// OOXML `w:combineBrackets` value.
|
||||
pub fn ooxml(self) -> &'static str {
|
||||
match self {
|
||||
CombineBrackets::None => "none",
|
||||
CombineBrackets::Round => "round",
|
||||
CombineBrackets::Square => "square",
|
||||
CombineBrackets::Angle => "angle",
|
||||
CombineBrackets::Curly => "curly",
|
||||
}
|
||||
}
|
||||
/// The value for `s`, `None` for one the schema doesn't have.
|
||||
pub fn from_ooxml(s: &str) -> Option<CombineBrackets> {
|
||||
CombineBrackets::ALL.into_iter().find(|b| b.ooxml() == s)
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracked formatting change (ECMA-376 §17.13.5: `w:rPrChange`, `w:pPrChange`,
|
||||
/// `w:tblPrChange`, `w:trPrChange`, `w:tcPrChange`, `w:sectPrChange`): the properties as they
|
||||
/// were before the change, and the revision (author, date) that made it.
|
||||
@@ -440,9 +547,9 @@ impl CharProps {
|
||||
/// The fields of `self` that differ from `base` (equal ones unset): what `self` adds when
|
||||
/// overlaid on `base`.
|
||||
pub fn minus(mut self, base: &CharProps) -> CharProps {
|
||||
drop_same_fields!(self, base; style, font, size, bold, italic, underline, underline_color, strike, double_strike, color, highlight,
|
||||
drop_same_fields!(self, base; style, font, sym_font, size, bold, italic, underline, underline_color, strike, double_strike, color, highlight,
|
||||
shading, border, vert_align, caps, small_caps, hidden, spacing, scale, position, kern, outline, shadow, emboss, engrave, lang, no_proof, rtl,
|
||||
cs, font_cs, size_cs, bold_cs, italic_cs, lang_bidi, link, ins, del);
|
||||
cs, font_cs, size_cs, bold_cs, italic_cs, lang_bidi, east_asian_layout, link, ins, del, ligatures);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -451,9 +558,9 @@ impl CharProps {
|
||||
/// Plain and complex-script properties inherit independently. Commands that intend to
|
||||
/// format both scripts must set both values explicitly.
|
||||
pub fn overlay(&mut self, patch: &CharProps) {
|
||||
overlay_fields!(self, patch; style, font, size, bold, italic, underline, underline_color, strike, double_strike, color, highlight,
|
||||
overlay_fields!(self, patch; style, font, sym_font, size, bold, italic, underline, underline_color, strike, double_strike, color, highlight,
|
||||
shading, border, vert_align, caps, small_caps, hidden, spacing, scale, position, kern, outline, shadow, emboss, engrave, lang, no_proof, rtl,
|
||||
cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, link, ins, del, fmt_change);
|
||||
cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, east_asian_layout, link, ins, del, fmt_change, ligatures);
|
||||
if let Some(p) = &patch.text_effects {
|
||||
self.text_effects.get_or_insert_with(Default::default).overlay(p);
|
||||
}
|
||||
@@ -465,10 +572,29 @@ impl CharProps {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == CharProps::default()
|
||||
}
|
||||
/// The font a character of this run is shown in: the symbol's own font when it has one
|
||||
/// ([`Self::sym_font`]), else the run's font.
|
||||
pub fn shown_font(&self) -> Option<&str> {
|
||||
self.sym_font.as_deref().filter(|f| !f.trim().is_empty()).or(self.font.as_deref())
|
||||
}
|
||||
/// The same formatting for text typed or painted next to a symbol: without the symbol's own
|
||||
/// font.
|
||||
pub fn without_symbol(mut self) -> CharProps {
|
||||
self.sym_font = None;
|
||||
self
|
||||
}
|
||||
/// Clear direct formatting but keep what isn't "formatting" (links, revisions, character style
|
||||
/// is cleared too, as Word's Clear Formatting does).
|
||||
pub fn cleared(&self) -> CharProps {
|
||||
CharProps { link: self.link.clone(), ins: self.ins, del: self.del, fmt_change: self.fmt_change.clone(), ..Default::default() }
|
||||
CharProps {
|
||||
link: self.link.clone(),
|
||||
ins: self.ins,
|
||||
del: self.del,
|
||||
fmt_change: self.fmt_change.clone(),
|
||||
// A symbol stays the symbol it is.
|
||||
sym_font: self.sym_font.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
/// Just the formatting: without the link, revision marks and tracked formatting change.
|
||||
pub fn formatting(&self) -> CharProps {
|
||||
@@ -793,6 +919,16 @@ pub struct ParaProps {
|
||||
/// Drop cap: lines to drop (0 = none) — applies to the first character(s).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub drop_cap: Option<u8>,
|
||||
/// Drop cap "In margin" (`w:dropCap="margin"`): the letter hangs in the left margin and the
|
||||
/// text keeps its indent. Unset = dropped into the text.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub drop_cap_margin: Option<bool>,
|
||||
/// The drop cap's distance from the text, in points (`w:hSpace`). Unset = 0.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub drop_cap_distance: Option<f32>,
|
||||
/// The drop cap letter's font family (the cap run's `w:rFonts`). Unset = the text's font.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub drop_cap_font: Option<String>,
|
||||
/// A text frame (`w:framePr` other than a drop cap): the paragraph is placed apart from the
|
||||
/// text, which may wrap around it — a footer's page number in a frame, for instance.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -833,7 +969,7 @@ impl ParaProps {
|
||||
pub fn overlay(&mut self, patch: &ParaProps) {
|
||||
overlay_fields!(self, patch; style, align, indent_left, indent_right, indent_first, indent_left_chars, indent_right_chars, indent_first_chars, space_before, space_after, space_before_auto, space_after_auto, line_spacing,
|
||||
contextual_spacing, mirror_indents, keep_next, keep_lines, page_break_before, widow_control, outline_level, numbering, tabs, shading, borders,
|
||||
suppress_hyphens, suppress_line_numbers, bidi, drop_cap, frame, kinsoku, word_wrap, overflow_punct, top_line_punct, auto_space_de, auto_space_dn,
|
||||
suppress_hyphens, suppress_line_numbers, bidi, drop_cap, drop_cap_margin, drop_cap_distance, drop_cap_font, frame, kinsoku, word_wrap, overflow_punct, top_line_punct, auto_space_de, auto_space_dn,
|
||||
snap_to_grid);
|
||||
}
|
||||
pub fn overlaid(mut self, patch: &ParaProps) -> ParaProps {
|
||||
@@ -1133,6 +1269,9 @@ pub struct CellProps {
|
||||
pub valign: Option<VAlign>,
|
||||
/// Cell margins override (top, left, bottom, right), points.
|
||||
pub margins: Option<[f32; 4]>,
|
||||
/// Per-side overrides when `margins` is absent; omitted sides inherit table defaults.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub partial_margins: Option<[Option<f32>; 4]>,
|
||||
/// Which way the cell's text runs.
|
||||
pub text_direction: TextDirection,
|
||||
/// The file states the horizontal direction (`lrTb`) outright; saving writes it back.
|
||||
@@ -1148,6 +1287,17 @@ pub struct CellProps {
|
||||
pub fmt_change: Option<Box<PropChange<CellProps>>>,
|
||||
}
|
||||
|
||||
impl CellProps {
|
||||
/// Resolve top, left, bottom and right margins against the current table defaults.
|
||||
/// A complete override takes precedence over per-side overrides.
|
||||
pub fn resolved_margins(&self, defaults: [f32; 4]) -> [f32; 4] {
|
||||
if let Some(margins) = self.margins {
|
||||
return margins;
|
||||
}
|
||||
self.partial_margins.map_or(defaults, |sides| std::array::from_fn(|i| sides[i].unwrap_or(defaults[i])))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1196,6 +1346,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 16 `w14:ligatures` values of [MS-DOCX], each to its flags and back.
|
||||
#[test]
|
||||
fn ligature_names() {
|
||||
let l = |standard, contextual, historical, discretional| Ligatures { standard, contextual, historical, discretional };
|
||||
for (name, flags) in [
|
||||
("none", l(false, false, false, false)),
|
||||
("standard", l(true, false, false, false)),
|
||||
("contextual", l(false, true, false, false)),
|
||||
("historical", l(false, false, true, false)),
|
||||
("discretional", l(false, false, false, true)),
|
||||
("standardContextual", l(true, true, false, false)),
|
||||
("standardHistorical", l(true, false, true, false)),
|
||||
("contextualHistorical", l(false, true, true, false)),
|
||||
("standardDiscretional", l(true, false, false, true)),
|
||||
("contextualDiscretional", l(false, true, false, true)),
|
||||
("historicalDiscretional", l(false, false, true, true)),
|
||||
("standardContextualHistorical", l(true, true, true, false)),
|
||||
("standardContextualDiscretional", l(true, true, false, true)),
|
||||
("standardHistoricalDiscretional", l(true, false, true, true)),
|
||||
("contextualHistoricalDiscretional", l(false, true, true, true)),
|
||||
("all", l(true, true, true, true)),
|
||||
] {
|
||||
assert_eq!(Ligatures::from_ooxml(name), Some(flags), "{name}");
|
||||
assert_eq!(flags.ooxml(), name);
|
||||
}
|
||||
assert_eq!(Ligatures::all().count(), 16);
|
||||
for bad in ["", "Standard", "contextualStandard", "standardstandard", "allx"] {
|
||||
assert_eq!(Ligatures::from_ooxml(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_direction_names() {
|
||||
let mut d = TextDirection::Horizontal;
|
||||
@@ -1257,4 +1438,19 @@ mod tests {
|
||||
let back: CharProps = serde_json::from_str(&s).unwrap();
|
||||
assert_eq!(back, p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_font_is_optional_in_json_and_survives_font_changes() {
|
||||
// Older documents (no `symFont`) still load.
|
||||
let old: CharProps = serde_json::from_str(r#"{"font":"Arial"}"#).unwrap();
|
||||
assert_eq!(old.sym_font, None);
|
||||
let p = CharProps { font: Some("Arial".into()), sym_font: Some("Wingdings".into()), ..Default::default() };
|
||||
let s = serde_json::to_string(&p).unwrap();
|
||||
assert!(s.contains(r#""symFont":"Wingdings""#), "{s}");
|
||||
assert_eq!(serde_json::from_str::<CharProps>(&s).unwrap(), p);
|
||||
// A font change keeps the symbol's own font; Clear Formatting too.
|
||||
let changed = p.clone().overlaid(&CharProps { font: Some("Times New Roman".into()), ..Default::default() });
|
||||
assert_eq!(changed.sym_font.as_deref(), Some("Wingdings"));
|
||||
assert_eq!(p.cleared().sym_font.as_deref(), Some("Wingdings"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ use crate::styles::{StyleKind, StyleSheet};
|
||||
/// Automatic (HTML-style) paragraph spacing, points: what Word for Windows gives `w:beforeAutospacing`
|
||||
/// and `w:afterAutospacing` at any font size (measured).
|
||||
pub const AUTO_SPACING: f32 = 14.0;
|
||||
/// The largest drop cap distance from the text, in points (22", as Word's dialog allows).
|
||||
pub const MAX_DROP_CAP_DISTANCE: f32 = 1584.0;
|
||||
|
||||
/// Concrete character formatting.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -39,6 +41,10 @@ pub struct ResolvedChar {
|
||||
/// Kerning: the smallest font size, in points, that is kerned (`w:kern`); 0 = never kerned.
|
||||
#[serde(default)]
|
||||
pub kern: f32,
|
||||
/// OpenType ligatures (`w14:ligatures`); `None` = the shaper's default (standard and
|
||||
/// contextual).
|
||||
#[serde(default)]
|
||||
pub ligatures: Option<crate::props::Ligatures>,
|
||||
pub outline: bool,
|
||||
pub shadow: bool,
|
||||
pub emboss: bool,
|
||||
@@ -70,7 +76,8 @@ pub struct ResolvedChar {
|
||||
impl ResolvedChar {
|
||||
fn from(c: &CharProps) -> ResolvedChar {
|
||||
ResolvedChar {
|
||||
font: c.font.clone().unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
|
||||
// A symbol character is shown in its own font (`w:sym`), whatever the run's font.
|
||||
font: c.shown_font().map(str::to_string).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
|
||||
size: c.size.unwrap_or(11.0).clamp(1.0, 1638.0),
|
||||
bold: c.bold.unwrap_or(false),
|
||||
italic: c.italic.unwrap_or(false),
|
||||
@@ -90,6 +97,7 @@ impl ResolvedChar {
|
||||
scale: c.scale.unwrap_or(100.0).clamp(1.0, 600.0),
|
||||
position: c.position.unwrap_or(0.0).clamp(-800.0, 800.0),
|
||||
kern: c.kern.filter(|k| k.is_finite()).unwrap_or(0.0).clamp(0.0, 1638.0),
|
||||
ligatures: c.ligatures,
|
||||
outline: c.outline.unwrap_or(false),
|
||||
shadow: c.shadow.unwrap_or(false),
|
||||
emboss: c.emboss.unwrap_or(false),
|
||||
@@ -172,6 +180,15 @@ pub struct ResolvedPara {
|
||||
pub borders: Option<Borders>,
|
||||
pub bidi: bool,
|
||||
pub drop_cap: u8,
|
||||
/// The drop cap hangs in the margin (see `ParaProps::drop_cap_margin`).
|
||||
#[serde(default)]
|
||||
pub drop_cap_margin: bool,
|
||||
/// The drop cap's distance from the text, in points.
|
||||
#[serde(default)]
|
||||
pub drop_cap_distance: f32,
|
||||
/// The drop cap letter's font family; `None` = the text's.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub drop_cap_font: Option<String>,
|
||||
/// A text frame the paragraph sits in (see `ParaProps::frame`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub frame: Option<crate::props::TextFrame>,
|
||||
@@ -250,6 +267,9 @@ impl ResolvedPara {
|
||||
borders: p.borders.filter(Borders::any_visible),
|
||||
bidi: p.bidi.unwrap_or(false),
|
||||
drop_cap: p.drop_cap.unwrap_or(0).min(10),
|
||||
drop_cap_margin: p.drop_cap_margin.unwrap_or(false),
|
||||
drop_cap_distance: p.drop_cap_distance.filter(|d| d.is_finite()).unwrap_or(0.0).clamp(0.0, MAX_DROP_CAP_DISTANCE),
|
||||
drop_cap_font: p.drop_cap_font.clone().filter(|f| !f.trim().is_empty()),
|
||||
frame: p.frame.clone().filter(|_| p.drop_cap.unwrap_or(0) == 0),
|
||||
suppress_hyphens: p.suppress_hyphens.unwrap_or(false),
|
||||
suppress_line_numbers: p.suppress_line_numbers.unwrap_or(false),
|
||||
@@ -349,6 +369,8 @@ impl StyleSheet {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Only a character itself has a symbol font of its own (`w:sym`); a style never gives one.
|
||||
cp.sym_font = None;
|
||||
let mut direct = c.clone();
|
||||
direct.style = None;
|
||||
cp.overlay(&direct);
|
||||
@@ -360,6 +382,19 @@ impl StyleSheet {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #2036: only a character itself (direct formatting) has a symbol font of its own; a
|
||||
/// style never gives one to its text.
|
||||
#[test]
|
||||
fn a_style_never_gives_text_a_symbol_font() {
|
||||
let mut s = StyleSheet::builtin();
|
||||
if let Some(n) = s.get_mut("Normal") {
|
||||
n.chr.sym_font = Some("Wingdings".into());
|
||||
}
|
||||
assert_ne!(s.resolve_char(None, &CharProps::default()).font, "Wingdings");
|
||||
let direct = CharProps { sym_font: Some("Wingdings".into()), ..Default::default() };
|
||||
assert_eq!(s.resolve_char(None, &direct).font, "Wingdings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_resolves() {
|
||||
let s = StyleSheet::builtin();
|
||||
|
||||
@@ -795,6 +795,16 @@ fn is_horizontal(d: &crate::props::TextDirection) -> bool {
|
||||
}
|
||||
|
||||
impl SectionProps {
|
||||
/// Join the section before this one into it, as when the break between them is deleted:
|
||||
/// this section's setup stays, as in Word, and the headers and footers it leaves out (linked
|
||||
/// to the previous section) are taken from `before`, so its text keeps showing them.
|
||||
pub fn absorb(&mut self, before: &SectionProps) {
|
||||
for (own, prev) in [(&mut self.headers, &before.headers), (&mut self.footers, &before.footers)] {
|
||||
own.default = own.default.or(prev.default);
|
||||
own.first = own.first.or(prev.first);
|
||||
own.even = own.even.or(prev.even);
|
||||
}
|
||||
}
|
||||
/// Width of the text area, points.
|
||||
pub fn text_width(&self) -> f32 {
|
||||
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
|
||||
|
||||
@@ -68,13 +68,14 @@ impl SmartArtLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// The layout an id names (any ASCII case; `list` is the basic list).
|
||||
/// The layout an id names (any ASCII case, ignoring hyphens, underscores and spaces;
|
||||
/// `list` is the basic list; `basic process` or `process` is process, etc.).
|
||||
pub fn from_id(id: &str) -> Option<SmartArtLayout> {
|
||||
let id = id.trim();
|
||||
if id.eq_ignore_ascii_case("list") {
|
||||
let norm = id.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '_').collect::<String>();
|
||||
if norm.eq_ignore_ascii_case("list") {
|
||||
return Some(SmartArtLayout::BasicList);
|
||||
}
|
||||
SmartArtLayout::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(id))
|
||||
SmartArtLayout::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(&norm) || l.label().replace(' ', "").eq_ignore_ascii_case(&norm))
|
||||
}
|
||||
|
||||
/// The name shown for it.
|
||||
@@ -159,7 +160,8 @@ impl SmartArtColors {
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<SmartArtColors> {
|
||||
SmartArtColors::ALL.into_iter().find(|c| c.id().eq_ignore_ascii_case(id.trim()))
|
||||
let norm = id.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '_').collect::<String>();
|
||||
SmartArtColors::ALL.into_iter().find(|c| c.id().eq_ignore_ascii_case(&norm) || c.label().replace(' ', "").eq_ignore_ascii_case(&norm))
|
||||
}
|
||||
|
||||
/// The name shown for it.
|
||||
@@ -287,8 +289,9 @@ impl SmartArtSpec {
|
||||
|
||||
/// `s` as item text: control characters as spaces, ends trimmed, at most [`MAX_TEXT`] characters.
|
||||
pub fn clean_text(s: &str) -> String {
|
||||
let s: String = s.chars().take(MAX_TEXT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim().chars().take(MAX_TEXT).collect::<String>().trim_end().to_string()
|
||||
let trimmed = s.trim_start_matches(|c: char| c.is_whitespace() || c.is_control());
|
||||
let s: String = trimmed.chars().take(MAX_TEXT).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim_end().to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -319,6 +322,13 @@ mod tests {
|
||||
assert_eq!(s.descendants(5), 6..6);
|
||||
assert_eq!(s.descendants(99), 0..0);
|
||||
assert_eq!(SmartArtLayout::from_id("VENN"), Some(SmartArtLayout::Venn));
|
||||
assert_eq!(SmartArtLayout::from_id("basic-list"), Some(SmartArtLayout::BasicList));
|
||||
assert_eq!(SmartArtLayout::from_id("Basic Process"), Some(SmartArtLayout::Process));
|
||||
assert_eq!(SmartArtLayout::from_id("basic_cycle"), Some(SmartArtLayout::Cycle));
|
||||
assert_eq!(SmartArtLayout::from_id("list"), Some(SmartArtLayout::BasicList));
|
||||
assert_eq!(SmartArtColors::from_id("colorful"), Some(SmartArtColors::Colorful));
|
||||
assert_eq!(SmartArtColors::from_id("Accent 2"), Some(SmartArtColors::Accent2));
|
||||
assert_eq!(SmartArtColors::from_id("accent-4"), Some(SmartArtColors::Accent4));
|
||||
assert_eq!(clean_text(&format!("{}Valid Text", " ".repeat(1500))), "Valid Text");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
/// The symbol fonts this module knows, by lowercase family name.
|
||||
fn table(family: &str) -> Option<&'static [u32; 224]> {
|
||||
let f = family.trim();
|
||||
if f.eq_ignore_ascii_case("symbol") {
|
||||
if f.eq_ignore_ascii_case("symbol") || f.eq_ignore_ascii_case("symbol (pcl6)") {
|
||||
Some(&SYMBOL)
|
||||
} else if f.eq_ignore_ascii_case("wingdings") {
|
||||
Some(&WINGDINGS)
|
||||
@@ -243,6 +243,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcl6_symbol_encoding() {
|
||||
for family in ["Symbol (PCL6)", " symbol (pcl6) "] {
|
||||
assert!(is_symbol_font(family));
|
||||
for code in 0x20..=0xFF {
|
||||
let c = char::from_u32(code).unwrap();
|
||||
assert_eq!(symbol_char(family, c), symbol_char("Symbol", c));
|
||||
let pua = char::from_u32(0xF000 + code).unwrap();
|
||||
assert_eq!(symbol_char(family, pua), symbol_char("Symbol", pua));
|
||||
}
|
||||
assert_eq!(symbol_char(family, '\u{F0B3}'), Some('≥'));
|
||||
}
|
||||
assert!(!is_symbol_font("Symbol (unknown)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_uses_the_adobe_symbol_encoding() {
|
||||
assert_eq!(symbol_char("Symbol", '\u{F061}'), Some('α'));
|
||||
|
||||
+144
-23
@@ -127,9 +127,27 @@ impl Table {
|
||||
}
|
||||
|
||||
pub fn delete_row(&mut self, r: usize) {
|
||||
if r < self.rows.len() {
|
||||
self.rows.remove(r);
|
||||
if r >= self.rows.len() {
|
||||
return;
|
||||
}
|
||||
// A vertical merge that starts in this row now starts in the row below.
|
||||
let starts: Vec<usize> = (0..self.rows.get(r).map_or(0, |row| row.cells.len()))
|
||||
.filter(|&c| self.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.props.vmerge == VMerge::Restart))
|
||||
.map(|c| self.grid_col(r, c))
|
||||
.collect();
|
||||
for g in starts {
|
||||
let continues = |t: &Self, row: usize| {
|
||||
t.cell_at_grid(row, g).and_then(|i| t.rows.get(row)?.cells.get(i)).is_some_and(|x| x.props.vmerge == VMerge::Continue)
|
||||
};
|
||||
if !continues(self, r + 1) {
|
||||
continue;
|
||||
}
|
||||
let more = continues(self, r + 2);
|
||||
if let Some(c) = self.cell_at_grid(r + 1, g).and_then(|i| self.rows.get_mut(r + 1)?.cells.get_mut(i)) {
|
||||
c.props.vmerge = if more { VMerge::Restart } else { VMerge::None };
|
||||
}
|
||||
}
|
||||
self.rows.remove(r);
|
||||
}
|
||||
|
||||
/// Insert a grid column at grid index `g` (cells spanning it widen instead).
|
||||
@@ -256,28 +274,15 @@ impl Table {
|
||||
}
|
||||
}
|
||||
|
||||
/// Split cell `c` of row `r` into `n` cells horizontally. When the cell spans fewer grid
|
||||
/// columns than that, the grid is refined inside the cell only: the new borders divide it
|
||||
/// Split cell `c` of row `r` into `n` cells horizontally. Where the cell's grid lines don't
|
||||
/// fall on the equal parts, the grid is refined inside the cell only: the new borders divide it
|
||||
/// into equal parts, and the cells of other rows widen over the new grid columns, so their
|
||||
/// extent and the table's width stay as they were.
|
||||
pub fn split_cell(&mut self, r: usize, c: usize, n: usize) {
|
||||
/// extent and the table's width stay as they were. Returns the parts' spans, left to right.
|
||||
pub fn split_cell(&mut self, r: usize, c: usize, n: usize) -> Vec<usize> {
|
||||
let n = n.clamp(1, MAX_COLS);
|
||||
let Some(span) = self.rows.get(r).and_then(|row| row.cells.get(c)).map(Cell::span) else { return };
|
||||
let Some(span) = self.rows.get(r).and_then(|row| row.cells.get(c)).map(Cell::span) else { return Vec::new() };
|
||||
if n <= 1 {
|
||||
return;
|
||||
}
|
||||
if span >= n {
|
||||
let Some(row) = self.rows.get_mut(r) else { return };
|
||||
let Some(cell) = row.cells.get_mut(c) else { return };
|
||||
let w = cell.props.width.map(|w| w / n as f32);
|
||||
cell.props.width = w;
|
||||
cell.props.span = (span - (n - 1)) as u32;
|
||||
for k in 1..n {
|
||||
let mut nc = Cell::empty();
|
||||
nc.props.width = w;
|
||||
row.cells.insert(c + k, nc);
|
||||
}
|
||||
return;
|
||||
return vec![span];
|
||||
}
|
||||
let g = self.grid_col(r, c);
|
||||
let mut end = g.saturating_add(span);
|
||||
@@ -286,7 +291,7 @@ impl Table {
|
||||
self.grid.push(72.0);
|
||||
}
|
||||
if self.grid.len() < end {
|
||||
return;
|
||||
return vec![span];
|
||||
}
|
||||
for w in self.grid.get_mut(g..end).into_iter().flatten() {
|
||||
if !(w.is_finite() && *w > 0.0) {
|
||||
@@ -341,7 +346,7 @@ impl Table {
|
||||
// The cell now spans `g..end`: cut it at the new lines.
|
||||
let grid = self.grid.clone();
|
||||
let width = |a: usize, b: usize| grid.get(a..b).map(|x| x.iter().sum::<f32>());
|
||||
let Some(row) = self.rows.get_mut(r) else { return };
|
||||
let Some(row) = self.rows.get_mut(r) else { return Vec::new() };
|
||||
let mut a = g;
|
||||
let mut parts = Vec::with_capacity(lines.len() + 1);
|
||||
for &b in lines.iter().chain(std::iter::once(&end)) {
|
||||
@@ -363,6 +368,122 @@ impl Table {
|
||||
row.cells.insert((c + k).min(row.cells.len()), nc);
|
||||
}
|
||||
}
|
||||
parts.iter().map(|&(a, b)| b - a).collect()
|
||||
}
|
||||
|
||||
/// The rows cell `c` of row `r` covers: (first row, count). A vertically merged cell runs from
|
||||
/// its `Restart` cell down through the `Continue` cells that start at the same grid column.
|
||||
pub fn vertical_extent(&self, r: usize, c: usize) -> Option<(usize, usize)> {
|
||||
let g = self.grid_col(r, c);
|
||||
let at = |rr: usize| -> Option<VMerge> {
|
||||
let ci = self.cell_at_grid(rr, g)?;
|
||||
if self.grid_col(rr, ci) != g {
|
||||
return None;
|
||||
}
|
||||
Some(self.rows.get(rr)?.cells.get(ci)?.props.vmerge)
|
||||
};
|
||||
let mut top = r;
|
||||
if self.rows.get(r)?.cells.get(c)?.props.vmerge == VMerge::Continue {
|
||||
while let Some(up) = top.checked_sub(1).and_then(at) {
|
||||
if up == VMerge::None {
|
||||
break;
|
||||
}
|
||||
top -= 1;
|
||||
if up == VMerge::Restart {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut k = 1;
|
||||
if at(top) != Some(VMerge::None) {
|
||||
while at(top + k) == Some(VMerge::Continue) {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
Some((top, k))
|
||||
}
|
||||
|
||||
/// Split Cells: cut cell `c` of row `r` into `cols` × `rows` cells. A cell one row high gets
|
||||
/// `rows - 1` new rows under it, over which the row's other cells merge down; a vertically
|
||||
/// merged cell is regrouped instead, so `rows` must divide its height. The content stays in
|
||||
/// the first part. Returns false (with the table unchanged) when the split can't be made.
|
||||
pub fn split_cell_grid(&mut self, r: usize, c: usize, cols: usize, rows: usize) -> bool {
|
||||
let (cols, rows) = (cols.clamp(1, MAX_COLS), rows.clamp(1, MAX_ROWS));
|
||||
let Some((top, k)) = self.vertical_extent(r, c) else { return false };
|
||||
let g = self.grid_col(r, c);
|
||||
let Some(ci) = self.cell_at_grid(top, g) else { return false };
|
||||
if (k > 1 && k % rows != 0) || (k == 1 && self.rows.len().saturating_add(rows - 1) > MAX_ROWS) {
|
||||
return false;
|
||||
}
|
||||
let height = if k > 1 { k } else { rows };
|
||||
if k > 1 && rows > 1 {
|
||||
let q = k / rows;
|
||||
for i in 0..k {
|
||||
if let Some(cj) = self.cell_at_grid(top + i, g)
|
||||
&& let Some(cell) = self.rows.get_mut(top + i).and_then(|row| row.cells.get_mut(cj))
|
||||
{
|
||||
cell.props.vmerge = if q == 1 {
|
||||
VMerge::None
|
||||
} else if i % q == 0 {
|
||||
VMerge::Restart
|
||||
} else {
|
||||
VMerge::Continue
|
||||
};
|
||||
}
|
||||
}
|
||||
} else if k == 1 && rows > 1 {
|
||||
let Some(src) = self.rows.get_mut(top) else { return false };
|
||||
let mut like = Row { props: src.props.clone(), cells: Vec::with_capacity(src.cells.len()), controls: ControlWrap::default() };
|
||||
like.props.header = false;
|
||||
for (i, cell) in src.cells.iter_mut().enumerate() {
|
||||
let mut nc = Cell::empty();
|
||||
nc.props = cell.props.clone();
|
||||
if i == ci {
|
||||
cell.props.vmerge = VMerge::None;
|
||||
nc.props.vmerge = VMerge::None;
|
||||
} else {
|
||||
// The row's other cells merge down over the new rows.
|
||||
if cell.props.vmerge == VMerge::None {
|
||||
cell.props.vmerge = VMerge::Restart;
|
||||
}
|
||||
nc.props.vmerge = VMerge::Continue;
|
||||
}
|
||||
like.cells.push(nc);
|
||||
}
|
||||
for _ in 1..rows {
|
||||
self.rows.insert(top + 1, like.clone());
|
||||
}
|
||||
}
|
||||
if cols > 1 {
|
||||
let spans = self.split_cell(top, ci, cols);
|
||||
let total: usize = spans.iter().sum();
|
||||
let vmerge = self.rows.get(top).and_then(|row| row.cells.get(ci)).map(|cell| cell.props.vmerge).unwrap_or_default();
|
||||
if let Some(row) = self.rows.get_mut(top) {
|
||||
for cell in row.cells.iter_mut().skip(ci + 1).take(spans.len().saturating_sub(1)) {
|
||||
cell.props.vmerge = vmerge;
|
||||
}
|
||||
}
|
||||
// The cells under it, which the new grid lines widened, are cut the same way.
|
||||
let grid = self.grid.clone();
|
||||
let width = |a: usize, b: usize| grid.get(a..b).map(|x| x.iter().sum::<f32>());
|
||||
for rr in top + 1..top + height {
|
||||
let Some(cj) = self.cell_at_grid(rr, g).filter(|&cj| self.grid_col(rr, cj) == g) else { continue };
|
||||
let Some(row) = self.rows.get_mut(rr) else { continue };
|
||||
let Some(cell) = row.cells.get_mut(cj).filter(|cell| cell.span() == total) else { continue };
|
||||
let mut a = g;
|
||||
let mut parts = Vec::with_capacity(spans.len());
|
||||
for (n, &span) in spans.iter().enumerate() {
|
||||
let mut part = if n == 0 { cell.clone() } else { Cell::empty() };
|
||||
part.props.vmerge = cell.props.vmerge;
|
||||
part.props.span = span as u32;
|
||||
part.props.width = width(a, a + span);
|
||||
a += span;
|
||||
parts.push(part);
|
||||
}
|
||||
row.cells.splice(cj..=cj, parts);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn total_width(&self) -> f32 {
|
||||
|
||||
@@ -27,7 +27,7 @@ fn u32_at(bytes: &[u8], offset: usize) -> Option<u32> {
|
||||
}
|
||||
|
||||
fn parse(bytes: &[u8]) -> Option<CoreProps> {
|
||||
if bytes.get(..2)? != [0xfe, 0xff] || bytes.get(28..44)? != SUMMARY_FMTID || u32_at(bytes, 24)? != 1 {
|
||||
if bytes.get(..2)? != [0xfe, 0xff] || bytes.get(28..44)? != SUMMARY_FMTID || u32_at(bytes, 24)? < 1 {
|
||||
return None;
|
||||
}
|
||||
if u16::from_le_bytes(bytes.get(2..4)?.try_into().ok()?) > 1 {
|
||||
@@ -65,12 +65,14 @@ fn parse(bytes: &[u8]) -> Option<CoreProps> {
|
||||
.min(set.len());
|
||||
set.get(start..end)
|
||||
};
|
||||
let cp = property(1)?;
|
||||
if u32_at(cp, 0)? != 2 {
|
||||
return None;
|
||||
} // VT_I2
|
||||
let codepage = u16::from_le_bytes(cp.get(4..6)?.try_into().ok()?);
|
||||
let codepage = property(1)
|
||||
.and_then(|cp| {
|
||||
let vt = u32_at(cp, 0)?;
|
||||
if vt == 2 || vt == 3 { Some(u16::from_le_bytes(cp.get(4..6)?.try_into().ok()?)) } else { None }
|
||||
})
|
||||
.unwrap_or(1252);
|
||||
let get = |id| property(id).and_then(|value| text(value, codepage)).unwrap_or_default();
|
||||
let get_filetime = |id| property(id).and_then(filetime_iso).unwrap_or_default();
|
||||
Some(CoreProps {
|
||||
title: get(2),
|
||||
subject: get(3),
|
||||
@@ -79,10 +81,47 @@ fn parse(bytes: &[u8]) -> Option<CoreProps> {
|
||||
description: get(6),
|
||||
last_modified_by: get(8),
|
||||
revision: get(9).parse().unwrap_or_default(),
|
||||
created: get_filetime(12),
|
||||
modified: get_filetime(13),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn civil(days: i64) -> (i64, u32, u32) {
|
||||
let z = days + 719_468;
|
||||
let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
|
||||
let doe = (z - era * 146_097) as u32;
|
||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
|
||||
let y = yoe as i64 + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = y + i64::from(m <= 2);
|
||||
(y, m, d)
|
||||
}
|
||||
|
||||
fn filetime_iso(value: &[u8]) -> Option<String> {
|
||||
let kind = u32_at(value, 0)?;
|
||||
if kind != 64 {
|
||||
return None;
|
||||
}
|
||||
let ft_low = u32_at(value, 4)? as u64;
|
||||
let ft_high = u32_at(value, 8)? as u64;
|
||||
let ft = (ft_high << 32) | ft_low;
|
||||
if ft == 0 {
|
||||
return None;
|
||||
}
|
||||
const EPOCH_DIFFERENCE: u64 = 116_444_736_000_000_000;
|
||||
let unix_100ns = ft.checked_sub(EPOCH_DIFFERENCE)?;
|
||||
let unix_secs = unix_100ns / 10_000_000;
|
||||
let days = (unix_secs / 86_400) as i64;
|
||||
let secs_of_day = (unix_secs % 86_400) as u32;
|
||||
let (h, mi, s) = (secs_of_day / 3600, (secs_of_day / 60) % 60, secs_of_day % 60);
|
||||
let (y, m, d) = civil(days);
|
||||
Some(format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z"))
|
||||
}
|
||||
|
||||
fn text(value: &[u8], codepage: u16) -> Option<String> {
|
||||
let kind = u32_at(value, 0)?;
|
||||
let count = u32_at(value, 4)? as usize;
|
||||
|
||||
@@ -77,6 +77,7 @@ pub(crate) struct RowInfo {
|
||||
/// automatic `Shd` (`None`) clears it.
|
||||
shading: Vec<(u8, Option<Rgb>)>,
|
||||
widths: Vec<(u8, f32)>,
|
||||
width_pcts: Vec<(u8, f32)>,
|
||||
valign: Vec<(u8, VAlign)>,
|
||||
}
|
||||
|
||||
@@ -93,6 +94,18 @@ impl RowInfo {
|
||||
pub(crate) fn shading_of(&self, i: u8) -> Option<Rgb> {
|
||||
self.shading.iter().rfind(|(k, _)| *k == i).and_then(|(_, s)| *s)
|
||||
}
|
||||
|
||||
/// The width cell `i` ends up with, for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn width_of(&self, i: u8) -> Option<f32> {
|
||||
self.widths.iter().rfind(|(k, _)| *k == i).map(|(_, w)| *w)
|
||||
}
|
||||
|
||||
/// The width percentage cell `i` ends up with, for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn width_pct_of(&self, i: u8) -> Option<f32> {
|
||||
self.width_pcts.iter().rfind(|(k, _)| *k == i).map(|(_, w)| *w)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode(papx: &[u8]) -> RowInfo {
|
||||
@@ -187,13 +200,20 @@ pub(crate) fn decode(papx: &[u8]) -> RowInfo {
|
||||
}
|
||||
}
|
||||
T_CELL_WIDTH => {
|
||||
// cb, itcFirst, itcLim, ftsWidth (3 = twips), wWidth.
|
||||
if let [a, b, fts, w0, w1, ..] = prl.operand
|
||||
&& *fts == 3
|
||||
{
|
||||
let w = (i16::from_le_bytes([*w0, *w1]) as f32 / 20.0).clamp(0.0, 1584.0);
|
||||
for c in *a..(*b).min(MAX_COLS as u8) {
|
||||
r.widths.push((c, w));
|
||||
// Operand: cb (1 byte), itcFirst (1 byte), itcLim (1 byte), ftsWidth (1 byte), wWidth (2 bytes).
|
||||
// [MS-DOC] §2.9.290 sprmTCellWidth (0xD635).
|
||||
// ftsWidth: 3 = twips (dxa), 2 = percentage (50ths of a percent).
|
||||
if let [_, a, b, fts, w0, w1, ..] = prl.operand {
|
||||
if *fts == 3 {
|
||||
let w = (i16::from_le_bytes([*w0, *w1]) as f32 / 20.0).clamp(0.0, 1584.0);
|
||||
for c in *a..(*b).min(MAX_COLS as u8) {
|
||||
r.widths.push((c, w));
|
||||
}
|
||||
} else if *fts == 2 {
|
||||
let pct = (u16::from_le_bytes([*w0, *w1]) as f32 / 50.0).clamp(0.0, 100.0);
|
||||
for c in *a..(*b).min(MAX_COLS as u8) {
|
||||
r.width_pcts.push((c, pct));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,13 +276,16 @@ pub(crate) fn assemble(paras: Vec<ParaOut>) -> Blocks {
|
||||
if let Some((_, m)) = info.vmerge.iter().find(|(k, _)| *k == i) {
|
||||
c.props.vmerge = *m;
|
||||
}
|
||||
if let Some((_, w)) = info.widths.iter().find(|(k, _)| *k == i) {
|
||||
if let Some((_, w)) = info.widths.iter().rfind(|(k, _)| *k == i) {
|
||||
c.props.width = Some(*w);
|
||||
}
|
||||
if let Some((_, pct)) = info.width_pcts.iter().rfind(|(k, _)| *k == i) {
|
||||
c.props.width_pct = Some(*pct);
|
||||
}
|
||||
if let Some((_, s)) = info.shading.iter().rfind(|(k, _)| *k == i) {
|
||||
c.props.shading = *s;
|
||||
}
|
||||
if let Some((_, v)) = info.valign.iter().find(|(k, _)| *k == i) {
|
||||
if let Some((_, v)) = info.valign.iter().rfind(|(k, _)| *k == i) {
|
||||
c.props.valign = Some(*v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2285,3 +2285,48 @@ fn second_table_gets_its_own_grid() {
|
||||
assert_eq!(tables[1].props.align, None, "alignment reset");
|
||||
assert_eq!(tables[1].props.indent, None, "indent reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprm_t_cell_width_twips_and_percentage() {
|
||||
// [MS-DOC] §2.9.290 sprmTCellWidth (0xD635):
|
||||
// cb (1 byte), itcFirst (1 byte), itcLim (1 byte), ftsWidth (1 byte), wWidth (2 bytes).
|
||||
// ftsWidth = 3 (twips): 1440 twips = 72.0 pt.
|
||||
let w_twips = [0u8, 2, 3, 0xA0, 0x05]; // cell 0..2, fts=3, 1440 dxa
|
||||
// ftsWidth = 2 (percentage in 50ths of a percent): 2500 = 50.0%.
|
||||
let w_pct = [2u8, 3, 2, 0xC4, 0x09]; // cell 2..3, fts=2, 2500 (50%)
|
||||
let papx = [sprm_cb(0xD635, &w_twips), sprm_cb(0xD635, &w_pct)].concat();
|
||||
|
||||
let row = crate::table::decode(&papx);
|
||||
assert_eq!(row.width_of(0), Some(72.0));
|
||||
assert_eq!(row.width_of(1), Some(72.0));
|
||||
assert_eq!(row.width_pct_of(2), Some(50.0));
|
||||
|
||||
// End-to-end document test: row cells receive the preferred widths.
|
||||
let text = "a\u{7}b\u{7}c\u{7}\u{7}\r";
|
||||
let in_tbl = grpprl(&[(0x2416, &[0x01]), (0x6649, &[1, 0, 0, 0])]);
|
||||
let ttp = [
|
||||
grpprl(&[(0x2416, &[0x01]), (0x2417, &[0x01]), (0x6649, &[1, 0, 0, 0])]),
|
||||
t_def_edges(&[0, 1440, 2880, 4320]),
|
||||
sprm_cb(0xD635, &w_twips),
|
||||
sprm_cb(0xD635, &w_pct),
|
||||
]
|
||||
.concat();
|
||||
let spec = StructSpec {
|
||||
text,
|
||||
header_stories: vec![],
|
||||
sections: vec![(text.chars().count() as u32, Vec::new())],
|
||||
chpx_runs: vec![(0, Vec::new())],
|
||||
papx_entries: vec![(0, 0, in_tbl), (6, 0, ttp), (7, 0, Vec::new())],
|
||||
plf_lst: Vec::new(),
|
||||
plf_lfo: Vec::new(),
|
||||
note_stories: vec![],
|
||||
endnote_stories: vec![],
|
||||
extra_pairs: Vec::new(),
|
||||
data_stream: Vec::new(),
|
||||
};
|
||||
let doc = read(&struct_doc(&spec)).expect("opens");
|
||||
let table = doc.body[0].as_table().expect("table block");
|
||||
assert_eq!(table.rows[0].cells[0].props.width, Some(72.0));
|
||||
assert_eq!(table.rows[0].cells[1].props.width, Some(72.0));
|
||||
assert_eq!(table.rows[0].cells[2].props.width_pct, Some(50.0));
|
||||
}
|
||||
|
||||
@@ -96,3 +96,69 @@ fn malformed_or_oversized_summary_does_not_break_doc_open() {
|
||||
assert!(open_with_metadata(&huge, false).core.title.is_empty());
|
||||
assert!(open_with_metadata(&vec![0; (2 << 20) + 1], false).core.title.is_empty());
|
||||
}
|
||||
|
||||
fn custom_summary(props: &[(u32, Vec<u8>)], num_property_sets: u32) -> Vec<u8> {
|
||||
let mut section = vec![0; 8 + 8 * props.len()];
|
||||
section[4..8].copy_from_slice(&(props.len() as u32).to_le_bytes());
|
||||
for (i, (id, value)) in props.iter().enumerate() {
|
||||
section[8 + i * 8..12 + i * 8].copy_from_slice(&id.to_le_bytes());
|
||||
let offset = section.len() as u32;
|
||||
section[12 + i * 8..16 + i * 8].copy_from_slice(&offset.to_le_bytes());
|
||||
section.extend_from_slice(value);
|
||||
}
|
||||
let size = section.len() as u32;
|
||||
section[..4].copy_from_slice(&size.to_le_bytes());
|
||||
let mut header = vec![0; 28 + 20 * num_property_sets as usize];
|
||||
header[..2].copy_from_slice(&[0xfe, 0xff]);
|
||||
header[24..28].copy_from_slice(&num_property_sets.to_le_bytes());
|
||||
// First property set FMTID and offset
|
||||
header[28..44].copy_from_slice(&[0xe0, 0x85, 0x9f, 0xf2, 0xf9, 0x4f, 0x68, 0x10, 0xab, 0x91, 0x08, 0, 0x2b, 0x27, 0xb3, 0xd9]);
|
||||
let first_offset = header.len() as u32;
|
||||
header[44..48].copy_from_slice(&first_offset.to_le_bytes());
|
||||
if num_property_sets > 1 {
|
||||
// Dummy second property set header
|
||||
header[48..64].copy_from_slice(&[1; 16]);
|
||||
let second_offset = (first_offset + size) as u32;
|
||||
header[64..68].copy_from_slice(&second_offset.to_le_bytes());
|
||||
}
|
||||
header.extend(section);
|
||||
header
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_defaults_codepage_and_accepts_vti4_and_num_property_sets() {
|
||||
let title_prop = [30u32.to_le_bytes().as_slice(), &7u32.to_le_bytes(), b"Default\0"].concat();
|
||||
// 1. Missing PID_CODEPAGE (property 1) should default to 1252 per MS-OLEPS.
|
||||
let no_cp = custom_summary(&[(2, title_prop.clone())], 1);
|
||||
assert_eq!(open_with_metadata(&no_cp, false).core.title, "Default");
|
||||
|
||||
// 2. PID_CODEPAGE as VT_I4 (type 3).
|
||||
let cp_vti4 = [3u32.to_le_bytes().as_slice(), &1252u32.to_le_bytes()].concat();
|
||||
let with_vti4 = custom_summary(&[(1, cp_vti4), (2, title_prop.clone())], 1);
|
||||
assert_eq!(open_with_metadata(&with_vti4, false).core.title, "Default");
|
||||
|
||||
// 3. Stream with NumPropertySets = 2.
|
||||
let multi_sets = custom_summary(&[(2, title_prop)], 2);
|
||||
assert_eq!(open_with_metadata(&multi_sets, false).core.title, "Default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_parses_filetime_created_and_modified_dates() {
|
||||
// 2024-03-15T12:30:45Z = 133549794450000000 in 100ns since 1601-01-01
|
||||
let ft_val: u64 = 133_549_794_450_000_000;
|
||||
let ft_low = (ft_val & 0xFFFFFFFF) as u32;
|
||||
let ft_high = (ft_val >> 32) as u32;
|
||||
let filetime_bytes = [64u32.to_le_bytes().as_slice(), &ft_low.to_le_bytes(), &ft_high.to_le_bytes()].concat();
|
||||
|
||||
let stream = custom_summary(
|
||||
&[
|
||||
(12, filetime_bytes.clone()), // PIDSI_CREATE_DTM
|
||||
(13, filetime_bytes), // PIDSI_LASTSAVE_DTM
|
||||
],
|
||||
1,
|
||||
);
|
||||
|
||||
let core = open_with_metadata(&stream, false).core;
|
||||
assert_eq!(core.created, "2024-03-15T12:30:45Z");
|
||||
assert_eq!(core.modified, "2024-03-15T12:30:45Z");
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ quick-xml = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
unicode-bidi = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
aes = { workspace = true }
|
||||
sha1 = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
//! Word bibliography sources: a `b:Sources` document — the custom XML part of a document, or
|
||||
//! Word's own `Sources.xml` master list, imported through Manage Sources (#2640).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use wordcraft_doc::Source;
|
||||
|
||||
use crate::DocxError;
|
||||
use crate::xml::El;
|
||||
|
||||
/// Bibliography sources kept from one file (Word's own source manager holds far fewer).
|
||||
pub const MAX_SOURCES: usize = 10_000;
|
||||
/// Characters kept of a bibliography's citation style name.
|
||||
pub const MAX_STYLE_NAME: usize = 64;
|
||||
|
||||
/// A `b:Sources` document read into the document model: its sources in file order, and the
|
||||
/// citation style it names (`b:Sources/@StyleName`), when it has one.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Sources {
|
||||
pub sources: Vec<Source>,
|
||||
pub style: Option<String>,
|
||||
}
|
||||
|
||||
/// The bibliography namespace Word's own `Sources.xml` files may carry instead of OOXML's (the
|
||||
/// VBA `Source.XML` format, `schemas.microsoft.com/office/word/2004/10/bibliography`).
|
||||
const WORD_2004_BIBLIOGRAPHY: &str = "http://schemas.microsoft.com/office/word/2004/10/bibliography";
|
||||
|
||||
/// Read a Word bibliography sources file — Word's `Sources.xml`, or any `b:Sources` document in
|
||||
/// one of the bibliography namespaces (ECMA-376's, or Word's own 2004/10) — into [`Sources`].
|
||||
pub fn read_sources(bytes: &[u8]) -> Result<Sources, DocxError> {
|
||||
// `parse_ns` maps Word's 2004/10 namespace onto the canonical `b` prefix as well, so both
|
||||
// formats read; the root check then refuses an un-namespaced or unrelated `<Sources>`.
|
||||
let root = crate::xml::parse_ns(bytes, &[("b", WORD_2004_BIBLIOGRAPHY)])?;
|
||||
if root.name != "b:Sources" {
|
||||
return Err(DocxError::NotWord(format!("root element is {}", root.name)));
|
||||
}
|
||||
Ok(parse(&root, &mut Seen::default(), MAX_SOURCES))
|
||||
}
|
||||
|
||||
/// Bibliography sources already read: tags, and (title, author) of untagged ones.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Seen {
|
||||
tags: HashSet<String>,
|
||||
untagged: HashSet<(String, String)>,
|
||||
}
|
||||
|
||||
/// The fresh sources and style of a parsed `b:Sources` root element: `seen` carries the tags and
|
||||
/// untagged (title, author) keys already taken, so repeated parts collapse into one source, and
|
||||
/// at most `room` fresh sources are built (later ones are left unread, bounding hostile files).
|
||||
pub(crate) fn parse(root: &El, seen: &mut Seen, room: usize) -> Sources {
|
||||
let style = root
|
||||
.attrs
|
||||
.iter()
|
||||
.find(|(k, _)| k.rsplit(':').next() == Some("StyleName"))
|
||||
.map(|(_, v)| v.trim())
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(|name| name.chars().take(MAX_STYLE_NAME).collect());
|
||||
let child_text = |el: &El, local: &str| el.els().find(|e| e.local() == local).map(|e| e.text()).unwrap_or_default();
|
||||
let parse_persons = |parent: &El| -> String {
|
||||
let mut names = Vec::new();
|
||||
let person_els: Vec<&El> = {
|
||||
let in_lists: Vec<&El> =
|
||||
parent.els().filter(|e| e.local() == "NameList").flat_map(|n| n.els().filter(|e| e.local() == "Person")).collect();
|
||||
if in_lists.is_empty() { parent.els().filter(|e| e.local() == "Person").collect() } else { in_lists }
|
||||
};
|
||||
for name_el in person_els {
|
||||
let last = child_text(name_el, "Last");
|
||||
let first = child_text(name_el, "First");
|
||||
let middle = child_text(name_el, "Middle");
|
||||
let name = if !first.is_empty() && !middle.is_empty() {
|
||||
format!("{last}, {first} {middle}")
|
||||
} else if !first.is_empty() {
|
||||
format!("{last}, {first}")
|
||||
} else {
|
||||
last
|
||||
};
|
||||
if !name.is_empty() {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
names.join("; ")
|
||||
};
|
||||
|
||||
let mut out = Sources { sources: Vec::new(), style };
|
||||
for src_el in root.els().filter(|e| e.local() == "Source") {
|
||||
if out.sources.len() >= room {
|
||||
log::warn!("docx: more than {MAX_SOURCES} bibliography sources; the rest are dropped");
|
||||
break;
|
||||
}
|
||||
let tag = child_text(src_el, "Tag");
|
||||
let raw_kind = child_text(src_el, "SourceType");
|
||||
let kind = crate::write::from_source_type(&raw_kind);
|
||||
let (author, editor) = match src_el.els().find(|e| e.local() == "Author") {
|
||||
Some(a) => {
|
||||
let auth = a.els().find(|e| e.local() == "Author").map(parse_persons).filter(|s| !s.is_empty()).unwrap_or_else(|| parse_persons(a));
|
||||
let ed = a.els().find(|e| e.local() == "Editor").map(parse_persons).unwrap_or_default();
|
||||
(auth, ed)
|
||||
}
|
||||
None => (String::new(), String::new()),
|
||||
};
|
||||
let editor = if editor.is_empty() { src_el.els().find(|e| e.local() == "Editor").map(parse_persons).unwrap_or_default() } else { editor };
|
||||
let title = child_text(src_el, "Title");
|
||||
let year = child_text(src_el, "Year");
|
||||
let month = child_text(src_el, "Month");
|
||||
let day = child_text(src_el, "Day");
|
||||
let city = child_text(src_el, "City");
|
||||
let publisher = child_text(src_el, "Publisher");
|
||||
let journal = child_text(src_el, "JournalName");
|
||||
let edition = child_text(src_el, "Edition");
|
||||
let volume = child_text(src_el, "Volume");
|
||||
let issue = child_text(src_el, "Issue");
|
||||
let pages = child_text(src_el, "Pages");
|
||||
let url = child_text(src_el, "URL");
|
||||
let accessed = match child_text(src_el, "Accessed") {
|
||||
a if !a.is_empty() => a,
|
||||
_ => {
|
||||
let y = child_text(src_el, "YearAccessed");
|
||||
let m = child_text(src_el, "MonthAccessed");
|
||||
let d = child_text(src_el, "DayAccessed");
|
||||
if !y.is_empty() && !m.is_empty() && !d.is_empty() {
|
||||
format!("{y}-{m}-{d}")
|
||||
} else if !y.is_empty() && !m.is_empty() {
|
||||
format!("{y}-{m}")
|
||||
} else {
|
||||
y
|
||||
}
|
||||
}
|
||||
};
|
||||
let doi = match child_text(src_el, "DOI") {
|
||||
d if !d.is_empty() => d,
|
||||
_ => child_text(src_el, "StandardNumber"),
|
||||
};
|
||||
|
||||
// Keep sources with some content, once each (by tag, or title and author untagged).
|
||||
if tag.is_empty() && title.is_empty() && author.is_empty() && editor.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let fresh = if tag.is_empty() {
|
||||
seen.untagged.insert((title.clone(), if author.is_empty() { editor.clone() } else { author.clone() }))
|
||||
} else {
|
||||
seen.tags.insert(tag.clone())
|
||||
};
|
||||
if !fresh {
|
||||
continue;
|
||||
}
|
||||
out.sources.push(Source {
|
||||
tag,
|
||||
kind,
|
||||
author,
|
||||
title,
|
||||
year,
|
||||
city,
|
||||
publisher,
|
||||
journal,
|
||||
volume,
|
||||
pages,
|
||||
url,
|
||||
editor,
|
||||
edition,
|
||||
issue,
|
||||
month,
|
||||
day,
|
||||
accessed,
|
||||
doi,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const WORD_SOURCES: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<b:Sources xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"
|
||||
xmlns="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"
|
||||
SelectedStyle="\MLA.XSL" StyleName="MLA">
|
||||
<b:Source>
|
||||
<b:Tag>Riv21</b:Tag>
|
||||
<b:SourceType>Book</b:SourceType>
|
||||
<b:Author>
|
||||
<b:Author>
|
||||
<b:NameList>
|
||||
<b:Person><b:Last>Rivera</b:Last><b:First>Alex</b:First></b:Person>
|
||||
<b:Person><b:Last>Chen</b:Last><b:First>Mei</b:First><b:Middle>L.</b:Middle></b:Person>
|
||||
</b:NameList>
|
||||
</b:Author>
|
||||
</b:Author>
|
||||
<b:Title>Shared Spaces</b:Title>
|
||||
<b:Year>2021</b:Year>
|
||||
<b:City>Portland</b:City>
|
||||
<b:Publisher>Harbor Books</b:Publisher>
|
||||
</b:Source>
|
||||
<b:Source>
|
||||
<b:Tag>Web19</b:Tag>
|
||||
<b:SourceType>InternetSite</b:SourceType>
|
||||
<b:Author>
|
||||
<b:Author>
|
||||
<b:NameList>
|
||||
<b:Person><b:Last>Okafor</b:Last><b:First>Ada</b:First></b:Person>
|
||||
</b:NameList>
|
||||
</b:Author>
|
||||
</b:Author>
|
||||
<b:Title>Dockyards of the north</b:Title>
|
||||
<b:Year>2019</b:Year>
|
||||
<b:URL>https://example.org/docks</b:URL>
|
||||
<b:YearAccessed>2024</b:YearAccessed>
|
||||
<b:MonthAccessed>May</b:MonthAccessed>
|
||||
<b:DayAccessed>17</b:DayAccessed>
|
||||
<b:StandardNumber>10.1234/x</b:StandardNumber>
|
||||
</b:Source>
|
||||
<b:Source>
|
||||
<b:Tag>NoDate</b:Tag>
|
||||
<b:SourceType>JournalArticle</b:SourceType>
|
||||
<b:Title>Untitled notes</b:Title>
|
||||
<b:JournalName>Field Notes</b:JournalName>
|
||||
<b:Volume>4</b:Volume>
|
||||
</b:Source>
|
||||
<b:Source>
|
||||
<b:Tag>Riv21</b:Tag>
|
||||
<b:SourceType>Book</b:SourceType>
|
||||
<b:Title>A duplicate of Riv21</b:Title>
|
||||
<b:Year>2021</b:Year>
|
||||
</b:Source>
|
||||
<b:Source>
|
||||
<b:SourceType>Book</b:SourceType>
|
||||
</b:Source>
|
||||
</b:Sources>"#;
|
||||
|
||||
/// A Word `Sources.xml` (`b:Sources`): its style, the `b:Source` elements with their names,
|
||||
/// kinds and fallback fields; a repeated tag and an entry with no content at all are dropped.
|
||||
#[test]
|
||||
fn a_word_sources_file_reads_into_sources() {
|
||||
let f = read_sources(WORD_SOURCES.as_bytes()).unwrap();
|
||||
assert_eq!(f.style.as_deref(), Some("MLA"), "the citation style comes from StyleName");
|
||||
assert_eq!(
|
||||
f.sources.len(),
|
||||
3,
|
||||
"the repeated tag and the empty b:Source are dropped: {:?}",
|
||||
f.sources.iter().map(|s| &s.tag).collect::<Vec<_>>()
|
||||
);
|
||||
let book = &f.sources[0];
|
||||
assert_eq!((book.tag.as_str(), book.kind.as_str()), ("Riv21", "book"));
|
||||
assert_eq!(book.author, "Rivera, Alex; Chen, Mei L.");
|
||||
assert_eq!(book.title, "Shared Spaces", "the first source of a repeated tag wins");
|
||||
assert_eq!(
|
||||
(book.title.as_str(), book.year.as_str(), book.city.as_str(), book.publisher.as_str()),
|
||||
("Shared Spaces", "2021", "Portland", "Harbor Books")
|
||||
);
|
||||
let web = &f.sources[1];
|
||||
assert_eq!(web.kind, "website");
|
||||
assert_eq!(web.author, "Okafor, Ada");
|
||||
assert_eq!(web.accessed, "2024-May-17", "assemble the accessed date from its parts");
|
||||
assert_eq!(web.doi, "10.1234/x", "StandardNumber stands in for a missing DOI");
|
||||
let notes = &f.sources[2];
|
||||
assert_eq!((notes.kind.as_str(), notes.journal.as_str(), notes.volume.as_str()), ("article", "Field Notes", "4"));
|
||||
}
|
||||
|
||||
/// Anything whose root isn't `b:Sources` is refused, not read as an empty bibliography.
|
||||
#[test]
|
||||
fn a_file_that_is_not_b_sources_is_an_error() {
|
||||
assert!(read_sources(b"<html><body>hi</body></html>").is_err());
|
||||
assert!(matches!(read_sources(b"not xml at all"), Err(DocxError::Xml(_))));
|
||||
assert!(read_sources(b"<Sources><Source><Tag>A</Tag></Source></Sources>").is_err(), "no namespace");
|
||||
assert!(read_sources(br#"<o:Sources xmlns:o="urn:example:other"><o:Source/></o:Sources>"#).is_err(), "an unrelated namespace");
|
||||
}
|
||||
|
||||
/// Word's own 2004/10 bibliography namespace (`Sources.xml` written by scripts and older
|
||||
/// builds, the VBA `Source.XML` format) reads as well as OOXML's.
|
||||
#[test]
|
||||
fn word_2004_bibliography_namespace_is_accepted() {
|
||||
let xml = br#"<b:Sources xmlns:b="http://schemas.microsoft.com/office/word/2004/10/bibliography" StyleName="MLA">
|
||||
<b:Source><b:Tag>Riv21</b:Tag><b:SourceType>Book</b:SourceType><b:Title>Shared Spaces</b:Title><b:Year>2021</b:Year></b:Source>
|
||||
</b:Sources>"#;
|
||||
let f = read_sources(xml).unwrap();
|
||||
assert_eq!(f.style.as_deref(), Some("MLA"));
|
||||
assert_eq!(f.sources.len(), 1);
|
||||
assert_eq!(f.sources[0].tag, "Riv21");
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,20 @@ const MAX_FONTS: usize = 64;
|
||||
/// The font table's references to embedded font files, one per style.
|
||||
const EMBEDS: [&str; 4] = ["w:embedRegular", "w:embedBold", "w:embedItalic", "w:embedBoldItalic"];
|
||||
|
||||
/// A font file a document embeds, and the name its font table gives the font: the name the text
|
||||
/// asks for, which a subset Word embeds doesn't carry inside (#2240).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct EmbeddedFont {
|
||||
/// `w:font/@w:name`.
|
||||
pub name: String,
|
||||
/// The font file, de-obfuscated.
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The font files `doc`'s font table embeds, de-obfuscated, in table order. Not checked to be
|
||||
/// fonts: that is up to the font database. Empty for a document read from anything but a package
|
||||
/// with a font table.
|
||||
pub fn embedded_fonts(doc: &Document) -> Vec<Vec<u8>> {
|
||||
pub fn embedded_fonts(doc: &Document) -> Vec<EmbeddedFont> {
|
||||
let Some(table) = doc.passthrough.get(FONT_TABLE_PART).and_then(|b| crate::xml::parse(b).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -26,7 +36,10 @@ pub fn embedded_fonts(doc: &Document) -> Vec<Vec<u8>> {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for embed in table.children("w:font").flat_map(|f| f.els().filter(|e| EMBEDS.contains(&e.name.as_str()))) {
|
||||
let embeds = table
|
||||
.children("w:font")
|
||||
.flat_map(|f| f.els().filter(|e| EMBEDS.contains(&e.name.as_str())).map(move |e| (f.attr("w:name").unwrap_or(""), e)));
|
||||
for (name, embed) in embeds {
|
||||
if out.len() >= MAX_FONTS {
|
||||
log::warn!("docx: more than {MAX_FONTS} embedded fonts; the rest are not loaded");
|
||||
break;
|
||||
@@ -52,7 +65,7 @@ pub fn embedded_fonts(doc: &Document) -> Vec<Vec<u8>> {
|
||||
for (i, b) in data.iter_mut().take(32).enumerate() {
|
||||
*b ^= key.get(i % 16).copied().unwrap_or(0);
|
||||
}
|
||||
out.push(data);
|
||||
out.push(EmbeddedFont { name: name.to_string(), data });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! error or a best-effort document, never a panic.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod bibliography;
|
||||
mod chart_spec;
|
||||
mod crypt;
|
||||
mod custom;
|
||||
@@ -21,13 +22,14 @@ mod wordml2003_write;
|
||||
mod write;
|
||||
mod xml;
|
||||
|
||||
pub use bibliography::{MAX_SOURCES, Sources, read_sources};
|
||||
pub use chart_spec::{chart_items, chart_xml};
|
||||
pub use crypt::{
|
||||
DEFAULT_SPIN_COUNT, MAX_PASSWORD_CHARS, PasswordCheck, check_password, check_protection_password, decrypt, encrypt, encrypt_with_spin_count,
|
||||
is_encrypted, protection_hash,
|
||||
};
|
||||
pub use flat::{XmlKind, sniff_xml, write as write_flat};
|
||||
pub use fonts::embedded_fonts;
|
||||
pub use fonts::{EmbeddedFont, embedded_fonts};
|
||||
pub use read::read;
|
||||
pub use smart_art::smart_art_items;
|
||||
pub use wordml2003_write::write as write_wordml2003;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::DocxError;
|
||||
use crate::xml::{self, El};
|
||||
@@ -44,6 +45,38 @@ pub mod rt {
|
||||
pub const DIAGRAM_QUICK_STYLE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramQuickStyle";
|
||||
pub const DIAGRAM_COLORS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramColors";
|
||||
pub const CUSTOM_XML: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
|
||||
pub const GLOSSARY: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument";
|
||||
}
|
||||
|
||||
/// Content type of a glossary document part (ECMA-376 Part 1 §11.3.8).
|
||||
pub const GLOSSARY_CONTENT_TYPE: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml";
|
||||
/// `Document::passthrough` key: a fingerprint of `Document::glossary` as read, so a save can tell
|
||||
/// an untouched glossary (written back verbatim) from an edited one (written from the model).
|
||||
/// Not a package part: WordCraft's own bookkeeping.
|
||||
pub const GLOSSARY_READ: &str = "wordcraft:glossary.read";
|
||||
/// Most building blocks read from one glossary.
|
||||
pub const MAX_GLOSSARY_ENTRIES: usize = 10_000;
|
||||
/// The glossary entry types `w:type` takes (ST_DocPartType); others aren't kept.
|
||||
pub const GLOSSARY_TYPES: [&str; 7] = ["none", "normal", "autoExp", "toolbar", "speller", "formFld", "bbPlcHdr"];
|
||||
/// The insertion behaviours `w:behavior` takes (ST_DocPartBehavior); others aren't kept.
|
||||
pub const GLOSSARY_BEHAVIORS: [&str; 3] = ["content", "p", "pg"];
|
||||
|
||||
/// A fingerprint of `glossary` (FNV-1a over its debug form): stable across runs and builds that
|
||||
/// keep the model's shape, and cheap (nothing is allocated).
|
||||
pub fn glossary_fingerprint(glossary: &[wordcraft_doc::BuildingBlock]) -> String {
|
||||
struct Fnv(u64);
|
||||
impl std::fmt::Write for Fnv {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
for b in s.bytes() {
|
||||
self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut h = Fnv(0xcbf2_9ce4_8422_2325);
|
||||
// Writing into `Fnv` never fails.
|
||||
let _ = std::fmt::Write::write_fmt(&mut h, format_args!("{glossary:?}"));
|
||||
format!("{:016x}", h.0)
|
||||
}
|
||||
|
||||
/// `Document::passthrough` key for a macro project, kept as opaque bytes (never parsed or run).
|
||||
@@ -154,9 +187,10 @@ pub fn rel_is(t: &str, full: &str) -> bool {
|
||||
t == full || tail(t) == tail(full)
|
||||
}
|
||||
|
||||
/// The decompressed parts of a package (bounded).
|
||||
/// The decompressed parts of a package (bounded). Shared, so a part the document keeps as it is (a
|
||||
/// picture, an embedded object) is handed over rather than copied.
|
||||
pub struct Package {
|
||||
files: BTreeMap<String, Vec<u8>>,
|
||||
files: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Package {
|
||||
@@ -198,7 +232,7 @@ impl Package {
|
||||
return Err(DocxError::Limit(format!("part {name} decompresses past the size limit")));
|
||||
}
|
||||
total = total.saturating_add(buf.len() as u64);
|
||||
files.insert(name, buf);
|
||||
files.insert(name, Arc::new(buf));
|
||||
}
|
||||
Ok(Package { files })
|
||||
}
|
||||
@@ -206,16 +240,22 @@ impl Package {
|
||||
/// A package from parts already in memory (a Flat OPC file, a converted document), by part
|
||||
/// name without the leading `/`.
|
||||
pub fn from_parts(files: BTreeMap<String, Vec<u8>>) -> Package {
|
||||
Package { files }
|
||||
Package { files: files.into_iter().map(|(name, bytes)| (name, Arc::new(bytes))).collect() }
|
||||
}
|
||||
|
||||
/// Part bytes by name (leading `/` ignored; case-insensitive fallback).
|
||||
pub fn get(&self, name: &str) -> Option<&[u8]> {
|
||||
self.get_shared(name).map(|v| v.as_slice())
|
||||
}
|
||||
|
||||
/// [`Package::get`], as the shared bytes themselves: for a part the document keeps whole, which
|
||||
/// then costs no copy (a picture document's pictures used to be held twice while it opened).
|
||||
pub fn get_shared(&self, name: &str) -> Option<&Arc<Vec<u8>>> {
|
||||
let n = name.trim_start_matches('/');
|
||||
if let Some(v) = self.files.get(n) {
|
||||
return Some(v);
|
||||
}
|
||||
self.files.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| v.as_slice())
|
||||
self.files.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
pub fn xml(&self, name: &str) -> Result<Option<El>, DocxError> {
|
||||
@@ -400,6 +440,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_document_shares_its_pictures_with_the_package() {
|
||||
// Each picture was copied out of the package, so a picture document held its pictures
|
||||
// twice while it opened, and left the package's copies behind as freed memory.
|
||||
let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture""#;
|
||||
let document = format!(
|
||||
r#"<w:document {ns}><w:body><w:p><w:r><w:drawing><wp:inline><wp:extent cx="635000" cy="635000"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:blipFill><a:blip r:embed="rIdImg"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdImg" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/pic.png"/></Relationships>"#;
|
||||
let z = zip_of(&[
|
||||
("word/document.xml", document.into_bytes()),
|
||||
("word/_rels/document.xml.rels", rels.as_bytes().to_vec()),
|
||||
("word/media/pic.png", b"\x89PNG picture bytes".to_vec()),
|
||||
]);
|
||||
let pkg = Package::open(&z).unwrap();
|
||||
let doc = crate::read::read_opened(&pkg).unwrap();
|
||||
let held = doc.media.values().next().expect("the picture is read");
|
||||
assert!(Arc::ptr_eq(held, pkg.get_shared("word/media/pic.png").unwrap()), "the same bytes, not a copy");
|
||||
assert_eq!(pkg.get("/WORD/media/PIC.png"), Some(&b"\x89PNG picture bytes"[..]), "lookups are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_targets() {
|
||||
assert_eq!(resolve("word", "media/image1.png"), "word/media/image1.png");
|
||||
|
||||
@@ -79,7 +79,8 @@ pub(crate) fn color(e: &El, theme: &[Rgb]) -> Option<Rgb> {
|
||||
/// A preset colour (`a:prstClr/@val`, ECMA-376 Part 1 §20.1.10.48): the common ones; others are
|
||||
/// unknown (`None`).
|
||||
pub(crate) fn preset_color(name: &str) -> Option<Rgb> {
|
||||
Some(match name {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
Some(match lower.as_str() {
|
||||
"black" => Rgb(0, 0, 0),
|
||||
"white" => Rgb(0xFF, 0xFF, 0xFF),
|
||||
"red" => Rgb(0xFF, 0, 0),
|
||||
@@ -91,8 +92,8 @@ pub(crate) fn preset_color(name: &str) -> Option<Rgb> {
|
||||
"magenta" | "fuchsia" => Rgb(0xFF, 0, 0xFF),
|
||||
"gray" | "grey" => Rgb(0x80, 0x80, 0x80),
|
||||
"silver" => Rgb(0xC0, 0xC0, 0xC0),
|
||||
"ltGray" | "ltGrey" => Rgb(0xD3, 0xD3, 0xD3),
|
||||
"dkGray" | "dkGrey" => Rgb(0xA9, 0xA9, 0xA9),
|
||||
"ltgray" | "ltgrey" | "lightgray" | "lightgrey" => Rgb(0xD3, 0xD3, 0xD3),
|
||||
"dkgray" | "dkgrey" | "darkgray" | "darkgrey" => Rgb(0xA9, 0xA9, 0xA9),
|
||||
"maroon" => Rgb(0x80, 0, 0),
|
||||
"navy" => Rgb(0, 0, 0x80),
|
||||
"olive" => Rgb(0x80, 0x80, 0),
|
||||
@@ -101,6 +102,18 @@ pub(crate) fn preset_color(name: &str) -> Option<Rgb> {
|
||||
"orange" => Rgb(0xFF, 0xA5, 0),
|
||||
"brown" => Rgb(0xA5, 0x2A, 0x2A),
|
||||
"pink" => Rgb(0xFF, 0xC0, 0xCB),
|
||||
"gold" => Rgb(0xFF, 0xD7, 0),
|
||||
"darkblue" | "dkblue" => Rgb(0, 0, 0x8B),
|
||||
"darkred" | "dkred" => Rgb(0x8B, 0, 0),
|
||||
"darkgreen" | "dkgreen" => Rgb(0, 0x64, 0),
|
||||
"lightblue" | "ltblue" => Rgb(0xAD, 0xD8, 0xE6),
|
||||
"coral" => Rgb(0xFF, 0x7F, 0x50),
|
||||
"salmon" => Rgb(0xFA, 0x80, 0x72),
|
||||
"tomato" => Rgb(0xFF, 0x63, 0x47),
|
||||
"violet" => Rgb(0xEE, 0x82, 0xEE),
|
||||
"indigo" => Rgb(0x4B, 0, 0x82),
|
||||
"beige" => Rgb(0xF5, 0xF5, 0xDC),
|
||||
"ivory" => Rgb(0xFF, 0xFF, 0xF0),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -241,4 +254,16 @@ mod tests {
|
||||
let b = el("a:srgbClr", r#"val="808080""#, r#"<a:lumOff val="50000"/><a:lumMod val="50000"/>"#);
|
||||
assert_ne!(color(&a, &theme), color(&b, &theme));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_colors_are_case_insensitive_and_include_common_names() {
|
||||
assert_eq!(preset_color("red"), Some(Rgb(255, 0, 0)));
|
||||
assert_eq!(preset_color("Red"), Some(Rgb(255, 0, 0)));
|
||||
assert_eq!(preset_color("darkBlue"), Some(Rgb(0, 0, 0x8B)));
|
||||
assert_eq!(preset_color("dkBlue"), Some(Rgb(0, 0, 0x8B)));
|
||||
assert_eq!(preset_color("lightGray"), Some(Rgb(0xD3, 0xD3, 0xD3)));
|
||||
assert_eq!(preset_color("ltGray"), Some(Rgb(0xD3, 0xD3, 0xD3)));
|
||||
assert_eq!(preset_color("gold"), Some(Rgb(0xFF, 0xD7, 0)));
|
||||
assert_eq!(preset_color("unknownColor"), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,12 @@ impl Reader<'_> {
|
||||
if !self.doc.sources.is_empty() && self.xml(&rel.target).ok().flatten().is_some_and(|r| r.local() == "Sources") {
|
||||
continue;
|
||||
}
|
||||
// Native ink shares the custom XML relationship type, but its part belongs to the
|
||||
// drawing that refers to it: kept with it, or dropped with it (no orphan part).
|
||||
let pkg = self.pkg;
|
||||
if self.content_types.get_or_insert_with(|| ContentTypes::read(pkg)).of(&rel.target) == Some("application/inkml+xml") {
|
||||
continue;
|
||||
}
|
||||
if self.keep_part_tree(&rel.target) {
|
||||
roots.push_str(&format!("{owner}\t{}\t{}\n", rel.kind, rel.target));
|
||||
}
|
||||
@@ -94,17 +100,21 @@ impl Reader<'_> {
|
||||
/// relationship the main document's markup refers to by id (its target goes with the
|
||||
/// element, or not at all).
|
||||
pub(super) fn keep_unmodelled(&mut self, package: &Rels, document: &Rels) {
|
||||
let main = self.pkg.get(&self.main).map(|b| b.to_vec()).unwrap_or_default();
|
||||
let pkg = self.pkg;
|
||||
let main = pkg.get(&self.main).unwrap_or_default();
|
||||
let referenced = |id: &str| {
|
||||
let needle = format!("\"{id}\"");
|
||||
main.windows(needle.len()).any(|w| w == needle.as_bytes())
|
||||
};
|
||||
let mut roots = String::new();
|
||||
// One glossary per main document (its first relationship; see `read_glossary`).
|
||||
let mut glossary = false;
|
||||
for (owner, rels) in [("P", package), ("D", document)] {
|
||||
for rel in rels.list.iter().filter(|r| !r.external).take(MAX_EMBEDDED_RELS) {
|
||||
let tail = rel.kind.rsplit('/').next().unwrap_or("");
|
||||
if HANDLED_RELS.contains(&tail)
|
||||
|| (owner == "D" && referenced(&rel.id))
|
||||
|| (owner == "D" && tail == "glossaryDocument" && std::mem::replace(&mut glossary, true))
|
||||
|| ![&rel.kind, &rel.target].iter().all(|s| manifest_field_ok(s))
|
||||
{
|
||||
continue;
|
||||
@@ -192,14 +202,14 @@ impl Reader<'_> {
|
||||
log::warn!("docx: more than {MAX_EMBEDDED_PARTS} parts for embedded objects; the rest are dropped");
|
||||
return false;
|
||||
}
|
||||
let Some(bytes) = self.pkg.get(part) else {
|
||||
let Some(bytes) = self.pkg.get_shared(part) else {
|
||||
log::warn!("docx: part {part} of an embedded object is missing");
|
||||
return false;
|
||||
};
|
||||
let pkg = self.pkg;
|
||||
let ct = self.content_types.get_or_insert_with(|| ContentTypes::read(pkg)).of(part).unwrap_or("application/octet-stream");
|
||||
let content_type = if manifest_field_ok(ct) { ct.to_string() } else { "application/octet-stream".to_string() };
|
||||
self.doc.passthrough.entry(part.to_string()).or_insert_with(|| Arc::new(bytes.to_vec()));
|
||||
self.doc.passthrough.entry(part.to_string()).or_insert_with(|| bytes.clone());
|
||||
self.embedded.parts.insert(part.to_string(), crate::package::EmbeddedPart { content_type, rels: Vec::new() });
|
||||
true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! The glossary document (ECMA-376 Part 1 §17.12): the document's own building blocks (Quick
|
||||
//! Parts, AutoText…), read into `Document::glossary`.
|
||||
//!
|
||||
//! The glossary part and everything it reaches are also kept verbatim (`keep_unmodelled`), with a
|
||||
//! fingerprint of the entries as read ([`GLOSSARY_READ`]): a save writes the kept part while the
|
||||
//! entries are unchanged, so whatever the model doesn't hold survives, and writes the glossary from
|
||||
//! the model once they change.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::{Blocks, BuildingBlock};
|
||||
|
||||
use super::Reader;
|
||||
use super::story::StoryCtx;
|
||||
use crate::package::{
|
||||
ContentTypes, GLOSSARY_BEHAVIORS, GLOSSARY_CONTENT_TYPE, GLOSSARY_READ, GLOSSARY_TYPES, MAX_GLOSSARY_ENTRIES, Rels, glossary_fingerprint, rel_is,
|
||||
rt,
|
||||
};
|
||||
use crate::xml::El;
|
||||
|
||||
/// Longest name, gallery, category, description, guid or behaviour value kept (characters).
|
||||
const MAX_FIELD: usize = 1024;
|
||||
|
||||
/// The known values of `parent`'s `tag` children, each once, in file order.
|
||||
fn listed(parent: Option<&El>, tag: &str, known: &[&str]) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for v in parent.into_iter().flat_map(|p| p.children(tag)).filter_map(|e| e.attr("w:val")) {
|
||||
if known.contains(&v) && !out.iter().any(|o| o == v) {
|
||||
out.push(v.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
/// Read the glossary the main document relates to (`document`: its relationships). The first
|
||||
/// internal glossary relationship counts; one pointing at the main document, a part that isn't a
|
||||
/// glossary, or a missing one gives no entries. Entries without a name or a body are skipped.
|
||||
pub(super) fn read_glossary(&mut self, document: &Rels) {
|
||||
// The first internal one, as `keep_unmodelled` keeps.
|
||||
let Some(rel) = document.list.iter().find(|r| !r.external && rel_is(&r.kind, rt::GLOSSARY)) else { return };
|
||||
let mut entries = Vec::new();
|
||||
if !rel.target.eq_ignore_ascii_case(&self.main) {
|
||||
let pkg = self.pkg;
|
||||
let ct = self.content_types.get_or_insert_with(|| ContentTypes::read(pkg)).of(&rel.target).map(str::to_string);
|
||||
let root = match self.xml(&rel.target) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
log::warn!("docx: ignoring unreadable glossary {}: {e}", rel.target);
|
||||
None
|
||||
}
|
||||
};
|
||||
// Without content types (a converted package) the root element alone decides.
|
||||
if let Some(root) = root.filter(|r| r.name == "w:glossaryDocument" && ct.as_deref().is_none_or(|t| t == GLOSSARY_CONTENT_TYPE)) {
|
||||
let rels = self.pkg.rels(&rel.target);
|
||||
entries = self.doc_parts(&root, &rels);
|
||||
}
|
||||
}
|
||||
self.doc.glossary = entries;
|
||||
let print = glossary_fingerprint(&self.doc.glossary);
|
||||
self.doc.passthrough.insert(GLOSSARY_READ.into(), Arc::new(print.into_bytes()));
|
||||
}
|
||||
|
||||
/// The building blocks of a `w:glossaryDocument`, read with the glossary's relationships.
|
||||
fn doc_parts(&mut self, root: &El, rels: &Rels) -> Vec<BuildingBlock> {
|
||||
// The glossary's notes, comments, bookmarks, permissions and moves are its own: what the
|
||||
// main document's ids mean doesn't apply to it, and its ids mustn't leak into the body's.
|
||||
let footnotes = std::mem::take(&mut self.footnotes);
|
||||
let endnotes = std::mem::take(&mut self.endnotes);
|
||||
let comments = std::mem::take(&mut self.comment_map);
|
||||
let ended = std::mem::take(&mut self.comments_ended);
|
||||
let bookmarks = std::mem::take(&mut self.bookmarks);
|
||||
let perms = std::mem::take(&mut self.perms);
|
||||
let moves = std::mem::take(&mut self.moves);
|
||||
let mut out = Vec::new();
|
||||
for part in root.child("w:docParts").into_iter().flat_map(|d| d.children("w:docPart")) {
|
||||
if out.len() >= MAX_GLOSSARY_ENTRIES {
|
||||
log::warn!("docx: glossary has more than {MAX_GLOSSARY_ENTRIES} entries; the rest are dropped");
|
||||
break;
|
||||
}
|
||||
let pr = part.child("w:docPartPr");
|
||||
let val = |e: Option<&El>| e.and_then(|e| e.attr("w:val")).unwrap_or("").chars().take(MAX_FIELD).collect::<String>();
|
||||
let name = val(pr.and_then(|p| p.child("w:name")));
|
||||
let Some(body) = part.child("w:docPartBody").filter(|_| !name.is_empty()) else { continue };
|
||||
let category = pr.and_then(|p| p.child("w:category"));
|
||||
let mut sc = StoryCtx::default();
|
||||
let mut blocks = Blocks::new();
|
||||
self.read_blocks(&mut sc, body, rels, &mut blocks, 0);
|
||||
self.flush_pending(&mut sc, &mut blocks);
|
||||
if blocks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(BuildingBlock {
|
||||
name,
|
||||
gallery: val(category.and_then(|c| c.child("w:gallery"))),
|
||||
category: val(category.and_then(|c| c.child("w:name"))),
|
||||
description: val(pr.and_then(|p| p.child("w:description"))),
|
||||
guid: val(pr.and_then(|p| p.child("w:guid"))),
|
||||
style: val(pr.and_then(|p| p.child("w:style"))),
|
||||
types: listed(pr.and_then(|p| p.child("w:types")), "w:type", &GLOSSARY_TYPES),
|
||||
behaviors: listed(pr.and_then(|p| p.child("w:behaviors")), "w:behavior", &GLOSSARY_BEHAVIORS),
|
||||
blocks,
|
||||
});
|
||||
}
|
||||
self.footnotes = footnotes;
|
||||
self.endnotes = endnotes;
|
||||
self.comment_map = comments;
|
||||
self.comments_ended = ended;
|
||||
self.bookmarks = bookmarks;
|
||||
self.perms = perms;
|
||||
self.moves = moves;
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use wordcraft_doc::math::{
|
||||
Arg, BrkBin, BrkBinSub, ColJc, FracKind, LimLoc, MAX_DEPTH, MNode, MRun, MScr, MSty, Math, MathJc, MathProps, ScriptKind, merge_runs,
|
||||
};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
use wordcraft_doc::symbol_fonts;
|
||||
|
||||
use crate::xml::El;
|
||||
|
||||
@@ -232,12 +233,21 @@ fn node(k: &El, depth: usize, out: &mut Arg) {
|
||||
e: sub_arg(k, "m:e", d),
|
||||
});
|
||||
}
|
||||
// Tracked insertions show; deletions don't.
|
||||
"w:ins" | "w:moveTo" | "w:smartTag" | "w:customXml" | "m:oMath" if depth <= MAX_DEPTH => {
|
||||
// Tracked insertions show; deletions don't. Hyperlinks, simple fields and direction
|
||||
// wrappers (EG_PContentMath, §22.1.2.77) keep their runs (#1273).
|
||||
"w:ins" | "w:moveTo" | "w:smartTag" | "w:customXml" | "w:hyperlink" | "w:fldSimple" | "w:dir" | "w:bdo" | "m:oMath" if depth <= MAX_DEPTH => {
|
||||
for c in k.els() {
|
||||
node(c, d, out);
|
||||
}
|
||||
}
|
||||
// Markup compatibility: the math choice (we read math), else the fallback.
|
||||
"mc:AlternateContent" if depth <= MAX_DEPTH => {
|
||||
if let Some(c) = k.child("mc:Choice").or_else(|| k.child("mc:Fallback")) {
|
||||
for c in c.els() {
|
||||
node(c, d, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
"w:sdt" => {
|
||||
if let Some(c) = k.child("w:sdtContent") {
|
||||
for c in c.els() {
|
||||
@@ -249,13 +259,24 @@ fn node(k: &El, depth: usize, out: &mut Arg) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `m:t` (and `w:t`) text of a run.
|
||||
/// `m:t` (and `w:t`) text of a run, with symbol characters (`w:sym`) and special hyphens.
|
||||
/// Text in a symbol font (Symbol, Wingdings…) becomes its Unicode equivalent: the math font has
|
||||
/// no glyphs at those private-use codes (#1273).
|
||||
fn run_text(r: &El) -> String {
|
||||
let font = r.child("w:rPr").and_then(|p| p.child("w:rFonts")).and_then(|f| f.attr("w:ascii").or_else(|| f.attr("w:hAnsi"))).unwrap_or("");
|
||||
let mut s = String::new();
|
||||
for c in r.els() {
|
||||
match c.name.as_str() {
|
||||
"m:t" | "w:t" => s.push_str(&c.text()),
|
||||
"m:t" | "w:t" => s.push_str(&symbol_fonts::map_text(font, &c.text())),
|
||||
"w:tab" => s.push('\t'),
|
||||
"w:noBreakHyphen" => s.push('\u{2011}'),
|
||||
"w:sym" => {
|
||||
let ch = c.attr("w:char").and_then(|h| u32::from_str_radix(h.trim(), 16).ok()).and_then(char::from_u32).filter(|c| *c as u32 >= 0x20);
|
||||
if let Some(ch) = ch {
|
||||
let f = c.attr("w:font").unwrap_or(font);
|
||||
s.push(symbol_fonts::symbol_char(f, ch).unwrap_or(ch));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -308,7 +329,10 @@ fn wrpr(pr: Option<&El>, out: &mut MRun) {
|
||||
out.color = Some(c);
|
||||
}
|
||||
if out.nor {
|
||||
if let Some(f) = pr.child("w:rFonts").and_then(|f| f.attr("w:ascii").or_else(|| f.attr("w:hAnsi"))) {
|
||||
// Symbol-font text was mapped to Unicode: it takes the text font.
|
||||
if let Some(f) =
|
||||
pr.child("w:rFonts").and_then(|f| f.attr("w:ascii").or_else(|| f.attr("w:hAnsi"))).filter(|f| !symbol_fonts::is_symbol_font(f))
|
||||
{
|
||||
out.font = Some(f.to_string());
|
||||
}
|
||||
let bold = pr.child("w:b").is_some_and(crate::units::on_off);
|
||||
@@ -364,4 +388,109 @@ mod tests {
|
||||
assert!(matches!(m.nodes[2], MNode::Nary { chr: '∫', .. }));
|
||||
assert!(matches!(&m.nodes[3], MNode::Matrix { rows, .. } if rows.len() == 1 && rows[0].len() == 2));
|
||||
}
|
||||
|
||||
/// Every run's text in the tree, in reading order.
|
||||
fn texts(m: &mut Math) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
wordcraft_doc::math_edit::each_run_mut(&mut m.nodes, &mut |r| out.push(r.text.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
fn t(s: &str) -> String {
|
||||
format!("<m:r><m:t>{s}</m:t></m:r>")
|
||||
}
|
||||
|
||||
/// #1273: one equation using every Office Math element of ECMA-376 §22.1 (each argument
|
||||
/// holding a distinct marker) keeps every argument's text: nothing is silently dropped.
|
||||
#[test]
|
||||
fn every_omml_element_keeps_its_content() {
|
||||
let parts = [
|
||||
format!("<m:acc><m:accPr><m:chr m:val=\"̃\"/></m:accPr><m:e>{}</m:e></m:acc>", t("A1")),
|
||||
format!("<m:bar><m:barPr><m:pos m:val=\"top\"/></m:barPr><m:e>{}</m:e></m:bar>", t("B1")),
|
||||
format!("<m:box><m:boxPr><m:opEmu m:val=\"1\"/></m:boxPr><m:e>{}</m:e></m:box>", t("C1")),
|
||||
format!("<m:borderBox><m:borderBoxPr><m:strikeH/></m:borderBoxPr><m:e>{}</m:e></m:borderBox>", t("D1")),
|
||||
format!("<m:d><m:dPr><m:begChr m:val=\"[\"/></m:dPr><m:e>{}</m:e><m:e>{}</m:e></m:d>", t("E1"), t("E2")),
|
||||
format!("<m:eqArr><m:e>{}</m:e><m:e>{}</m:e></m:eqArr>", t("F1"), t("F2")),
|
||||
format!("<m:f><m:fPr><m:type m:val=\"skw\"/></m:fPr><m:num>{}</m:num><m:den>{}</m:den></m:f>", t("G1"), t("G2")),
|
||||
format!("<m:func><m:fName>{}</m:fName><m:e>{}</m:e></m:func>", t("H1"), t("H2")),
|
||||
format!("<m:groupChr><m:groupChrPr><m:chr m:val=\"⏞\"/><m:pos m:val=\"top\"/></m:groupChrPr><m:e>{}</m:e></m:groupChr>", t("I1")),
|
||||
format!("<m:limLow><m:e>{}</m:e><m:lim>{}</m:lim></m:limLow>", t("J1"), t("J2")),
|
||||
format!("<m:limUpp><m:e>{}</m:e><m:lim>{}</m:lim></m:limUpp>", t("K1"), t("K2")),
|
||||
format!("<m:m><m:mr><m:e>{}</m:e><m:e>{}</m:e></m:mr><m:mr><m:e>{}</m:e><m:e/></m:mr></m:m>", t("L1"), t("L2"), t("L3")),
|
||||
format!(
|
||||
"<m:nary><m:naryPr><m:chr m:val=\"∑\"/></m:naryPr><m:sub>{}</m:sub><m:sup>{}</m:sup><m:e>{}</m:e></m:nary>",
|
||||
t("M1"),
|
||||
t("M2"),
|
||||
t("M3")
|
||||
),
|
||||
format!("<m:phant><m:phantPr><m:show m:val=\"0\"/></m:phantPr><m:e>{}</m:e></m:phant>", t("N1")),
|
||||
format!("<m:rad><m:deg>{}</m:deg><m:e>{}</m:e></m:rad>", t("O1"), t("O2")),
|
||||
format!("<m:sPre><m:sub>{}</m:sub><m:sup>{}</m:sup><m:e>{}</m:e></m:sPre>", t("P1"), t("P2"), t("P3")),
|
||||
format!("<m:sSub><m:e>{}</m:e><m:sub>{}</m:sub></m:sSub>", t("Q1"), t("Q2")),
|
||||
format!("<m:sSubSup><m:e>{}</m:e><m:sub>{}</m:sub><m:sup>{}</m:sup></m:sSubSup>", t("R1"), t("R2"), t("R3")),
|
||||
format!("<m:sSup><m:e>{}</m:e><m:sup>{}</m:sup></m:sSup>", t("S1"), t("S2")),
|
||||
// Run-level wrappers allowed in math (EG_PContentMath): hyperlinks, simple fields,
|
||||
// tracked insertions, content controls, markup compatibility.
|
||||
format!("<w:hyperlink w:anchor=\"x\">{}</w:hyperlink>", t("T1")),
|
||||
format!("<w:fldSimple w:instr=\"QUOTE\">{}</w:fldSimple>", t("T2")),
|
||||
format!("<w:ins w:id=\"1\" w:author=\"a\">{}</w:ins>", t("T3")),
|
||||
format!("<w:sdt><w:sdtContent>{}</w:sdtContent></w:sdt>", t("T4")),
|
||||
format!(
|
||||
"<mc:AlternateContent><mc:Choice Requires=\"m\">{}</mc:Choice><mc:Fallback><w:r><w:t>picture</w:t></w:r></mc:Fallback></mc:AlternateContent>",
|
||||
t("T5")
|
||||
),
|
||||
"<w:r><w:t>T6</w:t></w:r>".to_string(),
|
||||
];
|
||||
let x = format!(
|
||||
r#"<m:oMath xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">{}</m:oMath>"#,
|
||||
parts.concat()
|
||||
);
|
||||
let e = crate::xml::parse(x.as_bytes()).unwrap();
|
||||
let mut m = read_omath(&e, MathJc::CenterGroup);
|
||||
let got = texts(&mut m).concat();
|
||||
let markers = [
|
||||
"A1", "B1", "C1", "D1", "E1", "E2", "F1", "F2", "G1", "G2", "H1", "H2", "I1", "J1", "J2", "K1", "K2", "L1", "L2", "L3", "M1", "M2", "M3",
|
||||
"N1", "O1", "O2", "P1", "P2", "P3", "Q1", "Q2", "R1", "R2", "R3", "S1", "S2", "T1", "T2", "T3", "T4", "T5", "T6",
|
||||
];
|
||||
for k in markers {
|
||||
assert!(got.contains(k), "{k} dropped from {got}");
|
||||
}
|
||||
assert!(!got.contains("picture"), "the math choice wins over the fallback: {got}");
|
||||
}
|
||||
|
||||
/// #1273: deleted text stays out; symbol characters and symbol-font text become Unicode.
|
||||
#[test]
|
||||
fn symbols_and_deletions_in_math() {
|
||||
let e = omath(
|
||||
r#"<m:r><m:t>x</m:t></m:r><w:del w:id="1" w:author="a"><m:r><m:t>gone</m:t></m:r></w:del><m:r><w:sym w:font="Symbol" w:char="F061"/></m:r><m:r><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr><m:t></m:t><w:noBreakHyphen/></m:r><w:r><w:rPr><w:rFonts w:ascii="Symbol"/></w:rPr><w:t></w:t></w:r>"#,
|
||||
);
|
||||
let mut m = read_omath(&e, MathJc::CenterGroup);
|
||||
let got = texts(&mut m).concat();
|
||||
assert_eq!(got, "xαβ\u{2011}γ");
|
||||
let mut font = None;
|
||||
wordcraft_doc::math_edit::each_run_mut(&mut m.nodes, &mut |r| {
|
||||
if r.nor {
|
||||
font = Some(r.font.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(font, Some(None), "mapped symbol text takes the text font");
|
||||
}
|
||||
|
||||
/// Hostile nesting through the wrappers is bounded (no stack overflow, no panic).
|
||||
#[test]
|
||||
fn deeply_nested_wrappers_are_bounded() {
|
||||
// Deeper than the math limit, within the XML parser's own depth limit.
|
||||
let n = 120;
|
||||
let inner = format!("{}{}{}", "<w:hyperlink>".repeat(n), t("deep"), "</w:hyperlink>".repeat(n));
|
||||
let e = omath(&inner);
|
||||
let _ = read_omath(&e, MathJc::CenterGroup);
|
||||
let inner = format!(
|
||||
"{}{}{}",
|
||||
"<mc:AlternateContent xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"><mc:Choice Requires=\"m\">".repeat(n),
|
||||
t("deep"),
|
||||
"</mc:Choice></mc:AlternateContent>".repeat(n)
|
||||
);
|
||||
let e = omath(&inner);
|
||||
let _ = read_omath(&e, MathJc::CenterGroup);
|
||||
}
|
||||
}
|
||||
|
||||
+24
-136
@@ -5,6 +5,7 @@ pub(crate) mod diagram;
|
||||
mod drawing_color;
|
||||
mod embed;
|
||||
mod freeform;
|
||||
mod glossary;
|
||||
pub(crate) mod math;
|
||||
mod props;
|
||||
mod sdt;
|
||||
@@ -28,6 +29,7 @@ use wordcraft_doc::{
|
||||
};
|
||||
|
||||
use crate::DocxError;
|
||||
use crate::bibliography::{MAX_SOURCES, Seen};
|
||||
use crate::package::{ContentTypes, EMBEDDED_PARTS, EmbeddedManifest, MAX_VBA_RELATED, Package, Rels, VBA_PROJECT_PART, VBA_RELATED, rel_is, rt};
|
||||
use crate::units::{flag, int, on_off, tw, u32_of};
|
||||
use crate::xml::El;
|
||||
@@ -45,19 +47,8 @@ const MAX_HF_DEPTH: usize = 4;
|
||||
/// Most graphic work (items plus path segments, see `story::graphic_work`) built for one file's
|
||||
/// charts and diagrams; later ones are left empty.
|
||||
const MAX_GRAPHIC_WORK: usize = 2_000_000;
|
||||
/// Bibliography sources kept from a file (Word's own source manager holds far fewer).
|
||||
const MAX_SOURCES: usize = 10_000;
|
||||
/// Custom XML parts looked at for bibliography sources.
|
||||
const MAX_BIBLIOGRAPHY_PARTS: usize = 64;
|
||||
/// Characters kept of a bibliography's citation style name.
|
||||
const MAX_STYLE_NAME: usize = 64;
|
||||
|
||||
/// Bibliography sources already read: tags, and (title, author) of untagged ones.
|
||||
#[derive(Default)]
|
||||
struct BibSeen {
|
||||
tags: HashSet<String>,
|
||||
untagged: HashSet<(String, String)>,
|
||||
}
|
||||
|
||||
/// Longest attached-template path we keep (bytes); a longer one is not a real path.
|
||||
const MAX_TEMPLATE_PATH: usize = 32 * 1024;
|
||||
@@ -232,7 +223,7 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
bib_parts.push(path);
|
||||
}
|
||||
}
|
||||
let mut seen_sources = BibSeen::default();
|
||||
let mut seen_sources = Seen::default();
|
||||
for path in &bib_parts {
|
||||
if r.doc.sources.len() >= MAX_SOURCES {
|
||||
break;
|
||||
@@ -281,11 +272,12 @@ pub(crate) fn read_opened(pkg: &Package) -> Result<Document, DocxError> {
|
||||
// bytes, never parsed or run, so a .docm/.dotm saved again carries exactly what the file had.
|
||||
// Only the relationships and content types are read.
|
||||
if let Some(v) = part(rt::VBA_PROJECT)
|
||||
&& let Some(b) = pkg.get(&v).filter(|b| !b.is_empty())
|
||||
&& let Some(b) = pkg.get_shared(&v).filter(|b| !b.is_empty())
|
||||
{
|
||||
r.doc.passthrough.insert(VBA_PROJECT_PART.into(), Arc::new(b.to_vec()));
|
||||
r.doc.passthrough.insert(VBA_PROJECT_PART.into(), b.clone());
|
||||
r.read_vba_related(&v);
|
||||
}
|
||||
r.read_glossary(&rels);
|
||||
r.keep_custom_xml(&root_rels, &rels);
|
||||
r.keep_unmodelled(&root_rels, &rels);
|
||||
if !r.embedded.parts.is_empty() {
|
||||
@@ -577,7 +569,7 @@ impl Reader<'_> {
|
||||
log::warn!("docx: not carrying VBA-related part {path:?}");
|
||||
continue;
|
||||
}
|
||||
let Some(bytes) = self.pkg.get(path) else {
|
||||
let Some(bytes) = self.pkg.get_shared(path) else {
|
||||
log::warn!("docx: VBA-related part {path} is missing; keeping the project without it");
|
||||
continue;
|
||||
};
|
||||
@@ -587,7 +579,7 @@ impl Reader<'_> {
|
||||
}
|
||||
kept += 1;
|
||||
manifest.push_str(&format!("{}\t{path}\t{ct}\n", rel.kind));
|
||||
self.doc.passthrough.entry(path.to_string()).or_insert_with(|| Arc::new(bytes.to_vec()));
|
||||
self.doc.passthrough.entry(path.to_string()).or_insert_with(|| bytes.clone());
|
||||
}
|
||||
if !manifest.is_empty() {
|
||||
self.doc.passthrough.insert(VBA_RELATED.into(), Arc::new(manifest.into_bytes()));
|
||||
@@ -642,7 +634,7 @@ impl Reader<'_> {
|
||||
if let Some(k) = self.media_by_path.get(&rel.target) {
|
||||
return Some(k.clone());
|
||||
}
|
||||
let bytes = self.pkg.get(&rel.target)?;
|
||||
let bytes = self.pkg.get_shared(&rel.target)?;
|
||||
let base: String =
|
||||
rel.target.rsplit('/').next().unwrap_or("image").chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')).collect();
|
||||
let base = if base.is_empty() || base.starts_with('.') { format!("image{base}") } else { base };
|
||||
@@ -655,7 +647,7 @@ impl Reader<'_> {
|
||||
None => format!("{base}_{n}"),
|
||||
};
|
||||
}
|
||||
self.doc.media.insert(key.clone(), Arc::new(bytes.to_vec()));
|
||||
self.doc.media.insert(key.clone(), bytes.clone());
|
||||
self.media_by_path.insert(rel.target.clone(), key.clone());
|
||||
Some(key)
|
||||
}
|
||||
@@ -816,9 +808,6 @@ impl Reader<'_> {
|
||||
for s in root.children("w:style").take(10_000) {
|
||||
let Some(raw_id) = s.attr("w:styleId").filter(|i| !i.is_empty()) else { continue };
|
||||
let id = self.pc.style_id(raw_id);
|
||||
if sheet.get(&id).is_some() {
|
||||
continue;
|
||||
}
|
||||
let kind = match s.attr("w:type").unwrap_or("paragraph") {
|
||||
"character" => StyleKind::Character,
|
||||
"table" => StyleKind::Table,
|
||||
@@ -860,7 +849,13 @@ impl Reader<'_> {
|
||||
let parts = self.table_style_parts(s, &mut st);
|
||||
st.table = (parts != TableStyleParts::default()).then_some(parts);
|
||||
}
|
||||
sheet.styles.push(st);
|
||||
// A style defined twice (some generators write their own Heading 1 after a
|
||||
// placeholder one) is the last definition, whole: Word drops the earlier one rather
|
||||
// than merging the two (observed with synthetic documents).
|
||||
match sheet.styles.iter_mut().find(|s| s.id == id) {
|
||||
Some(earlier) => *earlier = st,
|
||||
None => sheet.styles.push(st),
|
||||
}
|
||||
}
|
||||
// Styles that give only a list level take the list from the style they are based on
|
||||
// (Heading 3: level 3 of Heading 2's outline list).
|
||||
@@ -1083,6 +1078,7 @@ impl Reader<'_> {
|
||||
s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off);
|
||||
}
|
||||
"w:trackRevisions" => s.track_changes = on_off(k),
|
||||
"w:doNotTrackMoves" => s.track_moves = !on_off(k),
|
||||
"w:defaultTabStop" => {
|
||||
if let Some(v) = tw(k, "w:val").filter(|v| *v > 0.0) {
|
||||
s.default_tab = v.clamp(1.0, 1584.0);
|
||||
@@ -1318,125 +1314,17 @@ impl Reader<'_> {
|
||||
|
||||
/// Sources from a `b:Sources` custom XML part (other custom XML is left alone); at most
|
||||
/// [`MAX_SOURCES`] in all, and the document's citation style from `StyleName`.
|
||||
fn read_bibliography(&mut self, path: &str, seen: &mut BibSeen) -> Result<(), DocxError> {
|
||||
fn read_bibliography(&mut self, path: &str, seen: &mut Seen) -> Result<(), DocxError> {
|
||||
let Some(root) = self.xml(path)? else { return Ok(()) };
|
||||
if root.local() != "Sources" {
|
||||
return Ok(());
|
||||
}
|
||||
if self.doc.settings.bib_style.is_none()
|
||||
&& let Some(name) = root.attrs.iter().find(|(k, _)| k.rsplit(':').next() == Some("StyleName")).map(|(_, v)| v.trim())
|
||||
&& !name.is_empty()
|
||||
{
|
||||
self.doc.settings.bib_style = Some(name.chars().take(MAX_STYLE_NAME).collect());
|
||||
}
|
||||
let child_text = |el: &El, local: &str| el.els().find(|e| e.local() == local).map(|e| e.text()).unwrap_or_default();
|
||||
let parse_persons = |parent: &El| -> String {
|
||||
let mut names = Vec::new();
|
||||
let person_els: Vec<&El> = {
|
||||
let in_lists: Vec<&El> =
|
||||
parent.els().filter(|e| e.local() == "NameList").flat_map(|n| n.els().filter(|e| e.local() == "Person")).collect();
|
||||
if in_lists.is_empty() { parent.els().filter(|e| e.local() == "Person").collect() } else { in_lists }
|
||||
};
|
||||
for name_el in person_els {
|
||||
let last = child_text(name_el, "Last");
|
||||
let first = child_text(name_el, "First");
|
||||
let middle = child_text(name_el, "Middle");
|
||||
let name = if !first.is_empty() && !middle.is_empty() {
|
||||
format!("{last}, {first} {middle}")
|
||||
} else if !first.is_empty() {
|
||||
format!("{last}, {first}")
|
||||
} else {
|
||||
last
|
||||
};
|
||||
if !name.is_empty() {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
names.join("; ")
|
||||
};
|
||||
|
||||
for src_el in root.els().filter(|e| e.local() == "Source") {
|
||||
if self.doc.sources.len() >= MAX_SOURCES {
|
||||
log::warn!("docx: more than {MAX_SOURCES} bibliography sources; the rest are dropped");
|
||||
break;
|
||||
}
|
||||
let tag = child_text(src_el, "Tag");
|
||||
let raw_kind = child_text(src_el, "SourceType");
|
||||
let kind = crate::write::from_source_type(&raw_kind);
|
||||
let (author, editor) = match src_el.els().find(|e| e.local() == "Author") {
|
||||
Some(a) => {
|
||||
let auth =
|
||||
a.els().find(|e| e.local() == "Author").map(parse_persons).filter(|s| !s.is_empty()).unwrap_or_else(|| parse_persons(a));
|
||||
let ed = a.els().find(|e| e.local() == "Editor").map(parse_persons).unwrap_or_default();
|
||||
(auth, ed)
|
||||
}
|
||||
None => (String::new(), String::new()),
|
||||
};
|
||||
let editor = if editor.is_empty() { src_el.els().find(|e| e.local() == "Editor").map(parse_persons).unwrap_or_default() } else { editor };
|
||||
let title = child_text(src_el, "Title");
|
||||
let year = child_text(src_el, "Year");
|
||||
let month = child_text(src_el, "Month");
|
||||
let day = child_text(src_el, "Day");
|
||||
let city = child_text(src_el, "City");
|
||||
let publisher = child_text(src_el, "Publisher");
|
||||
let journal = child_text(src_el, "JournalName");
|
||||
let edition = child_text(src_el, "Edition");
|
||||
let volume = child_text(src_el, "Volume");
|
||||
let issue = child_text(src_el, "Issue");
|
||||
let pages = child_text(src_el, "Pages");
|
||||
let url = child_text(src_el, "URL");
|
||||
let accessed = match child_text(src_el, "Accessed") {
|
||||
a if !a.is_empty() => a,
|
||||
_ => {
|
||||
let y = child_text(src_el, "YearAccessed");
|
||||
let m = child_text(src_el, "MonthAccessed");
|
||||
let d = child_text(src_el, "DayAccessed");
|
||||
if !y.is_empty() && !m.is_empty() && !d.is_empty() {
|
||||
format!("{y}-{m}-{d}")
|
||||
} else if !y.is_empty() && !m.is_empty() {
|
||||
format!("{y}-{m}")
|
||||
} else {
|
||||
y
|
||||
}
|
||||
}
|
||||
};
|
||||
let doi = match child_text(src_el, "DOI") {
|
||||
d if !d.is_empty() => d,
|
||||
_ => child_text(src_el, "StandardNumber"),
|
||||
};
|
||||
|
||||
// Keep sources with some content, once each (by tag, or title and author untagged).
|
||||
if tag.is_empty() && title.is_empty() && author.is_empty() && editor.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let fresh = if tag.is_empty() {
|
||||
seen.untagged.insert((title.clone(), if author.is_empty() { editor.clone() } else { author.clone() }))
|
||||
} else {
|
||||
seen.tags.insert(tag.clone())
|
||||
};
|
||||
if fresh {
|
||||
self.doc.sources.push(wordcraft_doc::Source {
|
||||
tag,
|
||||
kind,
|
||||
author,
|
||||
title,
|
||||
year,
|
||||
city,
|
||||
publisher,
|
||||
journal,
|
||||
volume,
|
||||
pages,
|
||||
url,
|
||||
editor,
|
||||
edition,
|
||||
issue,
|
||||
month,
|
||||
day,
|
||||
accessed,
|
||||
doi,
|
||||
});
|
||||
}
|
||||
let room = MAX_SOURCES.saturating_sub(self.doc.sources.len());
|
||||
let bib = crate::bibliography::parse(&root, seen, room);
|
||||
if self.doc.settings.bib_style.is_none() {
|
||||
self.doc.settings.bib_style = bib.style;
|
||||
}
|
||||
self.doc.sources.extend(bib.sources);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@ use std::collections::HashMap;
|
||||
|
||||
use wordcraft_doc::para::cap_alt;
|
||||
use wordcraft_doc::props::{
|
||||
Align, Border, BorderStyle, Borders, CellProps, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, Rgb, RowProps, TabAlign,
|
||||
TabLeader, TabStop, TableFloat, TableLook, TableProps, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign,
|
||||
Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, LineSpacing, NumRef,
|
||||
ParaProps, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextColor, TextDirection, Underline, VAlign, VMerge,
|
||||
VertAlign,
|
||||
};
|
||||
use wordcraft_doc::section::{
|
||||
Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, MAX_CHAR_SPACE, MAX_GRID_PITCH, NotePos, NoteProps, NoteRestart, NumFormat,
|
||||
@@ -13,7 +14,7 @@ use wordcraft_doc::section::{
|
||||
};
|
||||
|
||||
use super::drawing_color::adjust_lum;
|
||||
use crate::units::{int, measure, on_off, tw, u32_of};
|
||||
use crate::units::{int, line_multiple, measure, on_off, tw, u32_of};
|
||||
|
||||
/// A text frame (`w:framePr` without a drop cap, ECMA-376 §17.3.1.11), sizes and offsets in
|
||||
/// points (clamped), names kept as OOXML writes them.
|
||||
@@ -207,11 +208,8 @@ impl PropCtx {
|
||||
"w:szCs" => c.size_cs = k.attr("w:val").and_then(|v| measure(v, 2.0)).filter(|v| *v > 0.0).map(|v| v.clamp(1.0, 1638.0)),
|
||||
"w:highlight" => c.highlight = k.attr("w:val").map(Highlight::from_ooxml),
|
||||
"w:u" => {
|
||||
if let Some(v) = k.attr("w:val") {
|
||||
c.underline = Some(Underline::from_ooxml(v));
|
||||
} else {
|
||||
c.underline = Some(Underline::Single);
|
||||
}
|
||||
// w:val has no default in the schema: without it Word draws no underline
|
||||
c.underline = k.attr("w:val").map(Underline::from_ooxml);
|
||||
c.underline_color =
|
||||
self.theme_color(k, "w:themeColor", "w:themeTint", "w:themeShade").or_else(|| k.attr("w:color").and_then(Rgb::parse));
|
||||
}
|
||||
@@ -224,10 +222,15 @@ impl PropCtx {
|
||||
_ => VertAlign::Baseline,
|
||||
})
|
||||
}
|
||||
"w:eastAsianLayout" => {
|
||||
let l = east_asian_layout(k);
|
||||
c.east_asian_layout = (l != EastAsianLayout::default()).then_some(l);
|
||||
}
|
||||
"w:lang" => {
|
||||
c.lang = k.attr("w:val").filter(|v| !v.is_empty() && v.len() < 64).map(str::to_string);
|
||||
c.lang_bidi = k.attr("w:bidi").filter(|v| !v.is_empty() && v.len() < 64).map(str::to_string);
|
||||
}
|
||||
"w14:ligatures" => c.ligatures = k.attr("w14:val").and_then(wordcraft_doc::props::Ligatures::from_ooxml),
|
||||
n if n.starts_with("w14:") => {
|
||||
let fx = c.text_effects.get_or_insert_with(Default::default);
|
||||
super::wordart::read(k, &self.theme, fx);
|
||||
@@ -266,8 +269,11 @@ impl PropCtx {
|
||||
"w:autoSpaceDN" => p.auto_space_dn = Some(on_off(k)),
|
||||
"w:snapToGrid" => p.snap_to_grid = Some(on_off(k)),
|
||||
"w:framePr" => {
|
||||
if matches!(k.attr("w:dropCap"), Some("drop") | Some("margin")) {
|
||||
if let Some(kind @ ("drop" | "margin")) = k.attr("w:dropCap") {
|
||||
p.drop_cap = Some(k.attr("w:lines").and_then(u32_of).unwrap_or(3).clamp(1, 10) as u8);
|
||||
p.drop_cap_margin = (kind == "margin").then_some(true);
|
||||
p.drop_cap_distance =
|
||||
tw(k, "w:hSpace").filter(|d| d.is_finite() && *d > 0.0).map(|d| d.min(wordcraft_doc::resolve::MAX_DROP_CAP_DISTANCE));
|
||||
} else {
|
||||
p.frame = Some(text_frame(k));
|
||||
}
|
||||
@@ -312,7 +318,8 @@ impl PropCtx {
|
||||
p.line_spacing = match rule.as_str() {
|
||||
"exact" => measure(line, 20.0).map(|v| LineSpacing::Exactly(v.abs())),
|
||||
"atleast" => measure(line, 20.0).map(|v| LineSpacing::AtLeast(v.abs())),
|
||||
_ => measure(line, 240.0).map(|v| LineSpacing::Multiple(v.abs().clamp(0.06, 132.0))),
|
||||
// Strict OOXML writes the height with a unit (`13.90pt`, #2329).
|
||||
_ => line_multiple(line).map(|v| LineSpacing::Multiple(v.abs().clamp(0.06, 132.0))),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -372,14 +379,18 @@ fn tab_stop(t: &El) -> Option<TabStop> {
|
||||
"clear" => TabAlign::Clear,
|
||||
_ => TabAlign::Left,
|
||||
};
|
||||
let leader = match t.attr("w:leader").unwrap_or("none") {
|
||||
Some(TabStop { pos, align, leader: tab_leader(t.attr("w:leader").unwrap_or("none")) })
|
||||
}
|
||||
|
||||
/// A tab stop's or positional tab's `w:leader` (`ST_TabTlc`, `ST_PTabLeader`).
|
||||
pub(crate) fn tab_leader(v: &str) -> TabLeader {
|
||||
match v {
|
||||
"dot" => TabLeader::Dot,
|
||||
"hyphen" => TabLeader::Hyphen,
|
||||
"underscore" | "heavy" => TabLeader::Underscore,
|
||||
"middleDot" => TabLeader::MiddleDot,
|
||||
_ => TabLeader::None,
|
||||
};
|
||||
Some(TabStop { pos, align, leader })
|
||||
}
|
||||
}
|
||||
|
||||
/// `w:shd/@w:fill` (a solid fill colour; `auto` = none), ignoring theme fills ([`PropCtx::shd_fill`]).
|
||||
@@ -422,7 +433,11 @@ pub fn borders(e: &El) -> Borders {
|
||||
|
||||
/// Margins element (`w:tblCellMar`, `w:tcMar`) → [top, left, bottom, right].
|
||||
pub fn margins(e: &El) -> [f32; 4] {
|
||||
let get = |names: &[&str]| names.iter().find_map(|n| e.child(n)).and_then(|c| tw(c, "w:w")).unwrap_or(0.0).clamp(0.0, 1584.0);
|
||||
margin_sides(e).map(|side| side.unwrap_or(0.0))
|
||||
}
|
||||
|
||||
fn margin_sides(e: &El) -> [Option<f32>; 4] {
|
||||
let get = |names: &[&str]| names.iter().find_map(|n| e.child(n)).and_then(|c| tw(c, "w:w")).map(|v| v.clamp(0.0, 1584.0));
|
||||
[get(&["w:top"]), get(&["w:left", "w:start"]), get(&["w:bottom"]), get(&["w:right", "w:end"])]
|
||||
}
|
||||
|
||||
@@ -557,7 +572,14 @@ pub fn tcpr(pc: &PropCtx, e: &El) -> (CellProps, bool) {
|
||||
"w:shd" => c.shading = pc.shd_fill(k),
|
||||
"w:noWrap" => c.no_wrap = on_off(k),
|
||||
"w:hideMark" => c.hide_mark = on_off(k),
|
||||
"w:tcMar" => c.margins = Some(margins(k)),
|
||||
"w:tcMar" => {
|
||||
let sides = margin_sides(k);
|
||||
if sides.iter().all(Option::is_some) {
|
||||
c.margins = Some(sides.map(|side| side.unwrap_or(0.0)));
|
||||
} else {
|
||||
c.partial_margins = Some(sides);
|
||||
}
|
||||
}
|
||||
"w:textDirection" => {
|
||||
c.text_direction = TextDirection::from_ooxml(k.attr("w:val").unwrap_or(""));
|
||||
c.text_direction_set = k.attr("w:val") == Some("lrTb");
|
||||
@@ -742,3 +764,22 @@ fn table_float(e: &El) -> TableFloat {
|
||||
overlap: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `w:eastAsianLayout` (ISO/IEC 29500-1 §17.3.2.10). Attributes the schema doesn't allow (an id
|
||||
/// out of `xsd:int`, an unknown bracket, an on/off that isn't one) are left unset.
|
||||
fn east_asian_layout(e: &El) -> EastAsianLayout {
|
||||
let flag = |name: &str| {
|
||||
e.attr(name).and_then(|v| match v.trim() {
|
||||
"1" | "true" | "on" => Some(true),
|
||||
"0" | "false" | "off" => Some(false),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
EastAsianLayout {
|
||||
id: e.attr("w:id").and_then(int).and_then(|v| i32::try_from(v).ok()),
|
||||
combine: flag("w:combine"),
|
||||
combine_brackets: e.attr("w:combineBrackets").and_then(|v| CombineBrackets::from_ooxml(v.trim())),
|
||||
vert: flag("w:vert"),
|
||||
vert_compress: flag("w:vertCompress"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,18 +145,63 @@ pub(crate) fn shape_paint(sppr: Option<&El>, style: Option<&El>, theme: &[Rgb])
|
||||
ShapePaint { fill, stroke, stroke_width }
|
||||
}
|
||||
|
||||
/// A VML colour (`strokecolor`, `fillcolor`): `#rrggbb` or `#rgb` (Word follows it with the
|
||||
/// theme slot, as in `#4472c4 [3204]`), or a colour name.
|
||||
/// Explicit DrawingML dash stops override the solid default.
|
||||
pub(crate) fn line_dash(ln: Option<&El>) -> wordcraft_doc::line_dash::LineDash {
|
||||
use wordcraft_doc::line_dash::{LineDash, MAX_DASH_STOPS};
|
||||
let Some(ln) = ln else { return LineDash::Solid };
|
||||
if let Some(custom) = ln.child("a:custDash") {
|
||||
let stops: Vec<_> =
|
||||
custom.children("a:ds").take(MAX_DASH_STOPS).filter_map(|e| Some((dash_ratio(e.attr("d")?)?, dash_ratio(e.attr("sp")?)?))).collect();
|
||||
return if stops.is_empty() { LineDash::Solid } else { LineDash::Custom(stops) };
|
||||
}
|
||||
ln.child("a:prstDash").and_then(|e| e.attr("val")).map(LineDash::from_ooxml).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Strict OOXML may spell percentages with a percent sign instead of integer units.
|
||||
fn dash_ratio(value: &str) -> Option<u32> {
|
||||
const PERCENT_UNITS: f64 = 1000.0;
|
||||
let value = value.trim();
|
||||
let Some(percent) = value.strip_suffix('%') else { return value.parse().ok() };
|
||||
let units = percent.parse::<f64>().ok()? * PERCENT_UNITS;
|
||||
if !units.is_finite() || !(0.0..=f64::from(u32::MAX)).contains(&units) {
|
||||
return None;
|
||||
}
|
||||
Some(units.round() as u32)
|
||||
}
|
||||
|
||||
/// A VML colour (`strokecolor`, `fillcolor`): `#rrggbb`, `rrggbb`, `#rgb` or `rgb` (Word follows it
|
||||
/// with the theme slot, as in `#4472c4 [3204]` or `4472c4 [3204]`), an `rgb(...)` function, or a
|
||||
/// colour name.
|
||||
pub(crate) fn vml_color(v: &str) -> Option<Rgb> {
|
||||
let v = v.split_whitespace().next()?;
|
||||
if let Some(hex) = v.strip_prefix('#') {
|
||||
if hex.len() == 3 && hex.is_ascii() {
|
||||
let long: String = hex.chars().flat_map(|c| [c, c]).collect();
|
||||
return Rgb::parse(&long);
|
||||
let s = v.trim();
|
||||
if let Some(inner) = s.strip_prefix("rgb(").or_else(|| s.strip_prefix("rgba(")) {
|
||||
let nums: Vec<u8> = inner
|
||||
.trim_end_matches(')')
|
||||
.split(',')
|
||||
.take(3)
|
||||
.filter_map(|x| {
|
||||
let x = x.trim();
|
||||
if let Some(p) = x.strip_suffix('%') {
|
||||
p.trim().parse::<f32>().ok().map(|f| (f.clamp(0.0, 100.0) * 2.55).round() as u8)
|
||||
} else {
|
||||
x.parse::<f32>().ok().map(|f| f.clamp(0.0, 255.0).round() as u8)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if let [r, g, b] = nums[..] {
|
||||
return Some(Rgb(r, g, b));
|
||||
}
|
||||
}
|
||||
let tok = s.split_whitespace().next()?;
|
||||
let hex = tok.strip_prefix('#').unwrap_or(tok);
|
||||
if hex.len() == 3 && hex.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
let long: String = hex.chars().flat_map(|c| [c, c]).collect();
|
||||
return Rgb::parse(&long);
|
||||
}
|
||||
if hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Rgb::parse(hex);
|
||||
}
|
||||
super::drawing_color::preset_color(v)
|
||||
super::drawing_color::preset_color(tok)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -255,8 +300,13 @@ mod tests {
|
||||
#[test]
|
||||
fn vml_colours() {
|
||||
assert_eq!(vml_color("#ffc000 [3207]"), Some(Rgb(0xFF, 0xC0, 0)));
|
||||
assert_eq!(vml_color("ffc000 [3207]"), Some(Rgb(0xFF, 0xC0, 0)));
|
||||
assert_eq!(vml_color("#f00"), Some(Rgb(0xFF, 0, 0)));
|
||||
assert_eq!(vml_color("f00"), Some(Rgb(0xFF, 0, 0)));
|
||||
assert_eq!(vml_color("black"), Some(Rgb(0, 0, 0)));
|
||||
assert_eq!(vml_color("Red"), Some(Rgb(0xFF, 0, 0)));
|
||||
assert_eq!(vml_color("rgb(255, 128, 0)"), Some(Rgb(255, 128, 0)));
|
||||
assert_eq!(vml_color("rgb(100%, 0%, 0%)"), Some(Rgb(255, 0, 0)));
|
||||
assert_eq!(vml_color("#é"), None);
|
||||
assert_eq!(vml_color(""), None);
|
||||
}
|
||||
|
||||
+360
-35
@@ -6,7 +6,7 @@ use wordcraft_doc::connector::{ConnEnd, ShapeExtra};
|
||||
use wordcraft_doc::control::{ContentControl, ControlKind, ControlWrap};
|
||||
use wordcraft_doc::effects::{Glow, Shadow, ShapeEffects};
|
||||
use wordcraft_doc::graphic::{Embedded, Graphic, GraphicItem, GraphicKind};
|
||||
use wordcraft_doc::para::{AltText, Anchor, Float, FloatAlign, NoteKind, ShapeKind, Wrap, WrapText, cap_alt};
|
||||
use wordcraft_doc::para::{AltText, Anchor, Float, FloatAlign, NoteKind, PTabAlign, PTabBase, ShapeKind, Wrap, WrapText, cap_alt};
|
||||
use wordcraft_doc::props::{CharProps, NumChange, PropChange, Rgb, TextColor};
|
||||
use wordcraft_doc::table::{Cell, MAX_COLS, MAX_ROWS, Row, Table};
|
||||
use wordcraft_doc::{Block, Blocks, InlineObject, Paragraph, PartKind, RevisionKind, Run, para_block};
|
||||
@@ -30,6 +30,8 @@ const MAX_TABLE_DEPTH: usize = 24;
|
||||
const MAX_FIELD_DEPTH: usize = 32;
|
||||
/// Deepest text-box-in-text-box nesting.
|
||||
const MAX_STORY_DEPTH: usize = 4;
|
||||
/// Deepest `v:group` nesting followed (hostile files).
|
||||
const MAX_VML_GROUP_DEPTH: usize = 8;
|
||||
/// Longest field code we keep (Zotero's citation codes embed item data as JSON).
|
||||
const MAX_INSTR: usize = 2 * 1024 * 1024;
|
||||
/// Longest legacy form field definition (`w:ffData`) we keep.
|
||||
@@ -176,7 +178,8 @@ fn clean_text(s: &str) -> String {
|
||||
|
||||
fn children_of_choice(ac: &El) -> Option<&El> {
|
||||
// Prefer a Choice whose requirements we understand; else the Fallback; else any Choice.
|
||||
const KNOWN: &[&str] = &["wps", "wpg", "wpc", "wpi", "w14", "w15", "wp14", "a14", "w16se", "w16cid", "w16", "w16cex", "w16sdtdh", "v"];
|
||||
// `m`: Office Math (a producer may guard an equation with a picture fallback, #1273).
|
||||
const KNOWN: &[&str] = &["wps", "wpg", "wpc", "wpi", "w14", "w15", "wp14", "a14", "w16se", "w16cid", "w16", "w16cex", "w16sdtdh", "v", "m"];
|
||||
let ok = |c: &El| c.attr("Requires").unwrap_or("").split_whitespace().all(|r| KNOWN.contains(&r));
|
||||
ac.children("mc:Choice").find(|c| ok(c)).or_else(|| ac.child("mc:Fallback")).or_else(|| ac.child("mc:Choice"))
|
||||
}
|
||||
@@ -199,10 +202,21 @@ impl Reader<'_> {
|
||||
&& p.props.drop_cap.is_none()
|
||||
&& let Some(Block::Para(mut first)) = out.pop().map(|b| (*b).clone())
|
||||
{
|
||||
let lines = first.props.drop_cap;
|
||||
let mut props = p.props.clone();
|
||||
props.drop_cap = first.props.drop_cap;
|
||||
props.drop_cap_margin = first.props.drop_cap_margin;
|
||||
props.drop_cap_distance = first.props.drop_cap_distance;
|
||||
// A letter in a font of its own: the drop cap's font, the letter itself
|
||||
// in the text's (so taking the drop cap away gives the letter its font back).
|
||||
let cap_font = first.runs.first().and_then(|r| r.props.font.clone());
|
||||
let text_font = p.runs.first().and_then(|r| r.props.font.clone());
|
||||
if cap_font.is_some() && cap_font != text_font {
|
||||
for r in &mut first.runs {
|
||||
r.props.font = text_font.clone();
|
||||
}
|
||||
props.drop_cap_font = cap_font;
|
||||
}
|
||||
first.append(p);
|
||||
props.drop_cap = lines;
|
||||
first.props = props;
|
||||
out.push(para_block(first));
|
||||
continue;
|
||||
@@ -218,6 +232,13 @@ impl Reader<'_> {
|
||||
}
|
||||
"w:sdt" => self.read_block_sdt(sc, e, rels, out, depth),
|
||||
"w:customXml" | "w:smartTag" | "w:ins" | "w:moveTo" => self.read_blocks(sc, e, rels, out, depth + 1),
|
||||
// Math is allowed straight in a story (EG_BlockLevelElts takes EG_RunLevelElements,
|
||||
// which takes EG_MathContent): it gets a paragraph of its own (#1273).
|
||||
"m:oMathPara" | "m:oMath" => {
|
||||
let wrapped = El { name: "w:p".into(), attrs: Vec::new(), kids: vec![Node::El(e.clone())] };
|
||||
let p = self.read_para(sc, &wrapped, rels, depth);
|
||||
out.push(para_block(p));
|
||||
}
|
||||
"mc:AlternateContent" => {
|
||||
if let Some(c) = children_of_choice(e) {
|
||||
self.read_blocks(sc, c, rels, out, depth + 1);
|
||||
@@ -241,6 +262,7 @@ impl Reader<'_> {
|
||||
let Some(content) = e.child("w:sdtContent") else { return };
|
||||
let mut ctl = super::sdt::sdt_pr(e.child("w:sdtPr"), true);
|
||||
ctl.end_pr_xml = super::sdt::sdt_end_pr(e.child("w:sdtEndPr"));
|
||||
ctl.run_props = e.child("w:sdtPr").and_then(|pr| pr.child("w:rPr")).map(|r| self.pc.rpr(r));
|
||||
let mut inner = Blocks::new();
|
||||
self.read_blocks(sc, content, rels, &mut inner, depth + 1);
|
||||
// A table of contents' control belongs to the TOC: the writer puts it back around the
|
||||
@@ -295,17 +317,25 @@ impl Reader<'_> {
|
||||
}
|
||||
|
||||
fn marker(&mut self, e: &El) -> Option<InlineObject> {
|
||||
let id = e.attr("w:id").unwrap_or("").to_string();
|
||||
let id = e.attr("w:id").map(str::trim).unwrap_or("").to_string();
|
||||
match e.name.as_str() {
|
||||
"w:bookmarkStart" => {
|
||||
let name = e.attr("w:name").unwrap_or("").to_string();
|
||||
if self.bookmarks.len() >= 100_000 {
|
||||
return None;
|
||||
}
|
||||
let name = e.attr("w:name").map(str::trim).unwrap_or("").to_string();
|
||||
if name.is_empty() || name.len() > 256 {
|
||||
return None;
|
||||
}
|
||||
self.bookmarks.insert(id, name.clone());
|
||||
Some(InlineObject::BookmarkStart { name })
|
||||
}
|
||||
"w:bookmarkEnd" => self.bookmarks.get(&id).map(|n| InlineObject::BookmarkEnd { name: n.clone() }),
|
||||
"w:bookmarkEnd" => self
|
||||
.bookmarks
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.or_else(|| e.attr("w:name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 256).map(str::to_string))
|
||||
.map(|name| InlineObject::BookmarkEnd { name }),
|
||||
"w:commentRangeStart" => self.comment_id(&id).map(|id| InlineObject::CommentStart { id }),
|
||||
"w:permStart" => {
|
||||
// Bounded: a hostile file can't grow the map without end.
|
||||
@@ -494,6 +524,7 @@ impl Reader<'_> {
|
||||
let Some(c) = k.child("w:sdtContent") else { return };
|
||||
let mut ctl = super::sdt::sdt_pr(k.child("w:sdtPr"), false);
|
||||
ctl.end_pr_xml = super::sdt::sdt_end_pr(k.child("w:sdtEndPr"));
|
||||
ctl.run_props = k.child("w:sdtPr").and_then(|pr| pr.child("w:rPr")).map(|r| self.pc.rpr(r));
|
||||
// The markers take the formatting of the content's first run (typing at the
|
||||
// start of the content continues it).
|
||||
let props = c.find("w:rPr").map(|p| self.run_props(p, ctx)).unwrap_or_else(|| self.run_props_none(ctx));
|
||||
@@ -618,7 +649,15 @@ impl Reader<'_> {
|
||||
f.instr.push_str(&k.text());
|
||||
}
|
||||
}
|
||||
"w:tab" | "w:ptab" => self.emit_text(sc, pb, "\t", props),
|
||||
"w:tab" => self.emit_text(sc, pb, "\t", props),
|
||||
// Alignment and base are required (ECMA-376 §17.3.3.23); without them it stays a plain tab.
|
||||
"w:ptab" => match (k.attr("w:alignment").and_then(PTabAlign::from_ooxml), k.attr("w:relativeTo").and_then(PTabBase::from_ooxml)) {
|
||||
(Some(align), Some(relative_to)) => {
|
||||
let leader = super::props::tab_leader(k.attr("w:leader").unwrap_or("none"));
|
||||
self.emit_obj(sc, pb, InlineObject::PositionalTab { align, relative_to, leader }, props)
|
||||
}
|
||||
_ => self.emit_text(sc, pb, "\t", props),
|
||||
},
|
||||
"w:br" => {
|
||||
if sc.fields.iter().any(|f| f.phase == Phase::Instr) {
|
||||
return;
|
||||
@@ -641,8 +680,9 @@ impl Reader<'_> {
|
||||
let ch = k.attr("w:char").and_then(|h| u32::from_str_radix(h.trim(), 16).ok()).and_then(char::from_u32).filter(|c| *c as u32 >= 0x20);
|
||||
if let Some(ch) = ch {
|
||||
let mut p = props.clone();
|
||||
if let Some(f) = k.attr("w:font").filter(|f| !f.is_empty()) {
|
||||
p.font = Some(f.to_string());
|
||||
// The symbol's own font, kept apart from the run's (ECMA-376 §17.3.3.30).
|
||||
if let Some(f) = k.attr("w:font").filter(|f| !f.trim().is_empty()) {
|
||||
p.sym_font = Some(f.to_string());
|
||||
}
|
||||
self.emit_text(sc, pb, &ch.to_string(), &p);
|
||||
}
|
||||
@@ -662,7 +702,7 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
"w:pict" => {
|
||||
if let Some(o) = self.read_vml(sc, k, rels) {
|
||||
for o in self.read_vml_all(sc, k, rels) {
|
||||
self.emit_obj(sc, pb, o, props);
|
||||
}
|
||||
}
|
||||
@@ -879,6 +919,17 @@ impl Reader<'_> {
|
||||
Some(e) => (e.instr(), if result.is_empty() { e.text } else { result }),
|
||||
None => (f.instr.trim().to_string(), result),
|
||||
};
|
||||
// The visible result owns the field's formatting; empty results keep the begin's.
|
||||
let props = f
|
||||
.buf
|
||||
.iter()
|
||||
.find_map(|(it, p)| match it {
|
||||
Item::Text(t) if !t.is_empty() => Some(p),
|
||||
Item::Obj(o) if !o.plain_text().is_empty() => Some(p),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(&f.props)
|
||||
.clone();
|
||||
let obj = InlineObject::Field { instr, result, locked: f.locked, dirty: f.dirty, code: false, form: f.form };
|
||||
if let Some(parent) = sc.fields.last_mut()
|
||||
&& !parent.spilled
|
||||
@@ -887,7 +938,7 @@ impl Reader<'_> {
|
||||
parent.instr.push_str(obj.plain_text());
|
||||
return;
|
||||
}
|
||||
self.emit_obj(sc, pb, obj, &f.props);
|
||||
self.emit_obj(sc, pb, obj, &props);
|
||||
}
|
||||
|
||||
/// At a paragraph end, open fields can't keep buffering: emit them (empty result) and
|
||||
@@ -968,7 +1019,9 @@ impl Reader<'_> {
|
||||
float.set_spin(xfrm_spin(content.child("w14:xfrm")));
|
||||
let (px, py) = float.spin_pad(w, h);
|
||||
for (e, p) in float.effect.iter_mut().zip([px, py, px, py]) {
|
||||
*e = (*e - p).clamp(0.0, 1584.0);
|
||||
if *e != 0.0 {
|
||||
*e = (*e - p).clamp(0.0, 1584.0);
|
||||
}
|
||||
}
|
||||
// The renderer's existing missing-picture box marks ink without a usable preview.
|
||||
// InkML stays opaque: no approximation of its strokes or conversion to freeforms.
|
||||
@@ -1024,7 +1077,10 @@ impl Reader<'_> {
|
||||
if let Some(f) = obj.float_mut() {
|
||||
let (px, py) = f.spin_pad(w, h);
|
||||
for (e, p) in f.effect.iter_mut().zip([px, py, px, py]) {
|
||||
*e = (*e - p).clamp(0.0, 1584.0);
|
||||
// Zero adds no effects room when rotation contracts this axis.
|
||||
if *e != 0.0 {
|
||||
*e = (*e - p).clamp(0.0, 1584.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(obj)
|
||||
@@ -1081,6 +1137,29 @@ impl Reader<'_> {
|
||||
Some(InlineObject::Graphic { w, h, alt, float, graphic })
|
||||
}
|
||||
|
||||
/// A group or canvas member that is native ink (`content`, a `w14:contentPart`, inside
|
||||
/// `alternate` when it has a picture fallback): what to write back (the whole alternate when
|
||||
/// it can be kept, else the ink alone) and its fallback picture (a `Document::media` key).
|
||||
/// `None` when the ink's part is missing or isn't InkML.
|
||||
fn ink_member(&mut self, content: &El, alternate: Option<&El>, rels: &Rels) -> Option<(Arc<Embedded>, Option<String>)> {
|
||||
let InlineObject::Graphic { graphic, .. } = self.read_ink_content_part(content, rels)? else { return None };
|
||||
let mut source = graphic.source.clone()?;
|
||||
let mut preview = None;
|
||||
let choice = alternate.and_then(children_of_choice).filter(|c| c.name == "mc:Choice");
|
||||
if let (Some(choice), Some(fallback)) = (choice, alternate.and_then(|a| a.child("mc:Fallback"))) {
|
||||
let kept = El { name: "mc:AlternateContent".into(), attrs: Vec::new(), kids: vec![Node::El(choice.clone()), Node::El(fallback.clone())] };
|
||||
// A malformed or over-budget fallback must not discard a valid native part.
|
||||
if let Some(whole) = self.keep_embedded(&kept, rels, &[]) {
|
||||
source = whole;
|
||||
preview = match fallback.child("pic:pic").and_then(|p| self.read_pic(p, rels, 0.0, 0.0, String::new(), Float::default())) {
|
||||
Some(InlineObject::Image { media, .. }) => Some(media),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
Some((source, preview))
|
||||
}
|
||||
|
||||
fn read_ink_content_part(&mut self, content: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let part = super::part_of(rels, content.attr("r:id")?, INK_REL)?;
|
||||
let pkg = self.pkg;
|
||||
@@ -1212,16 +1291,32 @@ impl Reader<'_> {
|
||||
if out.len() >= wordcraft_doc::para::MAX_GROUP_CHILDREN {
|
||||
return;
|
||||
}
|
||||
let e = match e.name.as_str() {
|
||||
"mc:AlternateContent" => match children_of_choice(e).and_then(|c| c.els().next()) {
|
||||
Some(c) => c,
|
||||
None => continue,
|
||||
},
|
||||
_ => e,
|
||||
// Native ink (`w14:contentPart`), alone or with a picture fallback: kept whole, in its
|
||||
// place among the members. Ink that can't be kept gives way to its fallback.
|
||||
let (e, ink) = match e.name.as_str() {
|
||||
"w14:contentPart" => (e, self.ink_member(e, None, rels)),
|
||||
"mc:AlternateContent" => {
|
||||
let choice = children_of_choice(e);
|
||||
match choice.filter(|c| c.name == "mc:Choice").and_then(|c| c.els().next()).filter(|c| c.name == "w14:contentPart") {
|
||||
Some(content) => match self.ink_member(content, Some(e), rels) {
|
||||
Some(ink) => (content, Some(ink)),
|
||||
None => match e.child("mc:Fallback").and_then(|f| f.els().next()) {
|
||||
Some(c) => (c, None),
|
||||
None => continue,
|
||||
},
|
||||
},
|
||||
None => match choice.and_then(|c| c.els().next()) {
|
||||
Some(c) => (c, None),
|
||||
None => continue,
|
||||
},
|
||||
}
|
||||
}
|
||||
_ => (e, None),
|
||||
};
|
||||
let sppr = match e.name.as_str() {
|
||||
"wps:wsp" => e.child("wps:spPr"),
|
||||
"pic:pic" => e.child("pic:spPr"),
|
||||
"w14:contentPart" if ink.is_some() => Some(e),
|
||||
// A group inside a canvas is a whole `wpg:wgp`.
|
||||
"wpg:grpSp" | "wpg:wgp" => e.child("wpg:grpSpPr"),
|
||||
_ => continue,
|
||||
@@ -1243,10 +1338,21 @@ impl Reader<'_> {
|
||||
let max = crate::units::MAX_LEN_PT;
|
||||
let fit = |v: f32, lo: f32| wordcraft_geom::finite(v).clamp(lo, max);
|
||||
let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0));
|
||||
let nv = if e.name == "pic:pic" { e.find("pic:cNvPr") } else { e.child("wps:cNvPr") };
|
||||
let nv = match e.name.as_str() {
|
||||
"pic:pic" => e.find("pic:cNvPr"),
|
||||
"w14:contentPart" => e.child("w14:nvContentPartPr").and_then(|p| p.child("w14:cNvPr")),
|
||||
_ => e.child("wps:cNvPr"),
|
||||
};
|
||||
let (alt, meta) = nv_alt(nv);
|
||||
let float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() };
|
||||
let obj = if e.name == "pic:pic" {
|
||||
let obj = if let Some((source, preview)) = ink {
|
||||
let mut float = float;
|
||||
float.set_spin(xfrm_spin(e.child("w14:xfrm")));
|
||||
// As drawing-level ink: its fallback picture, else the missing-picture box.
|
||||
let items = vec![GraphicItem::Image { rect: [0.0, 0.0, w, h], media: preview.unwrap_or_default() }];
|
||||
let graphic = Arc::new(Graphic { kind: GraphicKind::Ink, items, w, h, source: Some(source), ..Default::default() });
|
||||
Some(InlineObject::Graphic { w, h, alt: alt.clone(), float, graphic })
|
||||
} else if e.name == "pic:pic" {
|
||||
self.read_pic(e, rels, w, h, alt.clone(), float)
|
||||
} else {
|
||||
let mut o = self.read_wsp(sc, e, rels, w, h, float);
|
||||
@@ -1327,7 +1433,15 @@ impl Reader<'_> {
|
||||
part.body.inset = (inset != wordcraft_doc::TEXT_BOX_INSET).then_some(inset);
|
||||
part.body.auto_fit = bp.child("a:spAutoFit").is_some();
|
||||
}
|
||||
let mut extra = ShapeExtra::default();
|
||||
// The shape style's text colour (`a:fontRef`, often `lt1`: white on the accent fill).
|
||||
if let Some(id) = story
|
||||
&& let Some(c) = wsp.child("wps:style").and_then(|s| s.child("a:fontRef"))
|
||||
&& let Some(rgb) = super::drawing_color::color(c, &self.doc.settings.theme_colors)
|
||||
&& let Some(part) = self.doc.parts.get_mut(&id)
|
||||
{
|
||||
part.body.auto_color = Some(rgb);
|
||||
}
|
||||
let mut extra = ShapeExtra { dash: super::shape_style::line_dash(ln), ..Default::default() };
|
||||
// A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56); other presets drawn as
|
||||
// rounded rectangles keep the default.
|
||||
if prst == "roundRect" {
|
||||
@@ -1380,20 +1494,125 @@ impl Reader<'_> {
|
||||
self.doc.add_part(PartKind::TextBox, blocks)
|
||||
}
|
||||
|
||||
/// Legacy VML pictures, text boxes, lines, rectangles, ovals and preset shapes (best effort).
|
||||
/// Every legacy VML drawing in one `w:pict`, in document order: a `w:pict` may hold any
|
||||
/// number of shapes (ECMA-376 Part 4, VML), and each one is its own object. A `v:group`
|
||||
/// becomes an [`InlineObject::Group`].
|
||||
fn read_vml_all(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Vec<InlineObject> {
|
||||
let mut out = Vec::new();
|
||||
for e in pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype") {
|
||||
if out.len() >= wordcraft_doc::para::MAX_GROUP_CHILDREN {
|
||||
break;
|
||||
}
|
||||
if sc.in_hf
|
||||
&& let Some(wm) = vml_watermark(e)
|
||||
{
|
||||
// The document's watermark (the first one found); drawn on every page, not as
|
||||
// a shape, so it is not one of the objects this picture contributes.
|
||||
self.doc.settings.watermark.get_or_insert(wm);
|
||||
continue;
|
||||
}
|
||||
let o = if e.local() == "group" { self.read_vml_group(sc, pict, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) };
|
||||
out.extend(o);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The first VML drawing in `pict`, for the places that show a single one: an OLE object's
|
||||
/// picture and a `mc:Fallback` preview.
|
||||
fn read_vml(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let shape = pict.els().find(|e| e.name.starts_with("v:") && e.local() != "shapetype")?;
|
||||
if sc.in_hf
|
||||
&& let Some(wm) = vml_watermark(shape)
|
||||
{
|
||||
// The document's watermark (the first one found); drawn on every page, not as a shape.
|
||||
self.doc.settings.watermark.get_or_insert(wm);
|
||||
self.read_vml_all(sc, pict, rels).into_iter().next()
|
||||
}
|
||||
|
||||
/// A `v:group`: its own box from its `style`, its members in the space `coordsize` and
|
||||
/// `coordorigin` give it, nested groups flattened into it as [`Self::group_members`] does for
|
||||
/// DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits
|
||||
/// in, where a member's `v:shapetype` is written.
|
||||
fn read_vml_group(&mut self, sc: &mut StoryCtx, pict: &El, grp: &El, rels: &Rels) -> Option<InlineObject> {
|
||||
let style = grp.attr("style").unwrap_or("");
|
||||
let len = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
|
||||
let (w, h) = (len("width"), len("height"));
|
||||
let float = vml_float(grp, style, sc.in_hf);
|
||||
// The members' space; without a usable `coordsize` it is the group's own box.
|
||||
let (ch_w, ch_h) = vml_coordpair(grp, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((w.max(1.0), h.max(1.0)));
|
||||
let (cx, cy) = vml_coordpair(grp, "coordorigin").unwrap_or((0.0, 0.0));
|
||||
let mut children = Vec::new();
|
||||
self.vml_group_members(sc, pict, grp, rels, (-cx, -cy, 1.0, 1.0), 0, &mut children);
|
||||
if children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(InlineObject::Group { w, h, float, ch_w, ch_h, children, canvas: None })
|
||||
}
|
||||
|
||||
/// The members of VML group `g` into `out`, mapped into the outermost group's space by `t`
|
||||
/// (x0, y0, sx, sy: outer = x0 + inner × sx). A member is placed by `left`/`top` in that
|
||||
/// space, except a `v:line`, which carries its own offset in `from`.
|
||||
fn vml_group_members(
|
||||
&mut self,
|
||||
sc: &mut StoryCtx,
|
||||
pict: &El,
|
||||
g: &El,
|
||||
rels: &Rels,
|
||||
t: (f32, f32, f32, f32),
|
||||
depth: usize,
|
||||
out: &mut Vec<wordcraft_doc::para::GroupChild>,
|
||||
) {
|
||||
let (x0, y0, sx, sy) = t;
|
||||
let max = crate::units::MAX_LEN_PT;
|
||||
let fit = |v: f32, lo: f32| wordcraft_geom::finite(v).clamp(lo, max);
|
||||
for e in g.els() {
|
||||
if out.len() >= wordcraft_doc::para::MAX_GROUP_CHILDREN {
|
||||
return;
|
||||
}
|
||||
if !e.name.starts_with("v:") || e.local() == "shapetype" {
|
||||
continue;
|
||||
}
|
||||
let style = e.attr("style").unwrap_or("");
|
||||
let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, wordcraft_geom::finite);
|
||||
let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height")));
|
||||
if e.local() == "group" {
|
||||
if depth >= MAX_VML_GROUP_DEPTH {
|
||||
continue;
|
||||
}
|
||||
// Its members' space maps onto its own box.
|
||||
let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0)));
|
||||
let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0));
|
||||
let (kx, ky) = (ew / cw, eh / ch);
|
||||
let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky);
|
||||
self.vml_group_members(sc, pict, e, rels, nt, depth + 1, out);
|
||||
continue;
|
||||
}
|
||||
let Some(mut obj) = self.read_vml_shape(sc, pict, e, rels, Some((sx, sy))) else { continue };
|
||||
// A member is placed by `x`/`y`, so a line's own offset comes off the member itself.
|
||||
let (dx, dy) = match obj.float_mut() {
|
||||
Some(f) => {
|
||||
let d = (f.x, f.y);
|
||||
(f.x, f.y) = (0.0, 0.0);
|
||||
d
|
||||
}
|
||||
None => (0.0, 0.0),
|
||||
};
|
||||
out.push(wordcraft_doc::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj });
|
||||
}
|
||||
}
|
||||
|
||||
/// One legacy VML picture, text box, line, rectangle, oval or preset shape (best effort).
|
||||
/// `pict` is the picture it sits in, where its `v:shapetype` is written -- for a group's
|
||||
/// member too, since Word writes each shapetype once, beside the group rather than inside
|
||||
/// it. `grp` scales a member from its group's space, and leaves placing it to the caller.
|
||||
fn read_vml_shape(&mut self, sc: &mut StoryCtx, pict: &El, shape: &El, rels: &Rels, grp: Option<(f32, f32)>) -> Option<InlineObject> {
|
||||
let style = shape.attr("style").unwrap_or("");
|
||||
let len = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
|
||||
let (mut w, mut h) = (len("width"), len("height"));
|
||||
let mut float = vml_float(shape, style);
|
||||
let (sx, sy) = grp.unwrap_or((1.0, 1.0));
|
||||
let (mut w, mut h) = ((len("width") * sx).min(crate::units::MAX_LEN_PT), (len("height") * sy).min(crate::units::MAX_LEN_PT));
|
||||
// A member of a group never floats: the group does, and places it.
|
||||
let mut float = match grp {
|
||||
Some(_) => {
|
||||
let mut f = Float { hidden: vml_style(style, "visibility").is_some_and(|v| v.eq_ignore_ascii_case("hidden")), ..Float::default() };
|
||||
f.set_spin(vml_spin(style));
|
||||
f
|
||||
}
|
||||
None => vml_float(shape, style, sc.in_hf),
|
||||
};
|
||||
if let Some(img) = shape.find("v:imagedata") {
|
||||
let id = img.attr("r:id").or_else(|| img.attr("r:pict"))?;
|
||||
let media = self.media_for(rels, id)?;
|
||||
@@ -1420,6 +1639,52 @@ impl Reader<'_> {
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// Word 2007 WordArt: a `v:shape` whose `v:textpath` draws its `string` (the header watermark
|
||||
// is taken before this). Shown as a text box holding that text, in the textpath's font and the
|
||||
// shape's `fillcolor`; the box itself has neither fill nor outline, as the letters are the art.
|
||||
if shape.local() == "shape"
|
||||
&& let Some(tp) = shape.child("v:textpath")
|
||||
&& !tp.attr("on").is_some_and(|v| matches!(v, "f" | "false" | "0"))
|
||||
&& let Some(text) = tp.attr("string").map(|t| t.chars().take(200).collect::<String>()).filter(|t| !t.trim().is_empty())
|
||||
&& sc.story_depth < MAX_STORY_DEPTH
|
||||
{
|
||||
let font = tp
|
||||
.attr("style")
|
||||
.and_then(|s| vml_style(s, "font-family"))
|
||||
.map(|f| f.trim_matches(|c: char| c == '"' || c == '\'' || c.is_whitespace()).chars().take(100).collect::<String>())
|
||||
.filter(|f| !f.is_empty());
|
||||
// The shapetype's WordArt shape (`o:spt` 136-175) bends the text like DrawingML's warp.
|
||||
let warp = vml_spt(shape, shapetype, type_id)
|
||||
.and_then(|spt| spt.checked_sub(136))
|
||||
.and_then(|i| VML_TEXT_WARPS.get(i as usize))
|
||||
.copied()
|
||||
.and_then(TextWarp::new);
|
||||
// The letters fill the box (`fitshape`): sized to its height.
|
||||
let props = CharProps {
|
||||
font,
|
||||
size: Some((h * 0.75).clamp(8.0, 200.0)),
|
||||
color: attr("fillcolor").and_then(vml_color).map(TextColor::Rgb),
|
||||
..CharProps::default()
|
||||
};
|
||||
let id = self.doc.add_part(PartKind::TextBox, vec![para_block(Paragraph::with_text(&text, props))]);
|
||||
if let Some(part) = self.doc.parts.get_mut(&id) {
|
||||
part.body.anchor = wordcraft_doc::props::VAlign::Center;
|
||||
part.body.inset = Some([0; 4]);
|
||||
}
|
||||
return Some(InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w,
|
||||
h,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width,
|
||||
float,
|
||||
story: Some(id),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: ShapeExtra { warp, ..ShapeExtra::default() },
|
||||
});
|
||||
}
|
||||
if let Some((tb, t)) = vml_textbox(shape, 0)
|
||||
&& sc.story_depth < MAX_STORY_DEPTH
|
||||
{
|
||||
@@ -1513,7 +1778,7 @@ impl Reader<'_> {
|
||||
};
|
||||
let ((x0, y0), (x1, y1)) = (pt("from"), pt("to"));
|
||||
let max = crate::units::MAX_LEN_PT;
|
||||
(w, h) = ((x1 - x0).abs().min(max), (y1 - y0).abs().min(max));
|
||||
(w, h) = (((x1 - x0).abs() * sx).min(max), ((y1 - y0).abs() * sy).min(max));
|
||||
float.x = (float.x + x0.min(x1)).clamp(-max, max);
|
||||
float.y = (float.y + y0.min(y1)).clamp(-max, max);
|
||||
// Drawn top-left to bottom-right; flipped for the other directions.
|
||||
@@ -1732,6 +1997,8 @@ fn anchor_float(c: &El) -> Float {
|
||||
f.dist = dist("distL").max(dist("distR"));
|
||||
f.dist_top = dist("distT");
|
||||
f.dist_bottom = dist("distB");
|
||||
// Required by the schema; a file leaving it out lays out in the cell, as before.
|
||||
f.outside_cell = !on_off_attr(c, "layoutInCell") && c.attr("layoutInCell").is_some();
|
||||
f
|
||||
}
|
||||
|
||||
@@ -1759,6 +2026,51 @@ fn wrap_polygon(e: &El) -> Option<wordcraft_doc::wrap::WrapPolygon> {
|
||||
wordcraft_doc::wrap::WrapPolygon::new(edited, pts)
|
||||
}
|
||||
|
||||
/// The DrawingML text warps of VML's WordArt shapes, `o:spt` 136 (plain text) to 175 (can down), in
|
||||
/// order: the same shapes under their DrawingML names (`ST_TextShapeType`).
|
||||
const VML_TEXT_WARPS: [&str; 40] = [
|
||||
"textPlain",
|
||||
"textStop",
|
||||
"textTriangle",
|
||||
"textTriangleInverted",
|
||||
"textChevron",
|
||||
"textChevronInverted",
|
||||
"textRingInside",
|
||||
"textRingOutside",
|
||||
"textArchUp",
|
||||
"textArchDown",
|
||||
"textCircle",
|
||||
"textButton",
|
||||
"textArchUpPour",
|
||||
"textArchDownPour",
|
||||
"textCirclePour",
|
||||
"textButtonPour",
|
||||
"textCurveUp",
|
||||
"textCurveDown",
|
||||
"textCascadeUp",
|
||||
"textCascadeDown",
|
||||
"textWave1",
|
||||
"textWave2",
|
||||
"textDoubleWave1",
|
||||
"textWave4",
|
||||
"textInflate",
|
||||
"textDeflate",
|
||||
"textInflateBottom",
|
||||
"textDeflateBottom",
|
||||
"textInflateTop",
|
||||
"textDeflateTop",
|
||||
"textDeflateInflate",
|
||||
"textDeflateInflateDeflate",
|
||||
"textFadeRight",
|
||||
"textFadeLeft",
|
||||
"textFadeUp",
|
||||
"textFadeDown",
|
||||
"textSlantUp",
|
||||
"textSlantDown",
|
||||
"textCanUp",
|
||||
"textCanDown",
|
||||
];
|
||||
|
||||
/// A VML shape's preset type (`o:spt`): its own, its shapetype's, or the number in Word's
|
||||
/// shapetype id `_x0000_tNN` (`type_id`), Word writing each shapetype only at its first use.
|
||||
fn vml_spt(shape: &El, shapetype: Option<&El>, type_id: Option<&str>) -> Option<u32> {
|
||||
@@ -1773,6 +2085,15 @@ fn vml_spt(shape: &El, shapetype: Option<&El>, type_id: Option<&str>) -> Option<
|
||||
/// The value of property `key` in a VML `style` attribute (CSS declarations; the last one wins).
|
||||
/// The first `v:textbox` under `e` holding text, with its `w:txbxContent` (depth-first, bounded
|
||||
/// like `El::find`): in a group, a member's margins go with that member's text.
|
||||
/// A VML `coordsize="w,h"` or `coordorigin="x,y"` pair (ECMA-376 Part 4 §14.1.2): the member
|
||||
/// space of a group, in its own unitless coordinates.
|
||||
fn vml_coordpair(e: &El, name: &str) -> Option<(f32, f32)> {
|
||||
let v = e.attr(name)?;
|
||||
let (x, y) = v.split_once(',')?;
|
||||
let n = |s: &str| measure(s.trim(), 1.0).map(wordcraft_geom::finite);
|
||||
Some((n(x)?, n(y)?))
|
||||
}
|
||||
|
||||
fn vml_textbox(e: &El, depth: usize) -> Option<(&El, &El)> {
|
||||
if depth > crate::xml::MAX_DEPTH {
|
||||
return None;
|
||||
@@ -1793,7 +2114,7 @@ fn vml_style<'a>(style: &'a str, key: &str) -> Option<&'a str> {
|
||||
/// `mso-position-horizontal` / `mso-position-vertical`), wrapped as its `w10:wrap` says. Without
|
||||
/// wrapping (`none`, or no `w10:wrap`) it's in front of the text, or behind it at a negative
|
||||
/// `z-index`. Anything else stays inline.
|
||||
fn vml_float(shape: &El, style: &str) -> Float {
|
||||
fn vml_float(shape: &El, style: &str, in_hf: bool) -> Float {
|
||||
let get = |k: &str| vml_style(style, k);
|
||||
let hidden = get("visibility").is_some_and(|v| v.eq_ignore_ascii_case("hidden"));
|
||||
if !get("position").is_some_and(|p| p.eq_ignore_ascii_case("absolute")) {
|
||||
@@ -1846,6 +2167,9 @@ fn vml_float(shape: &El, style: &str) -> Float {
|
||||
dist_top: dist("mso-wrap-distance-top"),
|
||||
dist_bottom: dist("mso-wrap-distance-bottom"),
|
||||
hidden,
|
||||
// Word for Mac draws a VML shape anchored in a header table cell on the page whatever
|
||||
// `o:allowincell` says (user-checked), as for Word's picture and text watermarks.
|
||||
outside_cell: in_hf,
|
||||
..Float::default()
|
||||
};
|
||||
f.set_spin(vml_spin(style));
|
||||
@@ -2000,7 +2324,8 @@ fn xfrm_spin(sppr: Option<&El>) -> wordcraft_geom::Spin {
|
||||
|
||||
/// The `a:xfrm` in shape properties `sppr` (zeros when missing).
|
||||
fn group_xfrm(sppr: Option<&El>) -> Xfrm {
|
||||
let x = sppr.and_then(|s| s.child("a:xfrm"));
|
||||
// A content part (native ink) has its own `w14:xfrm`.
|
||||
let x = sppr.and_then(|s| s.child("a:xfrm").or_else(|| s.child("w14:xfrm")));
|
||||
let pair = |name: &str, a: &str, b: &str, lim: f32| {
|
||||
let e = x.and_then(|x| x.child(name))?;
|
||||
let v = |n: &str| e.attr(n).and_then(|v| measure(v, 12_700.0)).map(|v| v.clamp(-lim, lim)).unwrap_or(0.0);
|
||||
|
||||
@@ -34,6 +34,17 @@ pub fn measure(s: &str, per_pt: f32) -> Option<f32> {
|
||||
pt.is_finite().then_some(pt.clamp(-MAX_LEN_PT, MAX_LEN_PT))
|
||||
}
|
||||
|
||||
/// `w:line` under `lineRule="auto"`: the multiple of single line spacing, in 240ths (240 =
|
||||
/// single). Without a unit the value already is that — the transitional form. A universal
|
||||
/// measure is a height (strict OOXML writes `w:line="13.90pt"`, ISO 29500
|
||||
/// `ST_SignedTwipsMeasure`), so it goes through twips as Word reads it: × 20 ÷ 240 (13.90 pt =
|
||||
/// 278 twips, the 1.1583 multiple Word renders).
|
||||
pub fn line_multiple(s: &str) -> Option<f32> {
|
||||
let t = s.trim();
|
||||
let measured = t.ends_with(|c: char| c.is_ascii_alphabetic());
|
||||
measure(t, 240.0).map(|v| if measured { v * 20.0 / 240.0 } else { v })
|
||||
}
|
||||
|
||||
/// Plain integer (accepts decimals, rounds; clamps into i64 range).
|
||||
pub fn int(s: &str) -> Option<i64> {
|
||||
let t = s.trim();
|
||||
@@ -98,6 +109,16 @@ mod tests {
|
||||
assert_eq!(measure("1e400", 20.0), None);
|
||||
assert_eq!(measure("99999999999999", 20.0), Some(MAX_LEN_PT));
|
||||
assert_eq!(measure("x", 20.0), None);
|
||||
// `w:line` auto: the multiple in 240ths without a unit, through twips with one (#2329).
|
||||
assert_eq!(line_multiple("240"), Some(1.0));
|
||||
assert_eq!(line_multiple("276"), Some(1.15));
|
||||
assert_eq!(line_multiple("0"), Some(0.0));
|
||||
let strict = line_multiple("13.90pt").expect("strict line height");
|
||||
assert!((strict - 278.0 / 240.0).abs() < 1e-5, "{strict}");
|
||||
let inches = line_multiple("1.2in").expect("inches");
|
||||
assert!((inches - 7.2).abs() < 1e-5, "{inches}");
|
||||
assert_eq!(line_multiple("junk"), None);
|
||||
assert_eq!(line_multiple(""), None);
|
||||
assert_eq!(int("12.6"), Some(13));
|
||||
assert_eq!(u32_of("-5"), Some(0));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Run direction for mixed right-to-left and left-to-right text (#1543).
|
||||
//!
|
||||
//! WordCraft lays a paragraph out with the Unicode Bidirectional Algorithm (UAX #9) from its
|
||||
//! text and direction alone, so a run need not say its direction. Word orders a run's characters
|
||||
//! by the run's `w:rtl` (ECMA-376 Part 1 §17.3.2.30): text in a run without it is laid out left
|
||||
//! to right, so Hebrew words on either side of a Latin name, and the punctuation between them,
|
||||
//! change places. A run that doesn't say its direction is therefore split where the resolved
|
||||
//! level changes parity, and the right-to-left pieces are written `w:rtl`, as Word writes text
|
||||
//! typed in a right-to-left paragraph. Runs that say their direction, and paragraphs without
|
||||
//! right-to-left characters, are written as they are.
|
||||
//!
|
||||
//! Word gives right-to-left text without a bidi language (`w:lang w:bidi`, §17.3.2.20) its
|
||||
//! default complex-script language, Arabic, so Hebrew would proof and show as Arabic. The pieces
|
||||
//! marked `w:rtl` therefore also say their language, unless the run or its styles already do.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_doc::styles::StyleSheet;
|
||||
|
||||
/// The language Word expects for right-to-left text of `c`'s script, for the scripts that have
|
||||
/// one usual language.
|
||||
fn script_lang(c: char) -> Option<&'static str> {
|
||||
match u32::from(c) {
|
||||
0x0590..=0x05FF | 0xFB1D..=0xFB4F => Some("he-IL"),
|
||||
0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => Some("ar-SA"),
|
||||
0x0700..=0x074F => Some("syr-SY"),
|
||||
0x0780..=0x07BF => Some("dv-MV"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The language of the first right-to-left letter of `text` with a usual language.
|
||||
fn text_lang(text: &str) -> Option<&'static str> {
|
||||
text.chars().find_map(script_lang)
|
||||
}
|
||||
|
||||
/// A language tag of a right-to-left language (`he-IL`, `yi`, `fa-IR`, `ar-EG`…)?
|
||||
fn is_rtl_lang(tag: &str) -> bool {
|
||||
let primary = tag.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase();
|
||||
matches!(primary.as_str(), "he" | "iw" | "yi" | "ar" | "fa" | "ur" | "ps" | "sd" | "ug" | "ckb" | "syr" | "dv" | "ku")
|
||||
}
|
||||
|
||||
/// Does a paragraph of style `para_style` inherit a bidi language from the document defaults or
|
||||
/// its style chain? (Resolved once per paragraph.)
|
||||
pub(super) fn para_inherits_lang_bidi(styles: &StyleSheet, para_style: Option<&str>) -> bool {
|
||||
styles.para_style_props(para_style.unwrap_or("Normal")).1.lang_bidi.is_some()
|
||||
}
|
||||
|
||||
/// Does `c`'s character style chain give it a bidi language?
|
||||
pub(super) fn char_style_has_lang_bidi(styles: &StyleSheet, c: &CharProps) -> bool {
|
||||
c.style.as_deref().is_some_and(|s| styles.chain(s).iter().any(|st| st.chr.lang_bidi.is_some()))
|
||||
}
|
||||
|
||||
/// Add `rtl` and, when given, the bidi language `lang` to `c` where it doesn't say them.
|
||||
fn direct(c: &mut CharProps, lang: Option<&String>) {
|
||||
c.rtl.get_or_insert(true);
|
||||
if let Some(l) = lang
|
||||
&& c.lang_bidi.is_none()
|
||||
{
|
||||
c.lang_bidi = Some(l.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// `runs` (byte ranges of `text` with their props), split where the bidi level of `text` in a
|
||||
/// paragraph of direction `rtl_para` changes parity; right-to-left pieces get `rtl: Some(true)`
|
||||
/// and, unless they have one or `inherits_lang` says it comes from a style, a bidi language.
|
||||
pub(super) fn direction_spans<'a>(
|
||||
text: &str,
|
||||
rtl_para: bool,
|
||||
runs: impl Iterator<Item = (Range<usize>, &'a CharProps)>,
|
||||
inherits_lang: impl Fn(&CharProps) -> bool,
|
||||
) -> Vec<(Range<usize>, Cow<'a, CharProps>)> {
|
||||
if !wordcraft_doc::bidi::has_rtl(text) {
|
||||
return runs.map(|(r, p)| (r, Cow::Borrowed(p))).collect();
|
||||
}
|
||||
let level = if rtl_para { unicode_bidi::Level::rtl() } else { unicode_bidi::Level::ltr() };
|
||||
let info = unicode_bidi::ParagraphBidiInfo::new(text, Some(level));
|
||||
let odd = |at: usize| info.levels.get(at).is_some_and(|l| l.is_rtl());
|
||||
let para_lang = text_lang(text);
|
||||
let mut out = Vec::new();
|
||||
for (range, props) in runs {
|
||||
let Some(run) = text.get(range.clone()).filter(|_| props.rtl.is_none()) else {
|
||||
out.push((range, Cow::Borrowed(props)));
|
||||
continue;
|
||||
};
|
||||
let named = props.lang_bidi.is_some() || inherits_lang(props);
|
||||
let piece = |r: Range<usize>, rtl: bool| {
|
||||
if !rtl {
|
||||
return (r, Cow::Borrowed(props));
|
||||
}
|
||||
let lang = if named {
|
||||
None
|
||||
} else {
|
||||
let own = props.lang.clone().filter(|l| is_rtl_lang(l));
|
||||
own.or_else(|| text.get(r.clone()).and_then(text_lang).or(para_lang).map(str::to_string))
|
||||
};
|
||||
let mut p = props.clone();
|
||||
direct(&mut p, lang.as_ref());
|
||||
// A tracked formatting change's "before" copy gets the same, so the change lists
|
||||
// nothing the author didn't do.
|
||||
if let Some(ch) = p.fmt_change.as_mut() {
|
||||
direct(&mut ch.old, lang.as_ref());
|
||||
}
|
||||
(r, Cow::Owned(p))
|
||||
};
|
||||
let mut start = range.start;
|
||||
let mut cur: Option<bool> = None;
|
||||
for (i, _) in run.char_indices() {
|
||||
let at = range.start.saturating_add(i);
|
||||
let rtl = odd(at);
|
||||
match cur {
|
||||
Some(c) if c != rtl => {
|
||||
out.push(piece(start..at, c));
|
||||
start = at;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
cur = Some(rtl);
|
||||
}
|
||||
out.push(piece(start..range.end, cur.unwrap_or(false)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hostile_ranges_never_panic() {
|
||||
let p = CharProps::default();
|
||||
let text = "עברית WordCraft";
|
||||
let runs = vec![(0..3, &p), (3..1000, &p), (usize::MAX - 1..usize::MAX, &p), (2..text.len(), &p)];
|
||||
let out = direction_spans(text, true, runs.into_iter(), |_| false);
|
||||
assert_eq!(out.len(), 5, "bad ranges pass through unsplit: {out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn languages_by_script() {
|
||||
assert_eq!(text_lang("(שלום"), Some("he-IL"));
|
||||
assert_eq!(text_lang("سلام"), Some("ar-SA"));
|
||||
assert_eq!(text_lang("ܫܠܡܐ"), Some("syr-SY"));
|
||||
assert_eq!(text_lang(". ,"), None);
|
||||
assert!(is_rtl_lang("he-IL") && is_rtl_lang("yi") && is_rtl_lang("FA_ir") && !is_rtl_lang("en-US") && !is_rtl_lang(""));
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ pub(crate) struct EmbedWriter<'d> {
|
||||
markup_bytes: u64,
|
||||
/// Parts to write: (name, bytes, content type, relationships).
|
||||
pub parts: Vec<(String, Vec<u8>, String, PartRels)>,
|
||||
/// Leave out the main document's kept glossary (it's written from the model instead).
|
||||
pub drop_glossary: bool,
|
||||
}
|
||||
|
||||
impl<'d> EmbedWriter<'d> {
|
||||
@@ -90,6 +92,7 @@ impl<'d> EmbedWriter<'d> {
|
||||
copy_bytes: MAX_COPY_BYTES,
|
||||
markup_bytes: MAX_MARKUP_BYTES,
|
||||
parts: Vec::new(),
|
||||
drop_glossary: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +145,7 @@ impl<'d> EmbedWriter<'d> {
|
||||
}
|
||||
|
||||
/// A number `n` for which every `{stem}{n}{ext}` is a free part name, with those names taken.
|
||||
fn fresh_set(&mut self, stems: &[&str], ext: &str) -> Vec<String> {
|
||||
pub(super) fn fresh_set(&mut self, stems: &[&str], ext: &str) -> Vec<String> {
|
||||
let mut n: u32 = 1;
|
||||
loop {
|
||||
let names: Vec<String> = stems.iter().map(|s| format!("{s}{n}{ext}")).collect();
|
||||
@@ -205,7 +208,7 @@ impl<'d> EmbedWriter<'d> {
|
||||
for line in String::from_utf8_lossy(&roots).lines().take(MAX_EMBEDDED_RELS * 2) {
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let [source, kind, target] = fields.as_slice() else { continue };
|
||||
if *source != owner {
|
||||
if *source != owner || (self.drop_glossary && owner == "D" && rel_is(kind, rt::GLOSSARY)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = self.copy_tree(target, &mut memo, &mut written) {
|
||||
@@ -216,6 +219,15 @@ impl<'d> EmbedWriter<'d> {
|
||||
self.first = memo;
|
||||
}
|
||||
|
||||
/// Whether `unmodelled_rels("D", …)` can write the main document's kept glossary back.
|
||||
pub fn kept_glossary(&self) -> bool {
|
||||
let Some(roots) = self.passthrough.get(crate::package::UNMODELLED_ROOTS) else { return false };
|
||||
String::from_utf8_lossy(roots).lines().take(MAX_EMBEDDED_RELS * 2).any(|line| {
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
matches!(fields.as_slice(), [source, kind, target] if *source == "D" && rel_is(kind, rt::GLOSSARY) && (self.first.contains_key(*target) || self.available(target)))
|
||||
})
|
||||
}
|
||||
|
||||
/// What copying the parts reached from `roots` costs against the copy budget.
|
||||
fn tree_cost(&self, roots: &[&str]) -> u64 {
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
@@ -519,6 +531,38 @@ impl super::Writer<'_> {
|
||||
Self::ink_transform(c, from, to, float, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Put a group or canvas member kept from a file (native ink and its picture fallback) at
|
||||
/// `frame` ([x, y, w, h] in points, in the group's space, as the group is written): its
|
||||
/// `w14:xfrm` and the fallback's `a:xfrm` get that offset and extent and the member's turn.
|
||||
/// It rewrites every `w14:xfrm` and `a:xfrm` under `e` and doesn't descend into them: right
|
||||
/// for the forms Word writes (the content part's own transform and one `pic:pic` fallback's
|
||||
/// `pic:spPr/a:xfrm`); a fallback holding several transforms (a group) would get one frame.
|
||||
pub(super) fn place_member(e: &mut El, frame: [f32; 4], float: &Float, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
if matches!(e.name.as_str(), "w14:xfrm" | "a:xfrm") {
|
||||
e.attrs.retain(|(k, _)| !matches!(k.as_str(), "rot" | "flipH" | "flipV"));
|
||||
for (k, v) in super::story::spin_attrs(float.spin()) {
|
||||
e.attrs.push((k.to_string(), v));
|
||||
}
|
||||
let [x, y, w, h] = frame.map(|v| v.clamp(-MAX_LEN_PT, MAX_LEN_PT));
|
||||
e.kids.retain(|k| !matches!(k, xml::Node::El(c) if matches!(c.name.as_str(), "a:off" | "a:ext")));
|
||||
let el = |name: &str, attrs: [(&str, String); 2]| {
|
||||
xml::Node::El(El { name: name.to_string(), attrs: attrs.map(|(k, v)| (k.to_string(), v)).to_vec(), kids: Vec::new() })
|
||||
};
|
||||
e.kids.insert(0, el("a:ext", [("cx", emu(w.max(0.0))), ("cy", emu(h.max(0.0)))]));
|
||||
e.kids.insert(0, el("a:off", [("x", emu(x)), ("y", emu(y))]));
|
||||
return;
|
||||
}
|
||||
for c in e.kids.iter_mut().filter_map(|k| match k {
|
||||
xml::Node::El(c) => Some(c),
|
||||
_ => None,
|
||||
}) {
|
||||
Self::place_member(c, frame, float, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set an extent's `cx` and `cy` (those it has) to `w` × `h` points.
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Writing the glossary document (ECMA-376 Part 1 §17.12) from `Document::glossary`, once its
|
||||
//! entries differ from the file's (an untouched glossary is written back verbatim: see
|
||||
//! `read::glossary`).
|
||||
|
||||
use wordcraft_doc::{Document, QUICK_PARTS_GALLERY};
|
||||
|
||||
use super::{CT_WML, PartRels, Writer, numbering_xml, push_part, styles_xml};
|
||||
use crate::package::{GLOSSARY_BEHAVIORS, GLOSSARY_CONTENT_TYPE, GLOSSARY_READ, GLOSSARY_TYPES, glossary_fingerprint, rt};
|
||||
use crate::xml::{self, W};
|
||||
|
||||
/// `values` known to `known`, as `parent` with one `tag` child each (nothing when none are).
|
||||
fn listed(w: &mut W, parent: &str, tag: &str, values: &[String], known: &[&str]) {
|
||||
let mut values = values.iter().filter(|v| known.contains(&v.as_str())).peekable();
|
||||
if values.peek().is_none() {
|
||||
return;
|
||||
}
|
||||
w.open(parent, &[]);
|
||||
for v in values {
|
||||
w.empty(tag, &[("w:val", v)]);
|
||||
}
|
||||
w.close(parent);
|
||||
}
|
||||
|
||||
/// Whether the glossary differs from the one read from the file (none read: an empty one).
|
||||
pub(super) fn edited(doc: &Document) -> bool {
|
||||
let print = glossary_fingerprint(&doc.glossary);
|
||||
match doc.passthrough.get(GLOSSARY_READ) {
|
||||
Some(read) => read.as_slice() != print.as_bytes(),
|
||||
None => print != glossary_fingerprint(&[]),
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Write the glossary part from the model, with a styles part of its own (the document's
|
||||
/// styles), related from the main document's `rels`. Its parts live in `word/`, beside the
|
||||
/// main document, so the relationships its stories add resolve as theirs do.
|
||||
pub(super) fn glossary(&mut self, entries: &mut Vec<(String, Vec<u8>)>, overrides: &mut Vec<(String, String)>, rels: &mut PartRels) {
|
||||
let doc = self.doc;
|
||||
if doc.glossary.is_empty() {
|
||||
return;
|
||||
}
|
||||
let names = self.embeds.fresh_set(&["word/glossary", "word/glossaryStyles", "word/glossaryNumbering"], ".xml");
|
||||
let [part, styles, numbering] = names.as_slice() else { return };
|
||||
let ns = xml::body_ns();
|
||||
let ns_refs: Vec<(&str, &str)> = ns.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
let mut prels = PartRels::default();
|
||||
let mut w = W::new();
|
||||
w.open("w:glossaryDocument", &ns_refs);
|
||||
w.open("w:docParts", &[]);
|
||||
for e in &doc.glossary {
|
||||
w.open("w:docPart", &[]);
|
||||
w.open("w:docPartPr", &[]);
|
||||
w.empty("w:name", &[("w:val", &e.name)]);
|
||||
if !e.style.is_empty() {
|
||||
w.empty("w:style", &[("w:val", &e.style)]);
|
||||
}
|
||||
w.open("w:category", &[]);
|
||||
w.empty("w:name", &[("w:val", if e.category.is_empty() { "General" } else { &e.category })]);
|
||||
w.empty("w:gallery", &[("w:val", if e.gallery.is_empty() { QUICK_PARTS_GALLERY } else { &e.gallery })]);
|
||||
w.close("w:category");
|
||||
listed(&mut w, "w:types", "w:type", &e.types, &GLOSSARY_TYPES);
|
||||
listed(&mut w, "w:behaviors", "w:behavior", &e.behaviors, &GLOSSARY_BEHAVIORS);
|
||||
if !e.description.is_empty() {
|
||||
w.empty("w:description", &[("w:val", &e.description)]);
|
||||
}
|
||||
if !e.guid.is_empty() {
|
||||
w.empty("w:guid", &[("w:val", &e.guid)]);
|
||||
}
|
||||
w.close("w:docPartPr");
|
||||
w.open("w:docPartBody", &[]);
|
||||
if e.blocks.is_empty() {
|
||||
w.empty("w:p", &[]);
|
||||
} else {
|
||||
self.blocks(&mut w, &e.blocks, &mut prels, false, 0);
|
||||
}
|
||||
w.close("w:docPartBody");
|
||||
w.close("w:docPart");
|
||||
}
|
||||
w.close("w:docParts");
|
||||
w.close("w:glossaryDocument");
|
||||
let file = |p: &str| p.strip_prefix("word/").unwrap_or(p).to_string();
|
||||
prels.add(rt::STYLES, &file(styles), false);
|
||||
// Lists in entries need their definitions within the glossary's reach.
|
||||
let lists = !doc.numbering.nums.is_empty() || !doc.numbering.abstracts.is_empty();
|
||||
if lists {
|
||||
prels.add(rt::NUMBERING, &file(numbering), false);
|
||||
}
|
||||
rels.add(rt::GLOSSARY, &file(part), false);
|
||||
push_part(entries, overrides, part, w.into_bytes(), GLOSSARY_CONTENT_TYPE, prels);
|
||||
push_part(entries, overrides, styles, styles_xml(doc), &format!("{CT_WML}styles+xml"), PartRels::default());
|
||||
if lists {
|
||||
push_part(entries, overrides, numbering, numbering_xml(doc), &format!("{CT_WML}numbering+xml"), PartRels::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! [`Document`] → DOCX.
|
||||
|
||||
mod bidi;
|
||||
mod embed;
|
||||
mod glossary;
|
||||
mod settings_merge;
|
||||
pub(crate) use settings_merge::has_unowned as settings_has_unowned;
|
||||
mod math;
|
||||
@@ -263,6 +265,13 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
);
|
||||
}
|
||||
|
||||
// The glossary: kept verbatim while its entries are as read and its parts were kept, else
|
||||
// written from the model (before the notes: references its entries hold are collected too).
|
||||
if glossary::edited(doc) || (!doc.glossary.is_empty() && !wr.embeds.kept_glossary()) {
|
||||
wr.embeds.drop_glossary = true;
|
||||
wr.glossary(&mut entries, &mut overrides, &mut rels);
|
||||
}
|
||||
|
||||
// Notes (references were collected from the body and headers).
|
||||
for foot in [true, false] {
|
||||
let seps = if foot { &doc.footnote_separators } else { &doc.endnote_separators };
|
||||
@@ -997,6 +1006,9 @@ fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, template_rel: O
|
||||
if s.track_changes {
|
||||
w.empty("w:trackRevisions", &[]);
|
||||
}
|
||||
if !s.track_moves {
|
||||
w.empty("w:doNotTrackMoves", &[]);
|
||||
}
|
||||
if let Some(p) = &s.protection {
|
||||
let mut a: Vec<(&str, &str)> = Vec::new();
|
||||
if p != "none" {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Property writers, in ECMA-376 schema element order.
|
||||
|
||||
use wordcraft_doc::props::{
|
||||
Align, Border, BorderStyle, Borders, CellProps, CharProps, HeightRule, Highlight, LineSpacing, ParaProps, RowProps, TabAlign, TabLeader,
|
||||
TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign,
|
||||
Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, LineSpacing, ParaProps, RowProps, TabAlign,
|
||||
TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign,
|
||||
};
|
||||
|
||||
use crate::units::{n, twips};
|
||||
@@ -81,11 +81,12 @@ pub fn rpr_inner(w: &mut W, c: &CharProps) {
|
||||
if let Some(h) = c.highlight {
|
||||
w.val("w:highlight", if h == Highlight::None { "none" } else { h.ooxml() });
|
||||
}
|
||||
if let Some(u) = c.underline {
|
||||
match c.underline_color {
|
||||
Some(col) => w.empty("w:u", &[("w:val", u.ooxml()), ("w:color", &col.hex())]),
|
||||
None => w.val("w:u", u.ooxml()),
|
||||
}
|
||||
match (c.underline, c.underline_color) {
|
||||
(Some(u), Some(col)) => w.empty("w:u", &[("w:val", u.ooxml()), ("w:color", &col.hex())]),
|
||||
(Some(u), None) => w.val("w:u", u.ooxml()),
|
||||
// A colour-only w:u, as read: keep it without inventing an underline
|
||||
(None, Some(col)) => w.empty("w:u", &[("w:color", &col.hex())]),
|
||||
(None, None) => {}
|
||||
}
|
||||
if let Some(b) = &c.border {
|
||||
border_el(w, "w:bdr", b);
|
||||
@@ -111,9 +112,39 @@ pub fn rpr_inner(w: &mut W, c: &CharProps) {
|
||||
(None, Some(b)) => w.empty("w:lang", &[("w:bidi", b)]),
|
||||
(None, None) => {}
|
||||
}
|
||||
// After w:lang (CT_RPr's sequence).
|
||||
if let Some(l) = &c.east_asian_layout {
|
||||
east_asian_layout(w, l);
|
||||
}
|
||||
if let Some(fx) = &c.text_effects {
|
||||
super::wordart::rpr_effects(w, fx);
|
||||
}
|
||||
if let Some(l) = c.ligatures {
|
||||
w.empty("w14:ligatures", &[("w14:val", &l.ooxml())]);
|
||||
}
|
||||
}
|
||||
|
||||
/// `w:eastAsianLayout` with the attributes that are set (ISO/IEC 29500-1 §17.3.2.10).
|
||||
fn east_asian_layout(w: &mut W, l: &EastAsianLayout) {
|
||||
let on = |v: bool| if v { "1" } else { "0" };
|
||||
let id = l.id.map(|v| v.to_string());
|
||||
let mut a: Vec<(&str, &str)> = Vec::new();
|
||||
if let Some(id) = &id {
|
||||
a.push(("w:id", id));
|
||||
}
|
||||
if let Some(v) = l.combine {
|
||||
a.push(("w:combine", on(v)));
|
||||
}
|
||||
if let Some(b) = l.combine_brackets {
|
||||
a.push(("w:combineBrackets", b.ooxml()));
|
||||
}
|
||||
if let Some(v) = l.vert {
|
||||
a.push(("w:vert", on(v)));
|
||||
}
|
||||
if let Some(v) = l.vert_compress {
|
||||
a.push(("w:vertCompress", on(v)));
|
||||
}
|
||||
w.empty("w:eastAsianLayout", &a);
|
||||
}
|
||||
|
||||
/// Does `c` produce any `w:rPr` content (besides a tracked change)?
|
||||
@@ -157,6 +188,17 @@ pub fn align_val(a: Align) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// A tab stop's or positional tab's `w:leader` value.
|
||||
pub fn tab_leader(l: TabLeader) -> &'static str {
|
||||
match l {
|
||||
TabLeader::None => "none",
|
||||
TabLeader::Dot => "dot",
|
||||
TabLeader::Hyphen => "hyphen",
|
||||
TabLeader::Underscore => "underscore",
|
||||
TabLeader::MiddleDot => "middleDot",
|
||||
}
|
||||
}
|
||||
|
||||
fn border_el(w: &mut W, name: &str, b: &Border) {
|
||||
let sz = n(round(b.width.clamp(0.0, 12.0) * 8.0));
|
||||
let space = n(round(b.space.clamp(0.0, 31.0)));
|
||||
@@ -205,10 +247,17 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha
|
||||
toggle(w, "w:keepLines", p.keep_lines);
|
||||
toggle(w, "w:pageBreakBefore", p.page_break_before);
|
||||
if framed && let Some(lines) = p.drop_cap.filter(|l| *l > 0) {
|
||||
w.empty(
|
||||
"w:framePr",
|
||||
&[("w:dropCap", "drop"), ("w:lines", &n(lines.min(10) as i64)), ("w:wrap", "around"), ("w:vAnchor", "text"), ("w:hAnchor", "text")],
|
||||
);
|
||||
// ECMA-376 §17.3.1.11: the drop cap's frame — dropped or in the margin, the lines it
|
||||
// spans and its distance from the text (`w:hSpace`, twips).
|
||||
let kind = if p.drop_cap_margin == Some(true) { "margin" } else { "drop" };
|
||||
let lines = n(lines.min(10) as i64);
|
||||
let space = p.drop_cap_distance.filter(|d| d.is_finite() && *d > 0.0).map(|d| twips(d.min(wordcraft_doc::resolve::MAX_DROP_CAP_DISTANCE)));
|
||||
let mut a: Vec<(&str, &str)> = vec![("w:dropCap", kind), ("w:lines", &lines)];
|
||||
if let Some(h) = &space {
|
||||
a.push(("w:hSpace", h));
|
||||
}
|
||||
a.extend([("w:wrap", "around"), ("w:vAnchor", "text"), ("w:hAnchor", "text")]);
|
||||
w.empty("w:framePr", &a);
|
||||
} else if let Some(f) = &p.frame {
|
||||
let (fw, fh, fx, fy) = (f.w.map(twips), f.h.map(twips), twips(f.x), twips(f.y));
|
||||
let (hs, vs) = (twips(f.h_space), twips(f.v_space));
|
||||
@@ -273,15 +322,7 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha
|
||||
let pos = twips(t.pos);
|
||||
match t.leader {
|
||||
TabLeader::None => w.empty("w:tab", &[("w:val", val), ("w:pos", &pos)]),
|
||||
l => {
|
||||
let lv = match l {
|
||||
TabLeader::Dot => "dot",
|
||||
TabLeader::Hyphen => "hyphen",
|
||||
TabLeader::Underscore => "underscore",
|
||||
_ => "middleDot",
|
||||
};
|
||||
w.empty("w:tab", &[("w:val", val), ("w:leader", lv), ("w:pos", &pos)]);
|
||||
}
|
||||
l => w.empty("w:tab", &[("w:val", val), ("w:leader", tab_leader(l)), ("w:pos", &pos)]),
|
||||
}
|
||||
}
|
||||
w.close("w:tabs");
|
||||
@@ -367,9 +408,15 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha
|
||||
}
|
||||
|
||||
pub fn margins(w: &mut W, tag: &str, m: &[f32; 4]) {
|
||||
margin_sides(w, tag, &m.map(Some));
|
||||
}
|
||||
|
||||
fn margin_sides(w: &mut W, tag: &str, m: &[Option<f32>; 4]) {
|
||||
w.open(tag, &[]);
|
||||
for (name, v) in ["w:top", "w:left", "w:bottom", "w:right"].iter().zip(m.iter()) {
|
||||
w.empty(name, &[("w:w", &twips(v.clamp(0.0, 1584.0))), ("w:type", "dxa")]);
|
||||
for (name, value) in ["w:top", "w:left", "w:bottom", "w:right"].iter().zip(m.iter()) {
|
||||
if let Some(v) = value {
|
||||
w.empty(name, &[("w:w", &twips(v.clamp(0.0, 1584.0))), ("w:type", "dxa")]);
|
||||
}
|
||||
}
|
||||
w.close(tag);
|
||||
}
|
||||
@@ -573,6 +620,8 @@ fn tcpr_inner(w: &mut W, c: &CellProps) {
|
||||
}
|
||||
if let Some(m) = &c.margins {
|
||||
margins(w, "w:tcMar", m);
|
||||
} else if let Some(m) = &c.partial_margins {
|
||||
margin_sides(w, "w:tcMar", m);
|
||||
}
|
||||
if c.text_direction.is_turned() || c.text_direction_set {
|
||||
w.val("w:textDirection", c.text_direction.ooxml());
|
||||
|
||||
@@ -21,6 +21,7 @@ const OWNED: &[&str] = &[
|
||||
"w:attachedTemplate",
|
||||
"w:linkStyles",
|
||||
"w:trackRevisions",
|
||||
"w:doNotTrackMoves",
|
||||
"w:documentProtection",
|
||||
"w:defaultTabStop",
|
||||
"w:autoHyphenation",
|
||||
@@ -222,9 +223,15 @@ fn merge_compat(orig: &str, generated: &str) -> Option<String> {
|
||||
match (mode(orig), mode(generated)) {
|
||||
(Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)),
|
||||
(None, Some((c, d))) => {
|
||||
// No mode in the original: add the generated one before `</w:compat>`.
|
||||
let close = orig.rfind("</w:compat>")?;
|
||||
Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?))
|
||||
// No mode in the original: add the generated one before `</w:compat>`, or expand a self-closing `<w:compat/>`.
|
||||
if let Some(close) = orig.rfind("</w:compat>") {
|
||||
Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?))
|
||||
} else if let Some(slash) = orig.rfind("/>") {
|
||||
let open = orig.get(..slash)?.trim_end();
|
||||
Some(format!("{open}>{}</w:compat>", generated.get(c..d)?))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => Some(orig.to_string()),
|
||||
}
|
||||
@@ -344,4 +351,12 @@ mod tests {
|
||||
assert!(has_unowned(orig.as_bytes()));
|
||||
assert!(!has_unowned(GEN.as_bytes()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_self_closing_compat_block_gets_the_generated_mode() {
|
||||
let orig = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat/><w:rsids><w:rsidRoot w:val="00112233"/></w:rsids></w:settings>"#;
|
||||
let out = String::from_utf8(merge(orig.as_bytes(), GEN.as_bytes()).unwrap()).unwrap();
|
||||
assert!(out.contains("<w:compat><w:compatSetting") && out.contains("</w:compat>"), "{out}");
|
||||
assert!(out.contains("<w:rsidRoot w:val=\"00112233\"/>"), "{out}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ enum Piece<'a> {
|
||||
Br(Option<&'static str>),
|
||||
NbHyphen,
|
||||
SoftHyphen,
|
||||
/// A symbol character in its own font (`w:sym`, ECMA-376 §17.3.3.30).
|
||||
Sym(&'a str, char),
|
||||
/// An object and its byte offset in the paragraph.
|
||||
Obj(&'a InlineObject, usize),
|
||||
}
|
||||
@@ -137,6 +139,12 @@ impl Writer<'_> {
|
||||
let tail = head.split_off(first.len_utf8()).ok();
|
||||
if let Some(mut tail) = tail {
|
||||
head.props.drop_cap = Some(lines);
|
||||
// The letter's own font goes on its run (`w:rFonts`).
|
||||
if let Some(f) = p.props.drop_cap_font.as_ref().filter(|f| !f.trim().is_empty()) {
|
||||
for r in &mut head.runs {
|
||||
r.props.font = Some(f.clone());
|
||||
}
|
||||
}
|
||||
head.section = None;
|
||||
self.para_inner(w, &head, rels, false, depth, true);
|
||||
tail.props.drop_cap = None;
|
||||
@@ -247,9 +255,19 @@ impl Writer<'_> {
|
||||
// Split into pieces with their props.
|
||||
let mut pieces: Vec<(Piece, &CharProps)> = Vec::new();
|
||||
let mut k = 0usize;
|
||||
for (range, props) in p.run_ranges() {
|
||||
// Runs of mixed direction are split so Word orders them as WordCraft does (#1543).
|
||||
let rtl_para = self.doc.styles.resolve_para(&p.props).bidi;
|
||||
let styles = &self.doc.styles;
|
||||
let para_style = p.props.style.as_deref();
|
||||
let para_lang = super::bidi::para_inherits_lang_bidi(styles, para_style);
|
||||
let spans =
|
||||
super::bidi::direction_spans(&p.text, rtl_para, p.run_ranges(), |c| para_lang || super::bidi::char_style_has_lang_bidi(styles, c));
|
||||
for (range, props) in &spans {
|
||||
let props: &CharProps = props;
|
||||
let range = range.clone();
|
||||
let base = range.start;
|
||||
let Some(text) = p.text.get(range) else { continue };
|
||||
let sym_font = props.sym_font.as_deref().filter(|f| !f.trim().is_empty());
|
||||
let mut buf = String::new();
|
||||
for (ci, c) in text.char_indices() {
|
||||
let special = match c {
|
||||
@@ -267,6 +285,9 @@ impl Writer<'_> {
|
||||
None => Piece::Text(String::new()),
|
||||
})
|
||||
}
|
||||
// `w:char` is a two-byte code (ST_ShortHexNumber) from U+0020, as the reader
|
||||
// takes it; anything else stays text.
|
||||
c if (0x20..=0xFFFF).contains(&u32::from(c)) => sym_font.map(|f| Piece::Sym(f, c)),
|
||||
_ => None,
|
||||
};
|
||||
match special {
|
||||
@@ -349,6 +370,7 @@ impl Writer<'_> {
|
||||
Piece::Br(Some(t)) => w.empty("w:br", &[("w:type", t)]),
|
||||
Piece::NbHyphen => w.empty("w:noBreakHyphen", &[]),
|
||||
Piece::SoftHyphen => w.empty("w:softHyphen", &[]),
|
||||
Piece::Sym(font, c) => w.empty("w:sym", &[("w:font", font), ("w:char", &format!("{:04X}", u32::from(*c)))]),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -520,7 +542,12 @@ impl Writer<'_> {
|
||||
self.rev_open(w, props);
|
||||
w.open("w:r", &[]);
|
||||
self.rpr(w, &p);
|
||||
w.empty(mark, &[]);
|
||||
// A custom mark is plain text; the placeholder would turn it into a number.
|
||||
if custom.is_empty() {
|
||||
w.empty(mark, &[]);
|
||||
} else {
|
||||
w.leaf("w:t", &[("xml:space", "preserve")], custom);
|
||||
}
|
||||
w.close("w:r");
|
||||
self.rev_close(w, props);
|
||||
}
|
||||
@@ -551,6 +578,12 @@ impl Writer<'_> {
|
||||
let root = match (graphic.chart.as_deref(), graphic.smart_art.as_deref(), graphic.source.as_deref()) {
|
||||
(Some(spec), _, _) => crate::xml::parse(self.chart_graphic(spec, rels).as_bytes()).ok(),
|
||||
(None, Some(spec), _) => crate::xml::parse(self.smart_art_graphic(spec, *gw, *gh, rels).as_bytes()).ok(),
|
||||
// Ink in a group member's form (no drawing of its own) can't stand alone: left
|
||||
// out before its parts are queued, so no orphan part or relationship is written.
|
||||
(None, None, Some(src)) if ink && !standalone_ink(src) => {
|
||||
log::warn!("docx: group-member ink outside its group can't be written; it is left out");
|
||||
None
|
||||
}
|
||||
(None, None, Some(src)) => self.embedded_tree(src, rels, ink.then_some((*gw, *gh, float, alt.as_str()))),
|
||||
(None, None, None) => None,
|
||||
};
|
||||
@@ -728,6 +761,15 @@ impl Writer<'_> {
|
||||
let id = self.shape_docpr(extra.id);
|
||||
self.wsp(w, &c.obj, Some(&id), at, rels, depth);
|
||||
}
|
||||
// Native ink kept from the file, with its fallback, at the member's place.
|
||||
InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == wordcraft_doc::graphic::GraphicKind::Ink => {
|
||||
if let Some(src) = graphic.source.as_deref()
|
||||
&& let Some(mut root) = self.embedded_tree(src, rels, None)
|
||||
{
|
||||
Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0);
|
||||
w.raw(&root.to_xml());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -780,6 +822,17 @@ impl Writer<'_> {
|
||||
w.close("w:r");
|
||||
self.rev_close(w, props);
|
||||
}
|
||||
InlineObject::PositionalTab { align, relative_to, leader } => {
|
||||
self.rev_open(w, props);
|
||||
w.open("w:r", &[]);
|
||||
self.rpr(w, props);
|
||||
w.empty(
|
||||
"w:ptab",
|
||||
&[("w:relativeTo", relative_to.ooxml()), ("w:alignment", align.ooxml()), ("w:leader", super::props::tab_leader(*leader))],
|
||||
);
|
||||
w.close("w:r");
|
||||
self.rev_close(w, props);
|
||||
}
|
||||
InlineObject::Opaque { format, xml, text } => {
|
||||
if format == "docx" && crate::xml::parse(xml.as_bytes()).is_ok() {
|
||||
w.raw(xml);
|
||||
@@ -1043,6 +1096,7 @@ impl Writer<'_> {
|
||||
w.empty("a:srgbClr", &[("val", &c.hex())]);
|
||||
}
|
||||
w.close("a:solidFill");
|
||||
line_dash(w, &extra.dash);
|
||||
if ink {
|
||||
w.empty("a:round", &[]);
|
||||
}
|
||||
@@ -1052,6 +1106,7 @@ impl Writer<'_> {
|
||||
None => {
|
||||
w.open("a:ln", &[]);
|
||||
w.empty("a:noFill", &[]);
|
||||
line_dash(w, &extra.dash);
|
||||
w.close("a:ln");
|
||||
}
|
||||
}
|
||||
@@ -1142,7 +1197,7 @@ impl Writer<'_> {
|
||||
("relativeHeight", &self.z.to_string()),
|
||||
("behindDoc", behind),
|
||||
("locked", "0"),
|
||||
("layoutInCell", "1"),
|
||||
("layoutInCell", if float.outside_cell { "0" } else { "1" }),
|
||||
("allowOverlap", "1"),
|
||||
],
|
||||
);
|
||||
@@ -1488,6 +1543,28 @@ fn cust_geom(w: &mut W, f: &wordcraft_doc::freeform::Freeform, sw: f32, sh: f32)
|
||||
w.close("a:custGeom");
|
||||
}
|
||||
|
||||
/// Explicit DrawingML outline dashes, before joins and arrowheads.
|
||||
fn line_dash(w: &mut W, dash: &wordcraft_doc::line_dash::LineDash) {
|
||||
use wordcraft_doc::line_dash::{LineDash, MAX_DASH_STOPS};
|
||||
if dash.is_solid() {
|
||||
return;
|
||||
}
|
||||
if let Some(preset) = dash.ooxml() {
|
||||
w.empty("a:prstDash", &[("val", preset)]);
|
||||
return;
|
||||
}
|
||||
if let LineDash::Custom(stops) = dash {
|
||||
if stops.is_empty() {
|
||||
return;
|
||||
}
|
||||
w.open("a:custDash", &[]);
|
||||
for (d, sp) in stops.iter().take(MAX_DASH_STOPS) {
|
||||
w.empty("a:ds", &[("d", &d.to_string()), ("sp", &sp.to_string())]);
|
||||
}
|
||||
w.close("a:custDash");
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape's `a:effectLst` (ECMA-376 Part 1 §20.1.8.26), children in schema order.
|
||||
/// A line's arrowheads (`a:headEnd`, `a:tailEnd`, ECMA-376 §20.1.8.38 / §20.1.8.57).
|
||||
fn arrow_ends(w: &mut W, extra: &wordcraft_doc::connector::ShapeExtra) {
|
||||
@@ -1696,3 +1773,38 @@ fn comment_reference_style(doc: &wordcraft_doc::Document) -> &str {
|
||||
.find(|s| s.kind == wordcraft_doc::styles::StyleKind::Character && s.name.eq_ignore_ascii_case("annotation reference"))
|
||||
.map_or("CommentReference", |s| s.id.as_str())
|
||||
}
|
||||
|
||||
/// Is kept ink `src` in a form the drawing-level writer writes: its `a:graphic`, a direct run-level
|
||||
/// `w:contentPart`, or an `mc:AlternateContent` whose choice holds a drawing (not a group member's
|
||||
/// bare `w14:contentPart`, nor one in `mc:AlternateContent` with a `pic:pic` fallback)?
|
||||
fn standalone_ink(src: &wordcraft_doc::graphic::Embedded) -> bool {
|
||||
match crate::xml::parse(src.xml.as_bytes()) {
|
||||
Ok(root) => match root.name.as_str() {
|
||||
"a:graphic" | "w:contentPart" => true,
|
||||
"mc:AlternateContent" => root.child("mc:Choice").and_then(|c| c.child("w:drawing")).is_some_and(|d| d.find("a:graphic").is_some()),
|
||||
_ => false,
|
||||
},
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod standalone_ink_tests {
|
||||
use super::standalone_ink;
|
||||
use wordcraft_doc::graphic::Embedded;
|
||||
|
||||
fn emb(xml: &str) -> Embedded {
|
||||
Embedded { xml: xml.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Review: an alternate whose choice has a drawing but no `a:graphic` is not writable as ink.
|
||||
#[test]
|
||||
fn alternate_content_needs_a_graphic() {
|
||||
let ns = r#"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#;
|
||||
let with =
|
||||
format!("<mc:AlternateContent {ns}><mc:Choice Requires=\"w14\"><w:drawing><a:graphic/></w:drawing></mc:Choice></mc:AlternateContent>");
|
||||
let without = format!("<mc:AlternateContent {ns}><mc:Choice Requires=\"w14\"><w:drawing/></mc:Choice></mc:AlternateContent>");
|
||||
assert!(standalone_ink(&emb(&with)));
|
||||
assert!(!standalone_ink(&emb(&without)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Runs of mixed right-to-left and left-to-right text (#1543). WordCraft lays a paragraph out with
|
||||
//! the Unicode Bidirectional Algorithm (UAX #9) from its text and direction alone, while Word
|
||||
//! orders a run's characters by the run's `w:rtl` (ECMA-376 Part 1 §17.3.2.30): text in a run
|
||||
//! without it is laid out left to right, so Hebrew words around a Latin name, and the punctuation
|
||||
//! between them, change places. The writer therefore splits such a run where the resolved
|
||||
//! direction changes and marks the right-to-left pieces `w:rtl`, as Word does with text typed
|
||||
//! in a right-to-left paragraph.
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
/// `word/document.xml` of a written package.
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The runs of the first paragraph of `xml`: (has `w:rtl`, text with `w:br` as `\n`).
|
||||
fn runs(xml: &str) -> Vec<(bool, String)> {
|
||||
let body = xml.split("<w:body>").nth(1).unwrap();
|
||||
let para = body.split("</w:p>").next().unwrap();
|
||||
para.split("<w:r>")
|
||||
.skip(1)
|
||||
.map(|r| {
|
||||
let r = r.split("</w:r>").next().unwrap();
|
||||
let rtl = r.contains("<w:rtl/>");
|
||||
let mut text = String::new();
|
||||
for part in r.split('<').skip(1) {
|
||||
if part.starts_with("w:br/>") {
|
||||
text.push('\n');
|
||||
} else if part.starts_with("w:t ") || part.starts_with("w:t>") {
|
||||
text.push_str(part.split_once('>').unwrap().1);
|
||||
}
|
||||
}
|
||||
(rtl, text)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn arial() -> CharProps {
|
||||
CharProps { font: Some("Arial".into()), font_cs: Some("Arial".into()), size: Some(16.0), size_cs: Some(16.0), ..Default::default() }
|
||||
}
|
||||
|
||||
fn doc_of(text: &str, rtl_para: bool, props: CharProps) -> Document {
|
||||
let mut p = Paragraph::with_text(text, props);
|
||||
if rtl_para {
|
||||
p.props.bidi = Some(true);
|
||||
}
|
||||
let mut d = Document::new();
|
||||
d.body = vec![para_block(p)];
|
||||
d
|
||||
}
|
||||
|
||||
fn written_runs(d: &Document) -> Vec<(bool, String)> {
|
||||
runs(&document_xml(&wordcraft_docx::write(d).unwrap()))
|
||||
}
|
||||
|
||||
fn owned(v: &[(bool, &str)]) -> Vec<(bool, String)> {
|
||||
v.iter().map(|(r, t)| (*r, (*t).to_string())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_paragraph_splits_latin_out_of_rtl_runs() {
|
||||
let d = doc_of("עברית WordCraft 2026 ואחריה עוד עברית.", true, arial());
|
||||
assert_eq!(written_runs(&d), owned(&[(true, "עברית "), (false, "WordCraft 2026"), (true, " ואחריה עוד עברית.")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_paragraph_brackets_email_and_final_stop_take_the_paragraph_direction() {
|
||||
let d = doc_of("לפני (ABC 123) אחרי; דוא״ל [email protected].", true, arial());
|
||||
assert_eq!(written_runs(&d), owned(&[(true, "לפני ("), (false, "ABC 123"), (true, ") אחרי; דוא״ל "), (false, "[email protected]"), (true, ".")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_breaks_stay_in_the_split_runs() {
|
||||
let d = doc_of("שלום עולם.\nעברית WordCraft 2026 ואחריה.", true, arial());
|
||||
assert_eq!(written_runs(&d), owned(&[(true, "שלום עולם.\nעברית "), (false, "WordCraft 2026"), (true, " ואחריה.")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_runs_keep_their_formatting() {
|
||||
let d = doc_of("עברית WordCraft עברית", true, arial());
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
let body = xml.split("<w:body>").nth(1).unwrap();
|
||||
assert_eq!(body.matches("<w:r>").count(), 3);
|
||||
assert_eq!(body.matches(r#"<w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/>"#).count(), 4, "three runs and the mark: {body}");
|
||||
assert_eq!(body.matches(r#"<w:szCs w:val="32"/>"#).count(), 4, "{body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hebrew_inside_an_ltr_paragraph_is_marked_right_to_left() {
|
||||
let d = doc_of("English with עברית מעורבת inside.", false, CharProps::default());
|
||||
assert_eq!(written_runs(&d), owned(&[(false, "English with "), (true, "עברית מעורבת"), (false, " inside.")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_without_rtl_characters_is_one_run() {
|
||||
let d = doc_of("Plain English, 2026.", true, arial());
|
||||
assert_eq!(written_runs(&d), owned(&[(false, "Plain English, 2026.")]));
|
||||
let d = doc_of("Plain English, 2026.", false, arial());
|
||||
assert_eq!(written_runs(&d), owned(&[(false, "Plain English, 2026.")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_run_direction_is_kept() {
|
||||
// A run that already says its direction is written as it is, unsplit.
|
||||
let d = doc_of("עברית WordCraft", true, CharProps { rtl: Some(true), ..arial() });
|
||||
assert_eq!(written_runs(&d), owned(&[(true, "עברית WordCraft")]));
|
||||
let d = doc_of("עברית WordCraft", true, CharProps { rtl: Some(false), ..arial() });
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains(r#"<w:rtl w:val="0"/>"#), "{xml}");
|
||||
assert_eq!(runs(&xml).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_paragraph_round_trips_text_and_direction() {
|
||||
let text = "לפני (ABC 123) אחרי; דוא״ל [email protected].\nעברית WordCraft 2026 ואחריה עוד עברית.";
|
||||
let d = doc_of(text, true, arial());
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let r = wordcraft_docx::read(&bytes).unwrap();
|
||||
let p = r.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.text, text);
|
||||
assert_eq!(p.props.bidi, Some(true));
|
||||
for run in &p.runs {
|
||||
assert_eq!(run.props.font.as_deref(), Some("Arial"));
|
||||
assert_eq!(run.props.size, Some(16.0));
|
||||
}
|
||||
assert!(p.runs.iter().any(|r| r.props.rtl == Some(true)));
|
||||
// Saving again writes the same runs: the read-back direction is now explicit.
|
||||
assert_eq!(written_runs(&r), written_runs(&d));
|
||||
}
|
||||
|
||||
// Word gives right-to-left text without a `w:lang w:bidi` its default complex-script language
|
||||
// (Arabic), so its status bar, proofing and hyphenation call Hebrew "Arabic". Right-to-left
|
||||
// pieces the writer marks say their language (§17.3.2.20), unless the run or a style already does.
|
||||
|
||||
/// `w:bidi` attribute of each run's `w:lang` in the first paragraph: (has `w:rtl`, bidi language).
|
||||
fn run_langs(xml: &str) -> Vec<(bool, Option<String>)> {
|
||||
let body = xml.split("<w:body>").nth(1).unwrap();
|
||||
let para = body.split("</w:p>").next().unwrap();
|
||||
para.split("<w:r>")
|
||||
.skip(1)
|
||||
.map(|r| {
|
||||
let r = r.split("</w:r>").next().unwrap();
|
||||
let lang = r.split("<w:lang ").nth(1).and_then(|l| l.split("w:bidi=\"").nth(1)).map(|v| v.split('"').next().unwrap().to_string());
|
||||
(r.contains("<w:rtl/>"), lang)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn langs(d: &Document) -> Vec<(bool, Option<String>)> {
|
||||
run_langs(&document_xml(&wordcraft_docx::write(d).unwrap()))
|
||||
}
|
||||
|
||||
fn he(rtl: bool) -> (bool, Option<String>) {
|
||||
(rtl, rtl.then(|| "he-IL".to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hebrew_pieces_say_they_are_hebrew() {
|
||||
let d = doc_of("לפני (ABC 123) אחרי; דוא״ל [email protected].", true, arial());
|
||||
// The final stop has no letters of its own; it takes the paragraph's language.
|
||||
assert_eq!(langs(&d), vec![he(true), he(false), he(true), he(false), he(true)]);
|
||||
let d = doc_of("English with עברית מעורבת inside.", false, CharProps::default());
|
||||
assert_eq!(langs(&d), vec![he(false), he(true), he(false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_pieces_say_they_are_arabic() {
|
||||
let d = doc_of("مرحبا WordCraft بالعالم", true, arial());
|
||||
let ar = Some("ar-SA".to_string());
|
||||
assert_eq!(langs(&d), vec![(true, ar.clone()), (false, None), (true, ar)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_language_the_run_already_has_is_kept() {
|
||||
let d = doc_of("سلام WordCraft دنیا", true, CharProps { lang_bidi: Some("fa-IR".into()), ..arial() });
|
||||
let fa = Some("fa-IR".to_string());
|
||||
assert_eq!(langs(&d), vec![(true, fa.clone()), (false, fa.clone()), (true, fa)]);
|
||||
// A right-to-left proofing language on the run (w:val) names the right-to-left text too.
|
||||
let d = doc_of("שלום WordCraft", true, CharProps { lang: Some("yi".into()), ..arial() });
|
||||
assert_eq!(langs(&d), vec![(true, Some("yi".into())), (false, None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_bidi_language_is_not_repeated() {
|
||||
let mut d = doc_of("سلام WordCraft دنیا", true, arial());
|
||||
d.styles.default_chr.lang_bidi = Some("fa-IR".into());
|
||||
assert_eq!(langs(&d), vec![(true, None), (false, None), (true, None)]);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Original partial-cell-margin fixture (ECMA-376 §17.4.69).
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
fn fixture() -> Vec<u8> {
|
||||
let document = r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl><w:tblPr><w:tblCellMar><w:top w:w="55" w:type="dxa"/><w:left w:w="45" w:type="dxa"/><w:bottom w:w="55" w:type="dxa"/><w:right w:w="55" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="4320"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcMar><w:left w:w="0" w:type="dxa"/></w:tcMar></w:tcPr><w:p><w:r><w:t>Point</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>"#;
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(document.as_bytes()).unwrap();
|
||||
zip.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_margin_stays_partial() {
|
||||
let doc = wordcraft_docx::read(&fixture()).unwrap();
|
||||
let table = doc.body[0].as_table().unwrap();
|
||||
assert_eq!(table.rows[0].cells[0].props.margins, None, "a left-only margin is not a complete override");
|
||||
assert_eq!(table.rows[0].cells[0].props.resolved_margins([6.0, 7.0, 8.0, 9.0]), [6.0, 0.0, 8.0, 9.0]);
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let reopened = wordcraft_docx::read(&bytes).unwrap();
|
||||
let cell = &reopened.body[0].as_table().unwrap().rows[0].cells[0];
|
||||
assert_eq!(cell.props.resolved_margins([6.0, 7.0, 8.0, 9.0]), [6.0, 0.0, 8.0, 9.0]);
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
zip.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
let margins = xml.split("<w:tcMar>").nth(1).unwrap().split("</w:tcMar>").next().unwrap();
|
||||
assert!(margins.contains("<w:left w:w=\"0\""));
|
||||
assert!(!margins.contains("<w:top"));
|
||||
assert!(!margins.contains("<w:bottom"));
|
||||
assert!(!margins.contains("<w:right"));
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
//! Synthetic packages, written here; no external documents or installed fonts are needed.
|
||||
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::{Document, Paragraph};
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_doc::{Document, Paragraph, Run};
|
||||
|
||||
fn package(run: &str, defaults: &str, styles: &str, paragraph_style: &str) -> Vec<u8> {
|
||||
let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
|
||||
@@ -29,13 +30,41 @@ fn paragraph(d: &Document) -> &Paragraph {
|
||||
d.body.iter().find_map(|b| b.as_para()).unwrap()
|
||||
}
|
||||
|
||||
/// `runs` without run direction and bidi language (in the formatting change too), adjacent equal
|
||||
/// runs merged.
|
||||
fn undirected(runs: &[Run]) -> Vec<Run> {
|
||||
let strip = |c: &mut CharProps| {
|
||||
c.rtl = None;
|
||||
c.lang_bidi = None;
|
||||
};
|
||||
let mut out: Vec<Run> = Vec::new();
|
||||
for r in runs {
|
||||
let mut props = r.props.clone();
|
||||
strip(&mut props);
|
||||
if let Some(ch) = props.fmt_change.as_mut() {
|
||||
strip(&mut ch.old);
|
||||
}
|
||||
match out.last_mut() {
|
||||
Some(last) if last.props == props => last.len += r.len,
|
||||
_ => out.push(Run { len: r.len, props }),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn check_generations(bytes: &[u8], check: impl Fn(&Document)) {
|
||||
let mut d = wordcraft_docx::read(bytes).unwrap();
|
||||
for _ in 0..3 {
|
||||
for generation in 0..3 {
|
||||
check(&d);
|
||||
let next = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(paragraph(&next).text, paragraph(&d).text);
|
||||
assert_eq!(paragraph(&next).runs, paragraph(&d).runs);
|
||||
if generation == 0 {
|
||||
// The first save splits the mixed Hebrew/Latin run by direction and names the
|
||||
// Hebrew's language (#1543); apart from that nothing changes.
|
||||
assert_eq!(undirected(¶graph(&next).runs), undirected(¶graph(&d).runs));
|
||||
} else {
|
||||
assert_eq!(paragraph(&next).runs, paragraph(&d).runs);
|
||||
}
|
||||
assert_eq!(paragraph(&next).props.bidi, Some(true));
|
||||
d = next;
|
||||
}
|
||||
@@ -133,3 +162,39 @@ fn tracked_formatting_keeps_independent_complex_script_values() {
|
||||
assert_eq!(overlaid.fmt_change, c.fmt_change);
|
||||
});
|
||||
}
|
||||
|
||||
/// `(w:rtl, w:lang)` elements of a run's current `w:rPr` and of its `w:rPrChange` "before" copy.
|
||||
fn direction_markup(run: &str) -> (String, String) {
|
||||
let pick = |rpr: &str| -> String {
|
||||
rpr.split('<').filter(|t| t.starts_with("w:rtl") || t.starts_with("w:lang")).map(|t| format!("<{t}")).collect::<Vec<_>>().join("")
|
||||
};
|
||||
let (now, change) = run.split_once("<w:rPrChange").unwrap_or((run, ""));
|
||||
(pick(now), pick(change))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_runs_add_no_phantom_tracked_formatting() {
|
||||
// #1543: direction and language the writer adds to a piece of a run that has a tracked
|
||||
// formatting change go into the change's "before" copy too, so Word lists no change the
|
||||
// author never made ("Formatted: Right-to-left, Hebrew").
|
||||
let run = r#"<w:sz w:val="24"/><w:rPrChange w:id="7" w:author="Synthetic Author" w:date="2026-10-11T00:00:00Z"><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrChange>"#;
|
||||
let d = wordcraft_docx::read(&package(run, "", "", "")).unwrap();
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("word/document.xml").unwrap(), &mut xml)
|
||||
.unwrap();
|
||||
let runs: Vec<&str> = xml.split("<w:r>").skip(1).map(|r| r.split("</w:r>").next().unwrap()).collect();
|
||||
assert!(runs.len() >= 2, "the mixed run is split: {xml}");
|
||||
assert!(runs.iter().any(|r| r.contains("<w:rtl/>")), "{xml}");
|
||||
for r in runs {
|
||||
assert!(r.contains("<w:rPrChange"), "every piece keeps the tracked change: {r}");
|
||||
let (now, before) = direction_markup(r);
|
||||
assert_eq!(now, before, "no direction or language difference to report: {r}");
|
||||
}
|
||||
// And WordCraft reads no difference back either.
|
||||
let r = wordcraft_docx::read(&bytes).unwrap();
|
||||
for run in ¶graph(&r).runs {
|
||||
let old = &run.props.fmt_change.as_ref().unwrap().old;
|
||||
assert_eq!((old.rtl, old.lang_bidi.as_deref()), (run.props.rtl, run.props.lang_bidi.as_deref()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,3 +228,20 @@ fn deeply_nested_controls_are_bounded() {
|
||||
let back = read(&write(&d).unwrap()).unwrap();
|
||||
assert_eq!(controls(&back).len(), 60);
|
||||
}
|
||||
|
||||
/// A control's `w:rPr` (ECMA-376 §17.5.2.27) is read as the formatting entered text takes, and
|
||||
/// still written back as it was.
|
||||
#[test]
|
||||
fn a_controls_run_properties_are_read_and_kept() {
|
||||
let docx = package(&p(&format!(
|
||||
"{}{}",
|
||||
t("Name: "),
|
||||
sdt(r#"<w:rPr><w:rStyle w:val="Eingabe"/><w:sz w:val="20"/></w:rPr><w:id w:val="11"/><w:showingPlcHdr/>"#, &t("Eingabe"))
|
||||
)));
|
||||
let d = read(&docx).unwrap();
|
||||
let c = by_id(&d, 11);
|
||||
let rp = c.run_props.expect("run properties read");
|
||||
assert_eq!((rp.style.as_deref(), rp.size), (Some("Eingabe"), Some(10.0)));
|
||||
let out = document_xml(&write(&d).unwrap());
|
||||
assert!(out.contains(r#"<w:rPr><w:rStyle w:val="Eingabe"/><w:sz w:val="20"/></w:rPr>"#), "{out}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! East Asian typography settings of a run (`w:eastAsianLayout`, ISO/IEC 29500-1 §17.3.2.10):
|
||||
//! two lines in one and horizontal in vertical are read and saved again. Fixtures are
|
||||
//! hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::props::{CombineBrackets, EastAsianLayout};
|
||||
|
||||
fn docx(body: &str, styles: Option<&str>) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut parts = vec![("_rels/.rels", root.to_string()), ("word/document.xml", doc)];
|
||||
if let Some(s) = styles {
|
||||
parts.push(("word/_rels/document.xml.rels", doc_rels.to_string()));
|
||||
parts.push((
|
||||
"word/styles.xml",
|
||||
format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{s}</w:styles>"#),
|
||||
));
|
||||
}
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, xml) in &parts {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn part(bytes: &[u8], name: &str) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(text: &str, rpr: &str) -> String {
|
||||
format!(r#"<w:r><w:rPr>{rpr}</w:rPr><w:t>{text}</w:t></w:r>"#)
|
||||
}
|
||||
|
||||
/// The East Asian layout of the run holding `text` in the first paragraph.
|
||||
fn layout_of(d: &wordcraft_doc::Document, text: &str) -> Option<EastAsianLayout> {
|
||||
let p = d.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
let start = p.text.find(text).unwrap();
|
||||
let mut at = 0;
|
||||
for r in &p.runs {
|
||||
if at == start {
|
||||
return r.props.east_asian_layout.clone();
|
||||
}
|
||||
at += r.len;
|
||||
}
|
||||
panic!("no run starts at {text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_lines_in_one_and_horizontal_in_vertical_survive_a_save() {
|
||||
// Warichu with round brackets, tate-chu-yoko compressed to the line, and a plain run beside them.
|
||||
let body = format!(
|
||||
r#"<w:p>{}{}{}{}</w:p><w:sectPr><w:textDirection w:val="tbRl"/></w:sectPr>"#,
|
||||
run("本文", ""),
|
||||
run("二行の注", r#"<w:eastAsianLayout w:id="1" w:combine="on" w:combineBrackets="round"/>"#),
|
||||
run("12", r#"<w:eastAsianLayout w:id="2" w:vert="on" w:vertCompress="true"/>"#),
|
||||
run("月", "")
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(&body, None)).unwrap();
|
||||
let warichu = EastAsianLayout { id: Some(1), combine: Some(true), combine_brackets: Some(CombineBrackets::Round), ..Default::default() };
|
||||
let tcy = EastAsianLayout { id: Some(2), vert: Some(true), vert_compress: Some(true), ..Default::default() };
|
||||
assert_eq!(layout_of(&d, "二行の注"), Some(warichu.clone()));
|
||||
assert_eq!(layout_of(&d, "12"), Some(tcy.clone()));
|
||||
assert_eq!(layout_of(&d, "本文"), None);
|
||||
assert_eq!(layout_of(&d, "月"), None);
|
||||
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = part(&out, "word/document.xml");
|
||||
assert_eq!(xml.matches("<w:eastAsianLayout ").count(), 2, "{xml}");
|
||||
assert!(xml.contains(r#"<w:eastAsianLayout w:id="1" w:combine="1" w:combineBrackets="round"/>"#), "{xml}");
|
||||
assert!(xml.contains(r#"<w:eastAsianLayout w:id="2" w:vert="1" w:vertCompress="1"/>"#), "{xml}");
|
||||
let back = wordcraft_docx::read(&out).unwrap();
|
||||
assert_eq!(layout_of(&back, "二行の注"), Some(warichu));
|
||||
assert_eq!(layout_of(&back, "12"), Some(tcy));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn east_asian_layout_is_written_after_lang() {
|
||||
// CT_RPr's sequence: … w:lang, w:eastAsianLayout, w:specVanish.
|
||||
let body = format!(r#"<w:p>{}</w:p>"#, run("12", r#"<w:eastAsianLayout w:vert="1"/><w:lang w:val="ja-JP"/><w:b/>"#));
|
||||
let d = wordcraft_docx::read(&docx(&body, None)).unwrap();
|
||||
let xml = part(&wordcraft_docx::write(&d).unwrap(), "word/document.xml");
|
||||
let lang = xml.find("<w:lang ").unwrap();
|
||||
let eal = xml.find("<w:eastAsianLayout ").unwrap();
|
||||
assert!(lang < eal, "{xml}");
|
||||
assert!(xml.contains(r#"<w:eastAsianLayout w:vert="1"/>"#), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_style_keeps_its_east_asian_layout() {
|
||||
let styles = r#"<w:style w:type="character" w:styleId="TCY"><w:name w:val="Tate Chu Yoko"/><w:rPr><w:eastAsianLayout w:id="7" w:vert="on"/></w:rPr></w:style>"#;
|
||||
let body = format!(r#"<w:p>{}</w:p>"#, run("12", r#"<w:rStyle w:val="TCY"/>"#));
|
||||
let d = wordcraft_docx::read(&docx(&body, Some(styles))).unwrap();
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = part(&out, "word/styles.xml");
|
||||
assert!(xml.contains(r#"<w:eastAsianLayout w:id="7" w:vert="1"/>"#), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_outside_the_schema_are_dropped_not_guessed() {
|
||||
// An id past xsd:int, an unknown bracket and an on/off that isn't one: those attributes are
|
||||
// unset; the valid one beside them is kept. An element with nothing valid writes nothing.
|
||||
let body = format!(
|
||||
r#"<w:p>{}{}</w:p>"#,
|
||||
run("注", r#"<w:eastAsianLayout w:id="99999999999" w:combine="yes" w:combineBrackets="wavy" w:vert="off"/>"#),
|
||||
run("x", r#"<w:eastAsianLayout w:combineBrackets="wavy"/>"#)
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(&body, None)).unwrap();
|
||||
assert_eq!(layout_of(&d, "注"), Some(EastAsianLayout { vert: Some(false), ..Default::default() }));
|
||||
assert_eq!(layout_of(&d, "x"), None);
|
||||
let xml = part(&wordcraft_docx::write(&d).unwrap(), "word/document.xml");
|
||||
assert_eq!(xml.matches("<w:eastAsianLayout ").count(), 1, "{xml}");
|
||||
assert!(xml.contains(r#"<w:eastAsianLayout w:vert="0"/>"#), "{xml}");
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::para::{Anchor, FloatAlign, NoteKind, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::{Align, Border, BorderStyle, Rgb, TextColor, VMerge};
|
||||
use wordcraft_doc::props::{Align, Border, BorderStyle, Rgb, TextColor, Underline, VMerge};
|
||||
use wordcraft_doc::{Block, Document, InlineObject, Paragraph, RevisionKind};
|
||||
|
||||
const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office""#;
|
||||
@@ -97,6 +97,28 @@ fn paras(d: &Document) -> Vec<&Paragraph> {
|
||||
d.body.iter().filter_map(|b| b.as_para()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_links_keep_cached_results() {
|
||||
let d = read_body(
|
||||
r#"
|
||||
<w:p><w:fldSimple w:instr="REF destination \h" w:fldLock="1"><w:r><w:rPr><w:b/></w:rPr><w:t>Cached simple</w:t></w:r></w:fldSimple></w:p>
|
||||
<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve">REF destination </w:instrText></w:r><w:r><w:instrText>\w \h</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>Cached complex</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>
|
||||
<w:p><w:bookmarkStart w:id="0" w:name="destination"/><w:r><w:t>Changed destination</w:t></w:r><w:bookmarkEnd w:id="0"/></w:p>"#,
|
||||
);
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
for doc in [&d, &again] {
|
||||
let p = paras(doc);
|
||||
for (index, instr, cached, locked) in
|
||||
[(0, r"REF destination \h", "Cached simple", true), (1, r"REF destination \w \h", "Cached complex", false)]
|
||||
{
|
||||
assert!(matches!(&p[index].objects[0], InlineObject::Field { instr: actual, result, locked: lock, .. }
|
||||
if actual == instr && result == cached && *lock == locked));
|
||||
}
|
||||
assert_eq!(p[0].props_of_char(0).bold, Some(true));
|
||||
assert!(doc.bookmarks().iter().any(|(name, _)| name == "destination"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_entry_toc_keeps_formatted_result_and_nested_page_field() {
|
||||
let d = read_body(
|
||||
@@ -205,7 +227,7 @@ fn hyperlink_runs_and_wrappers() {
|
||||
assert_eq!(p[0].props_of_char(0).style.as_deref(), Some("Hyperlink"));
|
||||
assert_eq!(p[0].props_of_char(4).link.as_deref(), Some("https://example.org/#frag"));
|
||||
let sym_off = p[0].text.find('\u{F04A}').unwrap();
|
||||
assert_eq!(p[0].props_of_char(sym_off).font.as_deref(), Some("Wingdings"));
|
||||
assert_eq!(p[0].props_of_char(sym_off).sym_font.as_deref(), Some("Wingdings"), "the symbol keeps its own font");
|
||||
let t = p[0].props_of_char(p[0].text.len() - 1);
|
||||
assert_eq!((t.bold, t.italic, t.caps, t.strike, t.color), (Some(false), Some(false), Some(false), Some(true), Some(TextColor::Auto)));
|
||||
assert_eq!(p[1].plain_text(), "in block sdt");
|
||||
@@ -236,6 +258,86 @@ fn symbol_font_text_reads_as_unicode_and_round_trips_unchanged() {
|
||||
assert_eq!(q[0].shown_text(), p[0].shown_text());
|
||||
}
|
||||
|
||||
/// The `w:sym` elements of a document's main part, as written.
|
||||
fn sym_elements(bytes: &[u8]) -> Vec<String> {
|
||||
let parts = unzip(bytes);
|
||||
let xml = String::from_utf8_lossy(parts.get("word/document.xml").unwrap()).to_string();
|
||||
xml.match_indices("<w:sym ").map(|(i, _)| xml[i..].split("/>").next().unwrap().to_string() + "/>").collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sym_character_keeps_its_symbol_font_when_the_text_font_changes() {
|
||||
// #2036: ECMA-376 §17.3.3.30 — a `w:sym` character's font is its own `w:font`, whatever the
|
||||
// run's font. Setting the whole paragraph in Times New Roman keeps the check mark.
|
||||
let body = r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:sym w:font="Wingdings" w:char="F0FC"/></w:r><w:r><w:t>b</w:t></w:r></w:p>"#;
|
||||
let mut d = wordcraft_docx::read(&docx(body, &[], &[])).unwrap();
|
||||
let len = paras(&d)[0].text.len();
|
||||
d.format_range(&wordcraft_doc::Pos::body(0, 0), &wordcraft_doc::Pos::body(0, len), &|c| c.font = Some("Times New Roman".into())).unwrap();
|
||||
let p = paras(&d)[0];
|
||||
assert_eq!(p.plain_text(), "a\u{F0FC}b", "the stored character is unchanged");
|
||||
assert_eq!(p.props_of_char(1).font.as_deref(), Some("Times New Roman"), "the run font did change");
|
||||
assert_eq!(p.shown_text(), "a\u{2713}b");
|
||||
assert_eq!(d.shown_text(wordcraft_doc::StoryRef::Body), "a\u{2713}b");
|
||||
// Written back as a `w:sym` in its symbol font, so Word shows the symbol too.
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
assert_eq!(sym_elements(&bytes), vec![r#"<w:sym w:font="Wingdings" w:char="F0FC"/>"#.to_string()]);
|
||||
let again = wordcraft_docx::read(&bytes).unwrap();
|
||||
let q = paras(&again)[0];
|
||||
assert_eq!(q.plain_text(), "a\u{F0FC}b");
|
||||
assert_eq!(q.shown_text(), "a\u{2713}b");
|
||||
assert_eq!(q.props_of_char(1).font.as_deref(), Some("Times New Roman"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sym_character_round_trips_as_w_sym() {
|
||||
let body = r#"<w:p><w:r><w:t xml:space="preserve">Done </w:t></w:r><w:r><w:sym w:font="Wingdings" w:char="F0FC"/><w:sym w:font="Symbol" w:char="F061"/></w:r></w:p>"#;
|
||||
let d = wordcraft_docx::read(&docx(body, &[], &[])).unwrap();
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
assert_eq!(
|
||||
sym_elements(&bytes),
|
||||
vec![r#"<w:sym w:font="Wingdings" w:char="F0FC"/>"#.to_string(), r#"<w:sym w:font="Symbol" w:char="F061"/>"#.to_string()]
|
||||
);
|
||||
let again = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(paras(&again)[0].shown_text(), "Done \u{2713}\u{3B1}");
|
||||
assert_eq!(sym_elements(&wordcraft_docx::write(&again).unwrap()), sym_elements(&bytes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_sym_fonts_never_panic() {
|
||||
// Built in the model (an XML file couldn't even hold some of these names).
|
||||
let huge = "W".repeat(100_000);
|
||||
for font in ["", " ", "\u{1}", huge.as_str(), "Wingdings\u{FFFF}", "<&\"'>"] {
|
||||
let mut d = Document::from_text("a\u{F0FC}\u{1}\u{1F600}b");
|
||||
let len = paras(&d)[0].text.len();
|
||||
let f = font.to_string();
|
||||
d.format_range(&wordcraft_doc::Pos::body(0, 0), &wordcraft_doc::Pos::body(0, len), &|c| c.sym_font = Some(f.clone())).unwrap();
|
||||
let _ = d.shown_text(wordcraft_doc::StoryRef::Body);
|
||||
let bytes = wordcraft_docx::write(&d).unwrap();
|
||||
let _ = wordcraft_docx::read(&bytes).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_printable_characters_are_written_as_w_sym() {
|
||||
// `w:sym` holds a character code from U+0020 (the reader drops lower ones), like `w:t`.
|
||||
let mut d = Document::from_text("a\u{7}");
|
||||
d.format_range(&wordcraft_doc::Pos::body(0, 0), &wordcraft_doc::Pos::body(0, 2), &|c| c.sym_font = Some("Wingdings".into())).unwrap();
|
||||
assert_eq!(sym_elements(&wordcraft_docx::write(&d).unwrap()), vec![r#"<w:sym w:font="Wingdings" w:char="0061"/>"#.to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcl6_symbol_roundtrip() {
|
||||
let body = r#"<w:p><w:r><w:sym w:font="Symbol (PCL6)" w:char="F0B3"/></w:r></w:p>"#;
|
||||
let d = wordcraft_docx::read(&docx(body, &[], &[])).unwrap();
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
for doc in [&d, &again] {
|
||||
let p = paras(doc)[0];
|
||||
assert_eq!(p.text, "\u{F0B3}");
|
||||
assert_eq!(p.props_of_char(0).sym_font.as_deref(), Some("Symbol (PCL6)"));
|
||||
assert_eq!(p.shown_text(), "≥");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternate_content_choice_and_fallback() {
|
||||
let body = r#"
|
||||
@@ -560,6 +662,26 @@ fn empty_tbl_borders_elements_leave_sides_unset() {
|
||||
assert!(b.top.is_some() && b.between.is_some() && b.inside_v.is_some());
|
||||
}
|
||||
|
||||
/// A style ID defined twice is its last definition, whole (Word drops the earlier one rather
|
||||
/// than merging: observed with synthetic documents). Generators that write a placeholder
|
||||
/// Heading 1 and then their own made headings come out in the placeholder's font and size.
|
||||
#[test]
|
||||
fn a_style_defined_twice_is_its_last_definition() {
|
||||
let styles = format!(
|
||||
r#"<w:styles {W_NS}>
|
||||
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:pPr><w:jc w:val="center"/></w:pPr><w:rPr><w:i/><w:color w:val="FF0000"/><w:sz w:val="40"/></w:rPr></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:b/><w:color w:val="0000FF"/><w:sz w:val="24"/></w:rPr></w:style>
|
||||
</w:styles>"#
|
||||
);
|
||||
let body = r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Probe</w:t></w:r></w:p>"#;
|
||||
let d = wordcraft_docx::read(&docx(body, &[("rId1", "styles", "styles.xml")], &[("word/styles.xml", &styles)])).unwrap();
|
||||
assert_eq!(d.styles.styles.iter().filter(|s| s.id == "Heading1").count(), 1);
|
||||
let h = d.styles.get("Heading1").unwrap();
|
||||
assert_eq!((h.chr.bold, h.chr.italic, h.chr.size), (Some(true), None, Some(12.0)));
|
||||
assert_eq!(h.chr.color, Some(TextColor::Rgb(Rgb(0, 0, 0xFF))));
|
||||
assert_eq!(h.para.align, None, "nothing kept from the first definition");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vml_image_and_inline_drawing() {
|
||||
let png: &[u8] = b"\x89PNG\r\n\x1a\nnot really a png";
|
||||
@@ -616,6 +738,24 @@ fn chart_and_diagram_drawings_are_graphic_objects() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A text box shape's style text colour (`wps:style/a:fontRef`) is kept on its story, as what
|
||||
/// automatic text colour means inside it; a box without one has none.
|
||||
#[test]
|
||||
fn a_text_box_s_style_font_colour_is_read() {
|
||||
let shape = |style: &str| {
|
||||
format!(
|
||||
r#"<w:r><w:drawing><wp:anchor behindDoc="0"><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="635000"/><wp:wrapNone/><wp:docPr id="1" name="S"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="rect"/></wps:spPr>{style}<wps:txbx><w:txbxContent><w:p><w:r><w:t>In the box</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
|
||||
)
|
||||
};
|
||||
let style = r#"<wps:style><a:lnRef idx="2"><a:srgbClr val="000000"/></a:lnRef><a:fillRef idx="1"><a:srgbClr val="203040"/></a:fillRef><a:effectRef idx="0"><a:srgbClr val="000000"/></a:effectRef><a:fontRef idx="minor"><a:srgbClr val="FFFFFF"/></a:fontRef></wps:style>"#;
|
||||
let d = read_body(&format!("<w:p>{}{}</w:p>", shape(style), shape("")));
|
||||
let boxes: Vec<_> =
|
||||
paras(&d)[0].objects.iter().filter_map(|o| if let InlineObject::Shape { story: Some(id), .. } = o { Some(*id) } else { None }).collect();
|
||||
let [styled, plain] = boxes.as_slice() else { panic!("{boxes:?}") };
|
||||
assert_eq!(d.parts[styled].body.auto_color, Some(Rgb(0xFF, 0xFF, 0xFF)));
|
||||
assert_eq!(d.parts[plain].body.auto_color, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chart_part_is_built_once_and_only_through_a_chart_relationship() {
|
||||
let chart = r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart><c:plotArea><c:barChart><c:ser><c:val><c:numLit><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numLit></c:val></c:ser></c:barChart></c:plotArea></c:chart></c:chartSpace>"#;
|
||||
@@ -809,6 +949,28 @@ fn line_rule_is_read_case_insensitively() {
|
||||
assert_eq!(p[1].props.line_spacing, Some(wordcraft_doc::props::LineSpacing::Exactly(15.0)));
|
||||
}
|
||||
|
||||
/// #2329: Word 2024 saves strict OOXML with the line height written out with a unit
|
||||
/// (`w:line="13.90pt"`). Under `auto` it reads through twips, as Word renders it (13.90 × 20 =
|
||||
/// 278; the 1.1583 multiple), not as 240ths of a line like the bare number — a Word file with
|
||||
/// a `line="13.90pt"` default came in at 13.9 lines per line of text.
|
||||
#[test]
|
||||
fn strict_line_heights_with_a_unit_are_read_as_point_multiples() {
|
||||
let d = read_body(
|
||||
r#"<w:p><w:pPr><w:spacing w:after="8pt" w:line="13.90pt" w:lineRule="auto"/></w:pPr><w:r><w:t>x</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:line="13.90pt" w:lineRule="exact"/></w:pPr></w:p>"#,
|
||||
);
|
||||
let p = paras(&d);
|
||||
let Some(wordcraft_doc::props::LineSpacing::Multiple(m)) = p[0].props.line_spacing else {
|
||||
panic!("auto line spacing: {:?}", p[0].props.line_spacing)
|
||||
};
|
||||
assert!((m - 278.0 / 240.0).abs() < 1e-5, "{m}");
|
||||
assert_eq!(p[0].props.space_after, Some(8.0), "the unit form of w:after too");
|
||||
assert_eq!(p[1].props.line_spacing, Some(wordcraft_doc::props::LineSpacing::Exactly(13.9)), "exact keeps reading it as points");
|
||||
// Saves as the transitional 240ths form and reads back the same multiple.
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
let Some(wordcraft_doc::props::LineSpacing::Multiple(m2)) = paras(&again)[0].props.line_spacing else { panic!("multiple after a save") };
|
||||
assert!((m2 - m).abs() < 1e-5, "{m2} vs {m}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn char_border_reads_and_nil_resolves_off() {
|
||||
let d = read_body(
|
||||
@@ -960,6 +1122,39 @@ fn vml_textpath_in_header_is_the_watermark() {
|
||||
assert_eq!(read(r#"<v:shape id="PowerPlusWaterMarkObject2"><v:textpath string=" "/></v:shape>"#, true).0, None);
|
||||
}
|
||||
|
||||
/// Issue #2875: Word 2007 WordArt, a body `v:shape` with a `v:textpath`, is shown as a text shape
|
||||
/// holding its string in the textpath's font and the shape's colour, bent by the warp of its WordArt
|
||||
/// shape, not dropped; a textpath turned off or with an empty string draws nothing.
|
||||
#[test]
|
||||
fn vml_textpath_in_body_is_shown() {
|
||||
let read = |shape: &str| {
|
||||
let body = format!("<w:p><w:r><w:t>Before</w:t></w:r><w:r><w:pict>{shape}</w:pict></w:r></w:p>");
|
||||
wordcraft_docx::read(&docx(&body, &[], &[])).unwrap()
|
||||
};
|
||||
let art = r##"<v:shape type="#_x0000_t136" style="position:absolute;width:300pt;height:60pt" fillcolor="#336699" stroked="f"><v:textpath style="font-family:"Impact";font-size:1pt" string="Sale"/></v:shape>"##;
|
||||
let d = read(art);
|
||||
let objs = ¶s(&d)[0].objects;
|
||||
assert_eq!(objs.len(), 1);
|
||||
let InlineObject::Shape { story: Some(id), w, h, .. } = &objs[0] else { panic!("not a text shape: {:?}", objs[0]) };
|
||||
assert_eq!((*w, *h), (300.0, 60.0));
|
||||
let p = d.parts.get(id).unwrap().blocks[0].as_para().unwrap();
|
||||
assert_eq!(p.text, "Sale");
|
||||
assert_eq!(p.runs[0].props.font.as_deref(), Some("Impact"));
|
||||
assert_eq!(p.runs[0].props.color, Some(TextColor::Rgb(Rgb(0x33, 0x66, 0x99))));
|
||||
|
||||
// Its WordArt shape bends the text: shapetype 144 (Arch Up) is DrawingML's `textArchUp`.
|
||||
let warp = |shape: &str| match ¶s(&read(shape))[0].objects[..] {
|
||||
[InlineObject::Shape { extra, .. }] => extra.warp.as_ref().map(|w| w.preset.clone()),
|
||||
other => panic!("not one shape: {other:?}"),
|
||||
};
|
||||
assert_eq!(warp(&art.replace("_x0000_t136", "_x0000_t144")).as_deref(), Some("textArchUp"));
|
||||
assert_eq!(warp(&art.replace("_x0000_t136", "_x0000_t175")).as_deref(), Some("textCanDown"));
|
||||
assert_eq!(warp(art).as_deref(), Some("textPlain"));
|
||||
|
||||
assert!(paras(&read(&art.replace("<v:textpath ", r#"<v:textpath on="f" "#)))[0].objects.is_empty());
|
||||
assert!(paras(&read(&art.replace(r#"string="Sale""#, r#"string=" ""#)))[0].objects.is_empty());
|
||||
}
|
||||
|
||||
/// Issue #1290: a file with Word's watermark keeps it through save and reopen: the same
|
||||
/// watermark, the same headers with the same text and paragraphs, one shape per header written;
|
||||
/// header WordArt that isn't a watermark doesn't become one on the way.
|
||||
@@ -1007,6 +1202,79 @@ fn word_watermark_survives_save() {
|
||||
assert_eq!(d2.settings.watermark, None);
|
||||
}
|
||||
|
||||
/// Issue #1775: a picture watermark in a header that starts with a table is anchored in a cell
|
||||
/// but placed on the page: any VML shape in a header (Word's picture watermark, `o:allowincell="f"`; user-checked
|
||||
/// in Word for Mac, the attribute makes no difference) or DrawingML `layoutInCell="0"`. That survives save and reopen; a shape laid out in its cell stays so.
|
||||
#[test]
|
||||
fn header_cell_picture_placed_on_the_page() {
|
||||
let vml = |allow: &str| {
|
||||
format!(
|
||||
r##"<w:r><w:pict><v:shape id="WordPictureWatermark1" o:spid="_x0000_s2049" type="#_x0000_t75" style="position:absolute;margin-left:0;margin-top:0;width:300pt;height:200pt;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" {allow}><v:imagedata r:id="rIdP" o:title="" gain="19661f" blacklevel="22938f"/></v:shape></w:pict></w:r>"##
|
||||
)
|
||||
};
|
||||
let anchor = |in_cell: &str| {
|
||||
format!(
|
||||
r#"<w:r><w:drawing><wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" behindDoc="1" locked="0" layoutInCell="{in_cell}" allowOverlap="1"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="margin"><wp:align>center</wp:align></wp:positionH><wp:positionV relativeFrom="margin"><wp:align>center</wp:align></wp:positionV><wp:extent cx="3810000" cy="2540000"/><wp:wrapNone/><wp:docPr id="1" name="Picture 1"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:nvPicPr><pic:cNvPr id="1" name="p.png"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rIdP"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="3810000" cy="2540000"/></a:xfrm><a:prstGeom prst="rect"/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
|
||||
)
|
||||
};
|
||||
let read = |run: &str| {
|
||||
let hdr = format!(
|
||||
r#"<w:hdr {W_NS}><w:tbl><w:tblGrid><w:gridCol w:w="4680"/><w:gridCol w:w="4680"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>Left</w:t></w:r></w:p></w:tc><w:tc><w:p>{run}<w:r><w:t>Right</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/></w:hdr>"#
|
||||
);
|
||||
let hrels = rels(&[("rIdP", "image", "media/p.png")]);
|
||||
let body = r#"<w:p><w:r><w:t>Body</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="rIdH"/></w:sectPr>"#;
|
||||
let parts = [("word/header1.xml", hdr.as_str()), ("word/_rels/header1.xml.rels", hrels.as_str()), ("word/media/p.png", "\u{89}PNG stand-in")];
|
||||
wordcraft_docx::read(&docx(body, &[("rIdH", "header", "header1.xml")], &parts)).unwrap()
|
||||
};
|
||||
let floats = |d: &Document| -> Vec<(bool, Wrap)> {
|
||||
let hid = d.last_section.headers.default.unwrap();
|
||||
let mut out = Vec::new();
|
||||
for b in &d.parts[&hid].blocks {
|
||||
if let Block::Table(t) = &**b {
|
||||
for c in &t.rows[0].cells {
|
||||
for p in c.blocks.iter().filter_map(|b| b.as_para()) {
|
||||
out.extend(p.objects.iter().filter_map(|o| o.frame()).map(|(_, _, f)| (f.outside_cell, f.wrap)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
for (run, outside) in [
|
||||
(vml(r#"o:allowincell="f""#), true),
|
||||
(vml(r#"o:allowincell="false""#), true),
|
||||
// Word for Mac draws every VML picture in a header cell on the page, ticked or not.
|
||||
(vml(""), true),
|
||||
(vml(r#"o:allowincell="t""#), true),
|
||||
(anchor("0"), true),
|
||||
(anchor("false"), true),
|
||||
(anchor("1"), false),
|
||||
] {
|
||||
let d = read(&run);
|
||||
assert_eq!(floats(&d), vec![(outside, Wrap::BehindText)], "{run}");
|
||||
let d2 = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(floats(&d2), vec![(outside, Wrap::BehindText)], "saved: {run}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #1775: only header and footer shapes are placed on the page from a cell (what was checked
|
||||
/// in Word); a VML picture in a body table cell stays laid out in its cell.
|
||||
#[test]
|
||||
fn body_cell_vml_picture_stays_in_its_cell() {
|
||||
let pic = r##"<w:r><w:pict><v:shape type="#_x0000_t75" style="position:absolute;margin-left:0;margin-top:0;width:100pt;height:80pt;z-index:-1;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin"><v:imagedata r:id="rIdP"/></v:shape></w:pict></w:r>"##;
|
||||
let body = format!(r#"<w:tbl><w:tblGrid><w:gridCol w:w="4680"/></w:tblGrid><w:tr><w:tc><w:p>{pic}</w:p></w:tc></w:tr></w:tbl><w:p/>"#);
|
||||
let parts = [("word/media/p.png", "\u{89}PNG stand-in")];
|
||||
let d = wordcraft_docx::read(&docx(&body, &[("rIdP", "image", "media/p.png")], &parts)).unwrap();
|
||||
let Block::Table(t) = &*d.body[0] else { panic!("table first") };
|
||||
let floats: Vec<bool> = t.rows[0].cells[0]
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.flat_map(|p| p.objects.iter().filter_map(|o| o.frame()).map(|(_, _, f)| f.outside_cell))
|
||||
.collect();
|
||||
assert_eq!(floats, vec![false]);
|
||||
}
|
||||
|
||||
/// Issue #149: an absolutely positioned VML text box in a header floats where its style puts it
|
||||
/// (relative to the page here, behind the text at a negative z-index, no wrapping) instead of
|
||||
/// sitting inline in the header's flow, and it keeps that placement when saved and read back.
|
||||
@@ -1593,6 +1861,23 @@ fn theme_colour_without_a_theme_keeps_the_fixed_colour() {
|
||||
assert_eq!(paras(&d)[0].props_of_char(0).color, Some(TextColor::Rgb(Rgb(0, 0xFF, 0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underline_without_a_val_draws_no_underline() {
|
||||
// w:val has no schema default (ECMA-376 CT_Underline); Word leaves a bare w:u with a colour plain.
|
||||
let d = read_body(
|
||||
r#"<w:p><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>a</w:t></w:r><w:r><w:rPr><w:u w:color="FF0000"/></w:rPr><w:t>b</w:t></w:r><w:r><w:t>c</w:t></w:r></w:p>"#,
|
||||
);
|
||||
let p = paras(&d);
|
||||
assert_eq!(p[0].props_of_char(0).underline, Some(Underline::Single));
|
||||
let b = p[0].props_of_char(1);
|
||||
assert_eq!(b.underline, None);
|
||||
assert_eq!(b.underline_color, Some(Rgb(0xFF, 0, 0)), "the colour is still read");
|
||||
assert_eq!(p[0].props_of_char(2).underline, None);
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
let b = paras(&back)[0].props_of_char(1);
|
||||
assert_eq!((b.underline, b.underline_color), (None, Some(Rgb(0xFF, 0, 0))), "saving keeps the colour, not an underline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_font_wins_over_the_fixed_font() {
|
||||
let styles = r#"<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:rFonts w:ascii="Calibri Light" w:hAnsi="Calibri Light" w:asciiTheme="majorHAnsi" w:hAnsiTheme="majorHAnsi"/></w:rPr></w:style>"#;
|
||||
@@ -2518,6 +2803,277 @@ fn native_ink_preserves_inner_transform_and_rotation_padding_on_unrelated_saves(
|
||||
}
|
||||
}
|
||||
|
||||
// ---- native Word ink as a member of a group or a drawing canvas (gap 2) ----
|
||||
|
||||
const GROUP_URI: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup";
|
||||
const CANVAS_URI: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas";
|
||||
const W14_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordml";
|
||||
|
||||
/// A rectangle member `name` at `x` (EMU) in its group's space.
|
||||
fn rect_member(name: &str, x: u32) -> String {
|
||||
format!(
|
||||
r#"<wps:wsp><wps:cNvPr id="{x}" name="{name}"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="{x}" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr><wps:bodyPr/></wps:wsp>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// A native-ink member (`w14:contentPart`) at `x` (EMU), optionally inside `mc:AlternateContent`
|
||||
/// with a picture fallback.
|
||||
fn ink_member(x: u32, fallback: bool) -> String {
|
||||
let content = format!(
|
||||
r#"<w14:contentPart xmlns:w14="{W14_NS}" bwMode="auto" r:id="rInk"><w14:nvContentPartPr><w14:cNvPr id="9" name="Ink 9"/><w14:cNvContentPartPr/></w14:nvContentPartPr><w14:xfrm><a:off x="{x}" y="0"/><a:ext cx="914400" cy="457200"/></w14:xfrm></w14:contentPart>"#
|
||||
);
|
||||
if !fallback {
|
||||
return content;
|
||||
}
|
||||
format!(
|
||||
r#"<mc:AlternateContent><mc:Choice xmlns:wpi="{INK_NS}" Requires="wpi">{content}</mc:Choice><mc:Fallback><pic:pic><pic:nvPicPr><pic:cNvPr id="9" name="Ink 9"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rPreview"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="{x}" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></mc:Fallback></mc:AlternateContent>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// A document whose second paragraph holds a group (or canvas) of a rectangle, `ink` and another
|
||||
/// rectangle, in that order.
|
||||
fn nested_ink_docx(canvas: bool, ink: &str, fallback: bool) -> Vec<u8> {
|
||||
let members = format!("{}{ink}{}", rect_member("Before", 0), rect_member("After", 1828800));
|
||||
let graphic = if canvas {
|
||||
format!(r#"<a:graphicData uri="{CANVAS_URI}"><wpc:wpc xmlns:wpc="{CANVAS_URI}"><wpc:bg/><wpc:whole/>{members}</wpc:wpc></a:graphicData>"#)
|
||||
} else {
|
||||
format!(
|
||||
r#"<a:graphicData uri="{GROUP_URI}"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2743200" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="2743200" cy="914400"/></a:xfrm></wpg:grpSpPr>{members}</wpg:wgp></a:graphicData>"#
|
||||
)
|
||||
};
|
||||
let body = format!(
|
||||
r#"<w:p><w:r><w:t>Original</w:t></w:r></w:p><w:p><w:r><w:drawing><wp:inline><wp:extent cx="2743200" cy="914400"/><wp:docPr id="1" name="Group 1"/><a:graphic>{graphic}</a:graphic></wp:inline></w:drawing></w:r></w:p>"#
|
||||
);
|
||||
let mut relationships = vec![("rInk", "customXml", "ink/ink1.xml")];
|
||||
let mut extra = vec![("[Content_Types].xml", INK_TYPES), ("word/ink/ink1.xml", INK_XML)];
|
||||
if fallback {
|
||||
relationships.push(("rPreview", "image", "media/preview.png"));
|
||||
extra.push(("word/media/preview.png", "original preview bytes"));
|
||||
}
|
||||
docx(&body, &relationships, &extra)
|
||||
}
|
||||
|
||||
/// The members of the one group or canvas in `d`.
|
||||
fn group_children(d: &Document) -> Vec<wordcraft_doc::para::GroupChild> {
|
||||
let groups: Vec<_> = paras(d)
|
||||
.iter()
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Group { children, .. } => Some(children.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let [children] = groups.try_into().unwrap_or_else(|g: Vec<_>| panic!("expected one group, found {}", g.len()));
|
||||
children
|
||||
}
|
||||
|
||||
fn assert_ink_between_rects(d: &Document) {
|
||||
let c = group_children(d);
|
||||
let kinds: Vec<_> = c
|
||||
.iter()
|
||||
.map(|c| match &c.obj {
|
||||
InlineObject::Shape { .. } => "shape",
|
||||
InlineObject::Graphic { graphic, .. } if graphic.kind.noun() == "ink" => "ink",
|
||||
_ => "other",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(kinds, ["shape", "ink", "shape"], "the ink member keeps its place among the members");
|
||||
let ink = &c[1];
|
||||
assert_eq!((ink.x, ink.y), (72.0, 0.0));
|
||||
let InlineObject::Graphic { w, h, .. } = &ink.obj else { panic!() };
|
||||
assert_eq!((*w, *h), (72.0, 36.0));
|
||||
}
|
||||
|
||||
fn edit_first_para(d: &mut Document) {
|
||||
let p = std::sync::Arc::make_mut(&mut d.body[0]);
|
||||
let Block::Para(p) = p else { panic!() };
|
||||
p.delete(0, p.len()).unwrap();
|
||||
p.insert_text(0, "Edited", &Default::default()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_ink_in_a_group_or_canvas_survives_unrelated_edit_and_two_saves() {
|
||||
for canvas in [false, true] {
|
||||
for fallback in [false, true] {
|
||||
let what = format!("canvas {canvas}, fallback {fallback}");
|
||||
let mut d = wordcraft_docx::read(&nested_ink_docx(canvas, &ink_member(914400, fallback), fallback)).unwrap();
|
||||
assert_ink_between_rects(&d);
|
||||
edit_first_para(&mut d);
|
||||
for _ in 0..2 {
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let files = unzip(&out);
|
||||
check_ink(&files);
|
||||
let body = text(&files, "word/document.xml");
|
||||
assert!(body.contains("Edited"));
|
||||
let at = |s: &str| body.find(s).unwrap_or_else(|| panic!("{s} missing ({what}): {body}"));
|
||||
let ink = at("<w14:contentPart");
|
||||
assert!(at("<wps:wsp") < ink && body.rfind("<wps:wsp").unwrap() > ink, "member order lost ({what}): {body}");
|
||||
assert!(body.contains("<w14:nvContentPartPr>") && body.contains(r#"name="Ink 9""#), "{what}: {body}");
|
||||
let xfrm = &body[ink..];
|
||||
let xfrm = &xfrm[xfrm.find("<w14:xfrm").unwrap()..];
|
||||
assert_eq!(attr_values(xfrm, "a:off", "x").first().map(String::as_str), Some("914400"), "{what}");
|
||||
assert_eq!(attr_values(xfrm, "a:ext", "cx").first().map(String::as_str), Some("914400"), "{what}");
|
||||
if fallback {
|
||||
assert!(body.contains("<mc:Fallback>"), "{what}: {body}");
|
||||
let [id] = attr_values(&body, "a:blip", "r:embed").try_into().unwrap();
|
||||
let (_, target) = rel(&text(&files, "word/_rels/document.xml.rels"), &id);
|
||||
assert_eq!(text(&files, &part_at("word", &target)), "original preview bytes");
|
||||
}
|
||||
d = wordcraft_docx::read(&out).unwrap();
|
||||
assert_ink_between_rects(&d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_ink_in_a_group_shows_its_fallback_picture() {
|
||||
let d = wordcraft_docx::read(&nested_ink_docx(false, &ink_member(914400, true), true)).unwrap();
|
||||
let c = group_children(&d);
|
||||
let InlineObject::Graphic { graphic, .. } = &c[1].obj else { panic!() };
|
||||
assert!(
|
||||
graphic.items.iter().any(|item| matches!(item, wordcraft_doc::graphic::GraphicItem::Image { media, .. } if d.media.contains_key(media))),
|
||||
"{:?}",
|
||||
graphic.items
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_ink_in_a_nested_group_is_written_at_its_place_in_the_outer_group() {
|
||||
// The inner group doubles its members: 1 inch of its space is 2 inches of the outer group's.
|
||||
let inner = format!(
|
||||
r#"<wpg:grpSp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="1828800" cy="1828800"/><a:chOff x="0" y="0"/><a:chExt cx="914400" cy="914400"/></a:xfrm></wpg:grpSpPr>{}</wpg:grpSp>"#,
|
||||
ink_member(0, false)
|
||||
);
|
||||
let d = wordcraft_docx::read(&nested_ink_docx(false, &inner, false)).unwrap();
|
||||
let c = group_children(&d);
|
||||
let ink = c.iter().find(|c| matches!(c.obj, InlineObject::Graphic { .. })).expect("ink member kept");
|
||||
let InlineObject::Graphic { w, h, .. } = &ink.obj else { panic!() };
|
||||
assert_eq!((ink.x, ink.y, *w, *h), (72.0, 0.0, 144.0, 72.0));
|
||||
let files = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
check_ink(&files);
|
||||
let body = text(&files, "word/document.xml");
|
||||
let xfrm = &body[body.find("<w14:xfrm").unwrap()..];
|
||||
assert_eq!(attr_values(xfrm, "a:off", "x").first().map(String::as_str), Some("914400"));
|
||||
assert_eq!(attr_values(xfrm, "a:ext", "cx").first().map(String::as_str), Some("1828800"));
|
||||
assert_eq!(attr_values(xfrm, "a:ext", "cy").first().map(String::as_str), Some("914400"));
|
||||
}
|
||||
|
||||
/// Ink parts share the custom XML relationship type with real custom XML stores: the store is
|
||||
/// carried as before, the ink part only with the ink that refers to it.
|
||||
#[test]
|
||||
fn custom_xml_store_beside_native_ink_is_kept_and_ink_leaves_no_orphan() {
|
||||
const STORE: &str = r#"<?xml version="1.0" encoding="UTF-8"?><data xmlns="urn:example:store"><item>kept</item></data>"#;
|
||||
let types = INK_TYPES.replace("<Default ", r#"<Override PartName="/customXml/item1.xml" ContentType="application/xml"/><Default "#);
|
||||
let mut files = unzip(&nested_ink_docx(false, &ink_member(914400, false), false));
|
||||
let rels = text(&files, "word/_rels/document.xml.rels").replace(
|
||||
"</Relationships>",
|
||||
r#"<Relationship Id="rStore" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml" Target="../customXml/item1.xml"/></Relationships>"#,
|
||||
);
|
||||
files.insert("word/_rels/document.xml.rels".into(), rels.into_bytes());
|
||||
files.insert("[Content_Types].xml".into(), types.into_bytes());
|
||||
files.insert("customXml/item1.xml".into(), STORE.as_bytes().to_vec());
|
||||
let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect();
|
||||
let mut d = wordcraft_docx::read(&zip(&entries)).unwrap();
|
||||
let out = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
check_ink(&out);
|
||||
assert!(out.values().any(|b| b == STORE.as_bytes()), "the store is kept");
|
||||
assert_eq!(out.values().filter(|b| *b == INK_XML.as_bytes()).count(), 1, "one ink part, not a second copy as a store");
|
||||
// Without the ink the store stays and the ink part goes.
|
||||
d.body.truncate(1);
|
||||
let out = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(out.values().any(|b| b == STORE.as_bytes()), "the store is kept");
|
||||
assert!(!out.values().any(|b| b == INK_XML.as_bytes()), "orphan ink part: {:?}", out.keys().collect::<Vec<_>>());
|
||||
assert!(!text(&out, "[Content_Types].xml").contains("inkml"));
|
||||
assert_eq!(text(&out, "word/_rels/document.xml.rels").matches("/customXml\"").count(), 1, "only the store's relationship");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_drawing_level_native_ink_writes_no_orphan_ink_part() {
|
||||
for fallback in [false, true] {
|
||||
let mut d = wordcraft_docx::read(&ink_docx(fallback, false)).unwrap();
|
||||
assert_eq!(graphics(&d).len(), 1);
|
||||
d.body.truncate(1);
|
||||
let files = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(!files.values().any(|b| b == INK_XML.as_bytes()), "orphan ink part: {:?}", files.keys().collect::<Vec<_>>());
|
||||
assert!(!text(&files, "[Content_Types].xml").contains("inkml"));
|
||||
assert!(!text(&files, "word/_rels/document.xml.rels").contains("customXml"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A group member's ink taken out of its group (not something WordCraft's commands do: Ungroup
|
||||
/// refuses such a group) can't be written as a stand-alone drawing: it is left out whole, never
|
||||
/// written in the wrong place, and its parts aren't written either.
|
||||
#[test]
|
||||
fn group_member_ink_on_its_own_is_left_out_without_orphans() {
|
||||
for fallback in [false, true] {
|
||||
let d = wordcraft_docx::read(&nested_ink_docx(false, &ink_member(914400, fallback), fallback)).unwrap();
|
||||
let ink = group_children(&d).into_iter().find(|c| matches!(c.obj, InlineObject::Graphic { .. })).expect("ink member").obj;
|
||||
let mut d = d;
|
||||
d.body.truncate(1);
|
||||
let mut p = Paragraph::new();
|
||||
p.insert_object(0, ink, &Default::default()).unwrap();
|
||||
d.body.push(wordcraft_doc::para_block(p));
|
||||
let files = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
let body = text(&files, "word/document.xml");
|
||||
assert!(!body.contains("contentPart"), "fallback {fallback}: {body}");
|
||||
assert!(!files.values().any(|b| b == INK_XML.as_bytes()), "orphan ink part: {:?}", files.keys().collect::<Vec<_>>());
|
||||
assert!(!text(&files, "word/_rels/document.xml.rels").contains("customXml"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_group_with_native_ink_writes_no_orphan_ink_part() {
|
||||
let mut d = wordcraft_docx::read(&nested_ink_docx(false, &ink_member(914400, true), true)).unwrap();
|
||||
d.body.truncate(1);
|
||||
let files = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(!text(&files, "word/document.xml").contains("contentPart"));
|
||||
assert!(!files.values().any(|b| b == INK_XML.as_bytes()), "orphan ink part: {:?}", files.keys().collect::<Vec<_>>());
|
||||
assert!(!text(&files, "[Content_Types].xml").contains("inkml"));
|
||||
assert!(!text(&files, "word/_rels/document.xml.rels").contains("customXml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_native_ink_in_a_group_never_panics() {
|
||||
// A dangling relationship, a missing part, or a part that isn't InkML: the ink member is
|
||||
// dropped (as drawing-level ink is), the other members stay.
|
||||
for fallback in [false, true] {
|
||||
for case in ["dangling", "missing", "wrong type"] {
|
||||
let mut files = unzip(&nested_ink_docx(false, &ink_member(914400, fallback), fallback));
|
||||
match case {
|
||||
"dangling" => {
|
||||
let body = text(&files, "word/document.xml").replace(r#"r:id="rInk""#, r#"r:id="rNowhere""#);
|
||||
files.insert("word/document.xml".into(), body.into_bytes());
|
||||
}
|
||||
"missing" => {
|
||||
files.remove("word/ink/ink1.xml");
|
||||
}
|
||||
_ => {
|
||||
let types = text(&files, "[Content_Types].xml").replace("application/inkml+xml", "application/xml");
|
||||
files.insert("[Content_Types].xml".into(), types.into_bytes());
|
||||
}
|
||||
}
|
||||
let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect();
|
||||
let d = wordcraft_docx::read(&zip(&entries)).unwrap();
|
||||
let c = group_children(&d);
|
||||
assert!(!c.iter().any(|c| matches!(c.obj, InlineObject::Graphic { .. })), "{case}");
|
||||
// With a picture fallback the picture takes the ink's place.
|
||||
let pictures = c.iter().filter(|c| matches!(c.obj, InlineObject::Image { .. })).count();
|
||||
assert_eq!(c.len(), if fallback { 3 } else { 2 }, "{case}, fallback {fallback}");
|
||||
assert_eq!(pictures, usize::from(fallback), "{case}");
|
||||
let out = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(!text(&out, "word/document.xml").contains("contentPart"), "{case}");
|
||||
}
|
||||
}
|
||||
// A garbled ink part is kept as it is: InkML stays opaque.
|
||||
let mut files = unzip(&nested_ink_docx(true, &ink_member(914400, false), false));
|
||||
files.insert("word/ink/ink1.xml".into(), vec![0xff, 0x00, b'<', 0xfe]);
|
||||
let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect();
|
||||
let d = wordcraft_docx::read(&zip(&entries)).unwrap();
|
||||
let out = unzip(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(out.values().any(|b| b == &[0xff, 0x00, b'<', 0xfe]));
|
||||
}
|
||||
|
||||
/// Word draws a table of contents' entry links without the Hyperlink character style (measured in
|
||||
/// Word for Windows); the import drops the style from them, keeping the link. A Hyperlink-styled run
|
||||
/// outside a hyperlink, and a hyperlink in another field, keep it.
|
||||
@@ -2830,3 +3386,157 @@ fn row_table_borders_round_trip() {
|
||||
let again = wordcraft_docx::read(&saved).unwrap();
|
||||
assert_eq!(d.body, again.body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_result_keeps_run_props() {
|
||||
let styles = format!(
|
||||
r#"<w:styles {W_NS}><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:rPr><w:sz w:val="8"/></w:rPr></w:style><w:style w:type="character" w:styleId="Result"><w:name w:val="Result"/><w:rPr><w:sz w:val="16"/><w:b/></w:rPr></w:style></w:styles>"#
|
||||
);
|
||||
for result_pr in [r#"<w:sz w:val="16"/><w:b/>"#, r#"<w:rStyle w:val="Result"/>"#, ""] {
|
||||
for simple in [false, true] {
|
||||
let result = format!(r#"<w:r><w:rPr>{result_pr}</w:rPr><w:t>7</w:t></w:r>"#);
|
||||
let field = if simple {
|
||||
format!(r#"<w:fldSimple w:instr="PAGE" w:fldLock="1" w:dirty="1">{result}</w:fldSimple>"#)
|
||||
} else {
|
||||
format!(
|
||||
r#"<w:r><w:rPr><w:sz w:val="6"/><w:i/></w:rPr><w:fldChar w:fldCharType="begin" w:fldLock="1" w:dirty="1"/></w:r><w:r><w:instrText>PAGE</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:t/></w:r>{result}<w:r><w:rPr><w:sz w:val="50"/></w:rPr><w:fldChar w:fldCharType="end"/></w:r>"#
|
||||
)
|
||||
};
|
||||
let body = format!(r#"<w:p><w:r><w:rPr><w:sz w:val="16"/></w:rPr><w:t>Counter </w:t></w:r>{field}</w:p>"#);
|
||||
let mut d = wordcraft_docx::read(&docx(&body, &[("styles", "styles", "styles.xml")], &[("word/styles.xml", &styles)])).unwrap();
|
||||
for _ in 0..2 {
|
||||
let p = paras(&d)[0];
|
||||
let props = p.props_of_char("Counter ".len());
|
||||
assert_eq!(p.props_at(0).size, Some(8.0));
|
||||
assert_eq!(props.size, result_pr.starts_with("<w:sz").then_some(8.0), "simple={simple}, result={result_pr}");
|
||||
assert_eq!(props.style.as_deref(), result_pr.starts_with("<w:rStyle").then_some("Result"));
|
||||
assert_eq!(props.italic, None);
|
||||
assert!(
|
||||
matches!(&p.objects[0], InlineObject::Field { instr, result, locked: true, dirty: true, .. } if instr == "PAGE" && result == "7")
|
||||
);
|
||||
d = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_field_keeps_begin_props() {
|
||||
let d = read_body(
|
||||
r#"<w:p><w:r><w:rPr><w:sz w:val="12"/><w:i/></w:rPr><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText>PAGE</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:t/></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#,
|
||||
);
|
||||
let p = paras(&d)[0];
|
||||
assert_eq!(p.props_at(0).size, Some(6.0));
|
||||
assert_eq!(p.props_at(0).italic, Some(true));
|
||||
assert!(matches!(&p.objects[0], InlineObject::Field { result, .. } if result.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_dashes_import_and_save() {
|
||||
use wordcraft_doc::line_dash::LineDash;
|
||||
for (xml, expected) in [
|
||||
(r#"<a:prstDash val="dash"/>"#, LineDash::Dash),
|
||||
(r#"<a:prstDash val="sysDashDot"/>"#, LineDash::SystemDashDot),
|
||||
(
|
||||
r#"<a:custDash><a:ds d="400000" sp="300000"/><a:ds d="100000" sp="300000"/></a:custDash>"#,
|
||||
LineDash::Custom(vec![(400_000, 300_000), (100_000, 300_000)]),
|
||||
),
|
||||
(r#"<a:custDash><a:ds d="400%" sp="300%"/></a:custDash>"#, LineDash::Custom(vec![(400_000, 300_000)])),
|
||||
(r#"<a:custDash><a:ds d="NaN%" sp="-1"/></a:custDash>"#, LineDash::Solid),
|
||||
(r#"<a:prstDash val="solid"/>"#, LineDash::Solid),
|
||||
("", LineDash::Solid),
|
||||
] {
|
||||
let sppr = format!(r#"<a:prstGeom prst="rect"/><a:noFill/><a:ln w="12700"><a:solidFill><a:srgbClr val="C00000"/></a:solidFill>{xml}</a:ln>"#);
|
||||
let body = anchored_wsp("Annotation", 889000, 355600, &sppr, "", "<wps:cNvSpPr/>");
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
let saved = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
for doc in [&d, &saved] {
|
||||
let InlineObject::Shape { w, h, stroke, stroke_width, extra, .. } = ¶s(doc)[0].objects[0] else { panic!("shape") };
|
||||
assert_eq!(extra.dash, expected);
|
||||
assert_eq!((*w, *h, *stroke, *stroke_width), (70.0, 28.0, Some(Rgb(192, 0, 0)), 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_end_name_and_id_trim() {
|
||||
let body = r#"<w:p>
|
||||
<w:bookmarkStart w:id=" 42 " w:name="section_intro"/>
|
||||
<w:r><w:t>Hello</w:t></w:r>
|
||||
<w:bookmarkEnd w:id="42"/>
|
||||
<w:bookmarkEnd w:id="999" w:name="standalone_target"/>
|
||||
</w:p>"#;
|
||||
let doc = wordcraft_docx::read(&docx(body, &[], &[])).unwrap();
|
||||
let p = doc.body.first().unwrap().as_para().unwrap();
|
||||
let names: Vec<(&'static str, String)> = p
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::BookmarkStart { name } => Some(("start", name.clone())),
|
||||
InlineObject::BookmarkEnd { name } => Some(("end", name.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(names, vec![("start", "section_intro".into()), ("end", "section_intro".into()), ("end", "standalone_target".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_effects_stay_zero_rotated() {
|
||||
const ANGLE_UNITS_PER_DEGREE: i32 = 60_000;
|
||||
|
||||
// ECMA-376 §20.4.2.6: zero effect extents add no space around a rotated picture.
|
||||
for degrees in [0, 90, 180, 270] {
|
||||
for effects in ["", r#"<wp:effectExtent l="0" t="0" r="0" b="0"/>"#] {
|
||||
let body = format!(
|
||||
r#"<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="457200"/>{effects}<wp:docPr id="1" name="Synthetic picture"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm rot="{}"><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#,
|
||||
degrees * ANGLE_UNITS_PER_DEGREE
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(&body, &[("rId1", "image", "media/marker.png")], &[("word/media/marker.png", "synthetic")])).unwrap();
|
||||
let (w, h, float) = paras(&d)[0].objects[0].frame().unwrap();
|
||||
assert_eq!(float.rot, degrees as f32);
|
||||
assert_eq!(float.effect, [0.0; 4], "rotation {degrees} must not invent effects");
|
||||
let (px, py) = float.spin_pad(w, h);
|
||||
let expected = if degrees % 180 == 0 { (w, h) } else { (h, w) };
|
||||
assert!((w + 2.0 * px - expected.0).abs() < 0.001);
|
||||
assert!((h + 2.0 * py - expected.1).abs() < 0.001);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The math namespace, declared on the math element itself (the fixture root doesn't).
|
||||
const M_NS: &str = r#"xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math""#;
|
||||
|
||||
fn equations(p: &Paragraph) -> Vec<(String, bool)> {
|
||||
p.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Equation { linear, display, .. } => Some((linear.clone(), *display)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// #1273: an equation straight in the body (EG_BlockLevelElts allows math content) gets a
|
||||
/// paragraph of its own instead of vanishing.
|
||||
#[test]
|
||||
fn body_level_equation_is_kept() {
|
||||
let d = read_body(&format!(
|
||||
r#"<w:p><w:r><w:t>before</w:t></w:r></w:p><m:oMathPara {M_NS}><m:oMath><m:r><m:t>a=b</m:t></m:r></m:oMath></m:oMathPara><m:oMath {M_NS}><m:r><m:t>c</m:t></m:r></m:oMath><w:p><w:r><w:t>after</w:t></w:r></w:p>"#
|
||||
));
|
||||
let ps = paras(&d);
|
||||
assert_eq!(ps.len(), 4, "{:?}", ps.iter().map(|p| p.plain_text()).collect::<Vec<_>>());
|
||||
assert_eq!(equations(ps[1]), vec![("a=b".to_string(), true)]);
|
||||
assert_eq!(equations(ps[2]), vec![("c".to_string(), false)]);
|
||||
}
|
||||
|
||||
/// #1273: an equation guarded by markup compatibility (`Requires="m"`) is read as an equation,
|
||||
/// not replaced by its fallback.
|
||||
#[test]
|
||||
fn equation_in_alternate_content_is_read() {
|
||||
let d = read_body(&format!(
|
||||
r#"<w:p><mc:AlternateContent {M_NS}><mc:Choice Requires="m"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></mc:Choice><mc:Fallback><w:r><w:t>[picture]</w:t></w:r></mc:Fallback></mc:AlternateContent></w:p>"#
|
||||
));
|
||||
let p = paras(&d)[0];
|
||||
assert_eq!(equations(p), vec![("x+1".to_string(), false)]);
|
||||
assert!(!p.plain_text().contains("[picture]"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
//! The glossary document (ECMA-376 §17.12: building blocks, Quick Parts, AutoText): kept byte
|
||||
//! for byte while unchanged, read into `Document::glossary`, and written from the model once
|
||||
//! edited. Hand-written fixtures (from the spec), no files produced by Word.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::{Block, BuildingBlock, CharProps, Document, Paragraph, para_block};
|
||||
|
||||
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
const R_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
const GLOSSARY_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument";
|
||||
const GLOSSARY_CT: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml";
|
||||
|
||||
fn zip(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
assert!(out.insert(f.name().to_string(), b).is_none(), "duplicate part {}", f.name());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn text(files: &BTreeMap<String, Vec<u8>>, name: &str) -> String {
|
||||
String::from_utf8(files.get(name).unwrap_or_else(|| panic!("no {name} in {:?}", files.keys())).clone()).unwrap()
|
||||
}
|
||||
|
||||
fn rels(list: &[(&str, &str, &str)]) -> String {
|
||||
let mut s =
|
||||
String::from(r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for (id, ty, target) in list {
|
||||
s.push_str(&format!(r#"<Relationship Id="{id}" Type="{ty}" Target="{target}"/>"#));
|
||||
}
|
||||
s.push_str("</Relationships>");
|
||||
s
|
||||
}
|
||||
|
||||
fn content_types(extra: &[(&str, &str)]) -> String {
|
||||
let mut s = String::from(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>"#,
|
||||
);
|
||||
for (part, ct) in extra {
|
||||
s.push_str(&format!(r#"<Override PartName="{part}" ContentType="{ct}"/>"#));
|
||||
}
|
||||
s.push_str("</Types>");
|
||||
s
|
||||
}
|
||||
|
||||
/// A package with body text, a main document relating to `doc_rels`, and `extra` parts.
|
||||
fn package(doc_rels: &[(&str, &str, &str)], extra: &[(&str, String)]) -> Vec<u8> {
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:r="{R_NS}"><w:body><w:p><w:r><w:t>Body</w:t></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let root = rels(&[("rIdMain", &format!("{REL}/officeDocument"), "word/document.xml")]);
|
||||
let mut entries: Vec<(&str, Vec<u8>)> = vec![
|
||||
("_rels/.rels", root.into_bytes()),
|
||||
("word/document.xml", doc.into_bytes()),
|
||||
("word/_rels/document.xml.rels", rels(doc_rels).into_bytes()),
|
||||
];
|
||||
for (p, c) in extra {
|
||||
entries.push((p, c.as_bytes().to_vec()));
|
||||
}
|
||||
zip(&entries)
|
||||
}
|
||||
|
||||
fn glossary_xml(doc_parts: &str) -> String {
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:glossaryDocument xmlns:w="{W}" xmlns:r="{R_NS}"><w:docParts>{doc_parts}</w:docParts></w:glossaryDocument>"#
|
||||
)
|
||||
}
|
||||
|
||||
const SIGNATURE: &str = r#"<w:docPart><w:docPartPr><w:name w:val="Signature"/><w:style w:val="Normal"/><w:category><w:name w:val="General"/><w:gallery w:val="docParts"/></w:category><w:types><w:type w:val="normal"/></w:types><w:behaviors><w:behavior w:val="content"/></w:behaviors><w:description w:val="A closing line"/><w:guid w:val="{0F1E2D3C-4B5A-6978-8796-A5B4C3D2E1F0}"/></w:docPartPr><w:docPartBody><w:p><w:r><w:t>Kind regards, Ann</w:t></w:r></w:p></w:docPartBody></w:docPart>"#;
|
||||
const PRICES: &str = r#"<w:docPart><w:docPartPr><w:name w:val="Price table"/><w:category><w:name w:val="Sales"/><w:gallery w:val="autoTxt"/></w:category><w:types><w:type w:val="bbPlcHdr"/><w:type w:val="autoExp"/><w:type w:val="madeUp"/></w:types><w:behaviors><w:behavior w:val="p"/><w:behavior w:val="pg"/></w:behaviors><w:guid w:val="{11111111-2222-3333-4444-555555555555}"/></w:docPartPr><w:docPartBody><w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>Item</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Price</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:t>Prices exclude tax.</w:t></w:r></w:p></w:docPartBody></w:docPart>"#;
|
||||
const GLOSSARY_STYLES: &str = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#;
|
||||
const GLOSSARY_WEB: &str =
|
||||
r#"<w:webSettings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:optimizeForBrowser/></w:webSettings>"#;
|
||||
|
||||
/// A document whose glossary holds a Quick Part and an AutoText entry (with a table), with the
|
||||
/// glossary's own styles and web settings.
|
||||
fn with_glossary() -> Vec<u8> {
|
||||
package(
|
||||
&[("rId7", GLOSSARY_REL, "glossary/document.xml")],
|
||||
&[
|
||||
(
|
||||
"[Content_Types].xml",
|
||||
content_types(&[
|
||||
("/word/glossary/document.xml", GLOSSARY_CT),
|
||||
("/word/glossary/styles.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"),
|
||||
("/word/glossary/webSettings.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"),
|
||||
]),
|
||||
),
|
||||
("word/glossary/document.xml", glossary_xml(&format!("{SIGNATURE}{PRICES}"))),
|
||||
(
|
||||
"word/glossary/_rels/document.xml.rels",
|
||||
rels(&[("rId1", &format!("{REL}/styles"), "styles.xml"), ("rId2", &format!("{REL}/webSettings"), "webSettings.xml")]),
|
||||
),
|
||||
("word/glossary/styles.xml", GLOSSARY_STYLES.to_string()),
|
||||
("word/glossary/webSettings.xml", GLOSSARY_WEB.to_string()),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn save(doc: &Document) -> BTreeMap<String, Vec<u8>> {
|
||||
unzip(&wordcraft_docx::write(doc).expect("write"))
|
||||
}
|
||||
|
||||
fn block_text(b: &Block) -> String {
|
||||
match b {
|
||||
Block::Para(p) => p.text.clone(),
|
||||
Block::Table(t) => {
|
||||
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).map(|b| block_text(b)).collect::<Vec<_>>().join("|")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn entry_text(e: &BuildingBlock) -> String {
|
||||
e.blocks.iter().map(|b| block_text(b)).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
/// The glossary part a saved package's main document relates to.
|
||||
fn glossary_target(files: &BTreeMap<String, Vec<u8>>) -> Option<String> {
|
||||
let doc_rels = text(files, "word/_rels/document.xml.rels");
|
||||
assert!(doc_rels.matches("/glossaryDocument\"").count() <= 1, "{doc_rels}");
|
||||
let at = doc_rels.find("/glossaryDocument\"")?;
|
||||
let rest = doc_rels.get(at..)?;
|
||||
let t = rest.find("Target=\"")? + "Target=\"".len();
|
||||
let end = rest.get(t..)?.find('"')?;
|
||||
Some(format!("word/{}", rest.get(t..t + end)?))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_glossary_is_carried_byte_for_byte() {
|
||||
let bytes = with_glossary();
|
||||
let mut doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
doc.body.push(para_block(Paragraph::with_text("Added after opening", CharProps::default())));
|
||||
let files = save(&doc);
|
||||
let input = unzip(&bytes);
|
||||
assert_eq!(glossary_target(&files).as_deref(), Some("word/glossary/document.xml"));
|
||||
for part in ["word/glossary/document.xml", "word/glossary/styles.xml", "word/glossary/webSettings.xml"] {
|
||||
assert_eq!(files.get(part), input.get(part), "{part} not carried verbatim");
|
||||
}
|
||||
let grels = text(&files, "word/glossary/_rels/document.xml.rels");
|
||||
assert!(grels.contains("styles.xml") && grels.contains("webSettings.xml"), "{grels}");
|
||||
let ct = text(&files, "[Content_Types].xml");
|
||||
assert!(ct.contains(&format!(r#"PartName="/word/glossary/document.xml" ContentType="{GLOSSARY_CT}""#)), "{ct}");
|
||||
assert!(ct.contains(r#"PartName="/word/glossary/styles.xml""#), "{ct}");
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(again.glossary.len(), 2);
|
||||
assert!(again.plain_text(wordcraft_doc::StoryRef::Body).contains("Added after opening"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glossary_entries_are_read_into_the_model() {
|
||||
let doc = wordcraft_docx::read(&with_glossary()).unwrap();
|
||||
let g = &doc.glossary;
|
||||
assert_eq!(g.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["Signature", "Price table"]);
|
||||
let sig = &g[0];
|
||||
assert_eq!((sig.gallery.as_str(), sig.category.as_str()), ("docParts", "General"));
|
||||
assert_eq!(sig.description, "A closing line");
|
||||
assert_eq!(sig.guid, "{0F1E2D3C-4B5A-6978-8796-A5B4C3D2E1F0}");
|
||||
assert_eq!(
|
||||
(sig.style.as_str(), sig.types.as_slice(), sig.behaviors.as_slice()),
|
||||
("Normal", &["normal".to_string()][..], &["content".to_string()][..])
|
||||
);
|
||||
assert_eq!(entry_text(sig), "Kind regards, Ann");
|
||||
let prices = &g[1];
|
||||
assert_eq!((prices.gallery.as_str(), prices.category.as_str()), ("autoTxt", "Sales"));
|
||||
// Types and behaviours outside the spec's lists aren't kept.
|
||||
assert_eq!(prices.types, ["bbPlcHdr", "autoExp"]);
|
||||
assert_eq!(prices.behaviors, ["p", "pg"]);
|
||||
assert!(matches!(&*prices.blocks[0], Block::Table(_)), "{:?}", prices.blocks);
|
||||
assert_eq!(entry_text(prices), "Item|Price\nPrices exclude tax.");
|
||||
// The glossary's text isn't the document's.
|
||||
assert!(!doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Kind regards"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_glossary_is_written_from_the_model() {
|
||||
let mut doc = wordcraft_docx::read(&with_glossary()).unwrap();
|
||||
doc.glossary[0].name = "Sign-off".into();
|
||||
let num = doc.numbering.add_list(wordcraft_doc::ListKind::Bullet);
|
||||
let mut listed = Paragraph::with_text("Second line", CharProps::default());
|
||||
listed.props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 0 });
|
||||
doc.glossary.push(BuildingBlock {
|
||||
name: "Address".into(),
|
||||
gallery: "docParts".into(),
|
||||
category: "General".into(),
|
||||
blocks: vec![para_block(Paragraph::with_text("1 Main Street", CharProps::default())), para_block(listed)],
|
||||
..Default::default()
|
||||
});
|
||||
let files = save(&doc);
|
||||
let target = glossary_target(&files).expect("a glossary relationship");
|
||||
let g = text(&files, &target);
|
||||
assert!(g.contains("w:glossaryDocument") && g.contains("Sign-off") && g.contains("1 Main Street"), "{g}");
|
||||
assert!(!files.values().any(|b| String::from_utf8_lossy(b).contains(r#"w:val="Signature""#)), "the old glossary is gone");
|
||||
let ct = text(&files, "[Content_Types].xml");
|
||||
assert!(ct.contains(&format!(r#"PartName="/{target}" ContentType="{GLOSSARY_CT}""#)), "{ct}");
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(again.glossary.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["Sign-off", "Price table", "Address"]);
|
||||
assert_eq!(entry_text(&again.glossary[1]), "Item|Price\nPrices exclude tax.");
|
||||
assert_eq!(again.glossary[1].gallery, "autoTxt");
|
||||
assert_eq!(again.glossary[0].guid, "{0F1E2D3C-4B5A-6978-8796-A5B4C3D2E1F0}");
|
||||
assert_eq!(again.glossary[0].description, "A closing line");
|
||||
assert_eq!(entry_text(&again.glossary[2]), "1 Main Street\nSecond line");
|
||||
// Style, types and behaviours survive the rewrite.
|
||||
for (a, b) in again.glossary.iter().zip(&doc.glossary) {
|
||||
assert_eq!((&a.style, &a.types, &a.behaviors), (&b.style, &b.types, &b.behaviors), "{}", a.name);
|
||||
}
|
||||
assert_eq!(again.glossary[1].types, ["bbPlcHdr", "autoExp"]);
|
||||
assert_eq!(again.glossary[1].behaviors, ["p", "pg"]);
|
||||
assert_eq!(again.glossary[0].style, "Normal");
|
||||
// A list in an entry has its definitions beside the glossary (its own numbering part).
|
||||
let grels = text(&files, &glossary_rels(&target));
|
||||
assert!(grels.contains("/numbering\""), "{grels}");
|
||||
let numbering = grels.split("/numbering\" Target=\"").nth(1).and_then(|r| r.split('"').next()).expect("numbering target");
|
||||
let numbering = text(&files, &format!("word/{numbering}"));
|
||||
assert!(numbering.contains("w:abstractNum") && numbering.contains(&format!(r#"w:numId="{num}""#)), "{numbering}");
|
||||
// Saving the reopened document again keeps its (now unchanged) glossary verbatim.
|
||||
let twice = save(&again);
|
||||
assert_eq!(glossary_target(&twice).as_deref(), Some(target.as_str()));
|
||||
assert_eq!(twice.get(&target), files.get(&target));
|
||||
}
|
||||
|
||||
/// The relationships part of a part in `word/`.
|
||||
fn glossary_rels(part: &str) -> String {
|
||||
let (dir, file) = part.rsplit_once('/').unwrap();
|
||||
format!("{dir}/_rels/{file}.rels")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_glossary_whose_bytes_werent_kept_is_written_from_the_model() {
|
||||
let mut doc = wordcraft_docx::read(&with_glossary()).unwrap();
|
||||
// The verbatim copy is gone (over the kept-part caps, say): the model is all there is.
|
||||
doc.passthrough.remove("word/glossary/document.xml");
|
||||
let files = save(&doc);
|
||||
let target = glossary_target(&files).expect("a glossary relationship");
|
||||
assert!(text(&files, &target).contains("Kind regards, Ann"));
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(again.glossary.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["Signature", "Price table"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_external_glossary_relationship_is_passed_over() {
|
||||
let doc_rels = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId6" Type="{GLOSSARY_REL}" Target="https://example.com/g.xml" TargetMode="External"/><Relationship Id="rId7" Type="{GLOSSARY_REL}" Target="glossary/document.xml"/></Relationships>"#
|
||||
);
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:r="{R_NS}"><w:body><w:p><w:r><w:t>Body</w:t></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let bytes = zip(&[
|
||||
("[Content_Types].xml", content_types(&[("/word/glossary/document.xml", GLOSSARY_CT)]).into_bytes()),
|
||||
("_rels/.rels", rels(&[("rIdMain", &format!("{REL}/officeDocument"), "word/document.xml")]).into_bytes()),
|
||||
("word/document.xml", doc.into_bytes()),
|
||||
("word/_rels/document.xml.rels", doc_rels.into_bytes()),
|
||||
("word/glossary/document.xml", glossary_xml(SIGNATURE).into_bytes()),
|
||||
]);
|
||||
let doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(doc.glossary.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["Signature"]);
|
||||
// The same glossary is the one kept: saved unchanged, it's written back as it was.
|
||||
let files = save(&doc);
|
||||
assert_eq!(files.get("word/glossary/document.xml"), unzip(&bytes).get("word/glossary/document.xml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_without_glossary_writes_none() {
|
||||
let files = save(&Document::new());
|
||||
assert_eq!(glossary_target(&files), None);
|
||||
assert!(!text(&files, "[Content_Types].xml").contains("glossary"));
|
||||
// Removing every entry removes the glossary.
|
||||
let mut doc = wordcraft_docx::read(&with_glossary()).unwrap();
|
||||
doc.glossary.clear();
|
||||
let files = save(&doc);
|
||||
assert_eq!(glossary_target(&files), None);
|
||||
assert!(!files.keys().any(|k| k.contains("glossary")), "{:?}", files.keys());
|
||||
assert!(!text(&files, "[Content_Types].xml").contains("glossary"));
|
||||
assert!(wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap().glossary.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_entry_in_a_new_document_makes_a_glossary() {
|
||||
let mut doc = Document::new();
|
||||
doc.glossary.push(BuildingBlock {
|
||||
name: "Greeting".into(),
|
||||
gallery: "docParts".into(),
|
||||
category: "General".into(),
|
||||
blocks: vec![para_block(Paragraph::with_text("Hello there", CharProps::default()))],
|
||||
..Default::default()
|
||||
});
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(again.glossary.len(), 1);
|
||||
assert_eq!(again.glossary[0].name, "Greeting");
|
||||
assert_eq!(entry_text(&again.glossary[0]), "Hello there");
|
||||
assert!(again.plain_text(wordcraft_doc::StoryRef::Body).trim().is_empty());
|
||||
}
|
||||
|
||||
/// Hostile glossaries open without a panic; entries that can't be read are skipped.
|
||||
#[test]
|
||||
fn hostile_glossaries_never_panic() {
|
||||
let ct = content_types(&[("/word/glossary/document.xml", GLOSSARY_CT)]);
|
||||
let one = |g: String| {
|
||||
package(&[("rId7", GLOSSARY_REL, "glossary/document.xml")], &[("[Content_Types].xml", ct.clone()), ("word/glossary/document.xml", g)])
|
||||
};
|
||||
let read = |bytes: Vec<u8>| -> Document {
|
||||
let doc = wordcraft_docx::read(&bytes).unwrap();
|
||||
// Saving and reopening must not panic either.
|
||||
let _ = wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap();
|
||||
doc
|
||||
};
|
||||
// No body, an empty body, no name, no properties: skipped.
|
||||
let doc = read(one(glossary_xml(
|
||||
r#"<w:docPart><w:docPartPr><w:name w:val="NoBody"/></w:docPartPr></w:docPart><w:docPart><w:docPartPr><w:name w:val="Empty"/></w:docPartPr><w:docPartBody/></w:docPart><w:docPart><w:docPartPr/><w:docPartBody><w:p><w:r><w:t>nameless</w:t></w:r></w:p></w:docPartBody></w:docPart><w:docPart><w:docPartBody><w:p/></w:docPartBody></w:docPart>"#,
|
||||
)));
|
||||
assert!(doc.glossary.iter().all(|e| !e.name.is_empty() && !e.blocks.is_empty()), "{:?}", doc.glossary);
|
||||
assert!(doc.glossary.iter().all(|e| e.name != "NoBody"));
|
||||
// Duplicate names: both read, file order.
|
||||
let doc = read(one(glossary_xml(&format!("{SIGNATURE}{SIGNATURE}"))));
|
||||
assert_eq!(doc.glossary.len(), 2);
|
||||
// Huge counts are capped.
|
||||
let many: String = (0..12_000)
|
||||
.map(|i| format!(r#"<w:docPart><w:docPartPr><w:name w:val="e{i}"/></w:docPartPr><w:docPartBody><w:p/></w:docPartBody></w:docPart>"#))
|
||||
.collect();
|
||||
let doc = read(one(glossary_xml(&many)));
|
||||
assert!(doc.glossary.len() <= 10_000, "{}", doc.glossary.len());
|
||||
// Deep nesting (tables in tables).
|
||||
let deep = format!(
|
||||
r#"<w:docPart><w:docPartPr><w:name w:val="Deep"/></w:docPartPr><w:docPartBody>{}<w:p/>{}</w:docPartBody></w:docPart>"#,
|
||||
"<w:tbl><w:tr><w:tc>".repeat(400),
|
||||
"</w:tc></w:tr></w:tbl>".repeat(400)
|
||||
);
|
||||
let _ = read(one(glossary_xml(&deep)));
|
||||
// Not a glossary at all, or a wrong content type: nothing read.
|
||||
let doc = read(one(format!(r#"<w:document xmlns:w="{W}"><w:body><w:p><w:r><w:t>x</w:t></w:r></w:p></w:body></w:document>"#)));
|
||||
assert!(doc.glossary.is_empty());
|
||||
let wrong = package(
|
||||
&[("rId7", GLOSSARY_REL, "glossary/document.xml")],
|
||||
&[
|
||||
("[Content_Types].xml", content_types(&[("/word/glossary/document.xml", "image/png")])),
|
||||
("word/glossary/document.xml", glossary_xml(SIGNATURE)),
|
||||
],
|
||||
);
|
||||
assert!(read(wrong).glossary.is_empty());
|
||||
// Broken XML.
|
||||
let _ = read(one("<w:glossaryDocument><w:docParts><w:docPart>".into()));
|
||||
// A glossary relationship pointing at the main document, or a missing part.
|
||||
for target in ["document.xml", "missing.xml", "../../../../etc/passwd"] {
|
||||
let doc = read(package(&[("rId7", GLOSSARY_REL, target)], &[("[Content_Types].xml", ct.clone())]));
|
||||
assert!(doc.glossary.is_empty(), "{target}");
|
||||
assert!(!doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Kind regards"));
|
||||
}
|
||||
// A glossary relating to itself, or with a glossary of its own.
|
||||
for own in
|
||||
[rels(&[("rId1", GLOSSARY_REL, "document.xml")]), rels(&[("rId1", GLOSSARY_REL, "inner.xml"), ("rId2", GLOSSARY_REL, "../document.xml")])]
|
||||
{
|
||||
let bytes = package(
|
||||
&[("rId7", GLOSSARY_REL, "glossary/document.xml")],
|
||||
&[
|
||||
("[Content_Types].xml", content_types(&[("/word/glossary/document.xml", GLOSSARY_CT), ("/word/glossary/inner.xml", GLOSSARY_CT)])),
|
||||
("word/glossary/document.xml", glossary_xml(SIGNATURE)),
|
||||
("word/glossary/_rels/document.xml.rels", own),
|
||||
("word/glossary/inner.xml", glossary_xml(PRICES)),
|
||||
],
|
||||
);
|
||||
let doc = read(bytes);
|
||||
assert_eq!(doc.glossary.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["Signature"]);
|
||||
}
|
||||
// Two glossary relationships: the first counts.
|
||||
let two = package(
|
||||
&[("rId7", GLOSSARY_REL, "glossary/document.xml"), ("rId8", GLOSSARY_REL, "glossary/document.xml")],
|
||||
&[("[Content_Types].xml", ct.clone()), ("word/glossary/document.xml", glossary_xml(SIGNATURE))],
|
||||
);
|
||||
let doc = read(two);
|
||||
assert_eq!(doc.glossary.len(), 1);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! OpenType ligatures (`w14:ligatures`, [MS-DOCX]) in document defaults, styles and runs.
|
||||
//! Synthetic packages, written here; no external documents are needed.
|
||||
|
||||
use std::io::Write;
|
||||
use wordcraft_doc::props::Ligatures;
|
||||
use wordcraft_doc::{Document, Paragraph};
|
||||
|
||||
fn package(defaults: &str, style: &str, run: &str) -> Vec<u8> {
|
||||
let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="w14""#;
|
||||
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="s1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let document = format!(
|
||||
r#"<w:document {ns}><w:body><w:p><w:r><w:rPr><w:rStyle w:val="Fancy"/>{run}</w:rPr><w:t>office affinity</w:t></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let styles = format!(
|
||||
r#"<w:styles {ns}><w:docDefaults><w:rPrDefault><w:rPr>{defaults}</w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="character" w:styleId="Fancy"><w:name w:val="Fancy"/><w:rPr>{style}</w:rPr></w:style></w:styles>"#
|
||||
);
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, data) in [
|
||||
("_rels/.rels", root),
|
||||
("word/_rels/document.xml.rels", rels),
|
||||
("word/document.xml", document.as_str()),
|
||||
("word/styles.xml", styles.as_str()),
|
||||
] {
|
||||
z.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(data.as_bytes()).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn paragraph(d: &Document) -> &Paragraph {
|
||||
d.body.iter().find_map(|b| b.as_para()).unwrap()
|
||||
}
|
||||
|
||||
fn lig(name: &str) -> Option<Ligatures> {
|
||||
Some(Ligatures::from_ooxml(name).unwrap())
|
||||
}
|
||||
|
||||
/// Word stores the Font dialog's Ligatures choice as `w14:ligatures`; each level keeps its own
|
||||
/// value through reading and saving, and an explicit `none` is not the same as no value.
|
||||
#[test]
|
||||
fn ligatures_in_defaults_styles_and_runs_survive_saving() {
|
||||
let el = |v: &str| format!(r#"<w14:ligatures w14:val="{v}"/>"#);
|
||||
let bytes = package(&el("standardContextual"), &el("none"), &el("historicalDiscretional"));
|
||||
let mut d = wordcraft_docx::read(&bytes).unwrap();
|
||||
for generation in 0..3 {
|
||||
assert_eq!(d.styles.default_chr.ligatures, lig("standardContextual"), "defaults, generation {generation}");
|
||||
assert_eq!(d.styles.get("Fancy").and_then(|s| s.chr.ligatures), lig("none"), "style, generation {generation}");
|
||||
let run = ¶graph(&d).runs[0].props;
|
||||
assert_eq!(run.ligatures, lig("historicalDiscretional"), "run, generation {generation}");
|
||||
assert_eq!(run.text_effects, None, "not read as a WordArt effect");
|
||||
d = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A value [MS-DOCX] doesn't define is ignored, the run keeps inheriting.
|
||||
#[test]
|
||||
fn unknown_ligature_values_are_ignored() {
|
||||
let d = wordcraft_docx::read(&package("", "", r#"<w14:ligatures w14:val="fancy"/>"#)).unwrap();
|
||||
assert_eq!(paragraph(&d).runs[0].props.ligatures, None);
|
||||
let d = wordcraft_docx::read(&package("", "", "<w14:ligatures/>")).unwrap();
|
||||
assert_eq!(paragraph(&d).runs[0].props.ligatures, None);
|
||||
}
|
||||
|
||||
/// Without a value nothing is written, so documents that never asked for ligatures stay as they
|
||||
/// were.
|
||||
#[test]
|
||||
fn no_ligatures_element_without_a_value() {
|
||||
let d = wordcraft_docx::read(&package("", "", "")).unwrap();
|
||||
let out = wordcraft_docx::write(&d).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(out)).unwrap();
|
||||
for name in ["word/document.xml", "word/styles.xml"] {
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name(name).unwrap(), &mut xml).unwrap();
|
||||
assert!(!xml.contains("ligatures"), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Positional tabs (`w:ptab`, ECMA-376 Part 1 §17.3.3.23). Fixtures are hand-written from the spec.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use wordcraft_doc::InlineObject;
|
||||
use wordcraft_doc::para::{PTabAlign, PTabBase};
|
||||
use wordcraft_doc::props::TabLeader;
|
||||
|
||||
fn docx(body: &str) -> Vec<u8> {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn document_xml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut s = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn ptab(relative_to: &str, alignment: &str, leader: &str) -> String {
|
||||
format!(r#"<w:r><w:ptab w:relativeTo="{relative_to}" w:alignment="{alignment}" w:leader="{leader}"/></w:r>"#)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positional_tabs_keep_their_alignment_base_and_leader() {
|
||||
let body = format!(
|
||||
r#"<w:p><w:r><w:t>A</w:t></w:r>{}<w:r><w:t>B</w:t></w:r>{}<w:r><w:t>C</w:t></w:r>{}<w:r><w:t>D</w:t></w:r></w:p>"#,
|
||||
ptab("margin", "right", "dot"),
|
||||
ptab("indent", "center", "none"),
|
||||
ptab("margin", "left", "underscore"),
|
||||
);
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
let p = d.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.plain_text(), "A\tB\tC\tD");
|
||||
assert_eq!(
|
||||
p.objects,
|
||||
vec![
|
||||
InlineObject::PositionalTab { align: PTabAlign::Right, relative_to: PTabBase::Margin, leader: TabLeader::Dot },
|
||||
InlineObject::PositionalTab { align: PTabAlign::Center, relative_to: PTabBase::Indent, leader: TabLeader::None },
|
||||
InlineObject::PositionalTab { align: PTabAlign::Left, relative_to: PTabBase::Margin, leader: TabLeader::Underscore },
|
||||
]
|
||||
);
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
for (rel, align, leader) in [("margin", "right", "dot"), ("indent", "center", "none"), ("margin", "left", "underscore")] {
|
||||
let want = format!(r#"<w:ptab w:relativeTo="{rel}" w:alignment="{align}" w:leader="{leader}"/>"#);
|
||||
assert!(xml.contains(&want), "{want} missing from {xml}");
|
||||
}
|
||||
assert!(!xml.contains("<w:tab/>"), "{xml}");
|
||||
}
|
||||
|
||||
/// A positional tab whose alignment or base isn't one the spec defines stays an ordinary tab.
|
||||
#[test]
|
||||
fn a_positional_tab_with_an_unknown_alignment_is_a_plain_tab() {
|
||||
let body = format!(r#"<w:p><w:r><w:t>A</w:t></w:r>{}<w:r><w:t>B</w:t></w:r></w:p>"#, ptab("margin", "decimal", "none"));
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
let p = d.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.plain_text(), "A\tB");
|
||||
assert!(p.objects.is_empty(), "{:?}", p.objects);
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains("<w:tab/>") && !xml.contains("w:ptab"), "{xml}");
|
||||
}
|
||||
@@ -56,6 +56,8 @@ fn every_char_prop_round_trips() {
|
||||
let all = CharProps {
|
||||
style: Some("Strong".into()),
|
||||
font: Some("Georgia".into()),
|
||||
// The symbol's own font: the run is written as `w:sym` characters (#2036).
|
||||
sym_font: Some("Wingdings".into()),
|
||||
size: Some(10.5),
|
||||
bold: Some(true),
|
||||
italic: Some(false),
|
||||
@@ -75,6 +77,7 @@ fn every_char_prop_round_trips() {
|
||||
scale: Some(150.0),
|
||||
position: Some(3.0),
|
||||
kern: Some(8.0),
|
||||
ligatures: Some(wordcraft_doc::props::Ligatures { standard: true, historical: true, ..Default::default() }),
|
||||
outline: Some(true),
|
||||
shadow: Some(true),
|
||||
emboss: Some(false),
|
||||
@@ -110,6 +113,13 @@ fn every_char_prop_round_trips() {
|
||||
bold_cs: Some(false),
|
||||
italic_cs: Some(true),
|
||||
lang_bidi: Some("fa-IR".into()),
|
||||
east_asian_layout: Some(wordcraft_doc::props::EastAsianLayout {
|
||||
id: Some(3),
|
||||
combine: Some(true),
|
||||
combine_brackets: Some(wordcraft_doc::props::CombineBrackets::Square),
|
||||
vert: Some(false),
|
||||
vert_compress: Some(true),
|
||||
}),
|
||||
link: None,
|
||||
ins: None,
|
||||
del: None,
|
||||
@@ -165,6 +175,9 @@ fn every_para_prop_round_trips() {
|
||||
suppress_line_numbers: Some(true),
|
||||
bidi: Some(false),
|
||||
drop_cap: None,
|
||||
drop_cap_margin: None,
|
||||
drop_cap_distance: None,
|
||||
drop_cap_font: None,
|
||||
frame: Some(wordcraft_doc::props::TextFrame {
|
||||
w: Some(144.0),
|
||||
h: Some(36.0),
|
||||
@@ -707,6 +720,32 @@ fn note_never_references_itself() {
|
||||
assert_eq!(part_text(&r, Some(*id)).trim(), "The note.");
|
||||
}
|
||||
|
||||
/// A note with a custom mark keeps it in the note's own text: a plain run with the mark, not the
|
||||
/// `w:footnoteRef` / `w:endnoteRef` placeholder that Word replaces by the automatic number.
|
||||
#[test]
|
||||
fn custom_note_mark_stays_in_the_note() {
|
||||
let mut d = Document::new();
|
||||
let f = d.add_part(PartKind::Footnote, Vec::new());
|
||||
let e = d.add_part(PartKind::Endnote, Vec::new());
|
||||
for (id, kind) in [(f, NoteKind::Footnote), (e, NoteKind::Endnote)] {
|
||||
let mut note = Paragraph::with_text(" The note.", CharProps::default());
|
||||
note.insert_object(0, InlineObject::NoteRef { kind, id, custom: "*".into() }, &CharProps::default()).unwrap();
|
||||
d.parts.get_mut(&id).unwrap().blocks = vec![para_block(note)];
|
||||
}
|
||||
let mut p = Paragraph::with_text("Text", CharProps::default());
|
||||
p.insert_object(4, InlineObject::NoteRef { kind: NoteKind::Footnote, id: f, custom: "*".into() }, &CharProps::default()).unwrap();
|
||||
let end = p.len();
|
||||
p.insert_object(end, InlineObject::NoteRef { kind: NoteKind::Endnote, id: e, custom: "*".into() }, &CharProps::default()).unwrap();
|
||||
d.body = vec![para_block(p)];
|
||||
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
for (file, mark) in [("word/footnotes.xml", "<w:footnoteRef/>"), ("word/endnotes.xml", "<w:endnoteRef/>")] {
|
||||
let xml = part_xml(&bytes, file);
|
||||
assert!(!xml.contains(mark), "{file}: the custom mark became an automatic number: {xml}");
|
||||
assert!(xml.contains(r#"<w:t xml:space="preserve">*</w:t>"#), "{file}: {xml}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A note read from a Word file starts with its own number (a reference to itself, from the
|
||||
/// `w:footnoteRef` mark). Saving writes that mark back exactly once, with its character style, and
|
||||
/// never as a `w:footnoteReference`; reading the saved file gives the same note again.
|
||||
@@ -2606,3 +2645,42 @@ fn page_background_picture_round_trips() {
|
||||
// Saved again, it is still there.
|
||||
assert!(rt(&r).settings.page_picture.is_some());
|
||||
}
|
||||
|
||||
/// #2601: Drop Cap Options — a dropped cap with its lines, distance from the text and font, and
|
||||
/// one in the margin, survive a save: `w:framePr w:dropCap="drop|margin" w:lines w:hSpace` on the
|
||||
/// letter's own paragraph, the font on the letter's run (ECMA-376 §17.3.1.11). The text after the
|
||||
/// letter keeps its own font.
|
||||
#[test]
|
||||
fn drop_cap_options_round_trip() {
|
||||
let body = CharProps { font: Some("Liberation Serif".into()), ..Default::default() };
|
||||
let mut dropped = Paragraph::with_text("Once upon a time", body.clone());
|
||||
dropped.props.drop_cap = Some(2);
|
||||
dropped.props.drop_cap_distance = Some(6.0);
|
||||
dropped.props.drop_cap_font = Some("Liberation Mono".into());
|
||||
let mut margin = Paragraph::with_text("In the margin", body.clone());
|
||||
margin.props.drop_cap = Some(4);
|
||||
margin.props.drop_cap_margin = Some(true);
|
||||
let d = doc_with(vec![dropped, margin]);
|
||||
let bytes = wordcraft_docx::write(&d).expect("write");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
assert!(xml.contains(r#"w:dropCap="drop" w:lines="2" w:hSpace="120""#), "{xml}");
|
||||
assert!(xml.contains(r#"w:dropCap="margin" w:lines="4""#), "{xml}");
|
||||
assert!(xml.contains(r#"w:ascii="Liberation Mono""#), "the letter's font on its run: {xml}");
|
||||
let r = wordcraft_docx::read(&bytes).expect("read");
|
||||
let got = paras(&r);
|
||||
assert_eq!(got.len(), 2, "each letter merges back into its paragraph");
|
||||
let (a, b) = (&got[0], &got[1]);
|
||||
assert_eq!(a.plain_text(), "Once upon a time");
|
||||
assert_eq!(
|
||||
(a.props.drop_cap, a.props.drop_cap_margin, a.props.drop_cap_distance, a.props.drop_cap_font.as_deref()),
|
||||
(Some(2), None, Some(6.0), Some("Liberation Mono"))
|
||||
);
|
||||
assert!(a.runs.iter().all(|r| r.props.font.as_deref() == Some("Liberation Serif")), "the letter keeps the text's font: {:?}", a.runs);
|
||||
assert_eq!(b.plain_text(), "In the margin");
|
||||
assert_eq!(
|
||||
(b.props.drop_cap, b.props.drop_cap_margin, b.props.drop_cap_distance, b.props.drop_cap_font.as_deref()),
|
||||
(Some(4), Some(true), None, None)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -133,3 +133,33 @@ fn settings_written_by_wordcraft_keep_no_original() {
|
||||
assert!(!back.passthrough.contains_key("wordcraft:settings.orig"), "{:?}", back.passthrough.keys());
|
||||
assert_eq!(text(&save(&back), "word/settings.xml"), text(&save(&doc), "word/settings.xml"));
|
||||
}
|
||||
|
||||
/// Gap #5: `w:doNotTrackMoves` (ECMA-376 §17.15.1.29) turns Track moves off; it is read, written
|
||||
/// back right after `w:trackRevisions` (in a merged part and a generated one), and left out
|
||||
/// while moves are tracked.
|
||||
#[test]
|
||||
fn do_not_track_moves_round_trips() {
|
||||
let original = SETTINGS.replace("<w:trackRevisions/>", "<w:trackRevisions/><w:doNotTrackMoves/>");
|
||||
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
|
||||
assert!(!doc.settings.track_moves);
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert_eq!(s.matches("<w:doNotTrackMoves/>").count(), 1, "{s}");
|
||||
assert!(pos(&s, "<w:trackRevisions/>") < pos(&s, "<w:doNotTrackMoves/>") && pos(&s, "<w:doNotTrackMoves/>") < pos(&s, "<w:defaultTabStop"));
|
||||
assert!(s.contains("ClauseSet"), "a merged part: {s}");
|
||||
doc.settings.track_moves = true;
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert!(!s.contains("doNotTrackMoves"), "{s}");
|
||||
|
||||
// `w:val="false"` keeps moves tracked.
|
||||
let off = SETTINGS.replace("<w:trackRevisions/>", r#"<w:trackRevisions/><w:doNotTrackMoves w:val="false"/>"#);
|
||||
assert!(wordcraft_docx::read(&with_settings(&off)).unwrap().settings.track_moves);
|
||||
|
||||
// A document of our own: absent by default, written when off, and read back.
|
||||
let mut doc = wordcraft_doc::Document::new();
|
||||
assert!(doc.settings.track_moves);
|
||||
assert!(!text(&save(&doc), "word/settings.xml").contains("doNotTrackMoves"));
|
||||
doc.settings.track_moves = false;
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert!(s.contains("<w:doNotTrackMoves/>"), "{s}");
|
||||
assert!(!wordcraft_docx::read(&wordcraft_docx::write(&doc).unwrap()).unwrap().settings.track_moves);
|
||||
}
|
||||
|
||||
@@ -24,10 +24,11 @@ fn document_xml(bytes: &[u8]) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// The text boxes' stories in body order.
|
||||
/// The text boxes' stories in body order, a group's members among them
|
||||
/// (`text_boxes`, not `text_box`, which only sees an object that is itself a box).
|
||||
fn boxes(d: &Document) -> Vec<u32> {
|
||||
let mut out = Vec::new();
|
||||
d.objects_in_reading_order(&mut |o| out.extend(o.text_box()));
|
||||
d.objects_in_reading_order(&mut |o| out.extend(o.text_boxes()));
|
||||
out.retain(|id| d.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Legacy VML drawings in a `w:pict`: every shape in one, and `v:group` members in the space
|
||||
//! `coordsize`/`coordorigin` give them. Fixtures are hand-written from ECMA-376 Part 4
|
||||
//! (VML, §14.1 `v:group`, `coordsize`, `coordorigin`; §14.2 shapes).
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::{Document, InlineObject, Paragraph};
|
||||
|
||||
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, bytes) in entries {
|
||||
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(bytes).unwrap();
|
||||
}
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// A document whose body is `body`.
|
||||
fn read_body(body: &str) -> Document {
|
||||
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w10="urn:schemas-microsoft-com:office:word"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
wordcraft_docx::read(&zip(&[("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())])).unwrap()
|
||||
}
|
||||
|
||||
fn paras(d: &Document) -> Vec<&Paragraph> {
|
||||
d.body.iter().filter_map(|b| b.as_para()).collect()
|
||||
}
|
||||
|
||||
/// The objects of the body's first paragraph.
|
||||
fn objects(d: &Document) -> &[InlineObject] {
|
||||
¶s(d).first().expect("a paragraph").objects
|
||||
}
|
||||
|
||||
fn pict(inner: &str) -> String {
|
||||
format!(r#"<w:p><w:r><w:pict>{inner}</w:pict></w:r></w:p>"#)
|
||||
}
|
||||
|
||||
fn kinds(objs: &[InlineObject]) -> Vec<ShapeKind> {
|
||||
objs.iter()
|
||||
.map(|o| match o {
|
||||
InlineObject::Shape { kind, .. } => *kind,
|
||||
o => panic!("{o:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_shape_in_a_pict_is_read() {
|
||||
// A `w:pict` may hold any number of shapes; each one is its own object. A `v:shapetype` is
|
||||
// a definition, not a shape, and is not one of them.
|
||||
let d = read_body(&pict(concat!(
|
||||
r#"<v:shapetype id="t1" o:spt="202"/>"#,
|
||||
r#"<v:rect style="width:10pt;height:20pt"/>"#,
|
||||
r#"<v:oval style="width:30pt;height:40pt"/>"#,
|
||||
r#"<v:roundrect style="width:50pt;height:60pt"/>"#,
|
||||
)));
|
||||
let objs = objects(&d);
|
||||
assert_eq!(kinds(objs), [ShapeKind::Rectangle, ShapeKind::Ellipse, ShapeKind::RoundedRectangle], "all three, in document order");
|
||||
let size = |o: &InlineObject| match o {
|
||||
InlineObject::Shape { w, h, .. } => (*w, *h),
|
||||
o => panic!("{o:?}"),
|
||||
};
|
||||
assert_eq!(objs.iter().map(size).collect::<Vec<_>>(), [(10.0, 20.0), (30.0, 40.0), (50.0, 60.0)], "each keeps its own size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vml_group_keeps_its_members() {
|
||||
// `coordsize` is the members' space, mapped onto the group's own box; `left`/`top` place a
|
||||
// member in that space.
|
||||
let d = read_body(&pict(concat!(
|
||||
r#"<v:group style="width:100pt;height:50pt" coordsize="1000,500">"#,
|
||||
r#"<v:rect style="left:0;top:0;width:400;height:500"/>"#,
|
||||
r#"<v:oval style="left:600;top:100;width:400;height:300"/>"#,
|
||||
r#"</v:group>"#,
|
||||
)));
|
||||
let InlineObject::Group { w, h, ch_w, ch_h, children, canvas, .. } = &objects(&d)[0] else { panic!("{:?}", objects(&d)) };
|
||||
assert_eq!((*w, *h, *ch_w, *ch_h), (100.0, 50.0, 1000.0, 500.0), "its own box, and its members' space");
|
||||
assert_eq!(*canvas, None, "a group is not a Drawing Canvas");
|
||||
assert_eq!(children.len(), 2, "both members");
|
||||
assert_eq!((children[0].x, children[0].y), (0.0, 0.0));
|
||||
assert_eq!((children[1].x, children[1].y), (600.0, 100.0), "placed in the members' space, not scaled");
|
||||
assert_eq!(kinds(&children.iter().map(|c| c.obj.clone()).collect::<Vec<_>>()), [ShapeKind::Rectangle, ShapeKind::Ellipse]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vml_group_shifts_its_members_by_its_coordorigin() {
|
||||
// `coordorigin` is the top-left of the members' space, so a member's offset is from there.
|
||||
let d = read_body(&pict(concat!(
|
||||
r#"<v:group style="width:100pt;height:100pt" coordsize="1000,1000" coordorigin="200,300">"#,
|
||||
r#"<v:rect style="left:200;top:300;width:100;height:100"/>"#,
|
||||
r#"<v:rect style="left:700;top:800;width:100;height:100"/>"#,
|
||||
r#"</v:group>"#,
|
||||
)));
|
||||
let InlineObject::Group { ch_w, children, .. } = &objects(&d)[0] else { panic!() };
|
||||
assert_eq!(*ch_w, 1000.0);
|
||||
assert_eq!((children[0].x, children[0].y), (0.0, 0.0), "a member at the origin sits at the group's corner");
|
||||
assert_eq!((children[1].x, children[1].y), (500.0, 500.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_vml_groups_are_flattened_into_the_outer_one() {
|
||||
// An inner group's members' space maps onto the inner group's own box, which is itself in
|
||||
// the outer group's space: 500 wide in a 1000-wide space inside a 1000-wide box halves it.
|
||||
let d = read_body(&pict(concat!(
|
||||
r#"<v:group style="width:100pt;height:100pt" coordsize="1000,1000">"#,
|
||||
r#"<v:rect style="left:100;top:100;width:50;height:50"/>"#,
|
||||
r#"<v:group style="left:400;top:400;width:500;height:500" coordsize="1000,1000">"#,
|
||||
r#"<v:oval style="left:200;top:600;width:100;height:100"/>"#,
|
||||
r#"</v:group>"#,
|
||||
r#"</v:group>"#,
|
||||
)));
|
||||
let InlineObject::Group { children, .. } = &objects(&d)[0] else { panic!() };
|
||||
assert_eq!(children.len(), 2, "the inner group's member comes into the outer group");
|
||||
assert_eq!((children[0].x, children[0].y), (100.0, 100.0));
|
||||
// 400 + 200 × (500/1000) = 500; 400 + 600 × 0.5 = 700.
|
||||
assert_eq!((children[1].x, children[1].y), (500.0, 700.0), "mapped through the inner group");
|
||||
let InlineObject::Shape { w, h, .. } = children[1].obj else { panic!() };
|
||||
assert_eq!((w, h), (50.0, 50.0), "and scaled by it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vml_group_with_no_member_we_can_show_is_left_out() {
|
||||
// Only a shape definition, and a shape we draw nothing for (no stroke, no fill).
|
||||
let d = read_body(&pict(concat!(
|
||||
r#"<v:group style="width:100pt;height:50pt" coordsize="1000,500">"#,
|
||||
r#"<v:shapetype id="t1" o:spt="202"/>"#,
|
||||
r#"<v:rect style="left:0;top:0;width:10;height:10" stroked="f" filled="f"/>"#,
|
||||
r#"</v:group>"#,
|
||||
)));
|
||||
assert!(objects(&d).is_empty(), "nothing to show: {:?}", objects(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_vml_groups_stop_at_the_depth_bound() {
|
||||
// A hostile file nests groups without end; reading one must not run away.
|
||||
let depth = 64;
|
||||
let mut inner = r#"<v:rect style="left:0;top:0;width:10;height:10"/>"#.to_string();
|
||||
for _ in 0..depth {
|
||||
inner = format!(r#"<v:group style="left:0;top:0;width:100;height:100" coordsize="100,100">{inner}</v:group>"#);
|
||||
}
|
||||
let d = read_body(&pict(&format!(r#"<v:group style="width:100pt;height:100pt" coordsize="100,100">{inner}</v:group>"#)));
|
||||
// Past the bound nothing is read, so the outermost group has no member and is left out.
|
||||
assert!(objects(&d).is_empty(), "{:?}", objects(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vml_group_survives_being_saved() {
|
||||
let body = pict(concat!(
|
||||
r#"<v:group style="width:100pt;height:50pt" coordsize="1000,500">"#,
|
||||
r#"<v:rect style="left:0;top:0;width:400;height:500"/>"#,
|
||||
r#"<v:oval style="left:600;top:100;width:400;height:300"/>"#,
|
||||
r#"</v:group>"#,
|
||||
));
|
||||
let d = read_body(&body);
|
||||
let InlineObject::Group { children, .. } = &objects(&d)[0] else { panic!("{:?}", objects(&d)) };
|
||||
assert_eq!(children.len(), 2, "read with both its members to begin with");
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(objects(&back), objects(&d), "saved as DrawingML and read again, it is the same group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pict_of_a_rect_a_text_box_and_a_group_all_come_through() {
|
||||
// The three shapes of issue #1643, which a round trip dropped the last of. The group's
|
||||
// member gives its size in points, not in the group's own coordinates, as Word writes it.
|
||||
let d = read_body(&format!(
|
||||
"{}{}{}",
|
||||
pict(r##"<v:rect style="position:absolute;width:100pt;height:50pt" fillcolor="#ff0000"/>"##),
|
||||
pict(
|
||||
r#"<v:shape style="width:100pt;height:50pt"><v:textbox><w:txbxContent><w:p><w:r><w:t>boxed</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape>"#
|
||||
),
|
||||
pict(concat!(
|
||||
r#"<v:group style="width:100pt;height:50pt" coordsize="100,50">"#,
|
||||
r##"<v:rect style="width:50pt;height:20pt" fillcolor="#00ff00"/>"##,
|
||||
r#"</v:group>"#,
|
||||
)),
|
||||
));
|
||||
let ps = paras(&d);
|
||||
assert_eq!(ps.len(), 3, "a paragraph each");
|
||||
assert_eq!(kinds(&ps[0].objects), [ShapeKind::Rectangle]);
|
||||
assert_eq!(kinds(&ps[1].objects), [ShapeKind::TextBox]);
|
||||
let InlineObject::Group { children, .. } = &ps[2].objects[0] else { panic!("{:?}", ps[2].objects) };
|
||||
assert_eq!(kinds(&children.iter().map(|c| c.obj.clone()).collect::<Vec<_>>()), [ShapeKind::Rectangle], "the green rectangle is read");
|
||||
let InlineObject::Shape { fill, .. } = children[0].obj else { panic!() };
|
||||
assert_eq!(fill, Some(wordcraft_doc::Rgb(0x00, 0xff, 0x00)), "with its colour");
|
||||
// And it is still there after a save, which is what the round trip lost.
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
assert_eq!(paras(&back).iter().map(|p| p.objects.len()).collect::<Vec<_>>(), [1, 1, 1]);
|
||||
let InlineObject::Group { children, .. } = ¶s(&back)[2].objects[0] else { panic!() };
|
||||
assert_eq!(children.len(), 1, "the group keeps its member");
|
||||
}
|
||||
|
||||
/// The text of text box story `id`, its paragraphs joined by newlines.
|
||||
fn part_text(d: &Document, id: u32) -> String {
|
||||
d.parts.get(&id).map(|p| p.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect::<Vec<_>>().join("\n")).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_of_several_text_boxes_keeps_every_one() {
|
||||
// Reported on #1643 by @KNUFFIXX, whose fixture is a `_x0000_t202` pair side by side in one
|
||||
// inline `v:group`: only box A came through a convert. `vml_textbox` recurses to the first
|
||||
// box with content, so before this every later box in a group was dropped -- and a text box
|
||||
// is the one member a group used to keep, which is why this case looked half-working.
|
||||
let shape = |left: u32, height: u32, label: &str| {
|
||||
let paras: String = (1..=3).map(|n| format!(r#"<w:p><w:r><w:t xml:space="preserve">{label} line {n}</w:t></w:r></w:p>"#)).collect();
|
||||
format!(
|
||||
r##"<v:shape style="position:absolute;left:{left};top:100;width:3500;height:{height}" type="#_x0000_t202" filled="false" stroked="true"><v:textbox inset="0,0,0,0"><w:txbxContent>{paras}</w:txbxContent></v:textbox></v:shape>"##
|
||||
)
|
||||
};
|
||||
// The control fixture, and the overflow one where box B is too short for its text; the
|
||||
// height of a box must not decide whether it is read.
|
||||
for (height_b, label_b) in [(1600, "Box B (tall)"), (400, "Box B (short)")] {
|
||||
let d = read_body(&pict(&format!(
|
||||
concat!(
|
||||
r##"<v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"/>"##,
|
||||
r##"<v:group style="width:400pt;height:100pt" coordorigin="0,0" coordsize="8000,2000">{}{}</v:group>"##,
|
||||
),
|
||||
shape(100, 1600, "Box A (tall)"),
|
||||
shape(4200, height_b, label_b),
|
||||
)));
|
||||
let InlineObject::Group { ch_w, ch_h, children, .. } = &objects(&d)[0] else { panic!("{:?}", objects(&d)) };
|
||||
assert_eq!((*ch_w, *ch_h), (8000.0, 2000.0), "the group's member space");
|
||||
assert_eq!(children.len(), 2, "both boxes, with box B {height_b} high");
|
||||
assert_eq!((children[0].x, children[1].x), (100.0, 4200.0), "side by side");
|
||||
|
||||
let stories: Vec<u32> = children.iter().filter_map(|c| c.obj.text_box()).collect();
|
||||
assert_eq!(stories.len(), 2, "each box has its own story");
|
||||
assert_ne!(stories[0], stories[1]);
|
||||
assert_eq!(part_text(&d, stories[0]), "Box A (tall) line 1\nBox A (tall) line 2\nBox A (tall) line 3");
|
||||
assert_eq!(part_text(&d, stories[1]), format!("{label_b} line 1\n{label_b} line 2\n{label_b} line 3"));
|
||||
|
||||
// Saved and read again -- the step the report loses the text at.
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
let InlineObject::Group { children: again, .. } = &objects(&back)[0] else { panic!() };
|
||||
let back_stories: Vec<u32> = again.iter().filter_map(|c| c.obj.text_box()).collect();
|
||||
assert_eq!(back_stories.len(), 2, "both boxes survive the save");
|
||||
assert_eq!(part_text(&back, back_stories[0]), part_text(&d, stories[0]));
|
||||
assert_eq!(part_text(&back, back_stories[1]), part_text(&d, stories[1]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_member_finds_its_shapetype_beside_the_group() {
|
||||
// Word writes each `v:shapetype` once, at its first use, as a child of the `w:pict` -- so a
|
||||
// group's member refers to one that is its *parent's* sibling, not its own. The member here
|
||||
// carries no geometry and no colours of its own: its diamond shape comes from the
|
||||
// shapetype's `o:spt` (4) and its fill from the shapetype's `fillcolor`.
|
||||
let d = read_body(&pict(concat!(
|
||||
r##"<v:shapetype id="_x0000_t4" o:spt="4" fillcolor="#0000ff"/>"##,
|
||||
r#"<v:group style="width:100pt;height:50pt" coordsize="1000,500">"#,
|
||||
r##"<v:shape style="left:0;top:0;width:400;height:500" type="#_x0000_t4"/>"##,
|
||||
r#"</v:group>"#,
|
||||
)));
|
||||
let InlineObject::Group { children, .. } = &objects(&d)[0] else { panic!("{:?}", objects(&d)) };
|
||||
assert_eq!(children.len(), 1, "the member is read");
|
||||
let InlineObject::Shape { kind, fill, .. } = children[0].obj else { panic!("{:?}", children[0].obj) };
|
||||
assert_eq!(kind, ShapeKind::Diamond, "the preset comes from the shapetype's o:spt");
|
||||
assert_eq!(fill, Some(wordcraft_doc::Rgb(0x00, 0x00, 0xff)), "and the fill from its fillcolor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_level_shape_still_finds_its_shapetype() {
|
||||
// The same lookup for a shape that is not in a group, which is what it was written for.
|
||||
let d = read_body(&pict(concat!(
|
||||
r##"<v:shapetype id="_x0000_t4" o:spt="4" fillcolor="#00ff00"/>"##,
|
||||
r##"<v:shape style="width:40pt;height:40pt" type="#_x0000_t4"/>"##,
|
||||
)));
|
||||
let InlineObject::Shape { kind, fill, .. } = objects(&d)[0] else { panic!("{:?}", objects(&d)) };
|
||||
assert_eq!((kind, fill), (ShapeKind::Diamond, Some(wordcraft_doc::Rgb(0x00, 0xff, 0x00))));
|
||||
}
|
||||
@@ -82,6 +82,7 @@ Home|Paragraph|Bullets|para.bullets
|
||||
Home|Paragraph|Numbering|para.numbering
|
||||
Home|Paragraph|Multilevel List|para.multilevel
|
||||
Home|Paragraph|Define New Multilevel List|list.define
|
||||
Home|Paragraph|Multilevel List Library|list.multilevelPreset
|
||||
Home|Paragraph|Change List Level|para.listLevel
|
||||
Home|Paragraph|Restart Numbering|para.restartNumbering
|
||||
Home|Paragraph|Define New Bullet|para.defineBullet
|
||||
@@ -482,6 +483,8 @@ Editing|Keyboard|Move Paragraph Down|para.moveDown
|
||||
Editing|Keyboard|Promote|para.promote
|
||||
Editing|Keyboard|Demote|para.demote
|
||||
Editing|Keyboard|Toggle Unicode Character|text.toggleUnicode
|
||||
Editing|Keyboard|Spike|edit.spike
|
||||
Editing|Keyboard|Insert Spike|edit.insertSpike
|
||||
Editing|Navigation|Word Left|caret.wordLeft
|
||||
Editing|Navigation|Word Right|caret.wordRight
|
||||
Editing|Navigation|Line Start|caret.home
|
||||
|
||||
@@ -290,7 +290,7 @@ pub fn style(name: &str) -> &'static CiteStyle {
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
|
||||
.params(r#"{"add"?: Source, "remove"?: tag} → list"#),
|
||||
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
|
||||
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
|
||||
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
|
||||
let st = p::str(v, "style").unwrap_or("APA");
|
||||
@@ -342,7 +342,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.crossReference", "Cross-reference", "Insert › Links", cross_ref)
|
||||
.params(r#"{"to": "heading|bookmark|figure|table|equation", "target": string (text / name / number), "show"?: "text|page|number|aboveBelow"} or {} to list targets"#),
|
||||
.params(r#"{"to": "heading|bookmark|figure|table|equation|label:<Name> (a caption label of your own)", "target": string (text / name / number), "show"?: "text|page|number|aboveBelow"} or {} to list targets"#),
|
||||
CommandSpec::new("references.noteOptions", "Footnote and Endnote", "References › Footnotes", super::references::note_options).params(
|
||||
r#"{"kind"?: "footnote|endnote", "pos"?: "pageBottom|beneathText" (footnotes) | "sectEnd|docEnd" (endnotes), "numFmt"?: "decimal|lowerRoman|upperRoman|lowerLetter|upperLetter|…", "numStart"?: 1-32767, "numRestart"?: "continuous|eachSect|eachPage" (each page: footnotes only), "scope"?: "document|section", "footnoteFormat"?: …, "endnoteFormat"?: …} — no settings: the options in effect at the caret"#,
|
||||
),
|
||||
@@ -519,18 +519,42 @@ pub fn entry(src: &Source, style_name: &str, n: usize) -> String {
|
||||
render(if src.journal.is_empty() { st.book } else { st.article }, &field)
|
||||
}
|
||||
|
||||
/// The tag a new source gets, as Word makes it: the first three letters of the first author's
|
||||
/// name and the last two digits of the year (`Smi20`), with `1`, `2`… added while it is taken.
|
||||
fn auto_tag(doc: &Document, src: &Source) -> String {
|
||||
let base = auto_tag_base(src);
|
||||
let taken = |t: &str| doc.sources.iter().any(|x| x.tag == t);
|
||||
if !taken(&base) {
|
||||
return base;
|
||||
}
|
||||
(1u32..).map(|n| format!("{base}{n}")).find(|t| !taken(t)).unwrap_or(base)
|
||||
}
|
||||
|
||||
/// The author of a source for matching untagged entries: the editor when there is no author.
|
||||
fn by_author(x: &Source) -> &str {
|
||||
if x.author.is_empty() { x.editor.as_str() } else { x.author.as_str() }
|
||||
}
|
||||
|
||||
/// The stem of a new source's tag, before `1`, `2`… are added while it is taken: the first three
|
||||
/// alphanumerics of the first author's name (nothing of the author's, `Src`) and the last two
|
||||
/// digits of the year.
|
||||
fn auto_tag_base(src: &Source) -> String {
|
||||
let name: String =
|
||||
authors(&src.author).first().map(|x| x.0.clone()).unwrap_or_default().chars().filter(|c| c.is_alphanumeric()).take(3).collect();
|
||||
let name = if name.is_empty() { "Src".to_string() } else { name };
|
||||
let digits: Vec<char> = src.year.chars().filter(char::is_ascii_digit).collect();
|
||||
let year: String = digits.get(digits.len().saturating_sub(2)..).unwrap_or_default().iter().collect();
|
||||
format!("{name}{year}")
|
||||
}
|
||||
|
||||
/// Manage Sources: applies `add`, `remove` and `import` (in that order) and returns the
|
||||
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
|
||||
fn sources(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(a) = v.get("add") {
|
||||
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
// A new source's tag is made from its author and year; an edit keeps the tag it has.
|
||||
if src.tag.is_empty() {
|
||||
let base: String = authors(&src.author)
|
||||
.first()
|
||||
.map(|x| x.0.clone())
|
||||
.unwrap_or_else(|| "Source".into())
|
||||
.chars()
|
||||
.filter(|c| c.is_alphanumeric())
|
||||
.collect();
|
||||
src.tag = format!("{base}{}", src.year);
|
||||
src.tag = auto_tag(&s.doc, &src);
|
||||
}
|
||||
// Edit Source keeps the source's place in the list and refreshes its citations.
|
||||
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
|
||||
@@ -547,9 +571,74 @@ fn sources(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(t) = p::str(v, "remove") {
|
||||
s.doc.sources.retain(|x| x.tag != t);
|
||||
}
|
||||
if let Some(path) = p::str(v, "import") {
|
||||
import_sources(s, path)?;
|
||||
}
|
||||
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
/// The largest bibliography sources file imported from disk.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SOURCES_FILE: u64 = 32 << 20;
|
||||
|
||||
/// Import the sources of a Word bibliography file (`b:Sources`: Word's own `Sources.xml`) into
|
||||
/// this document (#2640). A tag already here is left alone — an import never overwrites an
|
||||
/// edited source; a source with no tag is matched to an existing one by title and author, and
|
||||
/// otherwise gets a tag the way a new source does.
|
||||
fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (s, path);
|
||||
return Err(CmdError::Failed("reading files by path isn't available on the web".into()));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// Through `io`, which keeps automation inside its read root (#769).
|
||||
let bytes = crate::io::read_file_capped(path, MAX_SOURCES_FILE, "sources file").map_err(CmdError::Failed)?;
|
||||
let file = wordcraft_docx::read_sources(&bytes).map_err(|e| CmdError::Failed(e.to_string()))?;
|
||||
let mut added = false;
|
||||
// The tags and (title, author-or-editor) keys already here, once: an import of thousands
|
||||
// of untagged sources must not rescan the list per source. Tags follow `auto_tag`: the
|
||||
// stem, then 1, 2… while taken.
|
||||
let mut tags: std::collections::HashSet<String> = s.doc.sources.iter().map(|x| x.tag.clone()).collect();
|
||||
let mut keys: std::collections::HashSet<(String, String)> =
|
||||
s.doc.sources.iter().map(|x| (x.title.clone(), by_author(x).to_string())).collect();
|
||||
let mut next: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
|
||||
for mut src in file.sources {
|
||||
if s.doc.sources.len() >= wordcraft_docx::MAX_SOURCES {
|
||||
break;
|
||||
}
|
||||
if src.tag.is_empty() {
|
||||
// A source with no tag is matched to one already here by its title and author (or
|
||||
// editor), as repeated parts of a document are; otherwise it gets a tag the way a
|
||||
// new source does.
|
||||
if keys.contains(&(src.title.clone(), by_author(&src).to_string())) {
|
||||
continue;
|
||||
}
|
||||
let base = auto_tag_base(&src);
|
||||
let n = next.entry(base.clone()).or_insert(0);
|
||||
let mut tag = if *n == 0 { base.clone() } else { format!("{base}{}", *n) };
|
||||
while tags.contains(&tag) {
|
||||
*n += 1;
|
||||
tag = format!("{base}{}", *n);
|
||||
}
|
||||
*n = n.saturating_add(1);
|
||||
src.tag = tag;
|
||||
}
|
||||
if !tags.insert(src.tag.clone()) {
|
||||
continue;
|
||||
}
|
||||
keys.insert((src.title.clone(), by_author(&src).to_string()));
|
||||
s.doc.sources.push(src);
|
||||
added = true;
|
||||
}
|
||||
if added {
|
||||
s.touch();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn citation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if v.get("source").is_some() {
|
||||
sources(s, &json!({"add": v.get("source")}))?;
|
||||
@@ -906,11 +995,78 @@ fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"inserted": result}))
|
||||
}
|
||||
|
||||
/// The label of a caption: the text before its first field (`Plate ` in `Plate `, `SEQ Plate`,
|
||||
/// `: A rock`). When the caption starts with its chapter number, the text between that field and
|
||||
/// the `SEQ` number, unless it is only a separator. Failing both, the `SEQ` identifier names it.
|
||||
/// A caption without a `SEQ` field (typed by hand) has what comes before its first digit.
|
||||
fn caption_label(p: &Paragraph, text: &str) -> Option<String> {
|
||||
let fields: Vec<(usize, &str)> = p
|
||||
.object_offsets()
|
||||
.into_iter()
|
||||
.filter_map(|o| match p.object_at(o) {
|
||||
Some(InlineObject::Field { instr, .. }) => Some((o, instr.as_str())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let seq = fields.iter().position(|(_, instr)| instr.split_whitespace().next().is_some_and(|w| w.eq_ignore_ascii_case("SEQ")));
|
||||
let label = match seq.and_then(|i| Some((i, fields.get(i)?))) {
|
||||
Some((i, (seq_at, instr))) => {
|
||||
// The text in `from..to` with the bookmark marks dropped, if it says anything.
|
||||
let said = |from: usize, to: usize| {
|
||||
let t: String = p.text.get(from..to).unwrap_or_default().chars().filter(|c| *c != wordcraft_doc::para::OBJ).collect();
|
||||
let t = t.trim();
|
||||
t.chars().any(char::is_alphanumeric).then(|| t.to_string())
|
||||
};
|
||||
let first = fields.first().map_or(0, |(o, _)| *o);
|
||||
let after_previous =
|
||||
i.checked_sub(1).and_then(|k| fields.get(k)).map_or(0, |(o, _)| o.saturating_add(wordcraft_doc::para::OBJ.len_utf8()));
|
||||
said(0, first).or_else(|| said(after_previous, *seq_at)).or_else(|| instr.split_whitespace().nth(1).map(|id| id.replace('_', " ")))?
|
||||
}
|
||||
None => text.get(..text.find(|c: char| c.is_ascii_digit())?)?.trim().to_string(),
|
||||
};
|
||||
(!label.is_empty() && label.chars().count() <= 40).then_some(label)
|
||||
}
|
||||
|
||||
/// The caption paragraphs of the body: (text, position, label).
|
||||
fn captions(s: &Session) -> Vec<(String, Pos, Option<String>)> {
|
||||
s.doc
|
||||
.para_paths(StoryRef::Body)
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let p = s.doc.para(StoryRef::Body, &path).filter(|p| p.props.style.as_deref() == Some("Caption"))?;
|
||||
let text = p.plain_text();
|
||||
let label = caption_label(p, &text);
|
||||
Some((text, Pos { story: StoryRef::Body, path, off: 0 }, label))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The labels the body's captions use, first seen first: Figure, Table and Equation, and any the
|
||||
/// person made with Insert Caption › New Label. Each is a cross-reference type, `label:<Name>` (#2940).
|
||||
pub fn caption_labels(s: &Session) -> Vec<String> {
|
||||
let mut labels: Vec<String> = Vec::new();
|
||||
for l in captions(s).into_iter().filter_map(|(_, _, l)| l) {
|
||||
if !labels.contains(&l) {
|
||||
labels.push(l);
|
||||
}
|
||||
}
|
||||
labels
|
||||
}
|
||||
|
||||
/// Cross-reference targets of a kind: (shown text or bookmark name, position).
|
||||
pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> {
|
||||
let mut targets: Vec<(String, Pos)> = Vec::new();
|
||||
match to {
|
||||
"bookmark" => targets = s.doc.bookmarks(),
|
||||
// A caption label of the person's own: the captions that use exactly that label.
|
||||
t if t.starts_with("label:") => {
|
||||
let want = t.get("label:".len()..).unwrap_or_default();
|
||||
targets = captions(s)
|
||||
.into_iter()
|
||||
.filter(|(_, _, label)| !want.is_empty() && label.as_deref() == Some(want))
|
||||
.map(|(text, pos, _)| (text, pos))
|
||||
.collect();
|
||||
}
|
||||
"figure" | "table" | "equation" => {
|
||||
let label = match to {
|
||||
"table" => "Table",
|
||||
@@ -1105,6 +1261,80 @@ mod tests {
|
||||
assert!(fields(&s).contains(&(format!("REF {name} \\h"), "Figure 1".to_string())), "{:?}", fields(&s));
|
||||
}
|
||||
|
||||
/// #2940: a caption with a label of the person's own (Insert Caption › New Label) is a
|
||||
/// cross-reference type of its own, `label:<Name>`, next to Figure, Table and Equation.
|
||||
#[test]
|
||||
fn cross_reference_to_a_custom_caption_label() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Rock\nSee "));
|
||||
s.run("select.text", &json!({"text": "Rock"})).unwrap();
|
||||
s.run("references.caption", &json!({"label": "Plate", "text": "A rock"})).unwrap();
|
||||
assert_eq!(caption_labels(&s), vec!["Plate".to_string()]);
|
||||
let list = s.run("insert.crossReference", &json!({"to": "label:Plate"})).unwrap();
|
||||
assert_eq!(list, json!(["Plate 1: A rock"]));
|
||||
assert!(ref_targets(&s, "label:Figure").is_empty(), "only that label's captions");
|
||||
assert!(ref_targets(&s, "label:").is_empty() && ref_targets(&s, "label:Pla").is_empty(), "the whole label");
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.crossReference", &json!({"to": "label:Plate", "target": "Plate 1", "show": "number"})).unwrap();
|
||||
assert!(s.doc.plain_text(StoryRef::Body).ends_with("See Plate 1"), "{}", s.doc.plain_text(StoryRef::Body));
|
||||
assert!(fields(&s).iter().any(|(i, r)| i.starts_with("REF _Ref") && r == "Plate 1"), "{:?}", fields(&s));
|
||||
}
|
||||
|
||||
/// #2940: the label comes from the caption's structure (the text before its `SEQ` number), so
|
||||
/// letter and roman numbering, which have no digit, still name it; a multi-word label too.
|
||||
#[test]
|
||||
fn caption_labels_do_not_need_a_digit() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Rock\nGem\nSand\nSee "));
|
||||
for (text, label, format) in [("Rock", "Plate", "ALPHABETIC"), ("Gem", "Photo Plate", "ROMAN"), ("Sand", "Chart", "ARABIC")] {
|
||||
s.run("select.text", &json!({"text": text})).unwrap();
|
||||
s.run("references.caption", &json!({"label": label, "text": text, "format": format})).unwrap();
|
||||
}
|
||||
assert_eq!(caption_labels(&s), ["Plate", "Photo Plate", "Chart"]);
|
||||
assert_eq!(ref_targets(&s, "label:Plate").len(), 1);
|
||||
assert_eq!(ref_targets(&s, "label:Photo Plate").len(), 1);
|
||||
assert_eq!(ref_targets(&s, "label:Chart").len(), 1);
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.crossReference", &json!({"to": "label:Photo Plate", "target": "Photo Plate I", "show": "number"})).unwrap();
|
||||
assert!(s.doc.plain_text(StoryRef::Body).ends_with("See Photo Plate I"), "{}", s.doc.plain_text(StoryRef::Body));
|
||||
}
|
||||
|
||||
/// #2940: a caption may start with its chapter number (`STYLEREF`) and carry its label text
|
||||
/// between that and the `SEQ` number; the text is the label, not the `SEQ` identifier.
|
||||
#[test]
|
||||
fn caption_label_after_a_chapter_number_field() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Rock\nSee "));
|
||||
let field = |instr: &str| InlineObject::Field {
|
||||
instr: instr.into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
};
|
||||
let plain = CharProps::default();
|
||||
// STYLEREF, " Specimen ", SEQ Figure, ": A rock"
|
||||
let mut imported = Paragraph::new().styled("Caption");
|
||||
imported.insert_object(0, field("STYLEREF 1 \\s"), &plain).unwrap();
|
||||
imported.insert_text(imported.len(), " Specimen ", &plain).unwrap();
|
||||
imported.insert_object(imported.len(), field("SEQ Figure \\* ARABIC"), &plain).unwrap();
|
||||
imported.insert_text(imported.len(), ": A rock", &plain).unwrap();
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(1), Block::Para(imported)).unwrap();
|
||||
// A generated caption with a chapter number: label, STYLEREF, separator, SEQ.
|
||||
s.run("select.text", &json!({"text": "Rock"})).unwrap();
|
||||
s.run("references.caption", &json!({"label": "Plate", "chapter": 1, "separator": "-"})).unwrap();
|
||||
// No label text at all: the SEQ identifier names it, after the chapter number's separator.
|
||||
let mut bare = Paragraph::new().styled("Caption");
|
||||
bare.insert_object(0, field("STYLEREF 1 \\s"), &plain).unwrap();
|
||||
bare.insert_text(bare.len(), "-", &plain).unwrap();
|
||||
bare.insert_object(bare.len(), field("SEQ Photo_Plate"), &plain).unwrap();
|
||||
let end = s.doc.body.len();
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(end), Block::Para(bare)).unwrap();
|
||||
let labels = caption_labels(&s);
|
||||
assert!(labels.contains(&"Specimen".to_string()), "{labels:?}");
|
||||
assert!(labels.contains(&"Plate".to_string()), "{labels:?}");
|
||||
assert!(labels.contains(&"Photo Plate".to_string()), "{labels:?}");
|
||||
assert!(!labels.iter().any(|l| l == "-" || l.is_empty() || l == "Figure"), "{labels:?}");
|
||||
}
|
||||
|
||||
/// #661: References › Table of Authorities › Update Table picks up citations marked after the table.
|
||||
#[test]
|
||||
fn table_of_authorities_updates() {
|
||||
@@ -1185,6 +1415,52 @@ mod tests {
|
||||
assert_eq!(crate::cmd::references::bookmark_text(&s.doc, &name).as_deref(), Some("Kilns"));
|
||||
}
|
||||
|
||||
fn src_of(author: &str, year: &str) -> Value {
|
||||
json!({"author": author, "year": year, "title": "T"})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.sources", &json!({"add": src_of("Smith, Ann", "2020")})).unwrap();
|
||||
assert_eq!(s.doc.sources[0].tag, "Smi20");
|
||||
s.run("references.citation", &json!({"tag": "Smi20"})).unwrap();
|
||||
// What the Edit Source dialog sends: the unchanged tag with the new author and year.
|
||||
let mut edited = src_of("Jones, Bo", "2021");
|
||||
edited["tag"] = json!("Smi20");
|
||||
s.run("references.sources", &json!({"add": edited})).unwrap();
|
||||
assert_eq!(s.doc.sources.len(), 1);
|
||||
assert_eq!(s.doc.sources[0].tag, "Smi20");
|
||||
let f = fields(&s);
|
||||
assert_eq!(f[0].0, "CITATION Smi20");
|
||||
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
for (a, y) in [
|
||||
("Kim", "2000"),
|
||||
("Kim", "2000"),
|
||||
("Kim", "2000"),
|
||||
("Lee", "2019"),
|
||||
("Li", "1999"),
|
||||
("", ""),
|
||||
("", ""),
|
||||
("Ünal, Ece", "7"),
|
||||
("O'Neil", "20x5"),
|
||||
] {
|
||||
s.run("references.sources", &json!({"add": src_of(a, y)})).unwrap();
|
||||
}
|
||||
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
|
||||
assert_eq!(tags, ["Kim00", "Kim001", "Kim002", "Lee19", "Li99", "Src", "Src1", "Üna7", "ONe05"]);
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let mut a = src_of("Lee", "2019");
|
||||
a["tag"] = json!("MyTag");
|
||||
s.run("references.sources", &json!({"add": a})).unwrap();
|
||||
assert_eq!(s.doc.sources[0].tag, "MyTag");
|
||||
}
|
||||
|
||||
fn two_sources(s: &mut Session, a_title: &str) {
|
||||
let a = json!({"tag": "A", "author": "Rivera, Alex; Chen, Mei", "title": a_title, "year": "2021", "publisher": "Harbor Books", "city": "Portland"});
|
||||
let b = json!({"tag": "B", "author": "Okafor, Ngozi", "title": "Kilns and Clay", "year": "2019", "journal": "Studio Quarterly", "volume": "4", "pages": "10-20"});
|
||||
@@ -1226,6 +1502,92 @@ mod tests {
|
||||
assert_eq!(s.bib_style, "Turabian", "an unknown style keeps the current one");
|
||||
}
|
||||
|
||||
/// #2640: Manage Sources › Import reads a Word bibliography file (`b:Sources`: Word's own
|
||||
/// `Sources.xml`) into the document. An untagged source gets a tag like a new one; a tag
|
||||
/// already here is left alone; the whole import is one undo step; and a file that isn't
|
||||
/// `b:Sources` is an error, not a silent success.
|
||||
#[test]
|
||||
fn import_sources_reads_a_word_bibliography_file() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-import-sources-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Sources.xml");
|
||||
let xml = br#"<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<b:Sources xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"
|
||||
xmlns="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"
|
||||
SelectedStyle="\APA.XSL" StyleName="APA">
|
||||
<b:Source><b:Tag>Riv21</b:Tag><b:SourceType>Book</b:SourceType>
|
||||
<b:Author><b:Author><b:NameList><b:Person><b:Last>Rivera</b:Last><b:First>Alex</b:First></b:Person></b:NameList></b:Author></b:Author>
|
||||
<b:Title>Shared Spaces</b:Title><b:Year>2021</b:Year><b:City>Portland</b:City><b:Publisher>Harbor Books</b:Publisher>
|
||||
</b:Source>
|
||||
<b:Source><b:SourceType>Book</b:SourceType></b:Source>
|
||||
<b:Source><b:SourceType>JournalArticle</b:SourceType>
|
||||
<b:Author><b:Author><b:NameList><b:Person><b:Last>Okafor</b:Last><b:First>Ngozi</b:First></b:Person></b:NameList></b:Author></b:Author>
|
||||
<b:Title>Kilns and Clay</b:Title><b:JournalName>Studio Quarterly</b:JournalName><b:Year>2019</b:Year>
|
||||
</b:Source>
|
||||
</b:Sources>"#;
|
||||
std::fs::write(&path, xml).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.sources", &json!({"import": path})).unwrap();
|
||||
assert_eq!(s.doc.sources.len(), 2, "the source with no content is dropped");
|
||||
assert_eq!(s.doc.sources[0].tag, "Riv21");
|
||||
assert_eq!((s.doc.sources[0].author.as_str(), s.doc.sources[0].title.as_str()), ("Rivera, Alex", "Shared Spaces"));
|
||||
assert_eq!(
|
||||
(s.doc.sources[1].tag.as_str(), s.doc.sources[1].kind.as_str()),
|
||||
("Oka19", "article"),
|
||||
"an untagged source gets a tag like a new one"
|
||||
);
|
||||
assert!(s.dirty, "the document is marked edited");
|
||||
|
||||
// The import is one undo step, and importing again adds nothing.
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc.sources.is_empty(), "one undo takes the whole import back");
|
||||
s.run("references.sources", &json!({"import": path})).unwrap();
|
||||
s.doc.sources[0].title = "Shared Spaces, revised".into();
|
||||
s.run("references.sources", &json!({"import": path})).unwrap();
|
||||
assert_eq!(s.doc.sources.len(), 2, "a tag already here is not added again");
|
||||
assert_eq!(s.doc.sources[0].title, "Shared Spaces, revised", "an import never overwrites an edited source");
|
||||
assert_eq!(s.doc.sources[1].tag, "Oka19", "the untagged source keeps the tag it was given");
|
||||
|
||||
// Anything that isn't b:Sources is refused.
|
||||
let bad = dir.join("not-sources.xml");
|
||||
std::fs::write(&bad, "<html><body>no</body></html>").unwrap();
|
||||
let e = s.run("references.sources", &json!({"import": bad.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.to_string().contains("not a Word document"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #2640: untagged sources that share a tag stem get the tag, then `1`, `2`… in import order,
|
||||
/// and a second import adds none of them (the untagged one matches by title).
|
||||
#[test]
|
||||
fn an_import_tags_each_untagged_source_once() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-import-tags-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Sources.xml");
|
||||
std::fs::write(
|
||||
&path,
|
||||
r#"<b:Sources xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography">
|
||||
<b:Source><b:SourceType>Book</b:SourceType><b:Title>First Work</b:Title><b:Year>2021</b:Year>
|
||||
<b:Author><b:Author><b:NameList><b:Person><b:Last>Rivera</b:Last><b:First>Alex</b:First></b:Person></b:NameList></b:Author></b:Author></b:Source>
|
||||
<b:Source><b:SourceType>Book</b:SourceType><b:Title>Second Work</b:Title><b:Year>2021</b:Year>
|
||||
<b:Author><b:Author><b:NameList><b:Person><b:Last>Rivera</b:Last><b:First>Alex</b:First></b:Person></b:NameList></b:Author></b:Author></b:Source>
|
||||
<b:Source><b:SourceType>Book</b:SourceType><b:Title>Third Work</b:Title></b:Source>
|
||||
</b:Sources>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.sources", &json!({"import": path})).unwrap();
|
||||
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
|
||||
assert_eq!(tags, ["Riv21", "Riv211", "Src"], "{tags:?}");
|
||||
s.run("references.sources", &json!({"import": path})).unwrap();
|
||||
assert_eq!(s.doc.sources.len(), 3, "the tags are here and the untagged one matches by title");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_styles_count_in_order_of_first_citation() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
|
||||
@@ -159,6 +159,13 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
}
|
||||
return super::sel_result(s);
|
||||
}
|
||||
// Backspace over whole rows, whole columns or the whole table deletes them, as in Word
|
||||
// (Delete only clears them, as for any other cells).
|
||||
if id == "text.backspace"
|
||||
&& let Some(r) = super::table::backspace_cells(s)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
let Some(segs) = s.column_segments().map(<[(Pos, Pos)]>::to_vec) else { return run(s, v) };
|
||||
let cells = s.cell_range().is_some();
|
||||
match id {
|
||||
|
||||
@@ -142,12 +142,27 @@ pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
|
||||
/// The built-in name of the placeholder style. Its id is localized: German Word writes
|
||||
/// `Platzhaltertext`, English `PlaceholderText`.
|
||||
const PLACEHOLDER_STYLE_NAME: &str = "Placeholder Text";
|
||||
|
||||
/// The id of the document's placeholder style: the one named "Placeholder Text", else the
|
||||
/// English id.
|
||||
fn placeholder_style_id(doc: &wordcraft_doc::Document) -> String {
|
||||
doc.styles
|
||||
.styles
|
||||
.iter()
|
||||
.find(|st| st.kind == StyleKind::Character && st.name.eq_ignore_ascii_case(PLACEHOLDER_STYLE_NAME))
|
||||
.map(|st| st.id.clone())
|
||||
.unwrap_or_else(|| PLACEHOLDER_STYLE.into())
|
||||
}
|
||||
|
||||
/// The placeholder style, added to the document when it hasn't one.
|
||||
fn ensure_placeholder_style(s: &mut Session) {
|
||||
if s.doc.styles.get(PLACEHOLDER_STYLE).is_none() {
|
||||
if s.doc.styles.get(&placeholder_style_id(&s.doc)).is_none() {
|
||||
s.doc.styles.styles.push(Style {
|
||||
id: PLACEHOLDER_STYLE.into(),
|
||||
name: "Placeholder Text".into(),
|
||||
name: PLACEHOLDER_STYLE_NAME.into(),
|
||||
kind: StyleKind::Character,
|
||||
based_on: Some("DefaultParagraphFont".into()),
|
||||
chr: CharProps { color: Some(TextColor::Rgb(Rgb(0x66, 0x66, 0x66))), ..Default::default() },
|
||||
@@ -161,13 +176,13 @@ fn ensure_placeholder_style(s: &mut Session) {
|
||||
/// Formatting for placeholder text based on `base`.
|
||||
fn placeholder_props(s: &mut Session, base: &CharProps) -> CharProps {
|
||||
ensure_placeholder_style(s);
|
||||
CharProps { style: Some(PLACEHOLDER_STYLE.into()), link: None, ..base.clone() }
|
||||
CharProps { style: Some(placeholder_style_id(&s.doc)), link: None, ..base.clone() }
|
||||
}
|
||||
|
||||
/// `base` without the placeholder style (for real content).
|
||||
fn content_props(base: &CharProps) -> CharProps {
|
||||
/// `base` without the placeholder style (for real content), whatever its localized id.
|
||||
fn content_props(doc: &wordcraft_doc::Document, base: &CharProps) -> CharProps {
|
||||
let mut p = base.clone();
|
||||
if p.style.as_deref() == Some(PLACEHOLDER_STYLE) {
|
||||
if p.style.as_deref().is_some_and(|id| id == PLACEHOLDER_STYLE || id == placeholder_style_id(doc)) {
|
||||
p.style = None;
|
||||
}
|
||||
p
|
||||
@@ -248,7 +263,7 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
|
||||
.para_at(&a)
|
||||
.map(|p| if r.is_empty() { p.props_of_char(r.start.off).clone() } else { p.props_of_char(a.off).clone() })
|
||||
.unwrap_or_default();
|
||||
content_props(&props)
|
||||
content_props(&s.doc, &props)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -299,7 +314,14 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
|
||||
if !r.control.showing_placeholder || !r.contains(&b) {
|
||||
return Ok(None);
|
||||
}
|
||||
let props = content_base(s, &r);
|
||||
// Text typed in place of the placeholder takes the control's own run properties (Word, and
|
||||
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
|
||||
// showing placeholder's own character style is that style, whatever a producer called it
|
||||
// (Word localizes only the id; another program may localize the name too).
|
||||
let props = match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, &r) },
|
||||
};
|
||||
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
c.showing_placeholder = false;
|
||||
@@ -423,7 +445,7 @@ fn insert(s: &mut Session, v: &Value, kind: ControlKind) -> CmdResult {
|
||||
// An inline control: around the selection (text and pictures), else at the caret with its
|
||||
// placeholder or value.
|
||||
let wraps = a != b && a.path == b.path && matches!(ctl.kind, ControlKind::RichText | ControlKind::Text { .. } | ControlKind::Picture);
|
||||
let base = s.doc.para_at(&a).map(|p| content_props(&p.props_of_char(a.off).clone())).unwrap_or_default();
|
||||
let base = s.doc.para_at(&a).map(|p| content_props(&s.doc, &p.props_of_char(a.off).clone())).unwrap_or_default();
|
||||
if wraps {
|
||||
s.doc.insert_object(&b, InlineObject::ControlEnd, &base)?;
|
||||
let start = a.clone();
|
||||
@@ -464,7 +486,7 @@ fn insert_block(s: &mut Session, mut ctl: ContentControl, a: &Pos, b: &Pos) -> C
|
||||
let last = if b.path.parent() == a.path.parent() { b.path.clone() } else { a.path.clone() };
|
||||
ctl.block = true;
|
||||
let empty = a.path == last && s.doc.para(story, &a.path).is_some_and(|p| p.is_empty());
|
||||
let base = s.doc.para(story, &a.path).map(|p| content_props(&p.props_of_char(0).clone())).unwrap_or_default();
|
||||
let base = s.doc.para(story, &a.path).map(|p| content_props(&s.doc, &p.props_of_char(0).clone())).unwrap_or_default();
|
||||
let item = matches!(ctl.kind, ControlKind::RepeatingSection { .. }).then(|| {
|
||||
let mut i = ContentControl::new(ControlKind::RepeatingSectionItem);
|
||||
i.block = true;
|
||||
@@ -748,6 +770,55 @@ mod editing_tests {
|
||||
run(s, "developer.control", json!({}))
|
||||
}
|
||||
|
||||
/// A form from German Word names its placeholder style `Platzhaltertext` ("Placeholder Text"),
|
||||
/// and each control's `w:rPr` gives the style entered text takes (`Eingabe`, bold black).
|
||||
/// Text typed over the placeholder takes the control's run properties, as in Word (17 of 17
|
||||
/// values filled in Word did); without them it drops the placeholder style whatever its id.
|
||||
/// WordCraft kept the German placeholder style, so entries stayed grey.
|
||||
#[test]
|
||||
fn typing_over_a_localized_placeholder_takes_the_controls_formatting() {
|
||||
use wordcraft_doc::props::{CharProps, Rgb, TextColor};
|
||||
use wordcraft_doc::styles::{Style, StyleKind};
|
||||
let style =
|
||||
|id: &str, name: &str, chr: CharProps| Style { id: id.into(), name: name.into(), kind: StyleKind::Character, chr, ..Default::default() };
|
||||
let typed_style = |run_props: Option<CharProps>| {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let grey = CharProps { color: Some(TextColor::Rgb(Rgb(0x80, 0x80, 0x80))), ..Default::default() };
|
||||
s.doc.styles.styles.push(style("Platzhaltertext", "Placeholder Text", grey));
|
||||
s.doc.styles.styles.push(style("Eingabe", "Eingabe", CharProps { bold: Some(true), ..Default::default() }));
|
||||
run(&mut s, "text.insert", json!({"text": "Name: "}));
|
||||
run(&mut s, "developer.plainText", json!({"tag": "name"}));
|
||||
let start = s.doc.control_at(&s.sel.focus).unwrap().start;
|
||||
s.doc.control_mut(&start).unwrap().run_props = run_props;
|
||||
// The placeholder uses the document's own placeholder style; none is added.
|
||||
let r = s.doc.control_at(&s.sel.focus).unwrap();
|
||||
let shown = s.doc.para_at(&r.content_start()).unwrap().props_of_char(r.content_start().off).style.clone();
|
||||
assert_eq!(shown.as_deref(), Some("Platzhaltertext"));
|
||||
assert_eq!(s.doc.styles.styles.iter().filter(|st| st.name == "Placeholder Text").count(), 1);
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "Ada"}));
|
||||
let r = s.doc.control_at(&s.sel.focus).unwrap();
|
||||
s.doc.para_at(&r.content_start()).unwrap().props_of_char(r.content_start().off).style.clone()
|
||||
};
|
||||
let eingabe = CharProps { style: Some("Eingabe".into()), ..Default::default() };
|
||||
assert_eq!(typed_style(Some(eingabe)).as_deref(), Some("Eingabe"), "the control's run properties");
|
||||
assert_eq!(typed_style(None), None, "no placeholder style left");
|
||||
// A producer that localizes the style's name as well: the showing placeholder's own
|
||||
// style goes all the same.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let grey = CharProps { color: Some(TextColor::Rgb(Rgb(0x80, 0x80, 0x80))), ..Default::default() };
|
||||
s.doc.styles.styles.push(style("TexteEspaceReserve", "Texte de l'espace réservé", grey));
|
||||
run(&mut s, "text.insert", json!({"text": "Nom : "}));
|
||||
run(&mut s, "developer.plainText", json!({"tag": "nom"}));
|
||||
let r = s.doc.control_at(&s.sel.focus).unwrap();
|
||||
s.doc.format_range(&r.content_start(), &r.end, &|c| c.style = Some("TexteEspaceReserve".into())).unwrap();
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "Ada"}));
|
||||
let r = s.doc.control_at(&s.sel.focus).unwrap();
|
||||
let typed = s.doc.para_at(&r.content_start()).unwrap().props_of_char(r.content_start().off).style.clone();
|
||||
assert_eq!(typed, None, "a placeholder style localized in id and name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_replaces_the_placeholder_and_emptying_brings_it_back() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
|
||||
+300
-13
@@ -22,7 +22,7 @@ use wordcraft_doc::{CharProps, Pos, StoryRef};
|
||||
use wordcraft_geom::Rect;
|
||||
use wordcraft_layout::{DocLayout, Placed};
|
||||
|
||||
use super::ink_shape::{InkShape, recognise};
|
||||
use super::ink_shape::{ArrowParts, InkShape, arrow_parts, pair_parts, recognise};
|
||||
use super::pos_json;
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
|
||||
@@ -461,9 +461,26 @@ fn stroke(s: &mut Session, v: &Value) -> CmdResult {
|
||||
extra: Default::default(),
|
||||
};
|
||||
let at = place(s, &layout, obj, page, (fx, fy), (first[0], first[1]))?;
|
||||
// Ink to Shape: a stroke that looks like a shape becomes it (in the same undo step).
|
||||
let shape = if s.view.draw.ink_to_shape && tool != InkTool::Highlighter { convert_at(s, &at)? } else { None };
|
||||
Ok(json!({"pos": pos_json(&at), "page": page, "rect": [fx, fy, fw, fh], "shape": shape}))
|
||||
// Ink to Shape: a stroke that looks like a shape becomes it, and a line and a head drawn as two
|
||||
// strokes become one arrow (in the same undo step).
|
||||
let (at, shape, rect) = if s.view.draw.ink_to_shape && tool != InkTool::Highlighter {
|
||||
match pair_with_neighbour(s, page, &at)? {
|
||||
Some(arrow) => {
|
||||
// The arrow is the line drawn earlier (or just now): its frame, not the stroke's.
|
||||
s.touch();
|
||||
let r = s.layout().object(&arrow, page).map(|o| o.rect);
|
||||
let rect = r.map_or([fx, fy, fw, fh], |r| [r.x, r.y, r.w, r.h]);
|
||||
(arrow, Some("arrow"), rect)
|
||||
}
|
||||
None => {
|
||||
let shape = convert_at(s, &at)?;
|
||||
(at, shape, [fx, fy, fw, fh])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(at, None, [fx, fy, fw, fh])
|
||||
};
|
||||
Ok(json!({"pos": pos_json(&at), "page": page, "rect": rect, "shape": shape}))
|
||||
}
|
||||
|
||||
/// Insert floating `obj` with its top-left at `(x, y)` on `page`, anchored to the body paragraph
|
||||
@@ -676,28 +693,141 @@ fn lasso_color(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
// --- Ink to Shape --------------------------------------------------------------------------
|
||||
|
||||
/// Turn the lasso-selected strokes that look like shapes into those shapes (one undo step).
|
||||
/// Turn the lasso-selected strokes that look like shapes into those shapes, and a selected line
|
||||
/// and arrowhead drawn as two strokes into one arrow (one undo step).
|
||||
fn convert_selection(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let sel = lasso_required(s)?;
|
||||
let mut converted = Vec::new();
|
||||
for pos in &sel.items {
|
||||
let layout = s.layout();
|
||||
let pieces = arrow_pieces(s, &layout, sel.page, |pos, _| sel.items.contains(pos));
|
||||
let (mut used, mut heads, mut converted): (Vec<Pos>, Vec<Pos>, Vec<(Pos, &'static str)>) = (Vec::new(), Vec::new(), Vec::new());
|
||||
// Each piece was recognised once; pairing them is cheap geometry, even for a crowded page.
|
||||
for line in pieces.iter().filter(|k| k.parts.line.is_some()) {
|
||||
for head in pieces.iter().filter(|k| !k.parts.heads.is_empty()) {
|
||||
if line.pos == head.pos || used.contains(&line.pos) || used.contains(&head.pos) || !near(line.rect, head.rect) {
|
||||
continue;
|
||||
}
|
||||
if let Some(arrow) = pair_parts(&line.parts, &head.parts) {
|
||||
set_shape(s, &line.pos, &local_to(&arrow, line.rect))?;
|
||||
used.extend([line.pos.clone(), head.pos.clone()]);
|
||||
heads.push(head.pos.clone());
|
||||
converted.push((line.pos.clone(), "arrow"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for pos in sel.items.iter().filter(|p| !used.contains(p)) {
|
||||
if let Some(name) = convert_at(s, pos)? {
|
||||
converted.push(json!({"pos": pos_json(pos), "shape": name}));
|
||||
converted.push((pos.clone(), name));
|
||||
}
|
||||
}
|
||||
if converted.is_empty() {
|
||||
return Err(CmdError::Failed("none of the selected strokes looks like a shape".into()));
|
||||
}
|
||||
keep_lasso(s, sel);
|
||||
// The heads went into their arrows; last first, so the earlier ones keep their place.
|
||||
heads.sort();
|
||||
for pos in heads.iter().rev() {
|
||||
delete_object(s, pos)?;
|
||||
}
|
||||
let items = sel.items.iter().filter(|p| !heads.contains(p)).map(|p| after_deleting(p, &heads)).collect();
|
||||
let converted: Vec<Value> = converted.iter().map(|(p, name)| json!({"pos": pos_json(&after_deleting(p, &heads)), "shape": name})).collect();
|
||||
keep_lasso(s, LassoSelection { items, ..sel });
|
||||
Ok(json!({"count": converted.len(), "converted": converted}))
|
||||
}
|
||||
|
||||
/// Where `pos` is once the objects at `deleted` (none of them `pos`) are gone.
|
||||
fn after_deleting(pos: &Pos, deleted: &[Pos]) -> Pos {
|
||||
let before = deleted.iter().filter(|d| d.story == pos.story && d.path == pos.path && d.off < pos.off).count();
|
||||
Pos { off: pos.off.saturating_sub(before.saturating_mul(OBJ.len_utf8())), ..pos.clone() }
|
||||
}
|
||||
|
||||
/// A stroke (or an Ink to Shape line or triangle) on a page that may be one half of a two-stroke
|
||||
/// arrow: where it is, when it was drawn (ink's drawing order) and what it can be in an arrow.
|
||||
struct ArrowPiece {
|
||||
pos: Pos,
|
||||
rect: Rect,
|
||||
order: Option<u32>,
|
||||
parts: ArrowParts,
|
||||
}
|
||||
|
||||
/// Whether two objects laid out at `a` and `b` are close enough to make an arrow (a cheap test
|
||||
/// before recognising them).
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
let reach = 0.2 * a.w.max(a.h).max(b.w).max(b.h);
|
||||
reach.is_finite() && a.expand(reach).intersects(&b.expand(reach))
|
||||
}
|
||||
|
||||
/// The pieces of two-stroke arrows on `page` that `keep` (given the position and laid-out rect)
|
||||
/// accepts: unturned, unflipped pen and pencil strokes, and the open two-point lines and closed
|
||||
/// triangles Ink to Shape makes. `keep` runs first, so only kept pieces are recognised.
|
||||
fn arrow_pieces(s: &Session, layout: &DocLayout, page: usize, keep: impl Fn(&Pos, &Rect) -> bool) -> Vec<ArrowPiece> {
|
||||
let Some(pg) = layout.pages.get(page) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for it in &pg.items {
|
||||
let Placed::Object { rect, spin, story, path, off, .. } = it else { continue };
|
||||
let pos = Pos { story: *story, path: path.clone(), off: *off };
|
||||
if !spin.is_identity() || !keep(&pos, rect) {
|
||||
continue;
|
||||
}
|
||||
let Some(InlineObject::Shape { kind, freeform: Some(f), float, .. }) = s.doc.para_at(&pos).and_then(|p| p.object_at(*off)) else { continue };
|
||||
let Some(fp) = f.paths.first().filter(|_| f.paths.len() == 1) else { continue };
|
||||
let pen = matches!(f.ink, Some(InkTool::Pen | InkTool::Pencil)) && !s.view.hide_ink;
|
||||
let shape = f.ink.is_none() && *kind == ShapeKind::Freeform && matches!((fp.pts.len(), fp.closed), (2, false) | (3, true));
|
||||
if !(pen || shape) || float.rot != 0.0 || float.flip_h || float.flip_v {
|
||||
continue;
|
||||
}
|
||||
let Some((mut pts, closed)) = f.placed(rect.x, rect.y, rect.w, rect.h).into_iter().next() else { continue };
|
||||
if closed && let Some(&first) = pts.first() {
|
||||
pts.push(first);
|
||||
}
|
||||
out.push(ArrowPiece { pos, rect: *rect, order: f.order, parts: arrow_parts(&pts) });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Ink to Shape while drawing: when the stroke just drawn at `new` and another on the page are a
|
||||
/// line and an arrowhead (either drawn first), make the line an arrow and drop the head. Returns
|
||||
/// where the arrow is.
|
||||
fn pair_with_neighbour(s: &mut Session, page: usize, new: &Pos) -> Result<Option<Pos>, CmdError> {
|
||||
s.touch(); // lay out the new stroke where it was just placed
|
||||
let layout = s.layout();
|
||||
let Some(mine) = layout.object(new, page).map(|o| o.rect) else { return Ok(None) };
|
||||
// Only the new stroke and its neighbours are recognised, not the whole page.
|
||||
let mut pieces = arrow_pieces(s, &layout, page, |pos, rect| pos == new || near(mine, *rect));
|
||||
let Some(at) = pieces.iter().position(|k| k.pos == *new) else { return Ok(None) };
|
||||
let me = pieces.swap_remove(at);
|
||||
// The most recently drawn first (ink records its drawing order; shapes and ink from files
|
||||
// don't, and come after, latest on the page first), so the winner doesn't depend on layout.
|
||||
pieces.sort_by(|a, b| b.order.cmp(&a.order).then_with(|| b.pos.cmp(&a.pos)));
|
||||
for other in &pieces {
|
||||
for (line, head) in [(other, &me), (&me, other)] {
|
||||
if let Some(arrow) = pair_parts(&line.parts, &head.parts) {
|
||||
set_shape(s, &line.pos, &local_to(&arrow, line.rect))?;
|
||||
delete_object(s, &head.pos)?;
|
||||
return Ok(Some(after_deleting(&line.pos, std::slice::from_ref(&head.pos))));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// `shape` (in page points) in the frame of the object laid out at `rect`.
|
||||
fn local_to(shape: &InkShape, rect: Rect) -> InkShape {
|
||||
let m = |[x, y]: [f32; 2]| [x - rect.x, y - rect.y];
|
||||
match shape {
|
||||
InkShape::Arrow { a, b, head_at_end, head_at_start } => {
|
||||
InkShape::Arrow { a: m(*a), b: m(*b), head_at_end: *head_at_end, head_at_start: *head_at_start }
|
||||
}
|
||||
InkShape::Line { a, b } => InkShape::Line { a: m(*a), b: m(*b) },
|
||||
InkShape::Rectangle { x, y, w, h } => InkShape::Rectangle { x: x - rect.x, y: y - rect.y, w: *w, h: *h },
|
||||
InkShape::Ellipse { x, y, w, h } => InkShape::Ellipse { x: x - rect.x, y: y - rect.y, w: *w, h: *h },
|
||||
InkShape::Polygon(c) => InkShape::Polygon(c.iter().copied().map(m).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the ink stroke at `pos` by the shape it looks like, in its colour and thickness and
|
||||
/// where it was drawn. `None` (nothing changed) when it isn't a pen or pencil stroke, it is
|
||||
/// turned or flipped, or it doesn't look like a shape.
|
||||
fn convert_at(s: &mut Session, pos: &Pos) -> Result<Option<&'static str>, CmdError> {
|
||||
let para = s.doc.para_mut(pos.story, &pos.path)?;
|
||||
let Some(InlineObject::Shape { kind, w, h, fill, float, freeform, extra, .. }) = para.object_at_mut(pos.off) else { return Ok(None) };
|
||||
let Some(InlineObject::Shape { w, h, float, freeform, .. }) = s.doc.para_at(pos).and_then(|p| p.object_at(pos.off)) else { return Ok(None) };
|
||||
let Some(f) = freeform.as_deref().filter(|f| matches!(f.ink, Some(InkTool::Pen | InkTool::Pencil)) && f.paths.len() == 1) else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -707,13 +837,24 @@ fn convert_at(s: &mut Session, pos: &Pos) -> Result<Option<&'static str>, CmdErr
|
||||
// The stroke in its frame's own points (the frame may have been resized since).
|
||||
let Some((pts, _)) = f.placed(0.0, 0.0, *w, *h).into_iter().next() else { return Ok(None) };
|
||||
let Some(found) = recognise(&pts) else { return Ok(None) };
|
||||
set_shape(s, pos, &found)?;
|
||||
Ok(Some(found.name()))
|
||||
}
|
||||
|
||||
/// Make the drawing at `pos` the shape `found` (given in the drawing's own frame), keeping its
|
||||
/// colour and thickness, where it is.
|
||||
fn set_shape(s: &mut Session, pos: &Pos, found: &InkShape) -> Result<(), CmdError> {
|
||||
let para = s.doc.para_mut(pos.story, &pos.path)?;
|
||||
let Some(InlineObject::Shape { kind, w, h, fill, float, freeform, extra, .. }) = para.object_at_mut(pos.off) else {
|
||||
return Err(CmdError::Failed("no drawing there".into()));
|
||||
};
|
||||
let [bx, by, bw, bh] = found.bounds();
|
||||
let (bw, bh) = (bw.max(1.0), bh.max(1.0));
|
||||
let outline = |pts: Vec<[f32; 2]>, closed: bool| {
|
||||
Some(Arc::new(Freeform { w: bw, h: bh, paths: vec![FreePath { pts, closed }], ..Default::default() }.sanitized()))
|
||||
};
|
||||
let local = |c: &[[f32; 2]]| c.iter().map(|[x, y]| [x - bx, y - by]).collect::<Vec<_>>();
|
||||
let (new_kind, geometry) = match &found {
|
||||
let (new_kind, geometry) = match found {
|
||||
InkShape::Rectangle { .. } => (ShapeKind::Rectangle, None),
|
||||
InkShape::Ellipse { .. } => (ShapeKind::Ellipse, None),
|
||||
InkShape::Line { a, b } => (ShapeKind::Freeform, outline(local(&[*a, *b]), false)),
|
||||
@@ -735,7 +876,7 @@ fn convert_at(s: &mut Session, pos: &Pos) -> Result<Option<&'static str>, CmdErr
|
||||
float.x += bx;
|
||||
float.y += by;
|
||||
para.touch();
|
||||
Ok(Some(found.name()))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- Ink Replay ----------------------------------------------------------------------------
|
||||
@@ -1017,6 +1158,152 @@ mod tests {
|
||||
assert!(extra.arrow_end && !extra.arrow_start && float.flip_h, "{extra:?} {float:?}");
|
||||
}
|
||||
|
||||
/// Every drawing in the body, in document order.
|
||||
fn drawings(s: &Session) -> Vec<InlineObject> {
|
||||
s.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter(|o| matches!(o, InlineObject::Shape { .. }))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A straight stroke from (100, 300) to (300, 300).
|
||||
fn shaft_stroke() -> Vec<[f32; 2]> {
|
||||
(0..=40).map(|i| [100.0 + i as f32 * 5.0, 300.0]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_to_shape_turns_a_line_and_a_head_drawn_after_it_into_one_arrow_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
s.run("draw.inkToShape", &json!({"value": true})).unwrap();
|
||||
let r = s.run("draw.stroke", &json!({"page": 0, "points": shaft_stroke(), "color": "C00000", "width": 2})).unwrap();
|
||||
assert_eq!(r["shape"], "line");
|
||||
let steps = s.undo_depth();
|
||||
// An open V at the right-hand end, drawn as a second stroke.
|
||||
let head = [[274.0, 285.0], [287.0, 292.5], [300.0, 300.0], [287.0, 307.5], [274.0, 315.0]];
|
||||
let r = s.run("draw.stroke", &json!({"page": 0, "points": head})).unwrap();
|
||||
assert_eq!(r["shape"], "arrow");
|
||||
assert_eq!(s.undo_depth(), steps + 1, "paired in one undo step");
|
||||
assert!(ink(&s).is_empty(), "the head stroke is gone");
|
||||
let all = drawings(&s);
|
||||
let [InlineObject::Shape { kind, w, stroke, stroke_width, extra, float, .. }] = all.as_slice() else { panic!("one arrow: {all:?}") };
|
||||
assert_eq!((*kind, *stroke, *stroke_width), (ShapeKind::StraightConnector, Some(wordcraft_doc::Rgb(0xC0, 0, 0)), 2.0));
|
||||
assert!(extra.arrow_end && !extra.arrow_start && !float.flip_h && !float.flip_v, "{extra:?} {float:?}");
|
||||
assert!((w - 200.0).abs() < 1.0, "{w}");
|
||||
let at: wordcraft_doc::Pos = serde_json::from_value(r["pos"].clone()).unwrap();
|
||||
assert!(matches!(s.doc.para_at(&at).and_then(|p| p.object_at(at.off)), Some(InlineObject::Shape { kind: ShapeKind::StraightConnector, .. })));
|
||||
let rect = s.layout().object(&at, 0).unwrap().rect;
|
||||
assert!((rect.x - 100.0).abs() < 1.0 && (rect.y - 300.0).abs() < 1.0, "where the line was: {rect:?}");
|
||||
let got: Vec<f32> = r["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect();
|
||||
assert!(
|
||||
got.len() == 4 && [rect.x, rect.y, rect.w, rect.h].iter().zip(&got).all(|(a, b)| (a - b).abs() < 0.5),
|
||||
"the arrow's rect, not the deleted head's: {got:?} vs {rect:?}"
|
||||
);
|
||||
// It survives a DOCX save and open.
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap();
|
||||
let again: Vec<_> = back.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).collect();
|
||||
assert!(
|
||||
again
|
||||
.iter()
|
||||
.any(|o| matches!(o, InlineObject::Shape { kind: ShapeKind::StraightConnector, extra, .. } if extra.arrow_end && !extra.arrow_start)),
|
||||
"{again:?}"
|
||||
);
|
||||
// Undo brings back the line, without the head.
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
let all = drawings(&s);
|
||||
let [InlineObject::Shape { kind: ShapeKind::Freeform, extra, .. }] = all.as_slice() else { panic!("the line: {all:?}") };
|
||||
assert!(!extra.arrow_end);
|
||||
assert!(ink(&s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_to_shape_pairs_a_closed_triangle_head_at_the_start_and_a_head_drawn_first() {
|
||||
let mut s = session();
|
||||
s.run("draw.inkToShape", &json!({"value": true})).unwrap();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": shaft_stroke()})).unwrap();
|
||||
// A closed triangle at the left end, where the line began: the arrow points left.
|
||||
let tri = [[100.0, 300.0], [113.0, 292.5], [126.0, 285.0], [126.0, 300.0], [126.0, 315.0], [113.0, 307.5], [100.0, 300.0]];
|
||||
let r = s.run("draw.stroke", &json!({"page": 0, "points": tri})).unwrap();
|
||||
assert_eq!(r["shape"], "arrow");
|
||||
let all = drawings(&s);
|
||||
let [InlineObject::Shape { kind: ShapeKind::StraightConnector, extra, float, .. }] = all.as_slice() else { panic!("one arrow: {all:?}") };
|
||||
assert!(extra.arrow_end && float.flip_h && !float.flip_v, "tip at the left: {extra:?} {float:?}");
|
||||
// Head first (it stays ink on its own), then the shaft that ends at its apex.
|
||||
let mut s = session();
|
||||
s.run("draw.inkToShape", &json!({"value": true})).unwrap();
|
||||
let r = s.run("draw.stroke", &json!({"page": 0, "points": [[274.0, 285.0], [300.0, 300.0], [274.0, 315.0]]})).unwrap();
|
||||
assert!(r["shape"].is_null());
|
||||
let r = s.run("draw.stroke", &json!({"page": 0, "points": shaft_stroke()})).unwrap();
|
||||
assert_eq!(r["shape"], "arrow");
|
||||
assert!(ink(&s).is_empty());
|
||||
let all = drawings(&s);
|
||||
let [InlineObject::Shape { kind: ShapeKind::StraightConnector, extra, float, .. }] = all.as_slice() else { panic!("one arrow: {all:?}") };
|
||||
assert!(extra.arrow_end && !float.flip_h, "{extra:?} {float:?}");
|
||||
// A V far from the line's ends stays ink, and the line stays a line.
|
||||
let mut s = session();
|
||||
s.run("draw.inkToShape", &json!({"value": true})).unwrap();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": shaft_stroke()})).unwrap();
|
||||
let r = s.run("draw.stroke", &json!({"page": 0, "points": [[174.0, 385.0], [200.0, 400.0], [174.0, 415.0]]})).unwrap();
|
||||
assert!(r["shape"].is_null());
|
||||
assert_eq!(ink(&s).len(), 1);
|
||||
assert!(drawings(&s).iter().all(|o| !matches!(o, InlineObject::Shape { kind: ShapeKind::StraightConnector, .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converting_a_lasso_selection_pairs_a_line_and_a_head_stroke_into_an_arrow() {
|
||||
let mut s = session();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": shaft_stroke(), "color": "0070C0"})).unwrap();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": [[274.0, 285.0], [300.0, 300.0], [274.0, 315.0]]})).unwrap();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": rect_stroke(100.0, 400.0, 120.0, 60.0)})).unwrap();
|
||||
assert_eq!(ink(&s).len(), 3);
|
||||
let steps = s.undo_depth();
|
||||
s.run("draw.lasso", &json!({"page": 0, "points": [[80, 260], [340, 260], [340, 480], [80, 480]]})).unwrap();
|
||||
let r = s.run("draw.inkToShape", &json!({})).unwrap();
|
||||
let names: Vec<&str> = r["converted"].as_array().unwrap().iter().filter_map(|c| c["shape"].as_str()).collect();
|
||||
assert!(names.contains(&"arrow") && names.contains(&"rectangle"), "{names:?}");
|
||||
assert!(ink(&s).is_empty(), "the head stroke went into the arrow");
|
||||
let all = drawings(&s);
|
||||
assert_eq!(all.len(), 2, "{all:?}");
|
||||
let arrow = all.iter().find(|o| matches!(o, InlineObject::Shape { kind: ShapeKind::StraightConnector, .. }));
|
||||
let Some(InlineObject::Shape { extra, stroke, .. }) = arrow else { panic!("{all:?}") };
|
||||
assert!(extra.arrow_end && *stroke == Some(wordcraft_doc::Rgb(0, 0x70, 0xC0)));
|
||||
// The selection still holds what's left: deleting it removes both shapes.
|
||||
s.run("draw.lassoDelete", &json!({})).unwrap();
|
||||
assert!(drawings(&s).is_empty());
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(drawings(&s).len(), 2);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(ink(&s).len(), 3, "one undo step brings all three strokes back");
|
||||
assert_eq!(s.undo_depth(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converting_a_crowded_lasso_selection_recognises_each_stroke_a_bounded_number_of_times() {
|
||||
let mut s = session();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": shaft_stroke()})).unwrap();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": [[274.0, 285.0], [300.0, 300.0], [274.0, 315.0]]})).unwrap();
|
||||
// A stack of 40 lines close together: every pair is near, none makes an arrow.
|
||||
let n = 40;
|
||||
for i in 0..n {
|
||||
let y = 420.0 + i as f32 * 2.0;
|
||||
let pts: Vec<[f32; 2]> = (0..=40).map(|k| [100.0 + k as f32 * 5.0, y]).collect();
|
||||
s.run("draw.stroke", &json!({"page": 0, "points": pts})).unwrap();
|
||||
}
|
||||
s.run("draw.lasso", &json!({"page": 0, "points": [[80, 260], [340, 260], [340, 560], [80, 560]]})).unwrap();
|
||||
super::super::ink_shape::RECOGNISED.with(|c| c.set(0));
|
||||
let r = s.run("draw.inkToShape", &json!({})).unwrap();
|
||||
let calls = super::super::ink_shape::RECOGNISED.with(|c| c.get());
|
||||
let strokes = n + 2;
|
||||
assert!(calls <= 2 * strokes, "{calls} recognitions for {strokes} strokes");
|
||||
let names: Vec<&str> = r["converted"].as_array().unwrap().iter().filter_map(|c| c["shape"].as_str()).collect();
|
||||
assert_eq!(names.iter().filter(|n| **n == "arrow").count(), 1, "{names:?}");
|
||||
assert_eq!(names.iter().filter(|n| **n == "line").count(), n, "{names:?}");
|
||||
assert!(ink(&s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_replay_plays_strokes_in_the_order_they_were_drawn() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -61,6 +61,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.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(),
|
||||
// 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_sel),
|
||||
CommandSpec::new("edit.insertSpike", "Insert Spike", "Editing", insert_spike).key("Mod+Shift+F3").when(|s| {
|
||||
if s.math.is_some() {
|
||||
Some("leave the equation first")
|
||||
} else if s.building_blocks.contains_key(SPIKE) {
|
||||
None
|
||||
} else {
|
||||
Some("the Spike is empty")
|
||||
}
|
||||
}),
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste).key("Mod+V / Shift+Insert").params(r#"{"text"?: string, "html"?: string, "rtf"?: string}"#),
|
||||
CommandSpec::new("edit.pasteText", "Paste: Keep Text Only", "Home › Clipboard › Paste", paste_text)
|
||||
.params(r#"{"text"?: string}"#)
|
||||
@@ -167,13 +179,25 @@ fn copy(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
|
||||
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
|
||||
/// #816) for the host to put on the system clipboard too, so other programs keep the formatting.
|
||||
/// #816) for the host to put on the system clipboard too, so other programs keep the formatting;
|
||||
/// and for a copy of one equation alone, its MathML (#1297).
|
||||
pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
s.clipboard_html = match &s.clipboard {
|
||||
Some(f) => wordcraft_formats::html::export_fragment(&f.to_document()),
|
||||
None => String::new(),
|
||||
};
|
||||
if s.clipboard_html.is_empty() { json!({"text": s.clipboard_text}) } else { json!({"text": s.clipboard_text, "html": s.clipboard_html}) }
|
||||
let mut r = json!({"text": s.clipboard_text});
|
||||
if !s.clipboard_html.is_empty() {
|
||||
r["html"] = json!(s.clipboard_html);
|
||||
}
|
||||
// A copy of one equation alone, as MathML for the clipboard formats equation editors read
|
||||
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
|
||||
// before anything else when it pastes; a copy with text around the equation doesn't offer
|
||||
// them, so pasting it keeps the text.
|
||||
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
|
||||
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -186,11 +210,42 @@ fn cut(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Paste keeps the source formatting: our own copy while the system clipboard still holds it,
|
||||
/// else another program's HTML or RTF (#687), else the system clipboard's text.
|
||||
fn paste(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let frag = super::paste::paste_fragment(s, v)?;
|
||||
/// The AutoText entry the Spike collects into.
|
||||
const SPIKE: &str = "Spike";
|
||||
|
||||
/// Ctrl+F3: cut the selection to the end of the Spike. The clipboard is left alone.
|
||||
fn spike(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let (a, b) = s.sel.ordered();
|
||||
// Column selection collapses the selection before the command runs.
|
||||
if a == b {
|
||||
return Err(CmdError::Disabled("edit.spike: nothing is selected".into()));
|
||||
}
|
||||
let piece = s.doc.copy_range(&a, &b);
|
||||
if piece.blocks.is_empty() {
|
||||
return Err(CmdError::Disabled("edit.spike: this selection can't be collected".into()));
|
||||
}
|
||||
delete_selection(s)?;
|
||||
super::controls::restore_placeholder(s)?;
|
||||
s.building_blocks.entry(SPIKE.to_string()).or_default().append_piece(piece);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Ctrl+Shift+F3: insert everything the Spike collected, in order, and empty it.
|
||||
fn insert_spike(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let frag = s.building_blocks.get(SPIKE).cloned().ok_or_else(|| CmdError::Disabled("edit.insertSpike: the Spike is empty".into()))?;
|
||||
super::paste::insert(s, frag)?;
|
||||
s.building_blocks.remove(SPIKE);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Paste keeps the source formatting: our own copy while the system clipboard still holds it,
|
||||
/// else another program's HTML or RTF (#687). The system clipboard's text has none, so it pastes
|
||||
/// as Keep Text Only does.
|
||||
fn paste(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -644,7 +699,8 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
super::paste_text(s, &with)?;
|
||||
continue;
|
||||
}
|
||||
let props = s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default();
|
||||
// Replacing a symbol gives the new text the symbol's formatting, not its own font.
|
||||
let props = s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone().without_symbol()).unwrap_or_default();
|
||||
let mut at = s.doc.delete_range(&a, &b)?;
|
||||
for (k, part) in with.split(['\r', '\u{2029}']).enumerate() {
|
||||
if k > 0 {
|
||||
@@ -708,7 +764,8 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
let f = s.sel.ordered().0;
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone()).unwrap_or_default();
|
||||
// A symbol's own font isn't formatting to paint onto text.
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone()).unwrap_or_default();
|
||||
s.painter = Some((chr, para, false));
|
||||
}
|
||||
|
||||
@@ -891,4 +891,54 @@ mod tests {
|
||||
assert_eq!(s.run("equation.get", &json!({})).unwrap()["latex"], want, "{tex}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_multi_letter_scripts_stay_whole() {
|
||||
// #1609, Word for Mac 16.113.4: `V_dd` + Space leaves "dd" entirely in the subscript.
|
||||
for typed in ["V_dd", "V_(dd)"] {
|
||||
let mut s = session();
|
||||
s.run("insert.equation", &json!({})).unwrap();
|
||||
s.run("equation.type", &json!({"text": typed})).unwrap();
|
||||
s.run("equation.type", &json!({"text": " "})).unwrap();
|
||||
let nodes = nodes_of(&s, &s.math.as_ref().unwrap().at).unwrap();
|
||||
assert_eq!(nodes.len(), 1, "{typed}: {nodes:#?}");
|
||||
assert!(
|
||||
matches!(&nodes[0], MNode::Script { sub, .. } if matches!(sub.as_slice(), [MNode::Run(r)] if r.text == "dd")),
|
||||
"{typed}: {nodes:#?}"
|
||||
);
|
||||
}
|
||||
let mut s = session();
|
||||
s.run("insert.equation", &json!({})).unwrap();
|
||||
s.run("equation.type", &json!({"text": "x^ab "})).unwrap();
|
||||
let nodes = nodes_of(&s, &s.math.as_ref().unwrap().at).unwrap();
|
||||
assert!(matches!(&nodes[0], MNode::Script { sup, .. } if matches!(sup.as_slice(), [MNode::Run(r)] if r.text == "ab")), "{nodes:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_built_script_keeps_the_letter_typed_after_it() {
|
||||
// #1609 review: `x_i y ` built x_{iy}: the letter after a script is its own item.
|
||||
let mut s = session();
|
||||
s.run("insert.equation", &json!({})).unwrap();
|
||||
s.run("equation.type", &json!({"text": "x_i y "})).unwrap();
|
||||
let nodes = nodes_of(&s, &s.math.as_ref().unwrap().at).unwrap();
|
||||
assert_eq!(nodes.len(), 2, "{nodes:#?}");
|
||||
assert!(matches!(&nodes[0], MNode::Script { sub, .. } if matches!(sub.as_slice(), [MNode::Run(r)] if r.text == "i")), "{nodes:#?}");
|
||||
assert!(matches!(&nodes[1], MNode::Run(r) if r.text.trim() == "y"), "{nodes:#?}");
|
||||
let mut s = session();
|
||||
s.run("insert.equation", &json!({})).unwrap();
|
||||
s.run("equation.type", &json!({"text": "a_i b_j "})).unwrap();
|
||||
let nodes = nodes_of(&s, &s.math.as_ref().unwrap().at).unwrap();
|
||||
let subs: Vec<&str> = nodes
|
||||
.iter()
|
||||
.filter_map(|n| match n {
|
||||
MNode::Script { sub, .. } => match sub.as_slice() {
|
||||
[MNode::Run(r)] => Some(r.text.as_str()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(subs, ["i", "j"], "{nodes:#?}");
|
||||
assert!(nodes.iter().all(|n| matches!(n, MNode::Script { .. }) || matches!(n, MNode::Run(r) if r.text.trim().is_empty())), "{nodes:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,11 +188,17 @@ fn shown_text(s: &mut Session, f: &FieldAt) -> String {
|
||||
};
|
||||
let l = s.layout();
|
||||
let page = l.caret(&f.at).and_then(|c| l.pages.get(c.page));
|
||||
let section = page.map(|p| (p.section + 1) as u32).unwrap_or(1);
|
||||
let section_pages = page
|
||||
.map(|p| l.pages.iter().filter(|pg| pg.section == p.section).count() as u32)
|
||||
.unwrap_or_else(|| u32::try_from(l.pages.len()).unwrap_or(u32::MAX));
|
||||
let page_format = page.and_then(|p| s.doc.sections().get(p.section).map(|(_, sec)| sec.page_num_format)).unwrap_or_default();
|
||||
let ctx = wordcraft_layout::fields::FieldCtx {
|
||||
page: page.map(|p| p.number).unwrap_or(1),
|
||||
page_format,
|
||||
pages: u32::try_from(l.pages.len()).unwrap_or(u32::MAX),
|
||||
section_pages: u32::try_from(l.pages.len()).unwrap_or(u32::MAX),
|
||||
section: 1,
|
||||
section_pages,
|
||||
section,
|
||||
title: s.doc.core.title.as_str().into(),
|
||||
author: s.doc.core.creator.as_str().into(),
|
||||
filename: s.path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()).unwrap_or_default().into(),
|
||||
@@ -293,6 +299,30 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
/// #1765: ASK and SET fields draw nothing on the page; their stored results are kept (and
|
||||
/// saved), and code view still shows them.
|
||||
#[test]
|
||||
fn ask_and_set_fields_draw_nothing() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.field", &json!({"instr": "ASK Nominativo \"Inserire nome\" \\d \"N\"", "result": "«NOME» «COGNOME»"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": "SET Codice \"COD\"", "result": "COD"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Title"})).unwrap();
|
||||
let shown = page_text(&mut s);
|
||||
assert!(!shown.contains("NOME") && !shown.contains("COD"), "{shown}");
|
||||
let para = s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
let results: Vec<&str> = para
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Field { result, .. } => Some(result.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(results, ["«NOME» «COGNOME»", "COD"]);
|
||||
s.run("view.fieldCodes", &json!({})).unwrap();
|
||||
assert!(page_text(&mut s).contains("{ SET Codice \"COD\" }"));
|
||||
}
|
||||
|
||||
/// Alt+F9 shows every field's code in braces; Shift+F9 flips just the selected one; F9 shows
|
||||
/// its result again.
|
||||
#[test]
|
||||
@@ -384,4 +414,20 @@ mod tests {
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
assert!(s.run("fields.lock", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlink_uses_section_context() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
// Insert section break so there are 2 sections
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
// In section 2: insert SECTION and SECTIONPAGES fields
|
||||
s.run("insert.field", &json!({"instr": "SECTION"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " of "})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": "SECTIONPAGES"})).unwrap();
|
||||
// Select both and unlink
|
||||
s.run("select.all", &json!({})).unwrap();
|
||||
s.run("fields.unlink", &json!({})).unwrap();
|
||||
let text = s.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert!(text.contains("2 of 1"), "unlinked text should reflect section 2: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +80,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
|
||||
let path = p::req_str(v, "path")?;
|
||||
// No path (the command search, say): the app asks where to save, as File › Export
|
||||
// does, instead of failing on the required parameter (#2313).
|
||||
let Some(path) = p::str(v, "path") else {
|
||||
s.ui_requests.push(json!({"open": "exportPdf"}));
|
||||
return Ok(json!({"exported": false}));
|
||||
};
|
||||
let path = if path.to_ascii_lowercase().ends_with(".pdf") { path.to_string() } else { format!("{path}.pdf") };
|
||||
let opts = export_options(s, v);
|
||||
crate::io::save_path_with(std::path::Path::new(&path), &s.doc, None, &opts).map_err(CmdError::Failed)?;
|
||||
@@ -100,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
|
||||
.params(
|
||||
r#"{"path": string, "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true)}"#,
|
||||
r#"{"path": string, "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size)}"#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("file.print", "Print", "File", |s, _| {
|
||||
@@ -334,7 +339,11 @@ pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
|
||||
}
|
||||
|
||||
fn export_png(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let path = p::req_str(v, "path")?;
|
||||
// No path: the app asks where to save, as file.exportPdf does (#2313).
|
||||
let Some(path) = p::str(v, "path") else {
|
||||
s.ui_requests.push(json!({"open": "exportPng"}));
|
||||
return Ok(json!({"exported": false}));
|
||||
};
|
||||
let page = p::u64(v, "page").unwrap_or(1).max(1) as usize - 1;
|
||||
let scale = p::f32(v, "scale").unwrap_or(2.0).clamp(0.1, 8.0);
|
||||
let l = s.export_layout_with(export_options(s, v).markup);
|
||||
|
||||
@@ -685,6 +685,8 @@ pub fn state(s: &Session) -> Value {
|
||||
"caps": all.iter().all(|r| r.caps),
|
||||
"hidden": all.iter().all(|r| r.hidden),
|
||||
"spacing": same(&|r| json!(r.spacing)),
|
||||
// Kerning for fonts: the smallest kerned size, points; 0 = off.
|
||||
"kern": same(&|r| json!(r.kern)),
|
||||
"color": same(&|r| json!(match r.color { TextColor::Auto => "auto".to_string(), TextColor::Rgb(c) => c.hex() })),
|
||||
"highlight": same(&|r| json!(r.highlight.map(|c| c.hex()))),
|
||||
"style": style,
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
//! between its ends; a closed one is an ellipse when its points sit on the ellipse inscribed in
|
||||
//! its bounds (low RMS of the normalised radius), else a polygon from its corners (the closed
|
||||
//! path simplified with Ramer–Douglas–Peucker, near-straight and crowded corners merged) when
|
||||
//! that polygon stays close to every point. An arrow is a line-like shaft plus a head of two barbs
|
||||
//! drawn in the same stroke (shaft first or head first). Anything else (scribbles, curves, letters) stays ink.
|
||||
//! that polygon stays close to every point. An arrow is a line-like shaft plus a head drawn in the
|
||||
//! same stroke (shaft first or head first): two barbs, or a small closed triangle round the tip.
|
||||
//! [`pair_arrow`] makes one arrow of two strokes: a line, and a head (an open V or a small closed
|
||||
//! triangle) whose apex sits at one of its ends. Anything else (scribbles, curves, letters) stays ink.
|
||||
|
||||
use wordcraft_doc::freeform::MAX_POINTS;
|
||||
|
||||
@@ -55,15 +57,17 @@ const MIN_SIZE: f32 = 6.0;
|
||||
/// Most corners a polygon may have.
|
||||
pub const MAX_CORNERS: usize = 8;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`recognise`] ran on this thread (tests check the work stays bounded).
|
||||
pub static RECOGNISED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The shape `pts` draws, if it is one.
|
||||
pub fn recognise(pts: &[[f32; 2]]) -> Option<InkShape> {
|
||||
// Finite points only, without repeats.
|
||||
let mut p: Vec<[f32; 2]> = Vec::with_capacity(pts.len().min(MAX_POINTS));
|
||||
for q in pts.iter().take(MAX_POINTS).filter(|[x, y]| x.is_finite() && y.is_finite() && x.abs() < 1e6 && y.abs() < 1e6) {
|
||||
if p.last() != Some(q) {
|
||||
p.push(*q);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
RECOGNISED.with(|c| c.set(c.get().saturating_add(1)));
|
||||
let p = clean(pts);
|
||||
let (first, last) = (*p.first()?, *p.last()?);
|
||||
if p.len() < 2 {
|
||||
return None;
|
||||
@@ -83,8 +87,10 @@ pub fn recognise(pts: &[[f32; 2]]) -> Option<InkShape> {
|
||||
return Some(InkShape::Line { a: first, b: last });
|
||||
}
|
||||
}
|
||||
// An arrow: a shaft and a head with both barbs, drawn in one stroke (either end first).
|
||||
if let Some(arrow) = arrow(&p).or_else(|| arrow(&p.iter().rev().copied().collect::<Vec<_>>())) {
|
||||
// An arrow: a shaft and a head (both barbs, or a closed triangle), drawn in one stroke
|
||||
// (either end first).
|
||||
let rev: Vec<[f32; 2]> = p.iter().rev().copied().collect();
|
||||
if let Some(arrow) = arrow(&p).or_else(|| arrow(&rev)).or_else(|| closed_arrow(&p)).or_else(|| closed_arrow(&rev)) {
|
||||
return Some(arrow);
|
||||
}
|
||||
// Other shapes are closed: the stroke ends near where it began and goes around.
|
||||
@@ -126,27 +132,7 @@ const BARB_ANGLE: (f32, f32) = (15.0, 75.0);
|
||||
/// similar angles and lengths. (A stroke drawn head first is tried reversed by the caller.)
|
||||
fn arrow(p: &[[f32; 2]]) -> Option<InkShape> {
|
||||
let tail = *p.first()?;
|
||||
// The tip: start at the first point about as far from the start as any (a return that
|
||||
// overshoots it by a point or two must not move it), then follow the stroke on while it still
|
||||
// moves away from the start (densely sampled strokes have shaft points inside that window).
|
||||
// The first barb heads back, so the walk stops at the real tip and never reaches an overshoot;
|
||||
// jitter of under half a point doesn't stop it early.
|
||||
let dmax = p.iter().map(|q| dist(tail, *q)).fold(0.0, f32::max);
|
||||
let mut ti = p.iter().position(|q| dist(tail, *q) >= dmax - (0.03 * dmax).max(2.0))?;
|
||||
let mut best = dist(tail, *p.get(ti)?);
|
||||
for (i, q) in p.iter().enumerate().skip(ti + 1) {
|
||||
let d = dist(tail, *q);
|
||||
if d >= best {
|
||||
(ti, best) = (i, d);
|
||||
} else if d < best - 0.5 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let tip = *p.get(ti)?;
|
||||
let shaft = dist(tail, tip);
|
||||
if shaft < MIN_SIZE || p.get(..=ti)?.iter().any(|q| seg_distance(tail, tip, *q) > (0.06 * shaft).max(1.5)) {
|
||||
return None;
|
||||
}
|
||||
let (ti, tip, shaft) = shaft_tip(p)?;
|
||||
// The head: the stroke after the tip leaves it twice, once for each barb.
|
||||
let head = p.get(ti..)?;
|
||||
let reach = head.iter().map(|q| dist(tip, *q)).fold(0.0, f32::max);
|
||||
@@ -172,20 +158,166 @@ fn arrow(p: &[[f32; 2]]) -> Option<InkShape> {
|
||||
}
|
||||
let &[(l1, b1), (l2, b2)] = barbs.as_slice() else { return None };
|
||||
// The pen returns to the tip between the barbs.
|
||||
if gap > 0.35 * l1.min(l2) {
|
||||
if gap > 0.35 * l1.min(l2) || shaft <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Each barb as a vector from the tip, against the direction back along the shaft.
|
||||
head_fits(tail, tip, tip, b1, b2).then_some(InkShape::Arrow { a: tail, b: tip, head_at_end: true, head_at_start: false })
|
||||
}
|
||||
|
||||
/// An arrow with a closed triangle head, drawn shaft first: the shaft runs from the start to the
|
||||
/// tip like [`arrow`]'s, then the pen goes round a small triangle (tip, one barb end, the other)
|
||||
/// and ends back at the tip. (Drawn head first, the caller tries it reversed.)
|
||||
fn closed_arrow(p: &[[f32; 2]]) -> Option<InkShape> {
|
||||
let tail = *p.first()?;
|
||||
let (ti, tip, _) = shaft_tip(p)?;
|
||||
let head = p.get(ti..)?;
|
||||
// The corners: the point farthest from the tip, then the one farthest from that side.
|
||||
let b1 = head.iter().copied().fold(tip, |m, q| if dist(tip, q) > dist(tip, m) { q } else { m });
|
||||
let b2 = head.iter().copied().fold(tip, |m, q| if seg_distance(tip, b1, q) > seg_distance(tip, b1, m) { q } else { m });
|
||||
let (l1, l2) = (dist(tip, b1), dist(tip, b2));
|
||||
if l1.min(l2) <= 0.0 || dist(*head.last()?, tip) > 0.35 * l1.min(l2) {
|
||||
return None;
|
||||
}
|
||||
// Every point of the head is on the triangle.
|
||||
let tri = [tip, b1, b2];
|
||||
if head.iter().any(|q| polygon_distance(&tri, *q) > (0.15 * l1).max(1.5)) {
|
||||
return None;
|
||||
}
|
||||
head_fits(tail, tip, tip, b1, b2).then_some(InkShape::Arrow { a: tail, b: tip, head_at_end: true, head_at_start: false })
|
||||
}
|
||||
|
||||
/// Whether a head whose barbs run from `apex` to `b1` and `b2` fits a shaft from `tail` to `tip`:
|
||||
/// barbs 5–50 % of the shaft, each 15–75° off the way back along it, on opposite sides of it,
|
||||
/// and of similar length and angle.
|
||||
fn head_fits(tail: [f32; 2], tip: [f32; 2], apex: [f32; 2], b1: [f32; 2], b2: [f32; 2]) -> bool {
|
||||
let shaft = dist(tail, tip);
|
||||
let (l1, l2) = (dist(apex, b1), dist(apex, b2));
|
||||
if !(shaft > 0.0 && l1 > 0.0 && l2 > 0.0) {
|
||||
return false;
|
||||
}
|
||||
// Each barb as a vector from the apex, against the direction back along the shaft.
|
||||
let back = [tail[0] - tip[0], tail[1] - tip[1]];
|
||||
let angle_side = |e: [f32; 2], len: f32| {
|
||||
let u = [e[0] - tip[0], e[1] - tip[1]];
|
||||
let u = [e[0] - apex[0], e[1] - apex[1]];
|
||||
let angle = ((back[0] * u[0] + back[1] * u[1]) / (shaft * len)).clamp(-1.0, 1.0).acos().to_degrees();
|
||||
(angle, back[0] * u[1] - back[1] * u[0])
|
||||
};
|
||||
let ((a1, s1), (a2, s2)) = (angle_side(b1, l1), angle_side(b2, l2));
|
||||
let ok = |l: f32, a: f32| (BARB_LEN.0 * shaft..=BARB_LEN.1 * shaft).contains(&l) && (BARB_ANGLE.0..=BARB_ANGLE.1).contains(&a);
|
||||
let similar = l1.max(l2) <= 2.5 * l1.min(l2) && (a1 - a2).abs() <= 35.0;
|
||||
(ok(l1, a1) && ok(l2, a2) && s1 * s2 < 0.0 && similar).then_some(InkShape::Arrow { a: tail, b: tip, head_at_end: true, head_at_start: false })
|
||||
ok(l1, a1) && ok(l2, a2) && s1 * s2 < 0.0 && similar
|
||||
}
|
||||
|
||||
/// How far a two-stroke arrow's head apex may sit from the line's end, as a fraction of the line.
|
||||
const PAIR_REACH: f32 = 0.12;
|
||||
|
||||
/// What a stroke can be in a two-stroke arrow, worked out once (one recognition): the ends of the
|
||||
/// straight line it is, if it is one, and the ways it can be an arrowhead on its own.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct ArrowParts {
|
||||
pub line: Option<([f32; 2], [f32; 2])>,
|
||||
pub heads: Vec<[[f32; 2]; 3]>,
|
||||
}
|
||||
|
||||
/// `pts` as a possible half of a two-stroke arrow (see [`pair_parts`]).
|
||||
pub fn arrow_parts(pts: &[[f32; 2]]) -> ArrowParts {
|
||||
let p = clean(pts);
|
||||
let found = recognise(&p);
|
||||
let line = match found {
|
||||
Some(InkShape::Line { a, b }) => Some((a, b)),
|
||||
_ => None,
|
||||
};
|
||||
ArrowParts { line, heads: heads(&p, found.as_ref()) }
|
||||
}
|
||||
|
||||
/// One arrow from two strokes: `line`, a straight stroke, and `head`, an open V (one barb end,
|
||||
/// the apex, the other end) or a small closed triangle, whose apex is at one end of the line and
|
||||
/// whose barbs point back along it (the single-stroke head limits). The arrow runs from the
|
||||
/// line's other end to that end; `None` when they don't make one.
|
||||
pub fn pair_arrow(line: &[[f32; 2]], head: &[[f32; 2]]) -> Option<InkShape> {
|
||||
pair_parts(&arrow_parts(line), &arrow_parts(head))
|
||||
}
|
||||
|
||||
/// [`pair_arrow`] on strokes already recognised by [`arrow_parts`]: cheap geometry only.
|
||||
pub fn pair_parts(line: &ArrowParts, head: &ArrowParts) -> Option<InkShape> {
|
||||
let (a, b) = line.line?;
|
||||
let mut best: Option<(f32, InkShape)> = None;
|
||||
for &[apex, b1, b2] in &head.heads {
|
||||
for (tail, tip) in [(a, b), (b, a)] {
|
||||
let off = dist(apex, tip);
|
||||
let near = off <= (PAIR_REACH * dist(tail, tip)).max(3.0);
|
||||
if near && best.as_ref().is_none_or(|(d, _)| off < *d) && head_fits(tail, tip, apex, b1, b2) {
|
||||
best = Some((off, InkShape::Arrow { a: tail, b: tip, head_at_end: true, head_at_start: false }));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, arrow)| arrow)
|
||||
}
|
||||
|
||||
/// The ways the cleaned points `p` (which recognise as `found`) can be an arrowhead on their own,
|
||||
/// as `[apex, barb end, barb end]`: each corner of a closed triangle, or the corner of an open V
|
||||
/// whose two arms are straight.
|
||||
fn heads(p: &[[f32; 2]], found: Option<&InkShape>) -> Vec<[[f32; 2]; 3]> {
|
||||
if let Some(InkShape::Polygon(c)) = found
|
||||
&& let &[x, y, z] = c.as_slice()
|
||||
{
|
||||
return vec![[x, y, z], [y, z, x], [z, x, y]];
|
||||
}
|
||||
let (Some(&f), Some(&l)) = (p.first(), p.last()) else { return Vec::new() };
|
||||
// The apex: the point farthest from the chord between the ends.
|
||||
let Some((ai, apex)) = p.iter().copied().enumerate().fold(None, |m: Option<(usize, [f32; 2])>, (i, q)| match m {
|
||||
Some((_, b)) if seg_distance(f, l, b) >= seg_distance(f, l, q) => m,
|
||||
_ => Some((i, q)),
|
||||
}) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let straight = |a: [f32; 2], b: [f32; 2], arm: Option<&[[f32; 2]]>| {
|
||||
let len = dist(a, b);
|
||||
len >= 1.0 && arm.is_some_and(|arm| arm.iter().all(|q| seg_distance(a, b, *q) <= (0.12 * len).max(1.5)))
|
||||
};
|
||||
if ai == 0 || ai + 1 >= p.len() || !straight(f, apex, p.get(..=ai)) || !straight(apex, l, p.get(ai..)) {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![[apex, f, l]]
|
||||
}
|
||||
|
||||
/// Finite, not absurdly far points only (at most [`MAX_POINTS`]), without repeats.
|
||||
fn clean(pts: &[[f32; 2]]) -> Vec<[f32; 2]> {
|
||||
let mut p: Vec<[f32; 2]> = Vec::with_capacity(pts.len().min(MAX_POINTS));
|
||||
for q in pts.iter().take(MAX_POINTS).filter(|[x, y]| x.is_finite() && y.is_finite() && x.abs() < 1e6 && y.abs() < 1e6) {
|
||||
if p.last() != Some(q) {
|
||||
p.push(*q);
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// A shaft drawn from the start of `p`: the index of its tip, the tip and the shaft's length;
|
||||
/// `None` when it is too short or not straight.
|
||||
fn shaft_tip(p: &[[f32; 2]]) -> Option<(usize, [f32; 2], f32)> {
|
||||
let tail = *p.first()?;
|
||||
// The tip: start at the first point about as far from the start as any (a return that
|
||||
// overshoots it by a point or two must not move it), then follow the stroke on while it still
|
||||
// moves away from the start (densely sampled strokes have shaft points inside that window).
|
||||
// The first barb heads back, so the walk stops at the real tip and never reaches an overshoot;
|
||||
// jitter of under half a point doesn't stop it early.
|
||||
let dmax = p.iter().map(|q| dist(tail, *q)).fold(0.0, f32::max);
|
||||
let mut ti = p.iter().position(|q| dist(tail, *q) >= dmax - (0.03 * dmax).max(2.0))?;
|
||||
let mut best = dist(tail, *p.get(ti)?);
|
||||
for (i, q) in p.iter().enumerate().skip(ti + 1) {
|
||||
let d = dist(tail, *q);
|
||||
if d >= best {
|
||||
(ti, best) = (i, d);
|
||||
} else if d < best - 0.5 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let tip = *p.get(ti)?;
|
||||
let shaft = dist(tail, tip);
|
||||
if shaft < MIN_SIZE || p.get(..=ti)?.iter().any(|q| seg_distance(tail, tip, *q) > (0.06 * shaft).max(1.5)) {
|
||||
return None;
|
||||
}
|
||||
Some((ti, tip, shaft))
|
||||
}
|
||||
|
||||
/// Left, top, width and height of `pts` (zero for none).
|
||||
@@ -686,4 +818,153 @@ mod tests {
|
||||
let b = tip_of(&stroke);
|
||||
assert!(b.is_some_and(|b| dist(b, tip) < 1.0), "overshoot head first: {b:?}");
|
||||
}
|
||||
|
||||
/// A shaft from `tail` to `tip`, then a closed triangle head drawn round the tip in the same
|
||||
/// stroke (tip, one barb end, the other, back to the tip); `n` shaft points, `m` per side.
|
||||
fn closed_arrow_n(tail: [f32; 2], tip: [f32; 2], barb: f32, spread_deg: f32, n: usize, m: usize) -> Vec<[f32; 2]> {
|
||||
let [b1, b2] = barb_ends(tail, tip, barb, spread_deg);
|
||||
let mut pts = line(tail, tip, n);
|
||||
pts.extend(line(tip, b1, m));
|
||||
pts.extend(line(b1, b2, m));
|
||||
pts.extend(line(b2, tip, m));
|
||||
pts.push(tip);
|
||||
pts
|
||||
}
|
||||
|
||||
/// The ends of a head's two barbs at `tip`, `barb` long, `spread_deg` either side of the shaft.
|
||||
fn barb_ends(tail: [f32; 2], tip: [f32; 2], barb: f32, spread_deg: f32) -> [[f32; 2]; 2] {
|
||||
let back = (tail[1] - tip[1]).atan2(tail[0] - tip[0]);
|
||||
let end = |sign: f32| {
|
||||
let a = back + sign * spread_deg.to_radians();
|
||||
[tip[0] + barb * a.cos(), tip[1] + barb * a.sin()]
|
||||
};
|
||||
[end(1.0), end(-1.0)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_with_a_closed_triangle_head_in_one_stroke_are_recognised_both_ways() {
|
||||
for (tail, tip) in
|
||||
[([20.0, 100.0], [180.0, 100.0]), ([180.0, 100.0], [20.0, 100.0]), ([100.0, 180.0], [100.0, 20.0]), ([150.0, 120.0], [30.0, 30.0])]
|
||||
{
|
||||
for stroke in [closed_arrow_n(tail, tip, 25.0, 30.0, 24, 5), closed_arrow_n(tail, tip, 20.0, 25.0, dist(tail, tip).round() as usize, 15)]
|
||||
{
|
||||
let Some(InkShape::Arrow { a, b, head_at_end, head_at_start }) = recognise(&stroke) else {
|
||||
panic!("{tail:?}->{tip:?}: {:?}", recognise(&stroke))
|
||||
};
|
||||
assert!(head_at_end && !head_at_start);
|
||||
assert!(dist(a, tail) < 2.0 && dist(b, tip) < 2.0, "{a:?} {b:?} for {tail:?} {tip:?}");
|
||||
// The loop round the head first, then the shaft: the same arrow.
|
||||
let mut rev = stroke;
|
||||
rev.reverse();
|
||||
let Some(InkShape::Arrow { a, b, .. }) = recognise(&rev) else { panic!("head first {tail:?}->{tip:?}: {:?}", recognise(&rev)) };
|
||||
assert!(dist(a, tail) < 2.0 && dist(b, tip) < 2.0, "head first {a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
// The head size limits hold: 5 to 50 % of a 160 pt shaft, 15 to 75 degrees.
|
||||
let (tail, tip) = ([20.0, 100.0], [180.0, 100.0]);
|
||||
let is_arrow = |l: f32, deg: f32| matches!(recognise(&closed_arrow_n(tail, tip, l, deg, 24, 5)), Some(InkShape::Arrow { .. }));
|
||||
assert!(is_arrow(12.0, 30.0) && is_arrow(70.0, 30.0) && is_arrow(25.0, 20.0) && is_arrow(25.0, 70.0));
|
||||
assert!(!is_arrow(6.0, 30.0) && !is_arrow(90.0, 30.0) && !is_arrow(25.0, 8.0) && !is_arrow(25.0, 85.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_without_a_shaft_stay_triangles() {
|
||||
// Closed, and closed with the pen running on past the start along the first side.
|
||||
let tri = around(&[[0.0, 80.0], [45.0, 0.0], [90.0, 80.0]], 15);
|
||||
assert_eq!(recognise(&tri).map(|s| s.name()), Some("triangle"));
|
||||
let mut over = tri.clone();
|
||||
over.extend(line([0.0, 80.0], [45.0, 0.0], 15).into_iter().skip(1).take(8));
|
||||
assert!(!matches!(recognise(&over), Some(InkShape::Arrow { .. })), "{:?}", recognise(&over));
|
||||
// A long thin triangle is not a shaft with a head.
|
||||
let thin = around(&[[0.0, 0.0], [160.0, 10.0], [0.0, 20.0]], 20);
|
||||
assert!(!matches!(recognise(&thin), Some(InkShape::Arrow { .. })), "{:?}", recognise(&thin));
|
||||
// A shaft with a triangle as big as the shaft is not an arrow.
|
||||
let (tail, tip) = ([20.0, 100.0], [180.0, 100.0]);
|
||||
assert!(!matches!(recognise(&closed_arrow_n(tail, tip, 150.0, 30.0, 24, 5)), Some(InkShape::Arrow { .. })));
|
||||
// Hostile points around a closed head never panic.
|
||||
let mut junk = closed_arrow_n(tail, tip, 25.0, 30.0, 24, 5);
|
||||
junk.insert(30, [f32::NAN, f32::INFINITY]);
|
||||
assert!(matches!(recognise(&junk), Some(InkShape::Arrow { .. })));
|
||||
}
|
||||
|
||||
/// A head drawn on its own: an open V (one barb end, the apex, the other end) or a closed
|
||||
/// triangle (apex, barb end, barb end, apex), `m` points per side.
|
||||
fn v_head(apex: [f32; 2], [b1, b2]: [[f32; 2]; 2], m: usize) -> Vec<[f32; 2]> {
|
||||
let mut pts = line(b1, apex, m);
|
||||
pts.extend(line(apex, b2, m));
|
||||
pts.push(b2);
|
||||
pts
|
||||
}
|
||||
|
||||
fn triangle_head(apex: [f32; 2], [b1, b2]: [[f32; 2]; 2], m: usize) -> Vec<[f32; 2]> {
|
||||
let mut pts = line(apex, b1, m);
|
||||
pts.extend(line(b1, b2, m));
|
||||
pts.extend(line(b2, apex, m));
|
||||
pts.push(apex);
|
||||
pts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_head_stroke_at_a_line_end_pairs_into_an_arrow() {
|
||||
for (tail, tip) in [([20.0, 100.0], [180.0, 100.0]), ([180.0, 160.0], [40.0, 30.0]), ([100.0, 20.0], [100.0, 180.0])] {
|
||||
let shaft = line(tail, tip, 40).into_iter().chain([tip]).collect::<Vec<_>>();
|
||||
let ends = barb_ends(tail, tip, 25.0, 30.0);
|
||||
for (what, head) in [("V", v_head(tip, ends, 8)), ("triangle", triangle_head(tip, ends, 8)), ("bare V", vec![ends[0], tip, ends[1]])] {
|
||||
let Some(InkShape::Arrow { a, b, head_at_end, head_at_start }) = pair_arrow(&shaft, &head) else {
|
||||
panic!("{what} {tail:?}->{tip:?}: {:?}", pair_arrow(&shaft, &head))
|
||||
};
|
||||
assert!(head_at_end && !head_at_start);
|
||||
assert!(dist(a, tail) < 1.0 && dist(b, tip) < 1.0, "{what}: {a:?} {b:?}");
|
||||
// Drawn the other way round, the head is still found at its end.
|
||||
let mut rev = head.clone();
|
||||
rev.reverse();
|
||||
assert!(matches!(pair_arrow(&shaft, &rev), Some(InkShape::Arrow { b, .. }) if dist(b, tip) < 1.0), "{what} reversed");
|
||||
let mut back = shaft.clone();
|
||||
back.reverse();
|
||||
assert!(matches!(pair_arrow(&back, &head), Some(InkShape::Arrow { b, .. }) if dist(b, tip) < 1.0), "{what}, shaft drawn tip first");
|
||||
}
|
||||
// A triangle given as its corners (an Ink to Shape triangle), apex anywhere in the ring.
|
||||
let [b1, b2] = barb_ends(tail, tip, 25.0, 30.0);
|
||||
assert!(matches!(pair_arrow(&shaft, &[b1, b2, tip, b1]), Some(InkShape::Arrow { b, .. }) if dist(b, tip) < 1.0), "corners");
|
||||
// An apex a few points short of the end still pairs.
|
||||
let d = [(tip[0] - tail[0]) / dist(tail, tip), (tip[1] - tail[1]) / dist(tail, tip)];
|
||||
let near = [tip[0] - 6.0 * d[0] + 3.0 * d[1], tip[1] - 6.0 * d[1] - 3.0 * d[0]];
|
||||
assert!(pair_arrow(&shaft, &v_head(near, barb_ends(tail, near, 25.0, 30.0), 8)).is_some(), "near the end");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heads_away_from_the_end_the_wrong_way_or_the_wrong_size_dont_pair() {
|
||||
let (tail, tip) = ([20.0, 100.0], [180.0, 100.0]);
|
||||
let shaft = line(tail, tip, 40).into_iter().chain([tip]).collect::<Vec<_>>();
|
||||
let head_at = |apex: [f32; 2], barb: f32, deg: f32| v_head(apex, barb_ends(tail, apex, barb, deg), 8);
|
||||
// Far from either end: mid-shaft, and 40 pt past the tip.
|
||||
assert_eq!(pair_arrow(&shaft, &head_at([100.0, 100.0], 25.0, 30.0)), None);
|
||||
assert_eq!(pair_arrow(&shaft, &head_at([220.0, 100.0], 25.0, 30.0)), None);
|
||||
assert_eq!(pair_arrow(&shaft, &head_at([180.0, 140.0], 25.0, 30.0)), None);
|
||||
// Pointing back at the shaft (barbs forward), too big, too small, too narrow, too wide.
|
||||
let forward = v_head(tip, barb_ends([340.0, 100.0], tip, 25.0, 30.0), 8);
|
||||
assert_eq!(pair_arrow(&shaft, &forward), None);
|
||||
for (barb, deg) in [(100.0, 30.0), (5.0, 30.0), (25.0, 5.0), (25.0, 85.0)] {
|
||||
assert_eq!(pair_arrow(&shaft, &head_at(tip, barb, deg)), None, "barb {barb} at {deg} degrees");
|
||||
}
|
||||
// Lopsided: both barbs on one side.
|
||||
assert_eq!(pair_arrow(&shaft, &[[155.0, 87.0], tip, [158.0, 80.0]]), None);
|
||||
// The "line" must be a line, the head a head.
|
||||
let ends = barb_ends(tail, tip, 25.0, 30.0);
|
||||
let zig: Vec<[f32; 2]> = (0..9).map(|i| [20.0 + i as f32 * 20.0, if i % 2 == 0 { 100.0 } else { 120.0 }]).collect();
|
||||
assert_eq!(pair_arrow(&zig, &v_head(tip, ends, 8)), None);
|
||||
assert_eq!(pair_arrow(&shaft, &[[150.0, 80.0], [170.0, 120.0], [175.0, 80.0], [180.0, 120.0]]), None, "a scribble");
|
||||
assert_eq!(pair_arrow(&shaft, &around(&[[150.0, 60.0], [190.0, 60.0], [190.0, 140.0], [150.0, 140.0]], 8)), None, "a box");
|
||||
// Hostile input never panics.
|
||||
let mut junk = v_head(tip, ends, 8);
|
||||
junk.insert(2, [f32::NAN, 1.0]);
|
||||
junk.push([f32::INFINITY, 0.0]);
|
||||
assert!(pair_arrow(&shaft, &junk).is_some());
|
||||
assert_eq!(pair_arrow(&[], &[]), None);
|
||||
assert_eq!(pair_arrow(&shaft, &[[180.0, 100.0]]), None);
|
||||
let huge: Vec<[f32; 2]> = (0..MAX_POINTS * 2).map(|i| [(i % 977) as f32, ((i * 31) % 541) as f32]).collect();
|
||||
let _ = pair_arrow(&huge, &huge);
|
||||
let _ = pair_arrow(&shaft, &huge);
|
||||
}
|
||||
}
|
||||
|
||||
+166
-18
@@ -106,11 +106,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key(super::mac_or("Ctrl+Shift+T", "Alt+Shift+T")),
|
||||
CommandSpec::new("insert.pageField", "Insert Page Field", "Insert › Text › Quick Parts", |s, _| field(s, &json!({"instr": "PAGE"})))
|
||||
.key(super::mac_or("Ctrl+Shift+P", "Alt+Shift+P")),
|
||||
CommandSpec::new("insert.dropCap", "Drop Cap", "Insert › Text", |s, v| {
|
||||
let lines = p::u64(v, "lines").unwrap_or(3).min(10) as u8;
|
||||
super::para::fmt(s, &|p| p.drop_cap = Some(lines))
|
||||
})
|
||||
.params(r#"{"lines"?: n (0 = none)}"#),
|
||||
CommandSpec::new("insert.dropCap", "Drop Cap", "Insert › Text", drop_cap)
|
||||
.params(r#"{"position"?: "none"|"dropped"|"margin" (default dropped), "lines"?: 1..10 (default 3; 0 = none), "distance"?: pt from the text (0..1584, default 0), "font"?: family (omit for the text's font)}"#)
|
||||
.when(drop_cap_off),
|
||||
CommandSpec::new("insert.horizontalLine", "Horizontal Line", "Home › Paragraph › Borders", |s, _| {
|
||||
super::para::fmt(s, &|p| {
|
||||
p.borders = Some(wordcraft_doc::props::Borders { bottom: Some(wordcraft_doc::props::Border::single(1.5)), ..Default::default() })
|
||||
@@ -159,6 +157,11 @@ fn table(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = s.doc.styles.find(st).map(|x| x.id.clone()).ok_or_else(|| CmdError::Params(format!("no table style `{st}`")))?;
|
||||
t.props.style = Some(id);
|
||||
}
|
||||
// Like Word, a table inserted in a right-to-left paragraph is a right-to-left table (#2634):
|
||||
// its first cell stands at the right, so Tab, which follows reading order, moves leftwards.
|
||||
if s.doc.para_at(&s.sel.focus).is_some_and(|p| s.doc.styles.resolve_para(&p.props).bidi) {
|
||||
t.props.bidi_visual = true;
|
||||
}
|
||||
let story = s.sel.focus.story;
|
||||
let path = insert_block_at_caret(s, Block::Table(t))?;
|
||||
let mut first = path.0.clone();
|
||||
@@ -343,8 +346,11 @@ fn shape(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if super::canvas::add_member(s, obj.clone())?.is_some() {
|
||||
return sel_result(s);
|
||||
}
|
||||
// Word draws a new shape beside what is selected and never deletes it: the shape just
|
||||
// inserted (which is selected) stays, and so does selected text (#2019). It goes after the
|
||||
// selection and becomes the selection. (A picture does replace the selection, as in Word.)
|
||||
let props = s.typing_props();
|
||||
let at = delete_selection(s)?;
|
||||
let (_, at) = s.sel.ordered();
|
||||
let end = s.doc.insert_object(&at, obj, &props)?;
|
||||
s.sel = Selection { anchor: at, focus: end };
|
||||
sel_result(s)
|
||||
@@ -537,21 +543,30 @@ fn bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// The header (or footer) of the caret's section in the slot the caret's page uses (first page,
|
||||
/// even page or the default), made when there is none: with Different First Page on, a header
|
||||
/// inserted on page 1 is the one page 1 shows (#2826).
|
||||
fn hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let sect = s.doc.section_mut(block).clone();
|
||||
let existing = if header { sect.headers.default } else { sect.footers.default };
|
||||
let layout = s.layout();
|
||||
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
|
||||
let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default();
|
||||
fn slot_of(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => &mut set.first,
|
||||
wordcraft_layout::HfSlot::Even => &mut set.even,
|
||||
wordcraft_layout::HfSlot::Default => &mut set.default,
|
||||
}
|
||||
}
|
||||
let mut sect = s.doc.section_mut(block).clone();
|
||||
let existing = *slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers });
|
||||
if let Some(id) = existing.filter(|id| s.doc.parts.contains_key(id)) {
|
||||
return id;
|
||||
}
|
||||
let style = if header { "Header" } else { "Footer" };
|
||||
let id = s.doc.add_part(if header { PartKind::Header } else { PartKind::Footer }, vec![para_block(Paragraph::new().styled(style))]);
|
||||
let sect = s.doc.section_mut(block);
|
||||
if header {
|
||||
sect.headers.default = Some(id);
|
||||
} else {
|
||||
sect.footers.default = Some(id);
|
||||
}
|
||||
*slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
|
||||
id
|
||||
}
|
||||
|
||||
@@ -590,7 +605,12 @@ fn header_footer(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
}
|
||||
|
||||
fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let page = p::u64(v, "page").map(|page| usize::try_from(page).unwrap_or(usize::MAX));
|
||||
let mut page = p::u64(v, "page").map(|page| usize::try_from(page).unwrap_or(usize::MAX));
|
||||
if page.is_none() && s.sel.focus.story == StoryRef::Body {
|
||||
// The caret's page: with Different First Page on, page 1 edits its own header (#2826).
|
||||
let focus = s.sel.focus.clone();
|
||||
page = s.layout().page_of(&focus);
|
||||
}
|
||||
let shown = match page {
|
||||
Some(page) => shown_hf(s, page, header)?,
|
||||
None => {
|
||||
@@ -867,10 +887,27 @@ fn symbol(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Err(CmdError::Params("font: a family name".into()));
|
||||
}
|
||||
let base = s.typing_props();
|
||||
let mut props = base.clone();
|
||||
props.font = Some(font.to_string());
|
||||
s.pending = Some(props);
|
||||
let r = type_text(s, c);
|
||||
// A symbol font's character remembers it as its own font (`w:sym`), so changing the text's
|
||||
// font later keeps the symbol; other fonts are ordinary run formatting. `w:sym` holds a 16-bit
|
||||
// code, so a character beyond the Basic Multilingual Plane stays ordinary text in that font.
|
||||
// Each character decides for itself, so a mixed string keeps its symbols and its text apart.
|
||||
let font_is_symbol = wordcraft_doc::symbol_fonts::is_symbol_font(font);
|
||||
let mut r = Ok(());
|
||||
let mut buf = [0u8; 4];
|
||||
for ch in c.chars() {
|
||||
let mut props = base.clone();
|
||||
let private_use = ('\u{F020}'..='\u{F0FF}').contains(&ch);
|
||||
if u32::from(ch) <= 0xFFFF && (font_is_symbol || private_use) {
|
||||
props.sym_font = Some(font.to_string());
|
||||
} else {
|
||||
props.font = Some(font.to_string());
|
||||
}
|
||||
s.pending = Some(props);
|
||||
r = type_text(s, ch.encode_utf8(&mut buf));
|
||||
if r.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Typing on after the symbol goes on in the text's own font.
|
||||
s.pending = Some(base);
|
||||
r?;
|
||||
@@ -974,6 +1011,29 @@ mod tests {
|
||||
assert!(s.run("insert.editHeader", &json!({"page": u64::MAX})).is_err());
|
||||
}
|
||||
|
||||
/// #2826: with Different First Page on, Insert › Header and Edit Header with the caret on
|
||||
/// page 1 give page 1 its own header; page 2 keeps the default one.
|
||||
#[test]
|
||||
fn different_first_page_header_is_reachable_from_page_one() {
|
||||
let mut s = two_pages();
|
||||
s.run("insert.header", &json!({"text": "Head"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
let head = s.doc.last_section.headers.default.unwrap();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
assert_eq!(s.layout().pages[0].header_story, None, "page 1 shows the empty first-page header");
|
||||
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
|
||||
let first = s.run("insert.header", &json!({"preset": "title"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
assert_ne!(first, head);
|
||||
assert_eq!(s.doc.last_section.headers.first, Some(first));
|
||||
let pages = s.layout().pages.clone();
|
||||
assert_eq!((pages[0].header_story, pages[1].header_story), (Some(first), Some(head)));
|
||||
// Edit Footer from page 1 (no page given): page 1's own footer, not the default.
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
|
||||
let foot = s.run("insert.editFooter", &json!({})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
assert_eq!((s.doc.last_section.footers.first, s.doc.last_section.footers.default), (Some(foot), None));
|
||||
}
|
||||
|
||||
fn two_pages() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("text.insert", &json!({"text": "One"})).unwrap();
|
||||
@@ -1114,6 +1174,27 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Insert › Symbol with a font: only the symbol takes it, the caret's font carries on after.
|
||||
#[test]
|
||||
fn a_mixed_symbol_string_keeps_symbols_and_text_apart() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("a"));
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.symbol", &json!({"char": "\u{F041}A", "font": "My Custom Font"})).unwrap();
|
||||
let p = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props_of_char(1).sym_font.as_deref(), Some("My Custom Font"), "the private-use glyph");
|
||||
assert_eq!(p.props_of_char(4).sym_font, None, "the plain letter");
|
||||
assert_eq!(p.props_of_char(4).font.as_deref(), Some("My Custom Font"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_astral_symbol_stays_text_in_its_font() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("a"));
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.symbol", &json!({"char": "\u{1F600}", "font": "Wingdings"})).unwrap();
|
||||
let p = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props_of_char(1).sym_font, None, "w:sym can't hold it");
|
||||
assert_eq!(p.props_of_char(1).font.as_deref(), Some("Wingdings"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_takes_its_own_font() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("ab"));
|
||||
@@ -1141,3 +1222,70 @@ mod tests {
|
||||
assert_eq!(date_picture("DATE"), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why Insert › Drop Cap is off at the caret, as in Word: in a table cell, in an empty paragraph
|
||||
/// and in one that starts with a space.
|
||||
fn drop_cap_off(s: &Session) -> Option<&'static str> {
|
||||
if s.sel.focus.path.cell().is_some() {
|
||||
return Some("drop caps can't go in a table");
|
||||
}
|
||||
let first = s.doc.para_at(&s.sel.focus).and_then(|p| p.text.chars().next());
|
||||
match first {
|
||||
None => Some("the paragraph is empty"),
|
||||
Some(c) if c.is_whitespace() => Some("the paragraph starts with a space"),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert › Drop Cap and Drop Cap Options: none, or the letter dropped into the text or hung in
|
||||
/// the margin, `lines` tall, `distance` points from the text, in `font` (unset: the text's).
|
||||
/// None takes all of it away, the letter's font with it.
|
||||
fn drop_cap(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let lines = v.get("lines").and_then(Value::as_f64).filter(|l| l.is_finite());
|
||||
let none = p::str(v, "position") == Some("none") || lines == Some(0.0);
|
||||
let margin = p::str(v, "position") == Some("margin");
|
||||
let lines = lines.map_or(3.0, |l| l.round().clamp(1.0, 10.0)) as u8;
|
||||
let distance = p::f32(v, "distance").map_or(0.0, |d| d.clamp(0.0, wordcraft_doc::resolve::MAX_DROP_CAP_DISTANCE));
|
||||
// A family name, not a paragraph of text.
|
||||
let font = p::str(v, "font").map(str::trim).filter(|f| !f.is_empty()).map(|f| f.chars().take(64).collect::<String>());
|
||||
super::para::fmt(s, &|p| {
|
||||
p.drop_cap = (!none).then_some(lines);
|
||||
p.drop_cap_margin = (!none && margin).then_some(true);
|
||||
p.drop_cap_distance = (!none && distance > 0.0).then_some(distance);
|
||||
p.drop_cap_font = font.clone().filter(|_| !none);
|
||||
})
|
||||
}
|
||||
|
||||
/// Insert › Drop Cap at the caret: the menu's highlight and the Drop Cap dialog's values.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DropCapState {
|
||||
/// `none`, `dropped` or `margin`.
|
||||
pub position: &'static str,
|
||||
/// Lines to drop (3 when there is no drop cap).
|
||||
pub lines: u8,
|
||||
/// Distance from the text, points.
|
||||
pub distance: f32,
|
||||
/// The letter's own font, if it has one.
|
||||
pub font: Option<String>,
|
||||
/// The font of the paragraph's first character.
|
||||
pub text_font: String,
|
||||
}
|
||||
|
||||
pub fn drop_cap_state(s: &Session) -> DropCapState {
|
||||
let para = s.doc.para_at(&s.sel.focus);
|
||||
let props = para.map(|p| p.props.clone()).unwrap_or_default();
|
||||
let rp = s.doc.styles.resolve_para(&props);
|
||||
let first = para.map(|p| p.props_at(0).clone()).unwrap_or_default();
|
||||
let text_font = s.doc.styles.resolve_char_in(props.style.as_deref(), None, &first).font;
|
||||
DropCapState {
|
||||
position: match (rp.drop_cap, rp.drop_cap_margin) {
|
||||
(0, _) => "none",
|
||||
(_, true) => "margin",
|
||||
_ => "dropped",
|
||||
},
|
||||
lines: if rp.drop_cap == 0 { 3 } else { rp.drop_cap },
|
||||
distance: if rp.drop_cap == 0 { 0.0 } else { rp.drop_cap_distance },
|
||||
font: rp.drop_cap_font.filter(|_| rp.drop_cap > 0),
|
||||
text_font,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,11 +46,11 @@ fn para_props(s: &Session) -> ParaProps {
|
||||
fn char_props(s: &Session) -> CharProps {
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b {
|
||||
return s.typing_props();
|
||||
return s.caret_props();
|
||||
}
|
||||
match s.doc.para_at(&a) {
|
||||
Some(p) if a.off < p.len() => p.props_of_char(a.off).clone(),
|
||||
_ => s.typing_props(),
|
||||
_ => s.caret_props(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("list.get", "List Definition", "Home › Paragraph › Multilevel List", get)
|
||||
.params(r#"{"num"?: list id (default: the caret's list)} → {"num", "levels": [as list.define]}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("list.multilevelPreset", "Multilevel List Library", "Home › Paragraph › Multilevel List", preset).params(
|
||||
r#"{"preset": "headings" (1 / 1.1 / 1.1.1) | "article" (Article I. / Section 1.01 / (a)) | "outlineHeadings" (I. / A. / 1.) | "chapter" (Chapter 1, lower levels unnumbered)} — a new list whose nine levels are linked to Heading 1–9: every paragraph in those styles is numbered, selected paragraphs already in a Heading style keep it, and any other selected paragraph becomes Heading 1 (the first level)"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -226,6 +229,96 @@ fn define(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The heading-linked lists of the Multilevel List gallery's library, by preset id: level `i`
|
||||
/// is linked to Heading `i + 1`.
|
||||
fn preset_levels(preset: &str) -> Option<Vec<Level>> {
|
||||
use NumFormat as F;
|
||||
let levels = (0..LEVELS)
|
||||
.map(|i| {
|
||||
let n = i + 1;
|
||||
// Numbers start at the margin; each level's text a little further in.
|
||||
let at = |indent: f32| Level { indent, hanging: indent, style: Some(format!("Heading{n}")), ..Level::default() };
|
||||
let (format, text, indent) = match preset {
|
||||
"headings" => (F::Decimal, (1..=n).map(|k| format!("%{k}")).collect::<Vec<_>>().join("."), 21.6 + 7.2 * i as f32),
|
||||
"article" => match i {
|
||||
0 => (F::UpperRoman, "Article %1.".to_string(), 0.0),
|
||||
1 => (F::DecimalZero, "Section %1.%2".to_string(), 0.0),
|
||||
_ => {
|
||||
let f = [F::LowerLetter, F::LowerRoman, F::Decimal, F::LowerLetter, F::LowerRoman, F::LowerLetter, F::LowerRoman];
|
||||
let t = if i < 4 {
|
||||
format!("(%{n})")
|
||||
} else if i < 7 {
|
||||
format!("%{n})")
|
||||
} else {
|
||||
format!("%{n}.")
|
||||
};
|
||||
(f.get(i - 2).copied().unwrap_or(F::Decimal), t, 36.0 + 7.2 * (i - 2) as f32)
|
||||
}
|
||||
},
|
||||
"outlineHeadings" => {
|
||||
let f = [
|
||||
F::UpperRoman,
|
||||
F::UpperLetter,
|
||||
F::Decimal,
|
||||
F::LowerLetter,
|
||||
F::Decimal,
|
||||
F::LowerLetter,
|
||||
F::LowerRoman,
|
||||
F::LowerLetter,
|
||||
F::LowerRoman,
|
||||
];
|
||||
let t = match i {
|
||||
0..=2 => format!("%{n}."),
|
||||
3 => format!("%{n})"),
|
||||
_ => format!("(%{n})"),
|
||||
};
|
||||
(f.get(i).copied().unwrap_or(F::Decimal), t, 36.0 * n as f32)
|
||||
}
|
||||
"chapter" if i == 0 => (F::Decimal, "Chapter %1".to_string(), 0.0),
|
||||
"chapter" => (F::None, String::new(), 0.0),
|
||||
_ => return None,
|
||||
};
|
||||
// "Section 1.01" shows the article number in digits (legal numbering).
|
||||
Some(Level { format, text, legal: preset == "article" && i == 1, ..at(indent) })
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(levels)
|
||||
}
|
||||
|
||||
/// A Multilevel List gallery preset: a new list linked to Heading 1–9. The heading styles carry
|
||||
/// the number, so every heading (and every heading added later) is numbered. Paragraphs in a
|
||||
/// Heading style keep their level; any other paragraph under the caret or selection (Normal,
|
||||
/// Quote, Title…) becomes Heading 1, as in Word.
|
||||
fn preset(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = p::req_str(v, "preset")?;
|
||||
let levels = preset_levels(id).ok_or_else(|| CmdError::Params("`preset` must be headings, article, outlineHeadings or chapter".into()))?;
|
||||
let num = s.doc.numbering.try_add_levels(None, levels)?;
|
||||
let mut linked = Vec::new();
|
||||
for n in 1..=LEVELS as u8 {
|
||||
let id = super::para::ensure_heading_style(s, n);
|
||||
if let Some(st) = s.doc.styles.get_mut(&id) {
|
||||
st.para.numbering = Some(NumRef { num, level: n - 1 });
|
||||
linked.push(id);
|
||||
}
|
||||
}
|
||||
touch_styles(s, &linked)?;
|
||||
super::para::fmt(s, &|pp| {
|
||||
// A heading keeps its style and level; any other paragraph (Normal, Quote, Title…)
|
||||
// becomes the first level's heading, Heading 1. The number comes from the style.
|
||||
if !pp.style.as_ref().is_some_and(|st| linked.contains(st)) {
|
||||
pp.style = linked.first().cloned();
|
||||
}
|
||||
pp.numbering = None;
|
||||
pp.indent_left = None;
|
||||
pp.indent_first = None;
|
||||
pp.indent_left_chars = None;
|
||||
pp.indent_first_chars = None;
|
||||
})?;
|
||||
let mut r = sel_result(s)?;
|
||||
r["num"] = json!(num);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Lay out again every paragraph in one of `nums`.
|
||||
fn touch_lists(s: &mut Session, nums: &[u32]) -> Result<(), CmdError> {
|
||||
touch_where(s, &|p| p.props.numbering.is_some_and(|n| nums.contains(&n.num)))
|
||||
@@ -309,4 +402,138 @@ mod tests {
|
||||
// Programmatic calls without levels are an error, not a dialog.
|
||||
assert!(s.run("list.define", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Each body paragraph's number as laid out (`None`: no number), and its style.
|
||||
fn numbered(s: &mut Session) -> Vec<(Option<String>, String)> {
|
||||
let l = s.layout();
|
||||
let labels: Vec<Option<String>> = l
|
||||
.pages
|
||||
.iter()
|
||||
.flat_map(|p| &p.items)
|
||||
.filter_map(|i| if let Placed::Lines { para, l0: 0, .. } = i { Some(para.label.as_ref().map(|lb| lb.text.clone())) } else { None })
|
||||
.collect();
|
||||
let styles = s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.props.style.clone().unwrap_or_else(|| "Normal".into()));
|
||||
labels.into_iter().zip(styles).collect()
|
||||
}
|
||||
|
||||
fn n(label: Option<&str>, style: &str) -> (Option<String>, String) {
|
||||
(label.map(str::to_string), style.to_string())
|
||||
}
|
||||
|
||||
/// Paragraphs "One" (Heading 1), "Two" (Heading 2), "Three" (`third`), the caret in "One".
|
||||
fn headings(third: &str) -> Session {
|
||||
let mut s = Session::new(Document::new());
|
||||
for (i, (t, st)) in [("One", "Heading1"), ("Two", "Heading2"), ("Three", third)].iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
}
|
||||
s.run("text.insert", &json!({"text": t})).unwrap();
|
||||
s.run("para.style", &json!({"style": st})).unwrap();
|
||||
}
|
||||
s.sel = crate::Selection::caret(wordcraft_doc::Pos::body(0, 0));
|
||||
s
|
||||
}
|
||||
|
||||
/// #1793: the Multilevel List gallery's heading presets number headings through their styles
|
||||
/// (Word: One=1, Two=1.1, Three=2), keep the styles, and survive a save to .docx and back.
|
||||
#[test]
|
||||
fn a_heading_preset_numbers_headings_and_keeps_their_styles() {
|
||||
let mut s = headings("Heading1");
|
||||
s.run("list.multilevelPreset", &json!({"preset": "headings"})).unwrap();
|
||||
let want = [n(Some("1"), "Heading1"), n(Some("1.1"), "Heading2"), n(Some("2"), "Heading1")];
|
||||
assert_eq!(numbered(&mut s), want);
|
||||
// The number comes from the style, so a heading added later is numbered too.
|
||||
let h2 = s.doc.styles.get("Heading2").and_then(|st| st.para.numbering).unwrap();
|
||||
assert_eq!(h2.level, 1);
|
||||
let back = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap();
|
||||
assert_eq!(back.styles.get("Heading2").and_then(|st| st.para.numbering).map(|x| x.level), Some(1), "numPr on the style");
|
||||
let mut b = Session::new(back);
|
||||
assert_eq!(numbered(&mut b), want);
|
||||
}
|
||||
|
||||
/// #1793: the other heading presets of Word's List Library, level by level.
|
||||
#[test]
|
||||
fn every_heading_preset_numbers_three_heading_levels() {
|
||||
for (preset, want) in [
|
||||
("headings", [Some("1"), Some("1.1"), Some("1.1.1")]),
|
||||
("article", [Some("Article I."), Some("Section 1.01"), Some("(a)")]),
|
||||
("outlineHeadings", [Some("I."), Some("A."), Some("1.")]),
|
||||
("chapter", [Some("Chapter 1"), None, None]),
|
||||
] {
|
||||
let mut s = headings("Heading3");
|
||||
s.run("list.multilevelPreset", &json!({"preset": preset})).unwrap();
|
||||
let got: Vec<Option<String>> = numbered(&mut s).into_iter().map(|x| x.0).collect();
|
||||
assert_eq!(got, want.map(|x| x.map(str::to_string)), "{preset}");
|
||||
}
|
||||
let mut s = headings("Heading3");
|
||||
assert!(s.run("list.multilevelPreset", &json!({"preset": "nope"})).is_err());
|
||||
assert!(s.run("list.multilevelPreset", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Paragraphs (text, style id), the selection from paragraph `from` to the end of `to`.
|
||||
fn doc(paras: &[(&str, &str)], from: usize, to: usize) -> Session {
|
||||
let mut s = Session::new(Document::new());
|
||||
for (i, (t, st)) in paras.iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
}
|
||||
s.run("text.insert", &json!({"text": t})).unwrap();
|
||||
s.run("para.style", &json!({"style": st})).unwrap();
|
||||
}
|
||||
let end = paras.get(to).map_or(0, |p| p.0.len());
|
||||
s.sel = crate::Selection { anchor: wordcraft_doc::Pos::body(from, 0), focus: wordcraft_doc::Pos::body(to, end) };
|
||||
s
|
||||
}
|
||||
|
||||
/// #1793 (Word for Mac 16.113.4, 2026-10-16): with a caret or a selection, a heading preset
|
||||
/// leaves paragraphs already in a Heading style at their own style and level; every other
|
||||
/// selected paragraph (Normal, Quote, Title…) becomes Heading 1.
|
||||
#[test]
|
||||
fn a_heading_preset_keeps_headings_and_makes_other_paragraphs_heading_1() {
|
||||
let (h1, h2, h3) = ("Heading1", "Heading2", "Heading3");
|
||||
let cases: Vec<(Vec<(&str, &str)>, usize, usize, Vec<(Option<&str>, &str)>)> = vec![
|
||||
// All selected.
|
||||
(vec![("One", h1), ("Two", h2), ("Three", h3)], 0, 2, vec![(Some("1"), h1), (Some("1.1"), h2), (Some("1.1.1"), h3)]),
|
||||
// No Heading 1 above.
|
||||
(vec![("Two", h2), ("Three", h3)], 0, 1, vec![(Some("1.1"), h2), (Some("1.1.1"), h3)]),
|
||||
(vec![("Body", "Normal"), ("Three", h3)], 0, 1, vec![(Some("1"), h1), (Some("1.1.1"), h3)]),
|
||||
(vec![("One", h1), ("Body", "Normal"), ("Two", h2)], 0, 2, vec![(Some("1"), h1), (Some("2"), h1), (Some("2.1"), h2)]),
|
||||
(vec![("One", h1), ("Two", h2), ("Body", "Normal")], 0, 2, vec![(Some("1"), h1), (Some("1.1"), h2), (Some("2"), h1)]),
|
||||
// The caret in Two.
|
||||
(vec![("One", h1), ("Two", h2), ("Three", h3)], 1, 1, vec![(Some("1"), h1), (Some("1.1"), h2), (Some("1.1.1"), h3)]),
|
||||
(vec![("Quote", "Quote"), ("Two", h2)], 0, 1, vec![(Some("1"), h1), (Some("1.1"), h2)]),
|
||||
(vec![("Title", "Title")], 0, 0, vec![(Some("1"), h1)]),
|
||||
// Body text after the selection stays unnumbered.
|
||||
(vec![("One", h1), ("After", "Normal")], 0, 0, vec![(Some("1"), h1), (None, "Normal")]),
|
||||
];
|
||||
for (paras, from, to, want) in cases {
|
||||
let mut s = doc(¶s, from, to);
|
||||
s.run("list.multilevelPreset", &json!({"preset": "headings"})).unwrap();
|
||||
let want: Vec<_> = want.into_iter().map(|(l, st)| n(l, st)).collect();
|
||||
assert_eq!(numbered(&mut s), want, "{paras:?} {from}..={to}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1793 (Word for Mac): the caret alone in a Normal paragraph makes it Heading 1 numbered 1.
|
||||
#[test]
|
||||
fn a_heading_preset_on_a_lone_normal_paragraph_makes_it_heading_1() {
|
||||
let mut s = doc(&[("Body", "Normal")], 0, 0);
|
||||
s.sel = crate::Selection::caret(wordcraft_doc::Pos::body(0, 2));
|
||||
s.run("list.multilevelPreset", &json!({"preset": "headings"})).unwrap();
|
||||
assert_eq!(numbered(&mut s), [n(Some("1"), "Heading1")]);
|
||||
}
|
||||
|
||||
/// #1793: one Undo takes the preset back: paragraph styles and the heading styles' numbers.
|
||||
#[test]
|
||||
fn undo_takes_a_heading_preset_back_in_one_step() {
|
||||
let mut s = doc(&[("Body", "Normal"), ("Two", "Heading2")], 0, 1);
|
||||
let before = numbered(&mut s);
|
||||
s.run("list.multilevelPreset", &json!({"preset": "headings"})).unwrap();
|
||||
assert_ne!(numbered(&mut s), before);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(numbered(&mut s), before);
|
||||
for n in 1..=9 {
|
||||
assert_eq!(s.doc.styles.get(&format!("Heading{n}")).and_then(|st| st.para.numbering), None, "Heading{n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +226,16 @@ fn apply_filter(s: &mut Session) {
|
||||
if m.rows.is_empty() {
|
||||
m.preview = false;
|
||||
}
|
||||
refresh(s);
|
||||
refresh_shown(s);
|
||||
}
|
||||
|
||||
/// [`refresh`] for the non-mutating recipient-list commands: in a protected document the merge
|
||||
/// fields' shown results stay as they are, since these commands skip the protection checks and
|
||||
/// undo (Preview Results and the record buttons, which mutate, show the new list's values).
|
||||
fn refresh_shown(s: &mut Session) {
|
||||
if !super::protect::enforced(&s.doc) {
|
||||
refresh(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical field name for `f` (any case), or a params error.
|
||||
@@ -338,7 +347,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("mailings.editRecipients", "Edit Recipient List", "Mailings › Start Mail Merge", |s, v| {
|
||||
if v.get("rows").and_then(Value::as_array).is_some() {
|
||||
// Edited records keep the list's filter and sort (rules on removed fields drop).
|
||||
let (filter, sort) = (std::mem::take(&mut s.merge.filter), std::mem::take(&mut s.merge.sort));
|
||||
// Copies, so a list that fails to load leaves the filter and sort as they were.
|
||||
let (filter, sort) = (s.merge.filter.clone(), s.merge.sort.clone());
|
||||
let r = recipients(s, &json!({"rows": v.get("rows"), "fields": v.get("fields")}))?;
|
||||
s.merge.filter = filter;
|
||||
s.merge.sort = sort;
|
||||
@@ -604,11 +614,21 @@ fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let named = ext.as_deref().is_some_and(wordcraft_formats::sheet::is_extension);
|
||||
let text = wordcraft_formats::txt::is_text(&bytes);
|
||||
let spreadsheet = wordcraft_formats::sheet::detect(&bytes).is_some() || (named && !text);
|
||||
if named && !spreadsheet && decode(&bytes, v)?.trim_start().starts_with('<') {
|
||||
return Err(CmdError::Failed(
|
||||
"this spreadsheet file is a web page (HTML), not a workbook; open it in a spreadsheet program, save it as .xlsx or .csv and select it again"
|
||||
.into(),
|
||||
));
|
||||
if named && !spreadsheet {
|
||||
let text = decode(&bytes, v)?;
|
||||
let text = text.trim_start().trim_start_matches('\u{feff}');
|
||||
if text.starts_with("<?xml") {
|
||||
return Err(CmdError::Failed(
|
||||
"this spreadsheet file is an XML spreadsheet, not a workbook; open it in a spreadsheet program, save it as .xlsx or .csv and select it again"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if text.starts_with('<') {
|
||||
return Err(CmdError::Failed(
|
||||
"this spreadsheet file is a web page (HTML), not a workbook; open it in a spreadsheet program, save it as .xlsx or .csv and select it again"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if spreadsheet {
|
||||
use wordcraft_formats::sheet::{Pick, read_rows, sheet_names};
|
||||
@@ -647,7 +667,7 @@ fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.merge.filter.clear();
|
||||
s.merge.sort.clear();
|
||||
s.merge.record = 0;
|
||||
refresh(s);
|
||||
refresh_shown(s);
|
||||
let mut r = json!({"fields": s.merge.headers, "records": s.merge.rows.len()});
|
||||
if !sheet.is_null() {
|
||||
r["sheet"] = sheet;
|
||||
@@ -1703,6 +1723,10 @@ mod tests {
|
||||
assert_eq!(r["fields"], json!(["Name", "City"]));
|
||||
let e = s.run("mailings.recipients", &json!({"path": "export.xls", "data": b64(b"<html><table><tr><td>x</td></tr></table></html>")}));
|
||||
assert!(matches!(e, Err(CmdError::Failed(m)) if m.contains("web page")));
|
||||
// #1287: an Excel 2003 XML spreadsheet named .xls says what it is.
|
||||
let xml = b"<?xml version=\"1.0\"?>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"></Workbook>";
|
||||
let e = s.run("mailings.recipients", &json!({"path": "export.xls", "data": b64(xml)}));
|
||||
assert!(matches!(e, Err(CmdError::Failed(m)) if m.contains("XML spreadsheet")));
|
||||
assert!(
|
||||
s.run("mailings.recipients", &json!({"path": "junk.xls", "data": b64(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1, 0, 1])})).is_err()
|
||||
);
|
||||
@@ -1811,6 +1835,21 @@ mod tests {
|
||||
assert_eq!(names(&s), ["X", "Y"]);
|
||||
}
|
||||
|
||||
/// #1287: an Edit Recipient List that fails to load keeps the list's filter and sort.
|
||||
#[test]
|
||||
fn failed_edit_recipients_keeps_filter_and_sort() {
|
||||
let mut s = people();
|
||||
s.run("mailings.filterRecipients", &json!({"rules": [{"field": "Age", "op": "greater", "value": 20}], "sort": [{"field": "City"}]})).unwrap();
|
||||
let before = names(&s);
|
||||
// Array rows without `fields` fail to load.
|
||||
let e = s.run("mailings.editRecipients", &json!({"rows": [["X", "Y"]]}));
|
||||
assert!(matches!(e, Err(CmdError::Params(_))));
|
||||
assert_eq!(s.merge.filter.len(), 1);
|
||||
assert_eq!(s.merge.sort.len(), 1);
|
||||
assert_eq!(names(&s), before);
|
||||
assert_eq!(s.run("mailings.editRecipients", &json!({})).unwrap()["rules"].as_array().map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
/// Review fix for #885: sorting a column that mixes numbers and text is a total order
|
||||
/// (numbers first, numerically; then text; ties keep list order) and never panics.
|
||||
#[test]
|
||||
|
||||
@@ -287,9 +287,17 @@ fn insert_text(s: &mut Session, text: &str, enter: bool) -> Result<(), CmdError>
|
||||
if let Some(p) = controls::prepare_edit(s)? {
|
||||
props = p;
|
||||
}
|
||||
// Pasted text is text: pending properties left by AutoCorrect don't give it a symbol's font (#2036).
|
||||
if !enter {
|
||||
props = props.without_symbol();
|
||||
}
|
||||
delete_selection(s)?;
|
||||
// Typed text is new: never deleted, and not a formatting change of the text around it.
|
||||
props.fmt_change = None;
|
||||
// Its direction comes from its own letters, as on screen, not from the run it's typed into:
|
||||
// Latin typed into reopened Hebrew must not be saved as right-to-left (#1543). The DOCX
|
||||
// writer marks the right-to-left pieces itself.
|
||||
props.rtl = None;
|
||||
if s.doc.settings.track_changes {
|
||||
props.ins = Some(new_revision(s, RevisionKind::Insert));
|
||||
props.del = None;
|
||||
@@ -361,9 +369,14 @@ pub fn split_para(s: &mut Session, at: &Pos) -> Result<Pos, CmdError> {
|
||||
|
||||
/// [`split_para`]; without `enter` an empty list item is split like any other paragraph.
|
||||
fn split_para_as(s: &mut Session, at: &Pos, enter: bool) -> Result<Pos, CmdError> {
|
||||
// `num: 0` means "explicitly not in a list", so it isn't a list item.
|
||||
// `num: 0` means "explicitly not in a list", so it isn't a list item. The list may come from
|
||||
// the paragraph's style (List Number 2 in a Word file) rather than the paragraph itself.
|
||||
let (at_end, style, empty_list) = match s.doc.para_at(at) {
|
||||
Some(p) => (at.off >= p.len(), p.props.style.clone(), p.props.numbering.filter(|n| enter && n.num != 0 && p.is_empty())),
|
||||
Some(p) => (
|
||||
at.off >= p.len(),
|
||||
p.props.style.clone(),
|
||||
p.props.numbering.or_else(|| s.doc.styles.resolve_para(&p.props).numbering).filter(|n| enter && n.num != 0 && p.is_empty()),
|
||||
),
|
||||
None => return Err(CmdError::Failed("no paragraph at caret".into())),
|
||||
};
|
||||
if let Some(n) = empty_list {
|
||||
|
||||
@@ -53,7 +53,7 @@ fn in_use(s: &Session, rev: u32) -> bool {
|
||||
/// done) when it isn't such a cut.
|
||||
pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
|
||||
let (a, b) = s.sel.ordered();
|
||||
if !s.doc.settings.track_changes || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
|
||||
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
|
||||
return Ok(false);
|
||||
}
|
||||
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
|
||||
@@ -71,7 +71,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
|
||||
/// returns the revision for the pasted text (the destination). `None` = an ordinary insertion.
|
||||
pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
|
||||
let m = s.pending_move.take()?;
|
||||
if m.author != s.author || frag.plain_text() != m.text || !in_use(s, m.rev) {
|
||||
if !s.doc.settings.track_moves || m.author != s.author || frag.plain_text() != m.text || !in_use(s, m.rev) {
|
||||
return None;
|
||||
}
|
||||
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
|
||||
@@ -240,6 +240,25 @@ mod tests {
|
||||
assert_eq!(k, ["delete", "insert"]);
|
||||
}
|
||||
|
||||
/// Gap #5: with Track moves off (`w:doNotTrackMoves`), a tracked cut and paste of a
|
||||
/// paragraph is an ordinary deletion and insertion, with no move names.
|
||||
#[test]
|
||||
fn with_track_moves_off_a_cut_and_paste_is_a_deletion_and_an_insertion() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackMoves": false})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
|
||||
s.run("edit.cut", &json!({})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(texts(&s), ["Second one.", "First one.", "Second one.", "Third one."]);
|
||||
assert!(s.doc.revisions.iter().all(|r| r.move_name.is_none()), "{:?}", s.doc.revisions);
|
||||
let k = kinds(&mut s);
|
||||
assert!(k.iter().all(|(k, m)| (k == "insert" || k == "delete") && m.is_null()), "{k:?}");
|
||||
assert!(k.iter().any(|(k, _)| k == "insert") && k.iter().any(|(k, _)| k == "delete"), "{k:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_one_end_of_a_move_accepts_both() {
|
||||
let mut s = moved();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! caret). Picture adjustments re-encode the bitmap (originals are kept for Reset Picture).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::graphic::GraphicKind;
|
||||
use wordcraft_doc::para::{Float, InlineObject, Wrap, WrapText};
|
||||
use wordcraft_doc::props::{Rgb, TextVert, VAlign};
|
||||
use wordcraft_doc::{Pos, StoryRef, TextBody};
|
||||
@@ -56,9 +57,17 @@ fn has_movable(s: &Session) -> Option<&'static str> {
|
||||
_ => has_object(s),
|
||||
}
|
||||
}
|
||||
/// Word's own ink in a group is kept in the form a group member takes; it can't stand on its own
|
||||
/// yet, so such a group stays whole.
|
||||
const INK_GROUP: &str = "a group holding Word ink can't be ungrouped yet";
|
||||
/// Does group `o` hold a member that can't stand on its own (Word's ink)?
|
||||
fn holds_ink(o: &InlineObject) -> bool {
|
||||
matches!(o, InlineObject::Group { children, .. } if children.iter().any(|c| matches!(&c.obj, InlineObject::Graphic { graphic, .. } if graphic.kind == GraphicKind::Ink)))
|
||||
}
|
||||
fn has_group(s: &Session) -> Option<&'static str> {
|
||||
match selected(s) {
|
||||
Some((_, o)) if o.is_canvas() => Some("a drawing canvas can't be ungrouped"),
|
||||
Some((_, o)) if holds_ink(&o) => Some(INK_GROUP),
|
||||
Some((_, InlineObject::Group { .. })) => None,
|
||||
_ => Some("select a group first"),
|
||||
}
|
||||
@@ -82,7 +91,11 @@ fn has_shape(s: &Session) -> Option<&'static str> {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("picture.size", "Size", "Picture Format › Size", size).params(r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent}"#).when(has_sizable),
|
||||
CommandSpec::new("picture.size", "Size", "Picture Format › Size", size)
|
||||
.params(
|
||||
r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent, "original"?: bool} (scale: of the current size, or with original of the picture's original size, its pixels at 96 ppi less what is cropped; original alone restores that size; one side alone keeps the proportions unless lockAspect is false; 1–4000 pt: when the proportions are kept, a side past 4000 pt shrinks the other with it)"#,
|
||||
)
|
||||
.when(has_sizable),
|
||||
CommandSpec::new("picture.crop", "Crop", "Picture Format › Size", crop)
|
||||
.params(
|
||||
r#"{"left"?, "top"?, "right"?, "bottom"? (fractions of the source 0–0.45; a side left out is uncropped), "width"?: pt, "height"?: pt (the new display size, in the same undo step; a floating picture also moves by what a left/top crop trims, so the visible part stays put)}"#,
|
||||
@@ -151,32 +164,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
let e = p::str(v, "effect").unwrap_or("blur").to_string();
|
||||
adjust(s, move |img| match e.as_str() {
|
||||
"blur" => img.blur(3.0),
|
||||
"sharpen" => img.unsharpen(2.0, 2),
|
||||
"invert" => {
|
||||
let mut i = img;
|
||||
i.invert();
|
||||
i
|
||||
}
|
||||
"posterize" => {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
for c in px.0.iter_mut().take(3) {
|
||||
*c = (*c / 64) * 85;
|
||||
}
|
||||
}
|
||||
image::DynamicImage::ImageRgba8(rgba)
|
||||
}
|
||||
"pixelate" => {
|
||||
let (w, h) = (img.width().max(1), img.height().max(1));
|
||||
img.resize_exact((w / 12).max(1), (h / 12).max(1), image::imageops::FilterType::Nearest).resize_exact(w, h, image::imageops::FilterType::Nearest)
|
||||
}
|
||||
_ => img,
|
||||
})
|
||||
relook(s, move |l| l.effect = (e != "none").then_some(e))
|
||||
})
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate"}"#)
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
@@ -230,17 +222,22 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"path"?: string, "data"?: base64}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.style", "Picture Styles", "Picture Format › Picture Styles", |s, v| {
|
||||
// A style replaces the picture's style and border, as Word's gallery does (#2052).
|
||||
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
|
||||
adjust(s, move |img| picture_style(img, &style))
|
||||
relook(s, move |l| {
|
||||
l.style = Some(style);
|
||||
l.border = None;
|
||||
})
|
||||
})
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"}"#)
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
|
||||
adjust(s, move |img| frame(img, w, [c.0, c.1, c.2, 255]))
|
||||
// Replaces the picture's border, keeping its style (#2052).
|
||||
relook(s, move |l| l.border = Some((c, w)))
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px}"#)
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
|
||||
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
|
||||
@@ -721,15 +718,39 @@ fn copy_to(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// text it lands on flows around it, and it moves with that text. On a page where no paragraph
|
||||
/// starts, it anchors to the nearest line and is positioned on the page. Returns the object's
|
||||
/// position afterwards.
|
||||
///
|
||||
/// A drop across pages can be thrown back: while the object sits on its old page it wraps text
|
||||
/// away from the paragraph it is anchored to, so once it has moved, that paragraph can move back
|
||||
/// onto the old page itself — and the object goes with it. Dropping near the top of the next
|
||||
/// page does it every time (the anchor is that page's first paragraph, which fits on the old page
|
||||
/// again once the object's wrap is gone). So a cross-page drop is anchored again until the object
|
||||
/// really stays on the page asked for: the later passes see the pagination as it now is. A
|
||||
/// same-page move (a resize, a nudge) places once, and a drop that still won't stay keeps its
|
||||
/// last place rather than failing.
|
||||
fn move_object(s: &mut Session, pos: Pos, page: Option<u64>, x: f32, y: f32, (w, h): (f32, f32)) -> Result<Pos, CmdError> {
|
||||
let cur = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?.page;
|
||||
let target = page.map_or(cur, |n| usize::try_from(n).unwrap_or(usize::MAX));
|
||||
let tries = if target == cur { 1 } else { 3 };
|
||||
let mut at = pos;
|
||||
for _ in 0..tries {
|
||||
at = move_object_once(s, &at, target, x, y, (w, h))?;
|
||||
s.touch();
|
||||
if s.layout().object(&at, target).is_some_and(|hit| hit.page == target) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// [`move_object`]'s one placement: move the object's character to the anchor under (x, y) on
|
||||
/// `page` and offset it from there.
|
||||
fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w, h): (f32, f32)) -> Result<Pos, CmdError> {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
if pos.path.depth() > 0 || !movable_story(s, pos.story) {
|
||||
return Err(CmdError::Disabled("only objects in the body text, headers and footers can be moved".into()));
|
||||
}
|
||||
let story = pos.story;
|
||||
let layout = s.layout();
|
||||
let cur = layout.object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?;
|
||||
let page = page.map_or(cur.page, |n| usize::try_from(n).unwrap_or(usize::MAX));
|
||||
let pg = layout.pages.get(page).ok_or_else(|| CmdError::Params(format!("no page {page}")))?;
|
||||
// Keep a corner of it on the page.
|
||||
let x = x.max(12.0 - w).min(pg.w - 12.0);
|
||||
@@ -741,11 +762,11 @@ fn move_object(s: &mut Session, pos: Pos, page: Option<u64>, x: f32, y: f32, (w,
|
||||
};
|
||||
// Move its character to the anchor (unless it's already in that paragraph).
|
||||
let at = if anchor.story == pos.story && anchor.path == pos.path && !on_page {
|
||||
pos
|
||||
pos.clone()
|
||||
} else {
|
||||
let obj = s.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?;
|
||||
let obj = s.doc.para_at(pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?;
|
||||
let len = wordcraft_doc::para::OBJ.len_utf8();
|
||||
s.doc.delete_range(&pos, &Pos { off: pos.off + len, ..pos.clone() })?;
|
||||
s.doc.delete_range(pos, &Pos { off: pos.off + len, ..pos.clone() })?;
|
||||
let mut at = anchor;
|
||||
if at.story == pos.story && at.path == pos.path && at.off > pos.off {
|
||||
at.off = at.off.saturating_sub(len);
|
||||
@@ -985,35 +1006,83 @@ fn crop(s: &mut Session, v: &Value) -> CmdResult {
|
||||
})
|
||||
}
|
||||
|
||||
/// A picture's original size: its image's pixels at 96 ppi (the size Insert › Pictures gives it)
|
||||
/// or a metafile's own frame, before any crop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct OriginalSize {
|
||||
/// Points.
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
/// A bitmap's pixels (None for a metafile).
|
||||
pub pixels: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// The original size of the picture showing `media`, read from the image its Picture Format
|
||||
/// adjustments started from (Compress Pictures may have resampled the current one); None when the
|
||||
/// image can't be read.
|
||||
pub fn original_size(s: &Session, media: &str) -> Option<OriginalSize> {
|
||||
let key = s.originals.get(media).map_or(media, String::as_str);
|
||||
let bytes = s.doc.media.get(key).or_else(|| s.doc.media.get(media))?;
|
||||
if let Some((pw, ph)) = wordcraft_render::image_size(bytes) {
|
||||
return Some(OriginalSize { w: pw as f32 * 0.75, h: ph as f32 * 0.75, pixels: Some((pw, ph)) });
|
||||
}
|
||||
let (w, h, _) = wordcraft_render::metafile_size(bytes)?;
|
||||
Some(OriginalSize { w, h, pixels: None })
|
||||
}
|
||||
|
||||
/// What a picture's crop leaves of its original size: the size Reset gives back and what a scale
|
||||
/// of the original counts from. None for anything but a picture whose image can be read.
|
||||
pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)> {
|
||||
let InlineObject::Image { media, crop, .. } = o else { return None };
|
||||
let orig = original_size(s, media)?;
|
||||
let part = |lo: f32, hi: f32| (1.0 - lo - hi).max(0.1);
|
||||
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
|
||||
}
|
||||
|
||||
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
|
||||
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
|
||||
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
|
||||
fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?;
|
||||
let (w0, h0) = obj_size(&o);
|
||||
let lock = p::bool(v, "lockAspect").unwrap_or(true);
|
||||
let (mut w, mut h) = (w0, h0);
|
||||
if let Some(sc) = p::f32(v, "scale") {
|
||||
let (mut w, mut h) = obj_size(&o);
|
||||
let scale = p::f32(v, "scale");
|
||||
if p::bool(v, "original").unwrap_or(false) {
|
||||
let (ow, oh) =
|
||||
cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
|
||||
let k = scale.unwrap_or(100.0) / 100.0;
|
||||
(w, h) = (ow * k, oh * k);
|
||||
} else if let Some(sc) = scale {
|
||||
w *= sc / 100.0;
|
||||
h *= sc / 100.0;
|
||||
}
|
||||
match (p::f32(v, "width"), p::f32(v, "height")) {
|
||||
let (nw, nh) = (p::f32(v, "width"), p::f32(v, "height"));
|
||||
match (nw, nh) {
|
||||
(Some(nw), Some(nh)) => {
|
||||
w = nw;
|
||||
h = nh;
|
||||
}
|
||||
(Some(nw), None) => {
|
||||
if lock && w0 > 0.0 {
|
||||
h = h0 * nw / w0;
|
||||
if lock && w > 0.0 {
|
||||
h *= nw / w;
|
||||
}
|
||||
w = nw;
|
||||
}
|
||||
(None, Some(nh)) => {
|
||||
if lock && h0 > 0.0 {
|
||||
w = w0 * nh / h0;
|
||||
if lock && h > 0.0 {
|
||||
w *= nh / h;
|
||||
}
|
||||
h = nh;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0));
|
||||
// A size that keeps the proportions shrinks on both sides to fit, rather than flattening.
|
||||
let keep = match (nw, nh) {
|
||||
(Some(_), Some(_)) => false,
|
||||
(None, None) => true,
|
||||
_ => lock,
|
||||
};
|
||||
let (w, h) = fit_size(w, h, keep);
|
||||
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
|
||||
// SmartArt graphic lays itself out again at the new size.
|
||||
let theme = s.doc.settings.theme_colors.clone();
|
||||
@@ -1024,6 +1093,27 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
})
|
||||
}
|
||||
|
||||
/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest
|
||||
/// 1 that brings them within the limits, so the proportions hold; a shape too long and thin for any
|
||||
/// such factor is clamped side by side.
|
||||
pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
|
||||
let side = |x: f32| if x.is_nan() { 1.0 } else { x.clamp(1.0, 4000.0) };
|
||||
if keep && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 {
|
||||
let (lo, hi) = ((1.0 / w).max(1.0 / h), (4000.0 / w).min(4000.0 / h));
|
||||
if lo <= hi {
|
||||
let k = if lo > 1.0 {
|
||||
lo
|
||||
} else if hi < 1.0 {
|
||||
hi
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
return (side(w * k), side(h * k));
|
||||
}
|
||||
}
|
||||
(side(w), side(h))
|
||||
}
|
||||
|
||||
/// Apply an image operation to the selected picture's bitmap (stored as a new PNG).
|
||||
fn adjust(s: &mut Session, f: impl Fn(image::DynamicImage) -> image::DynamicImage) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
|
||||
@@ -1064,6 +1154,97 @@ fn adjust_media(s: &mut Session, base: &str, f: impl Fn(image::DynamicImage) ->
|
||||
})
|
||||
}
|
||||
|
||||
/// What Artistic Effects, Picture Styles and Picture Border drew on a picture's bitmap: the
|
||||
/// bitmap they started from and the effect, style and border on it, so the next one draws again
|
||||
/// from that bitmap instead of over the last result. Picking a second style replaces the first,
|
||||
/// as in Word, instead of framing the frame (#2052). Kept in [`Session::picture_looks`] under the
|
||||
/// media key of the drawn bitmap.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PictureLook {
|
||||
/// The media key of the bitmap before any of them.
|
||||
pub base: String,
|
||||
pub effect: Option<String>,
|
||||
pub style: Option<String>,
|
||||
pub border: Option<(Rgb, u32)>,
|
||||
/// The drawn bitmap: a media key that names other bytes later (undo then a new picture
|
||||
/// reusing the key) is not this look's.
|
||||
pub drawn: std::sync::Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Change the selected picture's effect, style or border and draw it again from the bitmap
|
||||
/// under them (effect, then style, then border).
|
||||
fn relook(s: &mut Session, change: impl FnOnce(&mut PictureLook)) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
|
||||
let InlineObject::Image { media, .. } = o else { return Err(CmdError::Disabled("not a picture".into())) };
|
||||
let cur = s.doc.media.get(&media).cloned();
|
||||
let mut look = s
|
||||
.picture_looks
|
||||
.get(&media)
|
||||
.filter(|l| cur.as_ref().is_some_and(|c| std::sync::Arc::ptr_eq(c, &l.drawn)) && s.doc.media.contains_key(&l.base))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| PictureLook { base: media.clone(), ..Default::default() });
|
||||
change(&mut look);
|
||||
if look.effect.is_none() && look.style.is_none() && look.border.is_none() {
|
||||
// Nothing left on it: the bitmap as it was.
|
||||
let base = look.base.clone();
|
||||
return with_obj(s, |o| {
|
||||
if let InlineObject::Image { media, .. } = o {
|
||||
*media = base.clone();
|
||||
}
|
||||
});
|
||||
}
|
||||
let l = look.clone();
|
||||
let out = adjust_media(s, &look.base, move |img| {
|
||||
let mut img = match &l.effect {
|
||||
Some(e) => artistic_effect(img, e),
|
||||
None => img,
|
||||
};
|
||||
if let Some(st) = &l.style {
|
||||
img = picture_style(img, st);
|
||||
}
|
||||
if let Some((c, w)) = l.border {
|
||||
img = frame(img, w, [c.0, c.1, c.2, 255]);
|
||||
}
|
||||
img
|
||||
})?;
|
||||
if let Some((_, InlineObject::Image { media, .. })) = selected(s)
|
||||
&& let Some(drawn) = s.doc.media.get(&media).cloned()
|
||||
{
|
||||
s.picture_looks.insert(media, PictureLook { drawn, ..look });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn artistic_effect(img: image::DynamicImage, effect: &str) -> image::DynamicImage {
|
||||
match effect {
|
||||
"blur" => img.blur(3.0),
|
||||
"sharpen" => img.unsharpen(2.0, 2),
|
||||
"invert" => {
|
||||
let mut i = img;
|
||||
i.invert();
|
||||
i
|
||||
}
|
||||
"posterize" => {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
for c in px.0.iter_mut().take(3) {
|
||||
*c = (*c / 64) * 85;
|
||||
}
|
||||
}
|
||||
image::DynamicImage::ImageRgba8(rgba)
|
||||
}
|
||||
"pixelate" => {
|
||||
let (w, h) = (img.width().max(1), img.height().max(1));
|
||||
img.resize_exact((w / 12).max(1), (h / 12).max(1), image::imageops::FilterType::Nearest).resize_exact(
|
||||
w,
|
||||
h,
|
||||
image::imageops::FilterType::Nearest,
|
||||
)
|
||||
}
|
||||
_ => img,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
|
||||
let InlineObject::Image { media, .. } = o else { return Err(CmdError::Disabled("not a picture".into())) };
|
||||
@@ -1359,6 +1540,9 @@ fn group(s: &mut Session, _: &Value) -> CmdResult {
|
||||
fn ungroup(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("select a group first".into()))?;
|
||||
let InlineObject::Group { w, h, float, .. } = &obj else { return Err(CmdError::Disabled("select a group first".into())) };
|
||||
if holds_ink(&obj) {
|
||||
return Err(CmdError::Disabled(INK_GROUP.into()));
|
||||
}
|
||||
// Its offsets, explicit: the members are placed from the same anchor.
|
||||
let pos = if float.wrap == Wrap::Inline {
|
||||
if pos.path.depth() > 0 || !movable_story(s, pos.story) {
|
||||
@@ -1594,6 +1778,41 @@ mod tests {
|
||||
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
|
||||
}
|
||||
|
||||
/// #2019: Insert › Shapes adds each new shape beside the selected one, as Word draws it, so
|
||||
/// shapes inserted in a row are all kept (the second used to replace the first, which stays
|
||||
/// selected after its insert). Selected text stays too, and the new shape is selected.
|
||||
#[test]
|
||||
fn shapes_inserted_in_a_row_are_all_kept_and_keep_selected_text() {
|
||||
let objects = |s: &mut Session| s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len);
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
for kind in ["rectangle", "ellipse", "star"] {
|
||||
s.run("insert.shape", &json!({"kind": kind})).unwrap();
|
||||
}
|
||||
assert_eq!(objects(&mut s), Some(3));
|
||||
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kiln room"));
|
||||
s.run("select.text", &json!({"text": "Kiln"})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
let text = s.doc.plain_text(StoryRef::Body);
|
||||
assert!(text.starts_with("Kiln") && text.ends_with(" room"), "{text:?}");
|
||||
assert_eq!(objects(&mut s), Some(1));
|
||||
let (a, b) = s.sel.ordered();
|
||||
let obj = wordcraft_doc::para::OBJ.len_utf8();
|
||||
assert_eq!((a.off, b.off), (4, 4 + obj), "the new shape, after the text, is selected");
|
||||
}
|
||||
|
||||
/// Insert › Pictures does replace a selected picture, as Word does (checked in Word for
|
||||
/// Windows while fixing #2019): only shapes are added beside the selection.
|
||||
#[test]
|
||||
fn an_inserted_picture_replaces_a_selected_picture() {
|
||||
let data = super::super::insert::base64_encode(&png(20, 10));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.sel = crate::Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, wordcraft_doc::para::OBJ.len_utf8()) };
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_pipeline() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
@@ -1669,6 +1888,59 @@ mod tests {
|
||||
assert_eq!(rgba(&s), orig, "reset still finds the original");
|
||||
}
|
||||
|
||||
/// #2052: a picture style picked after another replaces it (Thick Frame then Simple Frame is
|
||||
/// only the simple frame), a border replaces the border and keeps the style, an artistic
|
||||
/// effect replaces the effect, and transparency 50% then 10% is 10%, as in Word.
|
||||
#[test]
|
||||
fn picture_styles_borders_and_effects_replace_the_last_one() {
|
||||
let picture = || {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.picture", &json!({"data": super::super::insert::base64_encode(&png(80, 40))})).unwrap();
|
||||
s
|
||||
};
|
||||
let bitmap = |s: &Session| {
|
||||
let (_, o) = selected(s).unwrap();
|
||||
let InlineObject::Image { media, .. } = o else { panic!("a picture") };
|
||||
image::load_from_memory(&s.doc.media.get(&media).cloned().unwrap()).unwrap().to_rgba8()
|
||||
};
|
||||
let after = |cmds: &[(&str, Value)]| {
|
||||
let mut s = picture();
|
||||
for (id, v) in cmds {
|
||||
s.run(id, v).unwrap();
|
||||
}
|
||||
bitmap(&s)
|
||||
};
|
||||
let (thick, simple) = (json!({"style": "thickFrame"}), json!({"style": "simpleFrame"}));
|
||||
assert_eq!(after(&[("picture.style", thick.clone()), ("picture.style", simple.clone())]), after(&[("picture.style", simple.clone())]));
|
||||
let (wide, thin) = (json!({"width": 8}), json!({"width": 2}));
|
||||
assert_eq!(
|
||||
after(&[("picture.style", thick.clone()), ("picture.border", wide.clone()), ("picture.border", thin.clone())]),
|
||||
after(&[("picture.style", thick.clone()), ("picture.border", thin.clone())]),
|
||||
"a border replaces the border and keeps the style"
|
||||
);
|
||||
assert_eq!(
|
||||
after(&[("picture.border", wide), ("picture.style", simple.clone())]),
|
||||
after(&[("picture.style", simple)]),
|
||||
"a style replaces the border too"
|
||||
);
|
||||
assert_eq!(
|
||||
after(&[("picture.effects", json!({"effect": "invert"})), ("picture.effects", json!({"effect": "posterize"}))]),
|
||||
after(&[("picture.effects", json!({"effect": "posterize"}))])
|
||||
);
|
||||
assert_eq!(after(&[("picture.effects", json!({"effect": "invert"})), ("picture.effects", json!({"effect": "none"}))]), bitmap(&picture()));
|
||||
let fifty_then_ten = after(&[("picture.transparency", json!({"percent": 50})), ("picture.transparency", json!({"percent": 10}))]);
|
||||
assert!(fifty_then_ten.pixels().all(|p| p.0[3] == 229), "255 * 0.9");
|
||||
|
||||
// Undo then a new edit reusing the drawn bitmap's media key starts from what is there.
|
||||
let mut s = picture();
|
||||
s.run("picture.style", &thick).unwrap();
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
s.run("picture.effects", &json!({"effect": "invert"})).unwrap();
|
||||
s.run("picture.border", &json!({"width": 2})).unwrap();
|
||||
let (w, h) = bitmap(&s).dimensions();
|
||||
assert_eq!((w, h), (84, 44), "the effect and a 2 px border, no thick frame from before the undo");
|
||||
}
|
||||
|
||||
/// #513: Wrap Text › Fix Position on Page / Move with Text re-anchor a floating picture
|
||||
/// vertically without moving it; one undo step each; an inline picture can't.
|
||||
#[test]
|
||||
@@ -1925,6 +2197,67 @@ mod tests {
|
||||
assert_eq!(crop, [0.1, 0.2, 0.05, 0.0]);
|
||||
}
|
||||
|
||||
/// #2573: Size from the original. `original` alone gives the picture back its original size
|
||||
/// (its pixels at 96 ppi, less what is cropped) and `scale` is a percentage of it; Compress
|
||||
/// Pictures doesn't change what the original is. Only a picture has one.
|
||||
#[test]
|
||||
fn picture_size_counts_from_the_original() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let data = super::super::insert::base64_encode(&png(40, 20));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
let size = |s: &Session| obj_size(&selected(s).unwrap().1);
|
||||
assert_eq!(size(&s), (30.0, 15.0), "40×20 px at 96 ppi");
|
||||
s.run("picture.size", &json!({"width": 300.0, "height": 100.0, "lockAspect": false})).unwrap();
|
||||
s.run("picture.compress", &json!({"maxPixels": 32})).unwrap();
|
||||
let Some((_, InlineObject::Image { media, .. })) = selected(&s) else { panic!("a picture") };
|
||||
assert_eq!(wordcraft_render::image_size(&s.doc.media[&media]), Some((32, 16)), "compressed");
|
||||
assert_eq!(original_size(&s, &media), Some(OriginalSize { w: 30.0, h: 15.0, pixels: Some((40, 20)) }));
|
||||
s.run("picture.size", &json!({"original": true})).unwrap();
|
||||
assert_eq!(size(&s), (30.0, 15.0));
|
||||
s.run("picture.size", &json!({"original": true, "scale": 250})).unwrap();
|
||||
assert_eq!(size(&s), (75.0, 37.5));
|
||||
// Half the width cropped away: half the original width is left.
|
||||
s.run("picture.crop", &json!({"left": 0.25, "right": 0.25})).unwrap();
|
||||
s.run("picture.size", &json!({"original": true})).unwrap();
|
||||
assert_eq!(size(&s), (15.0, 15.0));
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(size(&s), (75.0, 37.5), "one undo step");
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
assert!(s.run("picture.size", &json!({"original": true})).is_err(), "a shape has no original size");
|
||||
}
|
||||
|
||||
/// #2573: a size past 4000 pt (or under 1 pt) that keeps the proportions scales as a whole
|
||||
/// instead of flattening against the limit; both sides given are clamped each on its own.
|
||||
#[test]
|
||||
fn picture_size_past_the_limit_keeps_the_proportions() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let data = super::super::insert::base64_encode(&png(40, 20));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
let size = |s: &Session| obj_size(&selected(s).unwrap().1);
|
||||
s.run("picture.size", &json!({"width": 9000.0})).unwrap();
|
||||
assert_eq!(size(&s), (4000.0, 2000.0));
|
||||
s.run("picture.size", &json!({"scale": 1000})).unwrap();
|
||||
assert_eq!(size(&s), (4000.0, 2000.0));
|
||||
s.run("picture.size", &json!({"width": 9000.0, "height": 10.0})).unwrap();
|
||||
assert_eq!(size(&s), (4000.0, 10.0));
|
||||
s.run("picture.size", &json!({"height": 30.0, "lockAspect": false})).unwrap();
|
||||
assert_eq!(size(&s), (4000.0, 30.0));
|
||||
// Below 1 pt as well: a 1% scale of 50×200 pt is 1×4 pt, not 1×2.
|
||||
s.run("picture.size", &json!({"width": 50.0, "height": 200.0})).unwrap();
|
||||
s.run("picture.size", &json!({"scale": 1})).unwrap();
|
||||
assert_eq!(size(&s), (1.0, 4.0));
|
||||
// Too long and thin for one factor: side by side. NaN and infinity stay in range.
|
||||
assert_eq!(fit_size(0.5, 5000.0, true), (1.0, 4000.0));
|
||||
assert_eq!(fit_size(f32::NAN, 10.0, true), (1.0, 10.0));
|
||||
assert_eq!(fit_size(f32::INFINITY, 10.0, true), (4000.0, 10.0));
|
||||
// Hostile values never leave the 1–4000 pt range.
|
||||
for v in [json!({"scale": -50}), json!({"width": -1.0}), json!({"original": "yes", "scale": 1e30}), json!({"height": 1e30})] {
|
||||
s.run("picture.size", &v).unwrap();
|
||||
let (w, h) = size(&s);
|
||||
assert!((1.0..=4000.0).contains(&w) && (1.0..=4000.0).contains(&h), "{v}: {w}×{h}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A crop handle drop: `picture.crop` with the new size is one edit, one undo step.
|
||||
#[test]
|
||||
fn picture_crop_with_size_is_one_undo_step() {
|
||||
@@ -2209,4 +2542,100 @@ mod tests {
|
||||
let got = anchor_paragraph(&s.doc, &layout, 1, (mid, top + 1.0), StoryRef::Body);
|
||||
assert_eq!(got, Some(wordcraft_doc::Path::top(plain)));
|
||||
}
|
||||
|
||||
/// A Word file whose only paragraph holds a group of a rectangle and Word's own ink (with its
|
||||
/// picture fallback).
|
||||
fn group_with_word_ink() -> Vec<u8> {
|
||||
use std::io::Write;
|
||||
let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk""#;
|
||||
let rect = r#"<wps:wsp><wps:cNvPr id="2" name="Box"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr><wps:bodyPr/></wps:wsp>"#;
|
||||
let ink = r#"<mc:AlternateContent><mc:Choice Requires="wpi"><w14:contentPart bwMode="auto" r:id="rInk"><w14:nvContentPartPr><w14:cNvPr id="3" name="Ink 3"/><w14:cNvContentPartPr/></w14:nvContentPartPr><w14:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="457200"/></w14:xfrm></w14:contentPart></mc:Choice><mc:Fallback><pic:pic><pic:nvPicPr><pic:cNvPr id="3" name="Ink 3"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rPreview"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></mc:Fallback></mc:AlternateContent>"#;
|
||||
let group = format!(
|
||||
r#"<w:drawing><wp:anchor behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1" relativeHeight="1" simplePos="0" distT="0" distB="0" distL="0" distR="0"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1828800" cy="914400"/><wp:wrapNone/><wp:docPr id="1" name="Group 1"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="1828800" cy="914400"/></a:xfrm></wpg:grpSpPr>{rect}{ink}</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
|
||||
);
|
||||
let rel = |id: &str, ty: &str, target: &str| {
|
||||
format!(r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{ty}" Target="{target}"/>"#)
|
||||
};
|
||||
let parts = [
|
||||
("_rels/.rels", format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{}</Relationships>"#, rel("rId1", "officeDocument", "word/document.xml"))),
|
||||
("[Content_Types].xml", r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/word/ink/ink1.xml" ContentType="application/inkml+xml"/><Default Extension="png" ContentType="image/png"/></Types>"#.to_string()),
|
||||
("word/document.xml", format!(r#"<w:document {ns}><w:body><w:p><w:r>{group}</w:r></w:p></w:body></w:document>"#)),
|
||||
(
|
||||
"word/_rels/document.xml.rels",
|
||||
format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{}{}</Relationships>"#, rel("rInk", "customXml", "ink/ink1.xml"), rel("rPreview", "image", "media/preview.png")),
|
||||
),
|
||||
("word/ink/ink1.xml", r#"<ink xmlns="http://www.w3.org/2003/InkML"><trace>0 0, 1 1</trace></ink>"#.to_string()),
|
||||
];
|
||||
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, xml) in parts {
|
||||
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(xml.as_bytes()).unwrap();
|
||||
}
|
||||
zw.start_file("word/media/preview.png", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zw.write_all(&png(8, 4)).unwrap();
|
||||
zw.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
fn ink_members(doc: &wordcraft_doc::Document) -> usize {
|
||||
let groups: Vec<_> = doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).collect();
|
||||
let nested = groups
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Group { children, .. } => Some(children.iter().filter(|c| matches!(c.obj, InlineObject::Graphic { .. })).count()),
|
||||
_ => None,
|
||||
})
|
||||
.sum::<usize>();
|
||||
let alone = groups.iter().filter(|o| matches!(o, InlineObject::Graphic { .. })).count();
|
||||
nested + alone
|
||||
}
|
||||
|
||||
/// Gap 2 review: a group holding Word's own ink can't be ungrouped (its ink can't stand alone
|
||||
/// yet), so open → Ungroup → save → reopen keeps the ink in the group with its part.
|
||||
#[test]
|
||||
fn ungroup_refuses_a_group_holding_word_ink_and_the_ink_survives_saving() {
|
||||
use std::io::Read;
|
||||
let mut s = Session::new(wordcraft_docx::read(&group_with_word_ink()).unwrap());
|
||||
assert_eq!(ink_members(&s.doc), 1, "the fixture's ink is read into the group");
|
||||
let pos = Pos::body(0, 0);
|
||||
s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos } };
|
||||
assert!(matches!(selected(&s), Some((_, InlineObject::Group { .. }))));
|
||||
let before = wordcraft_docx::write(&s.doc).unwrap();
|
||||
assert!(has_group(&s).is_some(), "Ungroup is greyed out");
|
||||
let err = s.run("arrange.ungroup", &json!({})).unwrap_err();
|
||||
assert!(matches!(err, CmdError::Disabled(_)), "{err:?}");
|
||||
let err = ungroup(&mut s, &json!({})).unwrap_err();
|
||||
assert!(matches!(err, CmdError::Disabled(_)), "{err:?}");
|
||||
let bytes = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
assert_eq!(xml.matches("<w14:contentPart").count(), 1, "{xml}");
|
||||
assert!(xml.contains("<mc:Fallback>"), "{xml}");
|
||||
assert_eq!(bytes, before, "the refused ungroup leaves the document unchanged");
|
||||
let names: Vec<String> = z.file_names().map(String::from).collect();
|
||||
assert_eq!(names.iter().filter(|n| n.starts_with("word/ink/")).count(), 1, "{names:?}");
|
||||
let mut rels = String::new();
|
||||
z.by_name("word/_rels/document.xml.rels").unwrap().read_to_string(&mut rels).unwrap();
|
||||
assert_eq!(rels.matches("/customXml\"").count(), 1, "one ink relationship: {rels}");
|
||||
let back = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(ink_members(&back), 1);
|
||||
}
|
||||
|
||||
/// Review: only Word's ink pins a group; a group of charts or diagrams ungroups as before.
|
||||
#[test]
|
||||
fn only_ink_members_pin_a_group() {
|
||||
let s = Session::new(wordcraft_docx::read(&group_with_word_ink()).unwrap());
|
||||
let pos = Pos::body(0, 0);
|
||||
let mut s = s;
|
||||
s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos } };
|
||||
let Some((_, mut group)) = selected(&s) else { panic!("no group") };
|
||||
assert!(holds_ink(&group));
|
||||
let InlineObject::Group { children, .. } = &mut group else { panic!("not a group") };
|
||||
for c in children.iter_mut() {
|
||||
if let InlineObject::Graphic { graphic, .. } = &mut c.obj {
|
||||
std::sync::Arc::make_mut(graphic).kind = GraphicKind::Chart;
|
||||
}
|
||||
}
|
||||
assert!(!holds_ink(&group), "a group of charts is not pinned");
|
||||
}
|
||||
}
|
||||
|
||||
+172
-13
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("layout.size", "Size", "Layout › Page Setup", size).params(r#"{"name"?: "Letter|Legal|A4|…", "width"?: pt, "height"?: pt} (each side clamped to 7.2–1584 pt, 0.1–22 in; the section keeps its orientation)"#),
|
||||
CommandSpec::new("layout.columns", "Columns", "Layout › Page Setup", columns)
|
||||
.params(
|
||||
r#"{"count": 1-12, "space"?: pt, "separator"?: bool, "preset"?: "left|right", "widths"?: [[width pt, space after pt], …] (unequal columns; sets the count), "apply"?: "section|document|forward"}"#,
|
||||
r#"{"count": 1-12, "space"?: pt, "separator"?: bool, "preset"?: "left|right", "widths"?: [[width pt, space after pt], …] (unequal columns; sets the count), "apply"?: "section|document|forward|selection"} (default: selection when text is selected in the main text — section breaks around it — else section)"#,
|
||||
),
|
||||
CommandSpec::new("layout.break", "Breaks", "Layout › Page Setup", breaks)
|
||||
.params(r#"{"kind": "page|column|textWrapping|nextPage|continuous|evenPage|oddPage"}"#),
|
||||
@@ -215,20 +215,46 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
|
||||
}
|
||||
|
||||
fn block_of(s: &Session) -> usize {
|
||||
s.sel.focus.path.0.first().copied().unwrap_or(0) as usize
|
||||
fn section_of_part(s: &Session, id: u32) -> usize {
|
||||
let sections = s.doc.sections();
|
||||
for (i, (_, sp)) in sections.iter().enumerate() {
|
||||
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
for (bi, block) in s.doc.body.iter().enumerate() {
|
||||
if let wordcraft_doc::Block::Para(p) = &**block {
|
||||
for o in &p.objects {
|
||||
if matches!(o, wordcraft_doc::para::InlineObject::NoteRef { id: nid, .. } if *nid == id) {
|
||||
return s.doc.section_index_of(bi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn section_index_of_focus(s: &Session) -> usize {
|
||||
match s.sel.focus.story {
|
||||
wordcraft_doc::StoryRef::Body => s.doc.section_index_of(s.sel.focus.path.0.first().copied().unwrap_or(0) as usize),
|
||||
wordcraft_doc::StoryRef::Part(id) => section_of_part(s, id),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sect(s: &Session) -> SectionProps {
|
||||
let i = s.doc.section_index_of(block_of(s));
|
||||
let i = section_index_of_focus(s);
|
||||
s.doc.sections().get(i).map(|(_, x)| (*x).clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The last block of each section of the selection.
|
||||
fn selected_section_ends(s: &Session) -> Vec<usize> {
|
||||
let (a, b) = s.sel.ordered();
|
||||
let (i0, i1) = (a.path.0.first().copied().unwrap_or(0) as usize, b.path.0.first().copied().unwrap_or(0) as usize);
|
||||
let ends: Vec<usize> = s.doc.sections().iter().map(|(e, _)| *e).collect();
|
||||
if a.story != wordcraft_doc::StoryRef::Body || b.story != wordcraft_doc::StoryRef::Body {
|
||||
let i = section_index_of_focus(s);
|
||||
return vec![ends.get(i).copied().unwrap_or(0)];
|
||||
}
|
||||
let (i0, i1) = (a.path.0.first().copied().unwrap_or(0) as usize, b.path.0.first().copied().unwrap_or(0) as usize);
|
||||
let first = ends.iter().position(|e| i0 <= *e).unwrap_or(0);
|
||||
let last = ends.iter().position(|e| i1 <= *e).unwrap_or(first);
|
||||
(first..=last).map(|k| ends.get(k).copied().unwrap_or(0)).collect()
|
||||
@@ -474,7 +500,9 @@ fn margins(s: &mut Session, v: &Value) -> CmdResult {
|
||||
)
|
||||
}
|
||||
};
|
||||
let gutter = p::f32(v, "gutter");
|
||||
// Negative margins count as zero before the fit check, so one can't offset another.
|
||||
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
|
||||
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
|
||||
let cur = sect(s);
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
return Err(CmdError::Params("margins leave no room for text".into()));
|
||||
@@ -485,12 +513,12 @@ fn margins(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.doc.settings.mirror_margins = on;
|
||||
}
|
||||
with_sect(s, |x| {
|
||||
x.margin_top = t.max(0.0);
|
||||
x.margin_bottom = b.max(0.0);
|
||||
x.margin_left = l.max(0.0);
|
||||
x.margin_right = r.max(0.0);
|
||||
x.margin_top = t;
|
||||
x.margin_bottom = b;
|
||||
x.margin_left = l;
|
||||
x.margin_right = r;
|
||||
if let Some(g) = gutter {
|
||||
x.gutter = g.max(0.0);
|
||||
x.gutter = g;
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -569,7 +597,9 @@ fn columns(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Equal columns keep one spacing; unequal ones remember the first gap for a later switch back.
|
||||
let space = widths.first().map(|w| w.1).unwrap_or(space);
|
||||
let cols = Columns { count: count as u32, space, separator: sep, widths };
|
||||
match p::str(v, "apply").unwrap_or("section") {
|
||||
// With text selected the gallery works on that text, as in Word (#2024).
|
||||
let default = if selection_sectionable(s) { "selection" } else { "section" };
|
||||
match p::str(v, "apply").unwrap_or(default) {
|
||||
"section" => with_sect(s, |x| x.columns = cols.clone()),
|
||||
"document" => {
|
||||
let ends: Vec<usize> = s.doc.sections().iter().map(|(e, _)| *e).collect();
|
||||
@@ -585,10 +615,61 @@ fn columns(s: &mut Session, v: &Value) -> CmdResult {
|
||||
breaks(s, &json!({"kind": "continuous"}))?;
|
||||
with_sect(s, |x| x.columns = cols.clone())
|
||||
}
|
||||
x => Err(CmdError::Params(format!("unknown apply `{x}` (section, document or forward)"))),
|
||||
"selection" => {
|
||||
selection_to_sections(s)?;
|
||||
with_sect(s, |x| x.columns = cols.clone())
|
||||
}
|
||||
x => Err(CmdError::Params(format!("unknown apply `{x}` (section, document, forward or selection)"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the selection can become sections of its own: text selected in the main text, outside
|
||||
/// tables.
|
||||
pub fn selection_sectionable(s: &Session) -> bool {
|
||||
let (a, b) = s.sel.ordered();
|
||||
!s.sel.is_collapsed() && [a, b].iter().all(|p| p.story == StoryRef::Body && p.path.depth() == 0)
|
||||
}
|
||||
|
||||
/// Columns for the selected text (#2024), as Word does it: a continuous section break where the
|
||||
/// selection starts and one where it ends, splitting paragraphs there, unless that end already
|
||||
/// meets a section boundary (the document's start or end, or a section break). The selection keeps
|
||||
/// its text, which is then the section(s) between.
|
||||
fn selection_to_sections(s: &mut Session) -> Result<(), CmdError> {
|
||||
if !selection_sectionable(s) {
|
||||
return Err(CmdError::Params("selected text in the main text, outside tables, is needed".into()));
|
||||
}
|
||||
let old = s.sel.clone();
|
||||
let (a, mut b) = old.ordered();
|
||||
let block = |p: &Pos| p.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let len = |s: &Session, p: &Pos| s.doc.para_at(p).map(|q| q.len()).unwrap_or(0);
|
||||
let ends: Vec<usize> = s.doc.sections().iter().map(|(e, _)| *e).collect();
|
||||
let after_break = |i: usize| i.checked_sub(1).is_some_and(|j| ends.contains(&j));
|
||||
// A selection that took a section break with it ends before that break.
|
||||
if b.off == 0 && block(&b) > block(&a) && after_break(block(&b)) {
|
||||
let prev = Pos { path: wordcraft_doc::Path::top(block(&b) - 1), off: 0, ..b.clone() };
|
||||
b = Pos { off: len(s, &prev), ..prev };
|
||||
}
|
||||
let last_block = s.doc.body.len().saturating_sub(1);
|
||||
let end_break = !(b.off == len(s, &b) && (ends.contains(&block(&b)) || block(&b) == last_block));
|
||||
let start_break = !(a.off == 0 && (block(&a) == 0 || after_break(block(&a))));
|
||||
// The end first: the start's position doesn't move.
|
||||
if end_break {
|
||||
s.sel = Selection::caret(b.clone());
|
||||
breaks(s, &json!({"kind": "continuous"}))?;
|
||||
}
|
||||
let (first, last) = if start_break {
|
||||
s.sel = Selection::caret(a.clone());
|
||||
breaks(s, &json!({"kind": "continuous"}))?;
|
||||
let first = s.sel.focus.clone();
|
||||
let last = shifted_by_split(&b, &a, &first);
|
||||
(first, last)
|
||||
} else {
|
||||
(a, b)
|
||||
};
|
||||
s.sel = if old.anchor <= old.focus { Selection { anchor: first, focus: last } } else { Selection { anchor: last, focus: first } };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `[[width, space after], …]` in points: 1–12 columns, each at least 0.25", that fit the text
|
||||
/// width (`tw`).
|
||||
fn column_widths(v: &Value, tw: f32) -> Result<Vec<(f32, f32)>, CmdError> {
|
||||
@@ -956,6 +1037,84 @@ mod tests {
|
||||
assert!(s.run("layout.columns", &json!({"count": 2, "apply": "elsewhere"})).is_err());
|
||||
}
|
||||
|
||||
/// Each section's paragraphs (a section break's own paragraph shows as "") and column count.
|
||||
fn sections_of(s: &Session) -> Vec<(Vec<String>, u32)> {
|
||||
let mut from = 0;
|
||||
let mut out = Vec::new();
|
||||
for (end, x) in s.doc.sections() {
|
||||
let paras = (from..=end).map(|i| s.doc.para_at(&Pos::body(i, 0)).map(|p| p.text.clone()).unwrap_or_default()).collect();
|
||||
out.push((paras, x.columns.count));
|
||||
from = end + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, from: (usize, usize), to: (usize, usize)) {
|
||||
s.sel = Selection { anchor: Pos::body(from.0, from.1), focus: Pos::body(to.0, to.1) };
|
||||
}
|
||||
|
||||
fn strs(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Columns on selected text (#2024), as observed in Word: a continuous section break before
|
||||
/// and after the selection, the columns on the section between, the rest left alone.
|
||||
#[test]
|
||||
fn columns_apply_to_the_selected_text() {
|
||||
let five = || Session::new(wordcraft_doc::Document::from_text("p1\np2\nalpha beta gamma\np4\np5"));
|
||||
// A whole paragraph (a triple-click takes its mark): each break gets a paragraph of its own.
|
||||
let mut s = five();
|
||||
select(&mut s, (2, 0), (3, 0));
|
||||
let whole = s.selected_text();
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s), vec![(strs(&["p1", "p2", ""]), 1), (strs(&["alpha beta gamma", ""]), 2), (strs(&["p4", "p5"]), 1)]);
|
||||
assert!(s.doc.sections().iter().skip(1).all(|(_, x)| x.start == SectionStart::Continuous));
|
||||
assert_eq!(s.selected_text(), whole, "the paragraph stays selected");
|
||||
// The same paragraph again: its section changes, no new breaks.
|
||||
select(&mut s, (3, 0), (4, 0));
|
||||
s.run("layout.columns", &json!({"count": 3})).unwrap();
|
||||
assert_eq!(sections_of(&s).iter().map(|(_, n)| *n).collect::<Vec<_>>(), vec![1, 3, 1]);
|
||||
// Taking the section break along changes nothing more.
|
||||
select(&mut s, (3, 0), (5, 0));
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s).iter().map(|(_, n)| *n).collect::<Vec<_>>(), vec![1, 2, 1]);
|
||||
// One undo step takes the breaks and the columns away.
|
||||
let mut s = five();
|
||||
select(&mut s, (2, 0), (3, 0));
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(sections_of(&s), vec![(strs(&["p1", "p2", "alpha beta gamma", "p4", "p5"]), 1)]);
|
||||
|
||||
// Words inside a paragraph: the breaks split it there.
|
||||
let mut s = five();
|
||||
select(&mut s, (2, 10), (2, 6));
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s), vec![(strs(&["p1", "p2", "alpha "]), 1), (strs(&["beta"]), 2), (strs(&[" gamma", "p4", "p5"]), 1)]);
|
||||
assert_eq!(s.selected_text(), "beta");
|
||||
assert!(s.sel.anchor > s.sel.focus, "a backward selection stays backward");
|
||||
|
||||
// At the document's start no break goes before it, at its end none after.
|
||||
let mut s = five();
|
||||
select(&mut s, (0, 0), (1, 0));
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s), vec![(strs(&["p1", ""]), 2), (strs(&["p2", "alpha beta gamma", "p4", "p5"]), 1)]);
|
||||
let mut s = five();
|
||||
select(&mut s, (4, 0), (4, 2));
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s), vec![(strs(&["p1", "p2", "alpha beta gamma", "p4", ""]), 1), (strs(&["p5"]), 2)]);
|
||||
// Select All: the whole document, no breaks.
|
||||
let mut s = five();
|
||||
s.run("select.all", &json!({})).unwrap();
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s), vec![(strs(&["p1", "p2", "alpha beta gamma", "p4", "p5"]), 2)]);
|
||||
|
||||
// Without a selection the caret's section changes; "selection" then needs one.
|
||||
let mut s = five();
|
||||
s.run("layout.columns", &json!({"count": 2})).unwrap();
|
||||
assert_eq!(sections_of(&s).len(), 1);
|
||||
assert!(s.run("layout.columns", &json!({"count": 2, "apply": "selection"})).is_err());
|
||||
}
|
||||
|
||||
/// #407 Line Numbers options: start, count by, distance and restart; options alone keep the
|
||||
/// restart mode, `none` turns numbering off.
|
||||
#[test]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user