mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-17 11:22:56 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80c944c87d | ||
|
|
1a56d041de | ||
|
|
880cda902f | ||
|
|
24885e830c | ||
|
|
40fd69b6d8 | ||
|
|
b7b528fbcf | ||
|
|
c7e84ae43d | ||
|
|
c7c7421acf | ||
|
|
bbfacd8f62 | ||
|
|
4029e29905 | ||
|
|
328e3738a0 | ||
|
|
0b99c871e9 | ||
|
|
c99dd5cc6e | ||
|
|
53e05c2420 | ||
|
|
8fced5d045 | ||
|
|
de694152a9 | ||
|
|
a216825578 | ||
|
|
ebe2f430d8 | ||
|
|
8fa2895202 | ||
|
|
d7215f4441 | ||
|
|
aeb9704d82 | ||
|
|
221faf2901 | ||
|
|
e234a536d8 | ||
|
|
a5753be57e | ||
|
|
caa4c4b114 | ||
|
|
ca075db458 | ||
|
|
4e2a5c2b8f | ||
|
|
54e82f7131 | ||
|
|
224bfdb2a0 | ||
|
|
abc04c1b41 | ||
|
|
29d862fabc | ||
|
|
406befeaa2 | ||
|
|
93bf14883c | ||
|
|
0cb315edaf | ||
|
|
2dd0f9a67b | ||
|
|
739cdcad0b | ||
|
|
b3f31666d3 | ||
|
|
68f758928e | ||
|
|
840efd03fb | ||
|
|
8e8ab631fd | ||
|
|
8a9d04eeb1 | ||
|
|
266407e840 | ||
|
|
c817cc95c6 | ||
|
|
ff0823f40d | ||
|
|
211f62231d | ||
|
|
9144b9bfda | ||
|
|
a61cef5d45 | ||
|
|
739491f5c7 | ||
|
|
8377ea8e8f | ||
|
|
4357166531 | ||
|
|
5d871d0519 | ||
|
|
ae2d2b43d6 | ||
|
|
cd23034f65 | ||
|
|
b2306fe5ef | ||
|
|
646fbc7cd5 | ||
|
|
4a347e070a | ||
|
|
3bf4c05461 | ||
|
|
7b26a94193 | ||
|
|
ace000b4a4 | ||
|
|
7adbdc574c | ||
|
|
f77eef9cb6 | ||
|
|
a2f41d728e | ||
|
|
9fe9bd5042 | ||
|
|
83c3b5890b | ||
|
|
f472620ac0 | ||
|
|
5467f998a0 | ||
|
|
78dfa8f648 | ||
|
|
82f0c467be | ||
|
|
837a610133 | ||
|
|
de977bcde6 | ||
|
|
4ba0595760 | ||
|
|
6854bd1fb3 | ||
|
|
4356771236 | ||
|
|
cdf146cabd | ||
|
|
54e3e1cf34 | ||
|
|
97c13a2990 | ||
|
|
fe8a8a838c | ||
|
|
2bd6f372c5 | ||
|
|
8a1f101c46 | ||
|
|
42f8559b97 | ||
|
|
bf8b37759c | ||
|
|
1ed889c24c | ||
|
|
6a7af0d679 | ||
|
|
ce6e4094d5 | ||
|
|
9088ed777d | ||
|
|
cc90520b9d | ||
|
|
a95b065c2b | ||
|
|
84026f98b2 | ||
|
|
5f228a0e24 | ||
|
|
b354e0f870 | ||
|
|
86352d5cf3 | ||
|
|
3e776e4c7d | ||
|
|
a9a1aa36a2 | ||
|
|
bc0e51ee4d | ||
|
|
ed66198574 | ||
|
|
d53a740be1 | ||
|
|
e9750c5cb7 | ||
|
|
3d5a153e3d | ||
|
|
7bff3b53e9 | ||
|
|
0909b15eae | ||
|
|
52d17a91df | ||
|
|
e6e8c61dbf | ||
|
|
1d150004f7 | ||
|
|
0aefd4d025 | ||
|
|
235a38c665 | ||
|
|
3bf7a5dbbe | ||
|
|
e40199bf6f | ||
|
|
e2f94ecef9 | ||
|
|
7ccfd4caef | ||
|
|
7b3b6f8041 | ||
|
|
fecb717f99 | ||
|
|
bd188c19d8 | ||
|
|
56a28f33b7 | ||
|
|
cd4ab71552 |
+5
-1
@@ -1 +1,5 @@
|
||||
craft-i18n.rev text eol=lf
|
||||
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
|
||||
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
|
||||
* text=auto
|
||||
|
||||
craft-i18n.rev text eol=lf
|
||||
@@ -18,4 +18,7 @@ jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets: inherit
|
||||
|
||||
@@ -138,3 +138,7 @@ Progress docs: `ROADMAP.md` (stage, headline numbers, progress log), `docs/targe
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
|
||||
|
||||
## Shared-library reuse
|
||||
|
||||
Before implementing file formats, codecs, protocols or reusable UI components, check [storytold/craft-libs](https://github.com/storytold/craft-libs) and relevant open PRs; reuse or extend shared APIs instead of duplicating app-local implementations. Keep app-specific policy and adapters local, preserve behavior and format fidelity, security and resource limits, repository layering and regression tests, and document any shared-API gap rather than silently reducing functionality.
|
||||
|
||||
Generated
+147
-43
@@ -185,6 +185,12 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "ambient-authority"
|
||||
version = "0.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
|
||||
|
||||
[[package]]
|
||||
name = "android-activity"
|
||||
version = "0.6.1"
|
||||
@@ -739,6 +745,24 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-primitives"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
|
||||
dependencies = [
|
||||
"ambient-authority",
|
||||
"fs-set-times",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.1",
|
||||
"ipnet",
|
||||
"maybe-owned",
|
||||
"rustix 1.1.5",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.6.0"
|
||||
@@ -1036,7 +1060,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"rustix 1.1.5",
|
||||
]
|
||||
@@ -1044,17 +1068,25 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
@@ -1070,7 +1102,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1090,7 +1122,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
@@ -1101,7 +1133,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1111,19 +1143,24 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"unicode-segmentation",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=762a06a4c6b48b522b7d4de84a87917ef90265e6#762a06a4c6b48b522b7d4de84a87917ef90265e6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
"craft-font-catalog",
|
||||
"flate2",
|
||||
@@ -1142,12 +1179,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1160,7 +1197,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1183,13 +1220,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
"craft-metadata",
|
||||
"craft-tiff",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
@@ -1206,7 +1247,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1214,7 +1255,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
@@ -1225,7 +1266,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
@@ -1235,7 +1276,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"serde",
|
||||
@@ -1244,7 +1285,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
@@ -1256,7 +1297,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1267,7 +1308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
@@ -1278,7 +1319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1304,7 +1345,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
@@ -1315,7 +1356,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1332,7 +1373,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1343,7 +1384,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1352,7 +1393,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a3e0b5a9440d18f19422a9dca13516747b7d3181#a3e0b5a9440d18f19422a9dca13516747b7d3181"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"log",
|
||||
@@ -1366,7 +1407,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=01315d9c92b5b0e69082d35ca56099461a1efd45#01315d9c92b5b0e69082d35ca56099461a1efd45"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1377,7 +1418,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1390,12 +1431,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1404,7 +1445,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1424,7 +1465,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1451,7 +1492,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -1462,7 +1503,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -1471,7 +1512,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1482,7 +1523,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-winprint-gdi"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -1490,7 +1531,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -1504,7 +1545,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -1517,7 +1558,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -1529,16 +1570,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=41fb227542efb8a7748caa1c659f271d8605303c#41fb227542efb8a7748caa1c659f271d8605303c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2316,6 +2358,17 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs-set-times"
|
||||
version = "0.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -3186,6 +3239,28 @@ dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "3.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -3341,7 +3416,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -3477,6 +3552,12 @@ version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
|
||||
|
||||
[[package]]
|
||||
name = "maybe-owned"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
@@ -4970,6 +5051,16 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix-linux-procfs"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"rustix 1.1.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
@@ -7149,7 +7240,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "winprint"
|
||||
version = "0.2.1"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49"
|
||||
source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"fmt-derive",
|
||||
@@ -7164,6 +7255,7 @@ dependencies = [
|
||||
"windows",
|
||||
"windows-core",
|
||||
"windows-implement",
|
||||
"windows-numerics",
|
||||
"xml",
|
||||
]
|
||||
|
||||
@@ -7193,6 +7285,16 @@ version = "0.0.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6"
|
||||
|
||||
[[package]]
|
||||
name = "winx"
|
||||
version = "0.36.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
@@ -7331,6 +7433,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-font-catalog",
|
||||
"craft-font-store",
|
||||
"craft-mime",
|
||||
"craft-proof",
|
||||
"craft-zip",
|
||||
"encoding_rs",
|
||||
@@ -7406,6 +7509,7 @@ name = "wordcraft-geom"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-tiff",
|
||||
"image",
|
||||
"serde",
|
||||
]
|
||||
|
||||
+32
-29
@@ -24,19 +24,19 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# Proofing is craft-libs' craft-proof (it was crates/proof); its Language data is craft-i18n's
|
||||
# language-data/, embedded from CRAFT_I18N_DIR (craft-i18n.rev). The package keeps the
|
||||
# `wordcraft-proof` name here so `wordcraft_proof::` paths are unchanged.
|
||||
# craft-proof is storytold/craft-libs main at the merge of #590 (ca-ES-valencia reads the ca-valencia
|
||||
# pack), after #589 (French elision suggestions first) and #497 (flag-based compounding), which also
|
||||
# has #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font store's
|
||||
# `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "01315d9c92b5b0e69082d35ca56099461a1efd45", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "762a06a4c6b48b522b7d4de84a87917ef90265e6", version = "=0.1.0" }
|
||||
# craft-proof is storytold/craft-libs main at 453b0da782. That commit has #590 (ca-ES-valencia
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -67,27 +67,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "41fb227542efb8a7748caa1c659f271d8605303c", version = "=0.1.0" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -122,6 +123,8 @@ arboard = { version = "3.7", default-features = false, features = ["wayland-data
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
# cargo llvm-cov sets `--cfg coverage`; timing tests skip themselves under its instrumentation.
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage)"] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
@@ -150,7 +153,7 @@ debug = 0
|
||||
|
||||
# Required by craft-pdf: the backend rejects writers that failed during unwinding.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -124,7 +124,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
|
||||
| **References** | Table of contents, footnotes and endnotes, citations and bibliography (APA, MLA, Chicago, IEEE), captions, table of figures, cross-references, index, table of authorities |
|
||||
| **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, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) or Slovenščina (follows the system language by default) |
|
||||
| **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, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) Slovenščina or Bosanski (follows the system language by default) |
|
||||
| **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
|
||||
@@ -451,8 +451,10 @@ Copyright (c) 2026 ArtCraft Team and the WordCraft contributors. Required notice
|
||||
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
|
||||
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), as
|
||||
English spelling first tries a matching Hunspell dictionary from the Dictionaries folder.
|
||||
Otherwise it uses dialect-specific SCOWL 2026 dictionaries when built with language data;
|
||||
without it, spelling falls back to system Hunspell dictionaries or Grady Ward's public-domain
|
||||
Moby Hyphenator II word list. English hyphenation uses the Moby list and patterns trained from it. 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
|
||||
|
||||
+15
-1
File diff suppressed because one or more lines are too long
@@ -35,10 +35,11 @@ USAGE:
|
||||
--strict writes nothing and exits 3 if a character on the
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] --cmd 'id={json}' [--cmd …]
|
||||
[--save OUT] [--print] [--author NAME]
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
|
||||
@@ -265,7 +266,7 @@ fn parse_scale_arg(command: &str, args: &[String]) -> Result<Option<f64>, String
|
||||
OptionArg::Value(val) => {
|
||||
let scale = val.parse::<f64>().map_err(|_| format!("{command}: invalid --scale `{val}`: not a number"))?;
|
||||
if !scale.is_finite() || scale <= 0.0 {
|
||||
return Err(format!("{command}: invalid --scale `{val}`: scale must be a positive number"));
|
||||
return Err(format!("{command}: invalid --scale `{val}`: scale must be a finite positive number"));
|
||||
}
|
||||
Ok(Some(scale))
|
||||
}
|
||||
@@ -602,6 +603,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
write_stdout(|o| writeln!(o, "{r}"))
|
||||
}
|
||||
"run" => {
|
||||
for (i, arg) in rest.iter().enumerate() {
|
||||
if arg == "--cmd" && rest.get(i + 1).is_none_or(|value| value.starts_with("--")) {
|
||||
return Err("--cmd needs a value".into());
|
||||
}
|
||||
}
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
@@ -635,7 +641,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
let mut i = 0;
|
||||
while i < rest.len() {
|
||||
if rest.get(i).map(String::as_str) == Some("--cmd") {
|
||||
let spec = rest.get(i + 1).ok_or("--cmd needs a value")?;
|
||||
let spec = rest.get(i + 1).filter(|value| !value.starts_with("--")).ok_or("--cmd needs a value")?;
|
||||
let (id, params) = match spec.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
(id.to_string(), serde_json::from_str::<Value>(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?)
|
||||
|
||||
@@ -267,19 +267,19 @@ fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
|
||||
Err("render: invalid --scale `0`: scale must be a positive number".into())
|
||||
Err("render: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
|
||||
Err("render: invalid --scale `-2`: scale must be a positive number".into())
|
||||
Err("render: invalid --scale `-2`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
|
||||
Err("render: invalid --scale `NaN`: scale must be a positive number".into())
|
||||
Err("render: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
|
||||
Err("render: invalid --scale `inf`: scale must be a positive number".into())
|
||||
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
@@ -322,19 +322,19 @@ fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a positive number".into())
|
||||
Err("run: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
|
||||
Err("run: invalid --scale `-1`: scale must be a positive number".into())
|
||||
Err("run: invalid --scale `-1`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
|
||||
Err("run: invalid --scale `NaN`: scale must be a positive number".into())
|
||||
Err("run: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
|
||||
Err("run: invalid --scale `inf`: scale must be a positive number".into())
|
||||
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
@@ -497,6 +497,27 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
|
||||
@@ -18,8 +18,8 @@ wordcraft-engine = { workspace = true }
|
||||
wordcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.wordcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -84,9 +84,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfi
|
||||
clipboard-win = { version = "5.4", features = ["std"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Pinned apart from craft-ui, which doesn't depend on it: `printer_queues`, the printer list that
|
||||
# At the same craft-libs commit as the workspace's crates: `printer_queues`, the printer list that
|
||||
# asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622).
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a3e0b5a9440d18f19422a9dca13516747b7d3181" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
rfd = { workspace = true }
|
||||
# Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94);
|
||||
# rfd itself already depends on it.
|
||||
|
||||
@@ -369,8 +369,11 @@ mod tests {
|
||||
|
||||
impl Conn {
|
||||
fn open(port: u16) -> Self {
|
||||
Self::open_within(port, Duration::from_secs(5))
|
||||
}
|
||||
fn open_within(port: u16, read_timeout: Duration) -> Self {
|
||||
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
s.set_read_timeout(Some(read_timeout)).unwrap();
|
||||
Self(BufReader::new(s.try_clone().unwrap()), s)
|
||||
}
|
||||
fn send(&mut self, line: &str) {
|
||||
@@ -388,7 +391,24 @@ mod tests {
|
||||
/// The server closed the connection.
|
||||
fn closed(&mut self) -> bool {
|
||||
let mut r = String::new();
|
||||
matches!(self.0.read_line(&mut r), Ok(0))
|
||||
closed_by_peer(self.0.read_line(&mut r))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
|
||||
/// which is how Windows can deliver a close when the writer had nothing to read back (the
|
||||
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
|
||||
/// not UTF-8, leaves the connection open.
|
||||
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
|
||||
match read {
|
||||
Ok(n) => n == 0,
|
||||
Err(e) => matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::ConnectionAborted
|
||||
| std::io::ErrorKind::NotConnected
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,13 +493,29 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closure_errors_mean_the_peer_closed() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert!(closed_by_peer(Ok(0)), "end of stream");
|
||||
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
|
||||
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
|
||||
}
|
||||
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
|
||||
// Not UTF-8, a timeout or a would-block leave the socket open.
|
||||
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
|
||||
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_connection_is_closed() {
|
||||
let (port, rx) = boot_with(Duration::from_millis(300));
|
||||
let mut quiet = Conn::open(port);
|
||||
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
|
||||
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
|
||||
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
|
||||
let t0 = Instant::now();
|
||||
assert!(quiet.closed());
|
||||
assert!(t0.elapsed() < Duration::from_secs(3));
|
||||
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
|
||||
// After an authorised request the connection may stay idle.
|
||||
let mut busy = Conn::open(port);
|
||||
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Linux: draw on the GPU that drives the screen.
|
||||
//!
|
||||
//! egui-wgpu picks the discrete GPU by default (`PowerPreference::HighPerformance`). On a laptop
|
||||
//! whose integrated GPU drives the panel, every frame drawn on the discrete one is copied across
|
||||
//! to it, and the discrete GPU leaves its idle state whenever the window redraws: on an Intel HD
|
||||
//! 530 + NVIDIA Quadro M4000M laptop, from 7 W at P8 to over 20 W at P0/P1. Forcing the integrated
|
||||
//! GPU instead breaks desktops whose screen is on the discrete card (storytold/pdfcraft#96), and a
|
||||
//! desktop with a monitor on each card needs the discrete one (storytold/pdfcraft#445). So the
|
||||
//! choice follows the connected displays, as in craft-anything (storytold/craft-anything#571):
|
||||
//!
|
||||
//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`,
|
||||
//! `none`), when set, decide;
|
||||
//! 2. a connected built-in panel: the GPU behind it;
|
||||
//! 3. displays on only one GPU: that GPU;
|
||||
//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as before.
|
||||
|
||||
mod drm;
|
||||
|
||||
use drm::DisplayCard;
|
||||
use eframe::wgpu::{DeviceType, PowerPreference};
|
||||
|
||||
/// What we know of one adapter wgpu offers.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Candidate {
|
||||
pub name: String,
|
||||
pub vendor: u32,
|
||||
pub device: u32,
|
||||
/// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL).
|
||||
pub pci_slot: String,
|
||||
pub device_type: DeviceType,
|
||||
pub gl: bool,
|
||||
}
|
||||
|
||||
/// What the person asked for through wgpu's environment variables.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Asked {
|
||||
pub adapter_name: Option<String>,
|
||||
pub power: Option<PowerPreference>,
|
||||
}
|
||||
|
||||
/// Why an adapter was chosen, for the log.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Why {
|
||||
AskedByName,
|
||||
AskedPower,
|
||||
BuiltInPanel,
|
||||
OnlyGpuWithDisplays,
|
||||
Fallback,
|
||||
}
|
||||
|
||||
/// The index of the adapter to draw with, and why; `None` when there is none.
|
||||
pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> {
|
||||
if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) {
|
||||
// As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice.
|
||||
if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) {
|
||||
return Some((i, Why::AskedByName));
|
||||
}
|
||||
log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name");
|
||||
}
|
||||
if let Some(power) = asked.power {
|
||||
return by_kind(candidates, power).map(|i| (i, Why::AskedPower));
|
||||
}
|
||||
let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect();
|
||||
let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect();
|
||||
let target = if !panels.is_empty() {
|
||||
Some((panels, Why::BuiltInPanel))
|
||||
} else if with_displays.len() == 1 {
|
||||
Some((with_displays, Why::OnlyGpuWithDisplays))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((wanted, why)) = target {
|
||||
// Vulkan before GL for the same card; otherwise wgpu's order.
|
||||
let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl);
|
||||
if let Some((i, _)) = found {
|
||||
return Some((i, why));
|
||||
}
|
||||
}
|
||||
by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback))
|
||||
}
|
||||
|
||||
/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by
|
||||
/// PCI ids, which count only when no other card has the same ids (two cards of one model); GL
|
||||
/// gives only a vendor, which counts only when no other card has that vendor.
|
||||
fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool {
|
||||
if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() {
|
||||
return adapter.pci_slot == card.pci_slot;
|
||||
}
|
||||
if adapter.device != 0 {
|
||||
return adapter.vendor == card.vendor
|
||||
&& adapter.device == card.device
|
||||
&& all.iter().filter(|c| c.vendor == card.vendor && c.device == card.device).count() == 1;
|
||||
}
|
||||
adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1
|
||||
}
|
||||
|
||||
/// The first adapter in wgpu's own order for that power preference.
|
||||
fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
|
||||
let rank = |t: DeviceType| match (power, t) {
|
||||
(PowerPreference::None, _) => 0,
|
||||
(PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1,
|
||||
(_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2,
|
||||
(_, DeviceType::Other) => 3,
|
||||
(_, DeviceType::VirtualGpu) => 4,
|
||||
(_, DeviceType::Cpu) => 5,
|
||||
};
|
||||
candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Candidate {
|
||||
fn of(info: &eframe::wgpu::AdapterInfo) -> Self {
|
||||
Candidate {
|
||||
name: info.name.clone(),
|
||||
vendor: info.vendor,
|
||||
device: info.device,
|
||||
pci_slot: info.device_pci_bus_id.to_ascii_lowercase(),
|
||||
device_type: info.device_type,
|
||||
gl: info.backend == eframe::wgpu::Backend::Gl,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Asked {
|
||||
fn from_env() -> Self {
|
||||
Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The adapter that draws the window, among those that can draw to it.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result<eframe::wgpu::Adapter, String> {
|
||||
let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
|
||||
let candidates: Vec<Candidate> = usable.iter().map(|a| Candidate::of(&a.get_info())).collect();
|
||||
let cards = drm::display_cards();
|
||||
let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why)));
|
||||
match picked {
|
||||
Some((a, why)) => {
|
||||
log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info());
|
||||
Ok(a.clone())
|
||||
}
|
||||
None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0");
|
||||
const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0");
|
||||
const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0");
|
||||
|
||||
fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate {
|
||||
Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false }
|
||||
}
|
||||
|
||||
fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate {
|
||||
Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true }
|
||||
}
|
||||
|
||||
fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard {
|
||||
DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel }
|
||||
}
|
||||
|
||||
/// What wgpu offers on a laptop whose AMD iGPU drives the panel, in its order (Vulkan, then GL).
|
||||
fn laptop_adapters() -> Vec<Candidate> {
|
||||
vec![
|
||||
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
|
||||
vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu),
|
||||
gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu),
|
||||
]
|
||||
}
|
||||
|
||||
/// The iGPU drives the panel; egui-wgpu's default drew on the discrete GPU.
|
||||
#[test]
|
||||
fn a_laptop_draws_on_the_gpu_behind_its_panel() {
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
|
||||
// The same with the discrete GPU listed first.
|
||||
let mut swapped = laptop_adapters();
|
||||
swapped.swap(0, 1);
|
||||
assert_eq!(choose(&swapped, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// The panel's GPU stays the choice with an external monitor on the discrete card as well.
|
||||
#[test]
|
||||
fn the_panel_wins_over_a_monitor_on_the_other_card() {
|
||||
let cards = [card(NVIDIA, 1, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// A desktop with its monitor on the discrete card and the iGPU left on (a low-power default
|
||||
/// draws on the iGPU there, and the window can't start: the case the panel rule must not break).
|
||||
#[test]
|
||||
fn a_desktop_draws_on_the_only_card_with_a_monitor() {
|
||||
let adapters =
|
||||
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
|
||||
let cards = [card(INTEL, 0, false), card(NVIDIA, 1, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
// And on the iGPU when that's where the only monitor is.
|
||||
let cards = [card(INTEL, 2, false), card(NVIDIA, 0, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((0, Why::OnlyGpuWithDisplays)));
|
||||
}
|
||||
|
||||
/// A desktop with a monitor on each card: the discrete GPU, as before (an iGPU choice there
|
||||
/// lost its surface as soon as it was set up).
|
||||
#[test]
|
||||
fn monitors_on_two_cards_keep_the_discrete_gpu() {
|
||||
let adapters =
|
||||
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
|
||||
let cards = [card(INTEL, 1, false), card(NVIDIA, 1, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// Nothing readable (no `/sys`, or a card the drivers don't name): the discrete GPU, as before.
|
||||
#[test]
|
||||
fn without_display_facts_the_old_choice_stands() {
|
||||
assert_eq!(choose(&laptop_adapters(), &[], &Asked::default()), Some((1, Why::Fallback)));
|
||||
let unknown = [card((0x1234, 0x1, "0000:09:00.0"), 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &unknown, &Asked::default()), Some((1, Why::Fallback)));
|
||||
assert_eq!(choose(&[], &[card(AMD, 1, true)], &Asked::default()), None);
|
||||
}
|
||||
|
||||
/// The environment variables still decide: prime-run style requests reach the NVIDIA card.
|
||||
#[test]
|
||||
fn wgpu_environment_variables_decide_when_set() {
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
let asked = |name: Option<&str>, power: Option<PowerPreference>| Asked { adapter_name: name.map(Into::into), power };
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))), Some((2, Why::AskedByName)));
|
||||
// A name nothing has: the usual choice, not a failure.
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some(""), None)), Some((0, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// Under `WGPU_BACKEND=gl` there's no PCI address or device id: the vendor alone finds the
|
||||
/// card, but only when no other card shares it.
|
||||
#[test]
|
||||
fn gl_adapters_are_matched_by_vendor_only_when_unambiguous() {
|
||||
let adapters =
|
||||
[gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)];
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
// Two AMD cards: the vendor can't tell them apart, so the old choice stands.
|
||||
let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)];
|
||||
let adapters = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)];
|
||||
assert_eq!(choose(&adapters, &two_amd, &Asked::default()), Some((1, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// Two adapters for the panel's card (Vulkan and GL): Vulkan, whatever the order.
|
||||
#[test]
|
||||
fn vulkan_comes_before_gl_for_the_same_card() {
|
||||
let adapters = [
|
||||
gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu),
|
||||
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
|
||||
];
|
||||
assert_eq!(choose(&adapters, &[card(AMD, 1, true)], &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// A laptop with the lid closed and a monitor on the NVIDIA card: the switched-off panel isn't
|
||||
/// read as one (`drm` skips it), so the card with the monitor draws.
|
||||
#[test]
|
||||
fn a_closed_laptop_draws_on_the_card_with_the_monitor() {
|
||||
let cards = [card(NVIDIA, 1, false), card(AMD, 0, false)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
}
|
||||
|
||||
/// Two cards of one model have the same PCI ids: only the PCI address tells them apart. Without
|
||||
/// one from the driver the display rule gives way to the old choice instead of guessing.
|
||||
#[test]
|
||||
fn identical_cards_are_told_apart_only_by_pci_address() {
|
||||
const SECOND: (u32, u32, &str) = (0x10de, 0x25a2, "0000:02:00.0");
|
||||
let cards = [card(NVIDIA, 0, false), card(SECOND, 1, false)];
|
||||
let with_slots = [vulkan("NVIDIA A", NVIDIA, DeviceType::DiscreteGpu), vulkan("NVIDIA B", SECOND, DeviceType::DiscreteGpu)];
|
||||
assert_eq!(choose(&with_slots, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
let without: Vec<Candidate> = with_slots.iter().cloned().map(|c| Candidate { pci_slot: String::new(), ..c }).collect();
|
||||
assert_eq!(choose(&without, &cards, &Asked::default()), Some((0, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// The laptop this was measured on: Intel HD 530 behind the panel (`card2-eDP-1`), a Quadro
|
||||
/// M4000M with nothing connected, and the Quadro offered first by wgpu.
|
||||
#[test]
|
||||
fn an_intel_and_nvidia_laptop_draws_on_intel() {
|
||||
const HD530: (u32, u32, &str) = (0x8086, 0x191b, "0000:00:02.0");
|
||||
const M4000M: (u32, u32, &str) = (0x10de, 0x13f9, "0000:01:00.0");
|
||||
let adapters = [
|
||||
vulkan("Quadro M4000M", M4000M, DeviceType::DiscreteGpu),
|
||||
vulkan("Intel(R) HD Graphics 530 (SKL GT2)", HD530, DeviceType::IntegratedGpu),
|
||||
];
|
||||
let cards = [card(M4000M, 0, false), card(HD530, 1, true)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`).
|
||||
//!
|
||||
//! A window drawn on one card and shown on a screen attached to another is copied across on every
|
||||
//! frame, so the app draws on the card that drives the screen (see the parent module).
|
||||
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
/// A graphics card and the displays connected to it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct DisplayCard {
|
||||
/// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel.
|
||||
pub vendor: u32,
|
||||
/// PCI device id.
|
||||
pub device: u32,
|
||||
/// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one.
|
||||
pub pci_slot: String,
|
||||
/// Connected displays that are switched on, of any kind, built-in panel included.
|
||||
pub displays: u32,
|
||||
/// A connected, switched-on built-in panel (eDP, LVDS or DSI): this card drives a laptop's
|
||||
/// own screen.
|
||||
pub built_in_panel: bool,
|
||||
}
|
||||
|
||||
/// Connector kinds that are a computer's own screen rather than a monitor plugged into it.
|
||||
const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"];
|
||||
|
||||
/// At most this many entries are read from the DRM folder.
|
||||
const MAX_ENTRIES: usize = 512;
|
||||
|
||||
/// At most this many bytes are read from one sysfs file.
|
||||
const MAX_FILE: u64 = 4096;
|
||||
|
||||
/// The graphics cards on this computer and what's connected to them. Empty where the system
|
||||
/// doesn't say (a sandbox without `/sys`).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn display_cards() -> Vec<DisplayCard> {
|
||||
display_cards_in(Path::new("/sys/class/drm"))
|
||||
}
|
||||
|
||||
/// [`display_cards`] read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per
|
||||
/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN-<kind>-<n>` entry per
|
||||
/// connector, with `connected` or `disconnected` in its `status` and, where the kernel gives it,
|
||||
/// `enabled` or `disabled` in its `enabled`. Cards without PCI ids (a firmware framebuffer) are
|
||||
/// left out.
|
||||
pub(crate) fn display_cards_in(drm: &Path) -> Vec<DisplayCard> {
|
||||
let Ok(entries) = std::fs::read_dir(drm) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut names: Vec<String> = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
|
||||
names.sort();
|
||||
let cards = names.iter().filter(|n| is_card(n));
|
||||
cards
|
||||
.filter_map(|card| {
|
||||
let uevent = read_small(&drm.join(card).join("device").join("uevent"))?;
|
||||
let (vendor, device) = pci_ids(&uevent)?;
|
||||
let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase();
|
||||
let prefix = format!("{card}-");
|
||||
let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false };
|
||||
for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) {
|
||||
let dir = drm.join(format!("{prefix}{connector}"));
|
||||
let status = read_small(&dir.join("status")).unwrap_or_default();
|
||||
// A panel can be connected but switched off (a closed lid with a monitor in use):
|
||||
// `enabled` then reads `disabled`, and it drives nothing. No `enabled`: as before.
|
||||
let enabled = read_small(&dir.join("enabled")).unwrap_or_default();
|
||||
if status.trim() != "connected" || enabled.trim() == "disabled" {
|
||||
continue;
|
||||
}
|
||||
out.displays = out.displays.saturating_add(1);
|
||||
if BUILT_IN_PANELS.contains(&connector_kind(connector)) {
|
||||
out.built_in_panel = true;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node.
|
||||
fn is_card(name: &str) -> bool {
|
||||
name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number.
|
||||
fn connector_kind(connector: &str) -> &str {
|
||||
match connector.rsplit_once('-') {
|
||||
Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind,
|
||||
_ => connector,
|
||||
}
|
||||
}
|
||||
|
||||
/// `PCI_ID=1002:1638` → (0x1002, 0x1638).
|
||||
fn pci_ids(uevent: &str) -> Option<(u32, u32)> {
|
||||
let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?;
|
||||
Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?))
|
||||
}
|
||||
|
||||
fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
|
||||
uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim)
|
||||
}
|
||||
|
||||
fn read_small(path: &Path) -> Option<String> {
|
||||
let mut text = String::new();
|
||||
std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?;
|
||||
Some(text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// A folder of its own under the system's temporary folder, removed when dropped.
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-drm-test-{}-{n}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
TempDir(dir)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as
|
||||
/// (name, status).
|
||||
fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
for (card, id, slot) in cards {
|
||||
let device = dir.path().join(card).join("device");
|
||||
fs::create_dir_all(&device).expect("card folder");
|
||||
fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).expect("uevent");
|
||||
}
|
||||
for (connector, status) in connectors {
|
||||
let c = dir.path().join(connector);
|
||||
fs::create_dir_all(&c).expect("connector folder");
|
||||
fs::write(c.join("status"), format!("{status}\n")).expect("status");
|
||||
}
|
||||
fs::create_dir_all(dir.path().join("renderD128")).expect("render node");
|
||||
fs::write(dir.path().join("version"), "drm 1.1.0\n").expect("version");
|
||||
dir
|
||||
}
|
||||
|
||||
/// A laptop whose AMD iGPU drives the panel, with an NVIDIA card that has no outputs.
|
||||
#[test]
|
||||
fn a_laptop_panel_is_found_on_the_integrated_gpu() {
|
||||
let d = drm(
|
||||
&[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
|
||||
&[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")],
|
||||
);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(
|
||||
cards,
|
||||
vec![
|
||||
DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false },
|
||||
DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A desktop with a monitor on each card: displays on both, no built-in panel.
|
||||
#[test]
|
||||
fn monitors_on_two_cards_are_counted_on_each() {
|
||||
let d = drm(
|
||||
&[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")],
|
||||
&[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")],
|
||||
);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(1, false), (2, false)]);
|
||||
}
|
||||
|
||||
/// `card10` is a different card from `card1`, and its connectors aren't `card1`'s.
|
||||
#[test]
|
||||
fn card_numbers_are_not_prefixes_of_each_other() {
|
||||
let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.vendor, c.displays)).collect::<Vec<_>>(), vec![(0x1002, 0), (0x10de, 1)]);
|
||||
}
|
||||
|
||||
/// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number.
|
||||
#[test]
|
||||
fn built_in_panels_are_told_from_monitors_by_connector_kind() {
|
||||
assert_eq!(connector_kind("eDP-1"), "eDP");
|
||||
assert_eq!(connector_kind("HDMI-A-1"), "HDMI-A");
|
||||
assert_eq!(connector_kind("DSI-12"), "DSI");
|
||||
assert_eq!(connector_kind("Virtual"), "Virtual");
|
||||
let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]);
|
||||
assert!(display_cards_in(d.path()).iter().all(|c| c.built_in_panel));
|
||||
}
|
||||
|
||||
/// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped, never a panic.
|
||||
#[test]
|
||||
fn what_cant_be_read_is_left_out() {
|
||||
let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]);
|
||||
fs::create_dir_all(d.path().join("card2")).expect("card without device");
|
||||
fs::create_dir_all(d.path().join("card")).expect("bare name");
|
||||
assert!(display_cards_in(d.path()).is_empty());
|
||||
assert!(display_cards_in(&d.path().join("missing")).is_empty());
|
||||
assert_eq!(pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2)));
|
||||
assert_eq!(pci_ids("PCI_IDX=10de:25a2"), None);
|
||||
}
|
||||
|
||||
/// A status of `unknown` (some virtual outputs) isn't a connected display.
|
||||
#[test]
|
||||
fn only_connected_counts() {
|
||||
let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]);
|
||||
assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0));
|
||||
}
|
||||
|
||||
/// A laptop with its lid closed and a monitor on the discrete card: the panel still reads
|
||||
/// `connected` but is switched off, so it neither counts nor marks its card as the panel's.
|
||||
#[test]
|
||||
fn a_switched_off_panel_does_not_count() {
|
||||
let d = drm(
|
||||
&[("card0", "10de:25a2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
|
||||
&[("card0-HDMI-A-1", "connected"), ("card1-eDP-1", "connected")],
|
||||
);
|
||||
fs::write(d.path().join("card0-HDMI-A-1").join("enabled"), "enabled\n").expect("enabled");
|
||||
fs::write(d.path().join("card1-eDP-1").join("enabled"), "disabled\n").expect("enabled");
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.vendor, c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(0x10de, 1, false), (0x1002, 0, false)]);
|
||||
}
|
||||
}
|
||||
+175
-18
@@ -20,9 +20,12 @@ mod default_apps;
|
||||
mod file_dialogs;
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", test))]
|
||||
mod graphics;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux_gpu;
|
||||
mod logging;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod portal_save;
|
||||
mod prefs_merge;
|
||||
mod print;
|
||||
mod region;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -222,31 +225,44 @@ fn user_dict_path() -> Option<std::path::PathBuf> {
|
||||
wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE))
|
||||
}
|
||||
|
||||
fn load_user_dictionary(app: &mut WordApp) {
|
||||
if !prefs_enabled() {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = user_dict_path() {
|
||||
wordcraft_proof::load_user_dictionary(&p);
|
||||
app.session.user_dict_path = Some(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write them.
|
||||
fn prefs_enabled() -> bool {
|
||||
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
}
|
||||
|
||||
/// The preferences as this process last loaded or saved them, which `save_prefs` compares with
|
||||
/// to write only what this process changed since (#3773, see `prefs_merge`).
|
||||
static LOADED_PREFS: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// Apply the saved preferences (`ui.json`) and the user dictionary to `app`, and remember the
|
||||
/// result for `save_prefs`. Runs without preferences neither read nor keep them.
|
||||
fn load_prefs(app: &mut WordApp) {
|
||||
if !prefs_enabled() {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = prefs_path()
|
||||
&& let Ok(bytes) = std::fs::read(&p)
|
||||
let loaded = load_prefs_from(app, prefs_path().as_deref(), user_dict_path());
|
||||
if let Ok(mut slot) = LOADED_PREFS.lock() {
|
||||
*slot = loaded;
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the preferences saved at `prefs` to `app`, then load the user dictionary at `dict`
|
||||
/// (`custom-dictionary.txt`, #40), and give back the preferences as `prefs()` does after both:
|
||||
/// the words only the dictionary file has are part of what was loaded, so a word another process
|
||||
/// removes from `ui.json` isn't written back as one added here (#3773).
|
||||
fn load_prefs_from(app: &mut WordApp, prefs: Option<&std::path::Path>, dict: Option<std::path::PathBuf>) -> Option<serde_json::Value> {
|
||||
if let Some(p) = prefs
|
||||
&& let Ok(bytes) = std::fs::read(p)
|
||||
&& let Some(ui) = UiState::from_json(&bytes)
|
||||
{
|
||||
app.apply_prefs(ui);
|
||||
}
|
||||
if let Some(p) = dict {
|
||||
wordcraft_proof::load_user_dictionary(&p);
|
||||
app.session.user_dict_path = Some(p);
|
||||
}
|
||||
// As `prefs()` gives them back, so a setting nobody touched compares equal at exit.
|
||||
serde_json::to_value(app.prefs()).ok()
|
||||
}
|
||||
|
||||
/// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts
|
||||
@@ -332,6 +348,8 @@ fn x11_libraries() -> Result<(), String> {
|
||||
if missing.is_empty() { Ok(()) } else { Err(missing.join("; ")) }
|
||||
}
|
||||
|
||||
/// Write `app`'s preferences to `ui.json`, merged with what other processes saved since this one
|
||||
/// loaded it (`merged_prefs`).
|
||||
fn save_prefs(app: &WordApp) {
|
||||
if let Err(e) = try_save_prefs(app) {
|
||||
log::warn!("preferences: {e}");
|
||||
@@ -348,11 +366,79 @@ fn try_save_prefs(app: &WordApp) -> Result<bool, String> {
|
||||
if let Some(dir) = p.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(&app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
|
||||
write_prefs(&p, &bytes).map_err(|e| format!("cannot save {}: {e}", p.display()))?;
|
||||
let ours = serde_json::to_value(app.prefs()).map_err(|e| format!("cannot serialize: {e}"))?;
|
||||
let mut base = LOADED_PREFS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
save_merged(&p, &mut base, ours)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Writes `ours` to `path`, merged with what other WordCraft processes saved there since this one
|
||||
/// loaded or saved `base` (`merged_prefs`), and makes `ours` the new `base`: a setting changed here
|
||||
/// before this save and by another process after it then takes the other's value at the next save.
|
||||
/// Holds `lock_prefs` from the read to the rename.
|
||||
fn save_merged(path: &std::path::Path, base: &mut Option<serde_json::Value>, ours: serde_json::Value) -> Result<(), String> {
|
||||
let _lock = lock_prefs(path);
|
||||
let merged = merged_prefs(path, base.as_ref(), ours.clone());
|
||||
let bytes = serde_json::to_vec_pretty(&merged).map_err(|e| format!("cannot serialize: {e}"))?;
|
||||
write_prefs(path, &bytes).map_err(|e| format!("cannot save {}: {e}", path.display()))?;
|
||||
*base = Some(ours);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `ours` with what other WordCraft processes saved to `path` since this one loaded or saved
|
||||
/// `base`, for the settings this one left alone (#3773, see `prefs_merge`). `ours` as it is when
|
||||
/// there's no `base`, or the file is missing or isn't preferences now.
|
||||
fn merged_prefs(path: &std::path::Path, base: Option<&serde_json::Value>, ours: serde_json::Value) -> serde_json::Value {
|
||||
let Some(base) = base else { return ours };
|
||||
let disk = match std::fs::read(path) {
|
||||
Ok(bytes) => prefs_merge::as_read(&bytes),
|
||||
Err(e) => {
|
||||
if e.kind() != std::io::ErrorKind::NotFound {
|
||||
log::debug!("preferences: cannot read {} to merge, saving this process's: {e}", path.display());
|
||||
}
|
||||
return ours;
|
||||
}
|
||||
};
|
||||
match disk {
|
||||
Some(disk) => prefs_merge::merge(base, ours, &disk),
|
||||
None => {
|
||||
log::debug!("preferences: {} isn't preferences, saving this process's", path.display());
|
||||
ours
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a save waits for another process's save to finish before going ahead anyway: a save
|
||||
/// takes milliseconds, and a process stuck holding the lock mustn't stop this one from saving.
|
||||
const PREFS_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// An advisory lock beside `path` (`.ui.json.lock`), held while it is returned, so that two
|
||||
/// processes saving at once (logging out closes every window together) take turns at reading,
|
||||
/// merging and replacing `ui.json` instead of one losing the other's changes. `None` (save
|
||||
/// unlocked) when the lock file can't be opened or the lock isn't free within [`PREFS_LOCK_WAIT`].
|
||||
fn lock_prefs(path: &std::path::Path) -> Option<std::fs::File> {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "ui.json".into());
|
||||
let lock = path.with_file_name(format!(".{name}.lock"));
|
||||
let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
log::debug!("preferences: cannot open {}, saving without it: {e}", lock.display());
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Some(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < PREFS_LOCK_WAIT => std::thread::sleep(std::time::Duration::from_millis(10)),
|
||||
Err(e) => {
|
||||
log::warn!("preferences: {} is held, saving without it: {e}", lock.display());
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a sibling temporary file and renames it over `path`, so a failed or
|
||||
/// interrupted write leaves the previous preferences in place.
|
||||
fn write_prefs(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
@@ -560,7 +646,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("WordCraft")
|
||||
.with_title(wordcraft_ui_egui::build_config::app_name())
|
||||
.with_app_id("ai.storyteller.wordcraft")
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size([760.0, 480.0])
|
||||
@@ -601,6 +687,13 @@ fn main() -> eframe::Result {
|
||||
}));
|
||||
}
|
||||
}
|
||||
// egui-wgpu draws on the discrete GPU by default; on a laptop whose integrated GPU drives the
|
||||
// panel, that wakes the discrete GPU whenever the window redraws. Draw on the GPU that drives
|
||||
// the screen; `WGPU_ADAPTER_NAME` and `WGPU_POWER_PREF` still decide (see linux_gpu.rs).
|
||||
#[cfg(target_os = "linux")]
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
|
||||
setup.native_adapter_selector = Some(std::sync::Arc::new(linux_gpu::pick_adapter));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -608,7 +701,7 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
eframe::run_native(
|
||||
"WordCraft",
|
||||
wordcraft_ui_egui::build_config::app_name(),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
@@ -626,7 +719,6 @@ fn main() -> eframe::Result {
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
load_user_dictionary(&mut app);
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
@@ -839,7 +931,72 @@ mod launch_arg_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod prefs_tests {
|
||||
use super::write_prefs;
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_ui_egui::{UiState, theme::Appearance};
|
||||
|
||||
use super::{load_prefs_from, lock_prefs, prefs_merge, save_merged, write_prefs};
|
||||
|
||||
/// The preferences saved with `theme` (every other setting at its default).
|
||||
fn with_theme(theme: &str) -> Value {
|
||||
prefs_merge::as_read(&serde_json::to_vec(&json!({"theme": theme})).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The theme the next process loads from `path`.
|
||||
fn saved_theme(path: &std::path::Path) -> Appearance {
|
||||
UiState::from_json(&std::fs::read(path).unwrap()).unwrap().theme
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_changed_by_another_process_after_a_save_here_keeps_its_value() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("ui.json");
|
||||
std::fs::write(&path, serde_json::to_vec(&with_theme("light")).unwrap()).unwrap();
|
||||
// A loads Light, switches to Dark and saves before exiting (taking a document off the
|
||||
// recent list does).
|
||||
let mut a = Some(with_theme("light"));
|
||||
save_merged(&path, &mut a, with_theme("dark")).unwrap();
|
||||
assert_eq!(saved_theme(&path), Appearance::Dark);
|
||||
// B starts, loads Dark, switches to Light and exits.
|
||||
save_merged(&path, &mut Some(with_theme("dark")), with_theme("light")).unwrap();
|
||||
// A exits without touching the theme since its save: B's choice, made later, stays.
|
||||
save_merged(&path, &mut a, with_theme("dark")).unwrap();
|
||||
assert_eq!(saved_theme(&path), Appearance::Light);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loaded_preferences_include_the_words_of_the_dictionary_file() {
|
||||
// A word only `custom-dictionary.txt` has is loaded, not added here: if another process
|
||||
// removes it from `ui.json`, this one mustn't write it back.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (prefs, dict) = (dir.path().join("ui.json"), dir.path().join("custom-dictionary.txt"));
|
||||
std::fs::write(&prefs, br#"{"dictionary": ["zqxinjson"]}"#).unwrap();
|
||||
std::fs::write(&dict, "zqxinfile\n").unwrap();
|
||||
let mut app = wordcraft_ui_egui::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let loaded = load_prefs_from(&mut app, Some(&prefs), Some(dict)).unwrap();
|
||||
let words = loaded["dictionary"].as_array().unwrap();
|
||||
for word in ["zqxinjson", "zqxinfile"] {
|
||||
assert!(words.contains(&json!(word)), "{word}: {words:?}");
|
||||
}
|
||||
wordcraft_engine::proof::remove_word("zqxinjson");
|
||||
wordcraft_engine::proof::remove_word("zqxinfile");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_waits_for_another_process_saving_at_the_same_moment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("ui.json");
|
||||
// Another process is between reading and replacing `ui.json`.
|
||||
let held = lock_prefs(&path).expect("the lock is free");
|
||||
let saver = {
|
||||
let path = path.clone();
|
||||
std::thread::spawn(move || save_merged(&path, &mut None, with_theme("dark")))
|
||||
};
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
assert!(!path.exists(), "saved while another process held the lock");
|
||||
drop(held);
|
||||
saver.join().unwrap().unwrap();
|
||||
assert_eq!(saved_theme(&path), Appearance::Dark);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_preferences_write_keeps_the_old_file_and_reports_the_error() {
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts
|
||||
//! another). Each reads it at start-up and writes it at exit (and when a change must survive a
|
||||
//! crash, like taking a document off the recent list), so without a merge the process that writes
|
||||
//! last writes back what it loaded and loses the others' changes (#3773).
|
||||
//!
|
||||
//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting
|
||||
//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are
|
||||
//! left out), and write it with only what this process changed since it last loaded or saved its
|
||||
//! preferences (`base`). Every other setting keeps what the file holds now, including the absence
|
||||
//! of one another process removed (a shortcut, a task pane's place).
|
||||
//!
|
||||
//! - A setting both changed takes this process's value.
|
||||
//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon,
|
||||
//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the
|
||||
//! window's size and place, or one task pane's place, are never mixed from two processes.
|
||||
//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed
|
||||
//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens,
|
||||
//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process
|
||||
//! added are kept, entries either process removed stay removed, and an entry both changed takes
|
||||
//! this process's version. A ribbon or toolbar left as it comes counts as its default entries.
|
||||
//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used
|
||||
//! again first, then the file's, without duplicates, without the entries this process removed,
|
||||
//! and within each list's limit ([`merge_recent`]).
|
||||
//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting.
|
||||
//!
|
||||
//! What this process changed is found by comparing with `base`, not by recording each change: a
|
||||
//! setting changed and then changed back counts as untouched, so the file's value stays, and a
|
||||
//! recent entry used again without moving (it was already first) counts as not used.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout};
|
||||
use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert};
|
||||
|
||||
/// Whether two entries of a recent list are the same entry.
|
||||
type Same = fn(&Value, &Value) -> bool;
|
||||
|
||||
/// What tells an entry of a list of user entries from the others. Entries with the same key are
|
||||
/// told apart by their order ([`ids`]).
|
||||
type Key = fn(&Value) -> String;
|
||||
|
||||
/// How a setting this process changed merges with the file's.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Rule {
|
||||
/// A group of settings: each entry on its own.
|
||||
Group,
|
||||
/// A recent list, most recent first: how many entries it keeps, and when two are the same.
|
||||
Recent(usize, Same),
|
||||
/// A list of user entries: each entry on its own.
|
||||
Entries(Key),
|
||||
/// One setting: this process's value.
|
||||
Whole,
|
||||
}
|
||||
|
||||
/// The rule for the setting at `path` (`ui.json`'s keys from the top).
|
||||
fn rule(path: &[&str]) -> Rule {
|
||||
match path {
|
||||
[] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => {
|
||||
Rule::Group
|
||||
}
|
||||
["recent"] => Rule::Recent(MAX_RECENT, same_entry),
|
||||
["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry),
|
||||
["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry),
|
||||
["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font),
|
||||
["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text),
|
||||
["ribbon", "tabs"] => Rule::Entries(tab_name),
|
||||
["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"]
|
||||
| ["keyboard", "removed"]
|
||||
| ["ribbon", "qat"]
|
||||
| ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry),
|
||||
_ => Rule::Whole,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a setting saved only when it isn't its default stands for when it is missing: the
|
||||
/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the
|
||||
/// default merge entry by entry.
|
||||
fn when_missing(path: &[&str]) -> Option<Value> {
|
||||
match path {
|
||||
["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(),
|
||||
["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries saved alike (colours are saved normalised, `colors::push_recent`).
|
||||
fn same_entry(a: &Value, b: &Value) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// Font names ignoring case, as `push_recent_font` compares them.
|
||||
fn same_font(a: &Value, b: &Value) -> bool {
|
||||
match (a.as_str(), b.as_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry as saved.
|
||||
fn whole_entry(v: &Value) -> String {
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// An AutoCorrect entry `[from, to]` by the text it replaces.
|
||||
fn replaced_text(v: &Value) -> String {
|
||||
v.get(0).unwrap_or(v).to_string()
|
||||
}
|
||||
|
||||
/// A ribbon tab by its name, ignoring case as the ribbon does.
|
||||
fn tab_name(v: &Value) -> String {
|
||||
v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase)
|
||||
}
|
||||
|
||||
/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't
|
||||
/// preferences at all.
|
||||
pub fn as_read(bytes: &[u8]) -> Option<Value> {
|
||||
serde_json::to_value(UiState::from_json(bytes)?).ok()
|
||||
}
|
||||
|
||||
/// The preferences to write: `ours` (this process's, now), with every value it left as it was in
|
||||
/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]).
|
||||
pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value {
|
||||
let fallback = ours.clone();
|
||||
merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback)
|
||||
}
|
||||
|
||||
/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it
|
||||
/// alone and another process removed it).
|
||||
fn merge_setting(path: &mut Vec<String>, base: Option<&Value>, ours: Option<Value>, disk: Option<&Value>) -> Option<Value> {
|
||||
if base == ours.as_ref() {
|
||||
// Unchanged here: whatever the file holds now.
|
||||
return disk.cloned();
|
||||
}
|
||||
let ours = ours?;
|
||||
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
Some(match (rule(&keys), ours, base, disk) {
|
||||
(Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => {
|
||||
Value::Object(merge_group(path, base, ours, disk))
|
||||
}
|
||||
(Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
|
||||
Value::Array(merge_recent(base, ours, disk, cap, same))
|
||||
}
|
||||
(Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
|
||||
Value::Array(merge_entries(base, &ours, disk, key))
|
||||
}
|
||||
(_, ours, ..) => ours,
|
||||
})
|
||||
}
|
||||
|
||||
/// A group of settings, entry by entry: this process's entries in their order, then those only
|
||||
/// the file or `base` has.
|
||||
fn merge_group(path: &mut Vec<String>, base: &Map<String, Value>, mut ours: Map<String, Value>, disk: &Map<String, Value>) -> Map<String, Value> {
|
||||
let mut names: Vec<String> = ours.keys().cloned().collect();
|
||||
let mut seen: HashSet<String> = names.iter().cloned().collect();
|
||||
for k in disk.keys().chain(base.keys()) {
|
||||
if seen.insert(k.clone()) {
|
||||
names.push(k.clone());
|
||||
}
|
||||
}
|
||||
let mut merged = Map::new();
|
||||
for k in names {
|
||||
path.push(k.clone());
|
||||
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
let missing = when_missing(&keys);
|
||||
let base_v = base.get(&k).cloned().or_else(|| missing.clone());
|
||||
let disk_v = disk.get(&k).cloned().or_else(|| missing.clone());
|
||||
let ours_v = ours.remove(&k).or_else(|| missing.clone());
|
||||
let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref());
|
||||
path.pop();
|
||||
// A setting saved only when it isn't its default is left out when it is.
|
||||
if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) {
|
||||
merged.insert(k, v);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// A list entry: its key, and how many entries before it have the same key.
|
||||
type Id = (String, usize);
|
||||
|
||||
/// The entries of `list` told apart by `key`, in order.
|
||||
fn ids(list: &[Value], key: Key) -> Vec<Id> {
|
||||
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||
list.iter()
|
||||
.map(|v| {
|
||||
let k = key(v);
|
||||
let n = seen.entry(k.clone()).or_default();
|
||||
*n += 1;
|
||||
(k, *n - 1)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A list of user entries, entry by entry. An entry either process added is kept, one either
|
||||
/// removed stays removed, and one this process changed takes its version (else the file's). The
|
||||
/// order is this process's if it reordered the entries it loaded, else the file's; an entry only
|
||||
/// the other list has goes after the entry it follows there.
|
||||
fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec<Value> {
|
||||
let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key));
|
||||
let index = |ids: &[Id], list: &[Value]| -> HashMap<Id, Value> { ids.iter().cloned().zip(list.iter().cloned()).collect() };
|
||||
let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk));
|
||||
let value = |id: &Id| -> Option<&Value> {
|
||||
match (b.get(id), o.get(id), d.get(id)) {
|
||||
// Left alone here: the file's, or gone if the other process removed it.
|
||||
(Some(b), Some(o), d) if b == o => d,
|
||||
// Added or changed here.
|
||||
(_, Some(o), _) => Some(o),
|
||||
// Removed here.
|
||||
(Some(_), None, _) => None,
|
||||
// Added there.
|
||||
(None, None, d) => d,
|
||||
}
|
||||
};
|
||||
let common = |ids: &[Id], other: &HashMap<Id, Value>| -> Vec<Id> { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() };
|
||||
let reordered = common(&ours_ids, &b) != common(&base_ids, &o);
|
||||
let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) };
|
||||
let in_first: HashSet<&Id> = first.iter().collect();
|
||||
let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect();
|
||||
// Entries only `second` has, by the kept entry they follow there (`None`: at the start).
|
||||
let mut after: HashMap<Option<&Id>, Vec<&Id>> = HashMap::new();
|
||||
let mut anchor = None;
|
||||
for id in second {
|
||||
if kept.contains(id) {
|
||||
anchor = Some(id);
|
||||
} else if !in_first.contains(id) && value(id).is_some() {
|
||||
after.entry(anchor).or_default().push(id);
|
||||
}
|
||||
}
|
||||
let mut merged = Vec::new();
|
||||
let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned()));
|
||||
emit(after.get(&None).map_or(&[], Vec::as_slice));
|
||||
for id in first.iter().filter(|id| kept.contains(id)) {
|
||||
emit(&[id]);
|
||||
emit(after.get(&Some(id)).map_or(&[], Vec::as_slice));
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving
|
||||
/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at
|
||||
/// most `cap` entries. Entries are told apart by `same`.
|
||||
fn merge_recent(base: &[Value], ours: Vec<Value>, disk: &[Value], cap: usize, same: Same) -> Vec<Value> {
|
||||
let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v));
|
||||
let removed = |v: &Value| has(base, v) && !has(&ours, v);
|
||||
let touched = &ours[..touched_len(base, &ours, same)];
|
||||
let mut merged: Vec<Value> = Vec::new();
|
||||
for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) {
|
||||
if merged.len() == cap {
|
||||
break;
|
||||
}
|
||||
if !has(&merged, &v) {
|
||||
merged.push(v);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// How many of `ours`'s first entries this process added or used again. Each use moves an entry
|
||||
/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the
|
||||
/// longest such tail is untouched, and everything before it (new entries, and entries that moved
|
||||
/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded
|
||||
/// (the first entry used again) can't be told from no use, and merges as none.
|
||||
fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize {
|
||||
let mut end = base.len();
|
||||
for (i, v) in ours.iter().enumerate().rev() {
|
||||
match base[..end].iter().rposition(|b| same(b, v)) {
|
||||
Some(at) => end = at,
|
||||
None => return i + 1,
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_ui_egui::UiState;
|
||||
|
||||
use super::{as_read, merge};
|
||||
|
||||
/// The preferences a process holds after loading a `ui.json` with `settings` (every other
|
||||
/// setting at its default), as it saves them.
|
||||
fn prefs(settings: Value) -> Value {
|
||||
as_read(&serde_json::to_vec(&settings).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// What the next process loads from the merged preferences.
|
||||
fn reloaded(merged: &Value) -> UiState {
|
||||
UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`.
|
||||
fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value {
|
||||
let after_b = merge(loaded, b, loaded);
|
||||
merge(loaded, a, &after_b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_processes_keep_each_others_changes() {
|
||||
// #3773: A and B both start from the same file.
|
||||
let loaded =
|
||||
json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}});
|
||||
// B changes the theme and opens c.docx, then exits first.
|
||||
let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}});
|
||||
// A changes the author name and opens d.docx, then exits.
|
||||
let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}});
|
||||
assert_eq!(
|
||||
b_then_a(&loaded, b, a),
|
||||
json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() {
|
||||
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
|
||||
let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]});
|
||||
assert_eq!(merge(&loaded, loaded.clone(), &disk), disk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_process_wins_a_setting_both_changed() {
|
||||
let loaded = json!({"theme": "light"});
|
||||
assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_changed_and_changed_back_counts_as_untouched() {
|
||||
// Changes are found by comparing with what was loaded: A switched to dark and back.
|
||||
let loaded = json!({"theme": "light"});
|
||||
assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_entry_removed_here_stays_removed() {
|
||||
let loaded = json!({"recent": ["a.docx", "b.docx"]});
|
||||
let ours = json!({"recent": ["b.docx"]});
|
||||
let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]}));
|
||||
// Clear Recent clears what the other process had added too only if it was loaded here.
|
||||
assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_entry_used_again_here_moves_to_the_front() {
|
||||
// Applying a font already in Recently Used Fonts moves it to the front without adding one.
|
||||
let loaded = json!({"recentFonts": ["A", "B"]});
|
||||
assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]}));
|
||||
// Here C was used again, D opened and A removed; the other process used B again and added E.
|
||||
let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]});
|
||||
let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]});
|
||||
let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]}));
|
||||
// Entries this process only kept, in the order it loaded them, don't override the file's order.
|
||||
let loaded = json!({"recentSymbols": ["x", "y", "z"]});
|
||||
let ours = json!({"recentSymbols": ["w", "x", "z"]});
|
||||
let disk = json!({"recentSymbols": ["z", "x", "y"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_fonts_are_one_entry_whatever_their_case() {
|
||||
// Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and
|
||||
// there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten.
|
||||
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]});
|
||||
let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}));
|
||||
// Other lists compare their entries as saved.
|
||||
let loaded = json!({"recent": ["a.docx"]});
|
||||
assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_recent_lists_keep_their_limit() {
|
||||
// Recently Used Fonts keeps ten.
|
||||
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]});
|
||||
let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_recent_entry_in_the_file_is_not_carried_forward() {
|
||||
// A non-string entry makes the whole list read as empty (`options::lenient` falls back per
|
||||
// setting). Merging it in would keep Recent empty in every later session; instead the
|
||||
// list reads as this version reads it, and the next save heals it.
|
||||
let loaded = prefs(json!({"recent": []}));
|
||||
let ours = prefs(json!({"recent": ["x.docx"]}));
|
||||
let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap();
|
||||
let merged = merge(&loaded, ours, &disk);
|
||||
assert_eq!(merged["recent"], json!(["x.docx"]));
|
||||
assert_eq!(loaded_recent(&merged), ["x.docx"]);
|
||||
// Same for recent symbols.
|
||||
let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]}));
|
||||
let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap();
|
||||
assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1);
|
||||
}
|
||||
|
||||
/// The recent documents the next process loads.
|
||||
fn loaded_recent(merged: &Value) -> Vec<String> {
|
||||
reloaded(merged).recent
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_keys_this_version_writes_are_kept() {
|
||||
// A legacy key read once to migrate, and junk, are not written back, even from the file.
|
||||
let loaded = prefs(json!({"theme": "light"}));
|
||||
let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap();
|
||||
let merged = merge(&loaded, loaded.clone(), &disk);
|
||||
for gone in ["dark", "interfaceSize", "junk"] {
|
||||
assert!(merged.get(gone).is_none(), "{gone}");
|
||||
}
|
||||
assert_eq!(merged["theme"], "light");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_another_process_damaged_gives_way_to_ours() {
|
||||
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
|
||||
let ours = json!({"theme": "dark", "recent": ["a.docx"]});
|
||||
// Not preferences at all: everything comes from this process.
|
||||
assert_eq!(as_read(b"\"garbage\""), None);
|
||||
assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours);
|
||||
// A list replaced by something else keeps ours.
|
||||
assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() {
|
||||
let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}}));
|
||||
// B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and
|
||||
// removes `approx.`. Each added entry follows the entry it was added after.
|
||||
let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}}));
|
||||
let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}}));
|
||||
let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect;
|
||||
let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect();
|
||||
assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]);
|
||||
assert_eq!(ac.exceptions, ["fig."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_customisations_merge_key_by_key() {
|
||||
let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}}));
|
||||
// B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and
|
||||
// assigns Mod+Shift+J.
|
||||
let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}}));
|
||||
let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}}));
|
||||
let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard;
|
||||
assert_eq!(keys.assigned.into_iter().collect::<Vec<_>>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]);
|
||||
assert_eq!(keys.removed.into_iter().collect::<Vec<_>>(), ["Mod+B", "Mod+I"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ribbon_changes_from_both_processes_are_kept() {
|
||||
// Both start from the default ribbon. B hides Draw; A adds a custom tab after Home.
|
||||
let loaded = prefs(json!({}));
|
||||
let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}}));
|
||||
let mut a_tabs = default_tabs();
|
||||
a_tabs.insert(1, json!({"name": "Mine", "custom": true}));
|
||||
let a = prefs(json!({"ribbon": {"tabs": a_tabs}}));
|
||||
let mut want = hide(default_tabs(), "Draw");
|
||||
want.insert(1, json!({"name": "Mine", "custom": true}));
|
||||
assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_toolbar_reset_by_one_process_stays_reset() {
|
||||
// B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a
|
||||
// custom tab. The toolbar stays the default.
|
||||
let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}}));
|
||||
let b = prefs(json!({}));
|
||||
let mut a_tabs = default_tabs();
|
||||
a_tabs.push(json!({"name": "Mine", "custom": true}));
|
||||
let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}}));
|
||||
let merged = b_then_a(&loaded, b, a);
|
||||
assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]);
|
||||
let ribbon = loaded_ribbon(&merged);
|
||||
assert_eq!(ribbon.qat, None);
|
||||
assert!(ribbon.tabs.iter().any(|t| t.name == "Mine"));
|
||||
// Two processes customizing the default toolbar: both commands, Save removed by A gone.
|
||||
let loaded = prefs(json!({}));
|
||||
let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}}));
|
||||
let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}}));
|
||||
assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]);
|
||||
}
|
||||
|
||||
/// The default ribbon tabs, as saved once the ribbon is customized.
|
||||
fn default_tabs() -> Vec<Value> {
|
||||
serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `tabs` with the tab `name` hidden.
|
||||
fn hide(mut tabs: Vec<Value>, name: &str) -> Vec<Value> {
|
||||
for t in &mut tabs {
|
||||
if t["name"] == name {
|
||||
t["hidden"] = json!(true);
|
||||
}
|
||||
}
|
||||
tabs
|
||||
}
|
||||
|
||||
/// The ribbon the next process loads.
|
||||
fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout {
|
||||
reloaded(merged).ribbon
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pane_order_changed_by_the_other_process_is_kept() {
|
||||
// `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and
|
||||
// switches to dark.
|
||||
let loaded = prefs(json!({}));
|
||||
let order = json!(["styles", "navigation"]);
|
||||
let b = prefs(json!({"paneOrder": order}));
|
||||
let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"})));
|
||||
assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark")));
|
||||
// B goes back to the default order; A, which loaded B's order and left it, doesn't bring
|
||||
// it back.
|
||||
let loaded = prefs(json!({"paneOrder": order}));
|
||||
let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"})));
|
||||
assert!(merged.get("paneOrder").is_none(), "{merged}");
|
||||
assert_eq!(merged["theme"], "dark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_and_a_pane_place_are_one_setting_each() {
|
||||
// A moved its window and B resized its own: the window is A's, not A's place with B's size.
|
||||
let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}});
|
||||
let loaded = prefs(window(0.0, 800.0));
|
||||
let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0)));
|
||||
assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pens_labels_and_dictionary_words_from_both_processes_are_kept() {
|
||||
let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0});
|
||||
let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]}));
|
||||
// B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a
|
||||
// label of its own. Identical pens stay apart, by their order.
|
||||
let b = prefs(
|
||||
json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}),
|
||||
);
|
||||
let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]}));
|
||||
let merged = b_then_a(&loaded, b, a);
|
||||
let ui = reloaded(&merged);
|
||||
let colors: Vec<String> = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]);
|
||||
assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]);
|
||||
assert_eq!(merged["dictionary"], json!(["foo", "baz"]));
|
||||
}
|
||||
}
|
||||
@@ -89,9 +89,11 @@ pub fn submit() -> Submit {
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
grey_pages: false,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "WordCraft document".into(),
|
||||
options,
|
||||
driver_settings: None,
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let sent = craft_print::submit_cancellable(&bytes, &job, &mut |_, _| {}, &token).map_err(|error| error.to_string());
|
||||
|
||||
@@ -15,6 +15,8 @@ use serde::{Deserialize, Serialize};
|
||||
const FLAG: &str = "--wordcraft-print-worker";
|
||||
const PREFIX: &str = "WORDCRAFT_PRINT:";
|
||||
const MAX_MESSAGE: u64 = 64 * 1024;
|
||||
/// The job's options, and a driver's settings of up to 1 MiB written as hex.
|
||||
const MAX_REQUEST: u64 = MAX_MESSAGE + 2 * 1024 * 1024;
|
||||
const MAX_PDF: u64 = 512 * 1024 * 1024;
|
||||
const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer";
|
||||
|
||||
@@ -32,9 +34,12 @@ struct Request {
|
||||
collate: bool,
|
||||
duplex: Option<Duplex>,
|
||||
grayscale: bool,
|
||||
grey_pages: bool,
|
||||
shrink: bool,
|
||||
title: String,
|
||||
options: Vec<(String, String)>,
|
||||
/// The printer the driver's settings were chosen for, and their DEVMODE as hex.
|
||||
driver_settings: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -50,15 +55,21 @@ impl Request {
|
||||
craft_print::Duplex::ShortEdge => Duplex::ShortEdge,
|
||||
}),
|
||||
grayscale: job.grayscale,
|
||||
grey_pages: job.grey_pages,
|
||||
shrink: job.scaling == craft_print::Scaling::ShrinkToFit,
|
||||
title: job.title.clone(),
|
||||
options: job.options.clone(),
|
||||
driver_settings: job.driver_settings.as_ref().map(|settings| (settings.printer().to_owned(), settings.dev_mode().to_hex())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the job without substituting printer defaults or changing copy semantics.
|
||||
fn job(self) -> craft_print::Job {
|
||||
craft_print::Job {
|
||||
fn job(self) -> Result<craft_print::Job, String> {
|
||||
let driver_settings = match self.driver_settings {
|
||||
Some((printer, hex)) => Some(craft_print::DriverSettings::new(printer, craft_print::rgb::DevMode::from_hex(&hex).map_err(error)?)),
|
||||
None => None,
|
||||
};
|
||||
Ok(craft_print::Job {
|
||||
printer: self.printer,
|
||||
copies: self.copies,
|
||||
collate: self.collate,
|
||||
@@ -68,10 +79,12 @@ impl Request {
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
}),
|
||||
grayscale: self.grayscale,
|
||||
grey_pages: self.grey_pages,
|
||||
scaling: if self.shrink { craft_print::Scaling::ShrinkToFit } else { craft_print::Scaling::Exact },
|
||||
title: self.title,
|
||||
options: self.options,
|
||||
}
|
||||
driver_settings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +179,7 @@ impl Submission {
|
||||
return Err("the print PDF exceeds the 512 MiB helper limit".into());
|
||||
}
|
||||
let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?;
|
||||
if request.len() as u64 > MAX_MESSAGE {
|
||||
if request.len() as u64 > MAX_REQUEST {
|
||||
return Err("the print settings exceed the helper message limit".into());
|
||||
}
|
||||
let directory = tempfile::tempdir().map_err(error)?;
|
||||
@@ -323,10 +336,10 @@ fn helper(
|
||||
})
|
||||
.map_err(error)?;
|
||||
let request: Request =
|
||||
serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_MESSAGE)?).map_err(error)?;
|
||||
serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_REQUEST)?).map_err(error)?;
|
||||
let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?;
|
||||
remove_inputs(directory)?;
|
||||
let result = submit(&pdf, &request.job(), &cancel);
|
||||
let result = submit(&pdf, &request.job()?, &cancel);
|
||||
emit(&Event::Done(result))
|
||||
}
|
||||
|
||||
@@ -463,21 +476,40 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Job transport preserves every explicit setting, including Unicode and duplex direction.
|
||||
/// Job transport preserves every explicit setting, including Unicode, duplex direction and the
|
||||
/// driver's own settings.
|
||||
fn job_options_survive_the_process_boundary() {
|
||||
// A DEVMODEW header of 156 bytes (`dmSize` at 68) and a 4-byte private part (`dmDriverExtra` at 70).
|
||||
let mut dev_mode = vec![0u8; 160];
|
||||
dev_mode[68..70].copy_from_slice(&156u16.to_le_bytes());
|
||||
dev_mode[70..72].copy_from_slice(&4u16.to_le_bytes());
|
||||
dev_mode[156..].copy_from_slice(&[1, 2, 3, 4]);
|
||||
let dev_mode = craft_print::rgb::DevMode::from_bytes(dev_mode).unwrap();
|
||||
let expected = craft_print::Job {
|
||||
printer: Some("Office λ".into()),
|
||||
copies: 3,
|
||||
collate: false,
|
||||
duplex: Some(craft_print::Duplex::ShortEdge),
|
||||
grayscale: true,
|
||||
grey_pages: true,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "A document".into(),
|
||||
options: vec![("media".into(), "iso_a4_210x297mm".into())],
|
||||
driver_settings: Some(craft_print::DriverSettings::new("Office λ", dev_mode)),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&Request::from_job(&expected)).unwrap();
|
||||
let received: Request = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(received.job(), expected);
|
||||
assert_eq!(received.job(), Ok(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Damaged driver settings on the wire are an error, not a job printed with other settings.
|
||||
fn damaged_driver_settings_are_refused() {
|
||||
for hex in ["", "0", "zz", "00"] {
|
||||
let mut request = Request::from_job(&job());
|
||||
request.driver_settings = Some(("Office".into(), hex.into()));
|
||||
assert!(request.job().is_err(), "{hex:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+259
-5
@@ -11,6 +11,8 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::Rgb;
|
||||
|
||||
/// Most series in a chart.
|
||||
pub const MAX_SERIES: usize = 255;
|
||||
/// Most categories (points per series) in a chart.
|
||||
@@ -123,17 +125,119 @@ impl LegendPos {
|
||||
}
|
||||
}
|
||||
|
||||
/// One series: its name and a value per category (`None` = no value, a gap).
|
||||
/// One series: its name, a value per category (`None` = no value, a gap) and how it is drawn:
|
||||
/// fill, line, markers, smooth lines, its own data labels and number format. Unset fields follow
|
||||
/// the chart's defaults.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartSeries {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub values: Vec<Option<f64>>,
|
||||
/// Fill color; `None`: the chart's accent color for the series.
|
||||
#[serde(default)]
|
||||
pub fill: Option<Rgb>,
|
||||
/// "None" fill: the series draws no fill.
|
||||
#[serde(default)]
|
||||
pub no_fill: bool,
|
||||
/// Line width in points; `None`: the chart's default.
|
||||
#[serde(default)]
|
||||
pub line_w: Option<f32>,
|
||||
/// "None" line: the series draws no line.
|
||||
#[serde(default)]
|
||||
pub no_line: bool,
|
||||
/// Markers on points; `None`: unset (scatter charts draw them; a saved scatter series then has
|
||||
/// no `c:marker`).
|
||||
#[serde(default)]
|
||||
pub markers: Option<bool>,
|
||||
/// Draw the line as a smooth curve.
|
||||
#[serde(default)]
|
||||
pub smooth: bool,
|
||||
/// Data labels for this series; `None`: follow the chart's setting.
|
||||
#[serde(default)]
|
||||
pub labels: Option<bool>,
|
||||
/// Number format of this series's labels and values; `None`: linked to the source.
|
||||
#[serde(default)]
|
||||
pub fmt: Option<String>,
|
||||
}
|
||||
|
||||
impl ChartSeries {
|
||||
/// A new series of a `kind` chart: a scatter series is drawn as markers without a line.
|
||||
pub fn new(kind: ChartType, name: String, values: Vec<Option<f64>>) -> ChartSeries {
|
||||
ChartSeries { name, values, no_line: kind == ChartType::Scatter, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One chart axis: title, scale bounds, tick-label number format, gridlines, tick labels and the
|
||||
/// axis line.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartAxis {
|
||||
/// `None`: no axis title; text cut to [`MAX_TEXT`] characters.
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
/// Fixed lower bound; `None`: automatic.
|
||||
#[serde(default)]
|
||||
pub min: Option<f64>,
|
||||
/// Fixed upper bound; `None`: automatic.
|
||||
#[serde(default)]
|
||||
pub max: Option<f64>,
|
||||
/// Tick-label number format (`#,##0`, `0.00`, `0%`…); `None`: linked to the source data.
|
||||
#[serde(default)]
|
||||
pub fmt: Option<String>,
|
||||
/// Major gridlines drawn along this axis.
|
||||
#[serde(default)]
|
||||
pub gridlines: bool,
|
||||
/// Tick labels; `false` hides them.
|
||||
#[serde(default = "the_true")]
|
||||
pub labels: bool,
|
||||
/// The axis line.
|
||||
#[serde(default = "the_true")]
|
||||
pub line: bool,
|
||||
}
|
||||
|
||||
fn the_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for ChartAxis {
|
||||
fn default() -> Self {
|
||||
ChartAxis { title: None, min: None, max: None, fmt: None, gridlines: false, labels: true, line: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The value axis as a new chart has it: gridlines, labels, no axis line.
|
||||
pub fn value_axis() -> ChartAxis {
|
||||
ChartAxis { gridlines: true, line: false, ..ChartAxis::default() }
|
||||
}
|
||||
|
||||
impl ChartAxis {
|
||||
/// Make the axis safe to store: texts cleaned, bounds finite, `min` under `max` (an
|
||||
/// impossible pair drops both), the format code cut to [`MAX_FMT`] characters.
|
||||
pub fn sanitize(&mut self) {
|
||||
self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty());
|
||||
self.min = self.min.filter(|v| v.is_finite());
|
||||
self.max = self.max.filter(|v| v.is_finite());
|
||||
if matches!((self.min, self.max), (Some(lo), Some(hi)) if lo >= hi) {
|
||||
self.min = None;
|
||||
self.max = None;
|
||||
}
|
||||
self.fmt = self.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest axis number format kept, characters.
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters.
|
||||
pub fn clean_fmt(s: &str) -> String {
|
||||
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
|
||||
}
|
||||
|
||||
/// A chart WordCraft can edit.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartSpec {
|
||||
#[serde(rename = "type")]
|
||||
@@ -151,6 +255,78 @@ pub struct ChartSpec {
|
||||
/// Show each point's value next to it.
|
||||
#[serde(default)]
|
||||
pub data_labels: bool,
|
||||
/// The category axis (scatter charts: the x axis).
|
||||
#[serde(default)]
|
||||
pub cat_axis: ChartAxis,
|
||||
/// The value axis (scatter charts: the y axis); gridlines on and no axis line in a new chart.
|
||||
#[serde(default = "value_axis")]
|
||||
pub val_axis: ChartAxis,
|
||||
}
|
||||
|
||||
/// A [`ChartSpec`] as stored. A scatter series saved without `noLine` (by a version without
|
||||
/// series formatting) is drawn as markers without a line, as that version drew it.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StoredSpec {
|
||||
#[serde(rename = "type")]
|
||||
kind: ChartType,
|
||||
#[serde(default)]
|
||||
categories: Vec<String>,
|
||||
#[serde(default)]
|
||||
series: Vec<StoredSeries>,
|
||||
#[serde(default)]
|
||||
title: Option<String>,
|
||||
#[serde(default)]
|
||||
legend: Option<LegendPos>,
|
||||
#[serde(default)]
|
||||
data_labels: bool,
|
||||
#[serde(default)]
|
||||
cat_axis: ChartAxis,
|
||||
#[serde(default = "value_axis")]
|
||||
val_axis: ChartAxis,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StoredSeries {
|
||||
#[serde(default)]
|
||||
no_line: Option<bool>,
|
||||
#[serde(flatten)]
|
||||
series: ChartSeries,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ChartSpec {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let s = StoredSpec::deserialize(deserializer)?;
|
||||
let scatter = s.kind == ChartType::Scatter;
|
||||
Ok(ChartSpec {
|
||||
kind: s.kind,
|
||||
categories: s.categories,
|
||||
series: s.series.into_iter().map(|x| ChartSeries { no_line: x.no_line.unwrap_or(scatter), ..x.series }).collect(),
|
||||
title: s.title,
|
||||
legend: s.legend,
|
||||
data_labels: s.data_labels,
|
||||
cat_axis: s.cat_axis,
|
||||
val_axis: s.val_axis,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ChartSpec {
|
||||
/// An empty chart whose value axis is the one a new chart (and a missing JSON field) has:
|
||||
/// gridlines on, no axis line.
|
||||
fn default() -> Self {
|
||||
ChartSpec {
|
||||
kind: ChartType::default(),
|
||||
categories: Vec::new(),
|
||||
series: Vec::new(),
|
||||
title: None,
|
||||
legend: None,
|
||||
data_labels: false,
|
||||
cat_axis: ChartAxis::default(),
|
||||
val_axis: value_axis(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChartSpec {
|
||||
@@ -168,10 +344,14 @@ impl ChartSpec {
|
||||
ChartSpec {
|
||||
kind,
|
||||
categories: categories.into_iter().map(str::to_string).collect(),
|
||||
series: series.into_iter().map(|(n, v)| ChartSeries { name: n.to_string(), values: v.into_iter().map(Some).collect() }).collect(),
|
||||
series: series.into_iter().map(|(n, v)| ChartSeries::new(kind, n.to_string(), v.into_iter().map(Some).collect())).collect(),
|
||||
title: None,
|
||||
legend: Some(LegendPos::Bottom),
|
||||
data_labels: false,
|
||||
cat_axis: ChartAxis::default(),
|
||||
// Pie and doughnut charts have no axes: their axes stay plain, so the chart reads back
|
||||
// as the same model.
|
||||
val_axis: if kind.is_round() { ChartAxis::default() } else { value_axis() },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,8 +383,12 @@ impl ChartSpec {
|
||||
*v = v.filter(|x| x.is_finite());
|
||||
}
|
||||
s.values.resize(n, None);
|
||||
s.fmt = s.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty());
|
||||
s.line_w = s.line_w.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 20.0));
|
||||
}
|
||||
self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty());
|
||||
self.cat_axis.sanitize();
|
||||
self.val_axis.sanitize();
|
||||
}
|
||||
|
||||
/// The chart after `sanitize`.
|
||||
@@ -229,7 +413,11 @@ mod tests {
|
||||
let mut c = ChartSpec {
|
||||
categories: vec!["a".into(); MAX_POINTS + 10],
|
||||
series: (0..MAX_SERIES + 5)
|
||||
.map(|i| ChartSeries { name: format!("{}\n{}", "x".repeat(400), i), values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)] })
|
||||
.map(|i| ChartSeries {
|
||||
name: format!("{}\n{}", "x".repeat(400), i),
|
||||
values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)],
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
title: Some(" ".into()),
|
||||
..Default::default()
|
||||
@@ -250,7 +438,7 @@ mod tests {
|
||||
fn short_categories_are_padded_to_the_longest_series() {
|
||||
let c = ChartSpec {
|
||||
categories: vec!["a".into()],
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)] }],
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)], ..Default::default() }],
|
||||
..Default::default()
|
||||
}
|
||||
.sanitized();
|
||||
@@ -258,4 +446,70 @@ mod tests {
|
||||
assert_eq!(ChartType::from_id("BARSTACKED"), Some(ChartType::BarStacked));
|
||||
assert_eq!(LegendPos::from_id("top"), Some(LegendPos::Top));
|
||||
}
|
||||
|
||||
/// A scatter series stored without `noLine` reads as markers without a line; a stored value
|
||||
/// and the other chart types keep theirs.
|
||||
#[test]
|
||||
fn stored_scatter_series_without_a_line_setting_draw_no_line() {
|
||||
let read = |json: &str| -> Vec<bool> { serde_json::from_str::<ChartSpec>(json).unwrap().series.iter().map(|s| s.no_line).collect() };
|
||||
let series = r#"[{"name":"a","values":[1,null,2.5]},{"name":"b","values":[3],"noLine":false}]"#;
|
||||
assert_eq!(read(&format!(r#"{{"type":"scatter","series":{series}}}"#)), [true, false]);
|
||||
assert_eq!(read(&format!(r#"{{"type":"line","series":{series}}}"#)), [false, false]);
|
||||
let c: ChartSpec = serde_json::from_str(&format!(r#"{{"type":"scatter","series":{series}}}"#)).unwrap();
|
||||
assert_eq!(c.series[0].values, [Some(1.0), None, Some(2.5)]);
|
||||
// What this version writes reads back as itself.
|
||||
for kind in ChartType::ALL {
|
||||
let spec = ChartSpec::sample(kind);
|
||||
assert_eq!(serde_json::from_str::<ChartSpec>(&serde_json::to_string(&spec).unwrap()).unwrap(), spec, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_and_missing_json_axis_fields_agree() {
|
||||
let from_json: ChartSpec = serde_json::from_str(r#"{"type":"column"}"#).unwrap();
|
||||
let d = ChartSpec::default();
|
||||
assert_eq!((d.cat_axis.clone(), d.val_axis.clone()), (from_json.cat_axis, from_json.val_axis));
|
||||
assert!(d.val_axis.gridlines && !d.val_axis.line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_bounds_and_formats_are_cleaned() {
|
||||
let mut a = ChartAxis {
|
||||
title: Some(" Sales\n".into()),
|
||||
min: Some(f64::NAN),
|
||||
max: Some(50.0),
|
||||
fmt: Some("x".repeat(MAX_FMT + 40)),
|
||||
gridlines: true,
|
||||
labels: false,
|
||||
line: true,
|
||||
};
|
||||
a.sanitize();
|
||||
assert_eq!(a.title.as_deref(), Some("Sales"));
|
||||
assert_eq!(a.min, None);
|
||||
assert_eq!(a.max, Some(50.0));
|
||||
assert_eq!(a.fmt.as_deref().map(|f| f.chars().count()), Some(MAX_FMT));
|
||||
|
||||
// min not under max drops the pair; a format of only spaces is no format.
|
||||
let mut b = ChartAxis { min: Some(50.0), max: Some(50.0), fmt: Some(" ".into()), ..Default::default() };
|
||||
b.sanitize();
|
||||
assert_eq!((b.min, b.max), (None, None));
|
||||
assert_eq!(b.fmt, None);
|
||||
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], ..Default::default() }],
|
||||
categories: vec!["a".into()],
|
||||
..Default::default()
|
||||
};
|
||||
spec.series[0].line_w = Some(f32::NAN);
|
||||
spec.series[0].fmt = Some("0.00".into());
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, None);
|
||||
assert_eq!(spec.series[0].fmt.as_deref(), Some("0.00"));
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![], line_w: Some(100.0), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,8 +270,11 @@ impl ShapeExtra {
|
||||
/// The largest rounded-rectangle corner: half the shorter side, which makes its ends round.
|
||||
pub const MAX_CORNER: u32 = 50_000;
|
||||
|
||||
/// A rounded rectangle's corner radius without its own: 16% of the shorter side.
|
||||
pub const DEFAULT_CORNER: f32 = 0.16;
|
||||
/// A rounded rectangle's corner radius without its own: a sixth of the shorter side, the preset's
|
||||
/// default `adj` of 16667 (ECMA-376 §20.1.10.56). Measured in Word for Windows: a 300 × 100 pt
|
||||
/// rounded rectangle without `adj` is drawn with corners of 16.67 pt, a 300 × 40 pt one of 6.67
|
||||
/// pt and a 60 × 150 pt one of 10 pt.
|
||||
pub const DEFAULT_CORNER: f32 = 16_667.0 / 100_000.0;
|
||||
|
||||
/// The corner radius, in points, of a `w` × `h` rounded rectangle with `corner` (see
|
||||
/// [`ShapeExtra::corner`]).
|
||||
@@ -521,7 +524,10 @@ mod tests {
|
||||
#[test]
|
||||
fn corner_radius_follows_the_shorter_side() {
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-4;
|
||||
assert!(near(corner_radius(None, 200.0, 100.0), 16.0));
|
||||
assert!(near(corner_radius(None, 200.0, 100.0), 16.667));
|
||||
assert!(near(corner_radius(None, 300.0, 40.0), 6.6668));
|
||||
assert!(near(corner_radius(None, 60.0, 150.0), 10.0002));
|
||||
assert!(near(corner_radius(None, 200.0, 100.0), corner_radius(Some(16_667), 200.0, 100.0)), "the preset's default");
|
||||
assert!(near(corner_radius(Some(0), 200.0, 100.0), 0.0));
|
||||
assert!(near(corner_radius(Some(3_565), 100.0, 200.0), 3.565));
|
||||
assert!(near(corner_radius(Some(MAX_CORNER), 200.0, 100.0), 50.0));
|
||||
|
||||
+16
-1
@@ -727,9 +727,16 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Split the paragraph at `pos`; returns the start of the new (second) paragraph.
|
||||
///
|
||||
/// A split after the first letters leaves the drop cap on the first paragraph only: the new
|
||||
/// one is plain (Word: Enter makes a normal paragraph). A split at offset 0 is unchanged.
|
||||
/// A drop cap that comes from a paragraph style, not the paragraph, is not cleared.
|
||||
pub fn split_paragraph(&mut self, pos: &Pos) -> Result<Pos> {
|
||||
let i = pos.path.last();
|
||||
let tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?;
|
||||
let mut tail = self.para_mut(pos.story, &pos.path)?.split_off(pos.off)?;
|
||||
if pos.off > 0 {
|
||||
clear_drop_cap(&mut tail.props);
|
||||
}
|
||||
let bl = self.container_mut(pos.story, &pos.path)?;
|
||||
bl.insert((i + 1).min(bl.len()), para_block(tail));
|
||||
Ok(Pos { story: pos.story, path: pos.path.with_last(i + 1), off: 0 })
|
||||
@@ -1599,5 +1606,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the drop cap (and its options) off a paragraph's properties.
|
||||
fn clear_drop_cap(props: &mut crate::props::ParaProps) {
|
||||
props.drop_cap = None;
|
||||
props.drop_cap_margin = None;
|
||||
props.drop_cap_distance = None;
|
||||
props.drop_cap_font = None;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -988,3 +988,38 @@ fn insert_fragment_remaps_conflicting_media_keys() {
|
||||
let remapped = para.objects.iter().find_map(|o| if let InlineObject::Image { media, .. } = o { Some(media.as_str()) } else { None }).unwrap();
|
||||
assert_eq!(remapped, other_key);
|
||||
}
|
||||
|
||||
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
|
||||
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
|
||||
#[test]
|
||||
fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
|
||||
let drop_cap = |d: &Document, i: usize| {
|
||||
let p = d.body.get(i).and_then(|b| b.as_para()).map(|p| p.props.clone()).unwrap_or_default();
|
||||
(p.drop_cap, p.drop_cap_margin, p.drop_cap_distance, p.drop_cap_font)
|
||||
};
|
||||
let capped = |text: &str| {
|
||||
let mut d = doc(&[text]);
|
||||
if let Ok(p) = d.para_mut(StoryRef::Body, &Path::top(0)) {
|
||||
p.props.drop_cap = Some(3);
|
||||
p.props.drop_cap_margin = Some(true);
|
||||
p.props.drop_cap_distance = Some(4.0);
|
||||
p.props.drop_cap_font = Some("Serif".into());
|
||||
}
|
||||
d
|
||||
};
|
||||
let cap = (Some(3), Some(true), Some(4.0), Some("Serif".to_string()));
|
||||
let plain = (None, None, None, None);
|
||||
|
||||
let mut d = capped("Sugar and knowledge");
|
||||
d.split_paragraph(&Pos::body(0, 10)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone()));
|
||||
|
||||
let mut d = capped("Sugar");
|
||||
d.split_paragraph(&Pos::body(0, 5)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), plain.clone()));
|
||||
|
||||
// At offset 0 nothing changes: both paragraphs keep the properties, as before.
|
||||
let mut d = capped("Sugar");
|
||||
d.split_paragraph(&Pos::body(0, 0)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
|
||||
}
|
||||
|
||||
@@ -127,6 +127,10 @@ pub enum GraphicItem {
|
||||
align: TextAlign,
|
||||
#[serde(default)]
|
||||
font: Option<String>,
|
||||
/// Degrees clockwise the text turns about `rect`'s center as it is drawn (a chart's vertical
|
||||
/// axis title is turned -90°).
|
||||
#[serde(default)]
|
||||
angle: f32,
|
||||
},
|
||||
/// A picture (`Document::media` key) stretched into `rect`.
|
||||
Image { rect: [f32; 4], media: String },
|
||||
|
||||
@@ -94,8 +94,8 @@ pub use settings::{
|
||||
COMPAT_MODE_CURRENT, CoreProps, CustomProp, DEFAULT_GRID, DEFAULT_HYPHENATION_ZONE, LEGACY_COMPAT_MODE, OdfLayout, PagePicture, Settings, Source,
|
||||
THEME_COLORS, Watermark, Zoom, ZoomFit,
|
||||
};
|
||||
pub(crate) use text_walk::{PARA_WALK_DEPTH, walk_between};
|
||||
pub use text_walk::{count_chars, count_chars_no_spaces, count_words};
|
||||
pub(crate) use text_walk::walk_between;
|
||||
pub use text_walk::{PARA_WALK_DEPTH, count_chars, count_chars_no_spaces, count_words};
|
||||
|
||||
/// A document.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -610,11 +610,12 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
|
||||
}
|
||||
MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => {
|
||||
s.push(*chr);
|
||||
if !sub_hide && !sub.is_empty() {
|
||||
// A shown limit is written even when empty (`_()`): left out, it reads back hidden (#6076).
|
||||
if !sub_hide {
|
||||
s.push('_');
|
||||
lin_script(sub, s, depth);
|
||||
}
|
||||
if !sup_hide && !sup.is_empty() {
|
||||
if !sup_hide {
|
||||
s.push('^');
|
||||
lin_script(sup, s, depth);
|
||||
}
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct Settings {
|
||||
pub default_tab: f32,
|
||||
pub even_odd_headers: bool,
|
||||
pub mirror_margins: bool,
|
||||
/// The gutter is added to the top margin instead of the left one (`w:gutterAtTop`).
|
||||
pub gutter_at_top: bool,
|
||||
pub auto_hyphenation: bool,
|
||||
/// Hyphenation zone (`w:hyphenationZone`), points: a line is hyphenated only when breaking
|
||||
/// it at a word boundary would leave more than this empty at its end.
|
||||
@@ -137,6 +139,12 @@ pub struct Settings {
|
||||
/// Keep contextual paragraph spacing inside legacy table cells (`allowSpaceOfSameStyleInTable`).
|
||||
/// Word ignores the layout override in compatibility mode 15, but the flag still round-trips.
|
||||
pub allow_space_of_same_style_in_table: bool,
|
||||
/// `w:doNotSuppressIndentation` (a `.doc`'s `Copts.fWW11IndentRules`): Word 2003's indent
|
||||
/// rules beside floating objects. An unnumbered paragraph's line starts right after a floating
|
||||
/// object before it on the line, its own indent ignored (ECMA-376 Part 4 §14.8.3.12). Word 2013's
|
||||
/// layout (compatibility mode 15) does not use it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub do_not_suppress_indentation: bool,
|
||||
/// Drawing grid spacing in points, across and down (View › Gridlines); ECMA-376's default is 1/8 inch.
|
||||
pub grid_h: f32,
|
||||
pub grid_v: f32,
|
||||
@@ -296,6 +304,7 @@ impl Default for Settings {
|
||||
default_tab: 36.0,
|
||||
even_odd_headers: false,
|
||||
mirror_margins: false,
|
||||
gutter_at_top: false,
|
||||
auto_hyphenation: false,
|
||||
hyphenation_zone: DEFAULT_HYPHENATION_ZONE,
|
||||
hyphenate_caps: true,
|
||||
@@ -319,6 +328,7 @@ impl Default for Settings {
|
||||
sum_paragraph_spacing: false,
|
||||
do_not_expand_shift_return: false,
|
||||
allow_space_of_same_style_in_table: false,
|
||||
do_not_suppress_indentation: false,
|
||||
grid_h: DEFAULT_GRID,
|
||||
grid_v: DEFAULT_GRID,
|
||||
math: None,
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn count_chars_no_spaces(s: &str) -> usize {
|
||||
}
|
||||
|
||||
/// How deep in nested tables [`Document::para_paths`] goes: cells below this are skipped.
|
||||
pub(crate) const PARA_WALK_DEPTH: usize = 16;
|
||||
pub const PARA_WALK_DEPTH: usize = 16;
|
||||
|
||||
/// The note and text box stories an object shows, for `Document::reachable`.
|
||||
pub(crate) fn notes_and_boxes(o: &InlineObject) -> Vec<(u32, &'static [PartKind])> {
|
||||
|
||||
@@ -265,10 +265,10 @@ mod tests {
|
||||
}
|
||||
assert!(shape_outline(ShapeKind::Rectangle, 10.0, 10.0, None).is_none());
|
||||
// The end of the bottom-right corner: in the frame's corner when the corner is square,
|
||||
// 16% of the height (8 of 100 wide) in from it by default.
|
||||
// a sixth of the height (8.33 of 100 wide) in from it by default.
|
||||
let corner_pt = |corner| shape_outline(ShapeKind::RoundedRectangle, 100.0, 50.0, corner).unwrap()[6];
|
||||
assert!(corner_pt(Some(0)).0 > 0.999 && corner_pt(Some(0)).1 > 0.999, "{:?}", corner_pt(Some(0)));
|
||||
assert!((corner_pt(None).0 - 0.92).abs() < 0.001, "{:?}", corner_pt(None));
|
||||
assert!((corner_pt(None).0 - 0.916_67).abs() < 0.0001, "{:?}", corner_pt(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//! An n-ary operator's empty but shown limit survives linear text (#6076): half-typed `∑_` has an
|
||||
//! empty lower limit that is shown, and `to_linear` writes it as `_()`. Left out, it reads back as a
|
||||
//! hidden limit.
|
||||
|
||||
use wordcraft_doc::math::{MNode, MRun, parse_linear, to_linear};
|
||||
|
||||
#[test]
|
||||
fn an_empty_shown_limit_prints_back_the_same() {
|
||||
for s in ["∑_", "∑^", "∫_0^▒x", "∑_()^n▒i"] {
|
||||
let n = parse_linear(s);
|
||||
assert_eq!(parse_linear(&to_linear(&n)), n, "{s} → {}", to_linear(&n));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_filled_limits_print_as_before() {
|
||||
let nary = |sub_hide, sup_hide, sub: &str, sup: &str| {
|
||||
let arg = |t: &str| if t.is_empty() { Vec::new() } else { vec![MNode::Run(MRun::new(t))] };
|
||||
vec![MNode::Nary { chr: '∑', lim_loc: None, grow: false, sub_hide, sup_hide, sub: arg(sub), sup: arg(sup), e: arg("x") }]
|
||||
};
|
||||
assert_eq!(to_linear(&nary(true, true, "", "")), "∑▒x");
|
||||
assert_eq!(to_linear(&nary(false, false, "i", "n")), "∑_i^n▒x");
|
||||
assert_eq!(to_linear(&nary(false, true, "", "")), "∑_()▒x");
|
||||
}
|
||||
@@ -94,6 +94,15 @@ fn object_value_from_shared(
|
||||
};
|
||||
Ok(Target::Graphic { w, h, alt, float: convert(float)?, graphic })
|
||||
}
|
||||
// This model has no picture frame shape: DrawingML's `frame` preset is read as a
|
||||
// rectangle, without the frame's border width.
|
||||
mut shape @ Source::Shape { kind: craft_wordmodel::para::ShapeKind::Frame, .. } => {
|
||||
if let Source::Shape { kind, extra, .. } = &mut shape {
|
||||
*kind = craft_wordmodel::para::ShapeKind::Rectangle;
|
||||
extra.corner = None;
|
||||
}
|
||||
convert(shape)
|
||||
}
|
||||
Source::Group { w, h, float, ch_w, ch_h, children, canvas } => Ok(Target::Group {
|
||||
w,
|
||||
h,
|
||||
@@ -442,6 +451,110 @@ pub fn to_shared_model(source: &wordcraft_doc::Document) -> Result<craft_wordmod
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn doc_with(objects: Vec<craft_wordmodel::para::InlineObject>) -> craft_wordmodel::Document {
|
||||
let mut source = craft_wordmodel::Document::new();
|
||||
let mut para = craft_wordmodel::para::Paragraph::new();
|
||||
para.objects = objects;
|
||||
source.body = vec![Arc::new(craft_wordmodel::Block::Para(para))];
|
||||
source
|
||||
}
|
||||
|
||||
fn objects(doc: &wordcraft_doc::Document) -> Vec<wordcraft_doc::para::InlineObject> {
|
||||
doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn chart_object(spec: craft_wordmodel::chart::ChartSpec) -> craft_wordmodel::para::InlineObject {
|
||||
let graphic = craft_wordmodel::graphic::Graphic { chart: Some(Arc::new(spec)), ..Default::default() };
|
||||
craft_wordmodel::para::InlineObject::Graphic { w: 100.0, h: 60.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }
|
||||
}
|
||||
|
||||
fn charts(doc: &wordcraft_doc::Document) -> Vec<Option<wordcraft_doc::chart::ChartSpec>> {
|
||||
objects(doc)
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
wordcraft_doc::para::InlineObject::Graphic { graphic, .. } => Some(graphic.chart.as_deref().cloned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A picture frame shape opens as a rectangle instead of failing the whole document.
|
||||
#[test]
|
||||
fn a_frame_shape_reads_as_a_rectangle() {
|
||||
let shape = |kind| craft_wordmodel::para::InlineObject::Shape {
|
||||
kind,
|
||||
w: 40.0,
|
||||
h: 30.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: Default::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: craft_wordmodel::connector::ShapeExtra { corner: Some(2604), ..Default::default() },
|
||||
};
|
||||
let doc = from_shared_model(doc_with(vec![shape(craft_wordmodel::para::ShapeKind::Frame)])).expect("from_shared_model");
|
||||
let found = objects(&doc);
|
||||
let [wordcraft_doc::para::InlineObject::Shape { kind, w, extra, .. }] = found.as_slice() else { panic!("{found:?}") };
|
||||
assert_eq!((*kind, *w, extra.corner), (wordcraft_doc::para::ShapeKind::Rectangle, 40.0, None));
|
||||
}
|
||||
|
||||
/// A chart's series formatting and axis settings survive the trip through this model, so
|
||||
/// saving writes the chart part the reader read.
|
||||
#[test]
|
||||
fn chart_formatting_survives_the_bridge() {
|
||||
use craft_wordmodel::chart::{ChartSpec, ChartType};
|
||||
let mut formatted = ChartSpec::sample(ChartType::Line);
|
||||
formatted.series[0].fill = Some(craft_wordmodel::props::Rgb(0x12, 0x34, 0x56));
|
||||
formatted.series[0].line_w = Some(2.5);
|
||||
formatted.series[1].smooth = true;
|
||||
formatted.series[1].markers = Some(true);
|
||||
formatted.series[2].labels = Some(true);
|
||||
formatted.series[2].fmt = Some("0.0".into());
|
||||
formatted.val_axis.title = Some("Sales".into());
|
||||
formatted.val_axis.min = Some(0.0);
|
||||
formatted.cat_axis.gridlines = true;
|
||||
let mut scatter_lines = ChartSpec::sample(ChartType::Scatter);
|
||||
scatter_lines.series[0].no_line = false;
|
||||
let all = [formatted, ChartSpec::sample(ChartType::Scatter), ChartSpec::sample(ChartType::Pie), scatter_lines];
|
||||
let doc = from_shared_model(doc_with(all.iter().cloned().map(chart_object).collect())).expect("from_shared_model");
|
||||
assert!(charts(&doc).iter().all(Option::is_some));
|
||||
let back = to_shared_model(&doc).expect("to_shared_model");
|
||||
let back: Vec<ChartSpec> = back
|
||||
.body
|
||||
.first()
|
||||
.and_then(|b| b.as_para())
|
||||
.map(|p| {
|
||||
p.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
craft_wordmodel::para::InlineObject::Graphic { graphic, .. } => graphic.chart.as_deref().cloned(),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
assert_eq!(back, all);
|
||||
}
|
||||
|
||||
/// A scatter chart this model makes is written as markers without lines, the same part the
|
||||
/// shared model writes for its own new scatter chart.
|
||||
#[test]
|
||||
fn a_new_scatter_chart_is_written_without_lines() {
|
||||
let local = wordcraft_doc::chart::ChartSpec::sample(wordcraft_doc::chart::ChartType::Scatter);
|
||||
assert!(!local.series.is_empty() && local.series.iter().all(|s| s.no_line));
|
||||
assert_eq!(
|
||||
crate::chart_xml(&local),
|
||||
craft_docx::chart_xml(&craft_wordmodel::chart::ChartSpec::sample(craft_wordmodel::chart::ChartType::Scatter)).into_bytes()
|
||||
);
|
||||
for kind in wordcraft_doc::chart::ChartType::ALL {
|
||||
let local = wordcraft_doc::chart::ChartSpec::sample(kind);
|
||||
let shared: craft_wordmodel::chart::ChartSpec = convert_ref(&local).expect("convert");
|
||||
assert_eq!(shared, craft_wordmodel::chart::ChartSpec::sample(shared.kind), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridges_nested_stories_and_moves_media_both_directions() {
|
||||
let mut source = craft_wordmodel::Document::new();
|
||||
|
||||
@@ -217,6 +217,8 @@ const PINNED_PARTS: &[&str] = &[
|
||||
"word/styles.xml",
|
||||
"word/settings.xml",
|
||||
"word/theme/theme1.xml",
|
||||
// The fonts the document uses, with their families: it brings no font table of its own.
|
||||
"word/fontTable.xml",
|
||||
"docProps/core.xml",
|
||||
"docProps/app.xml",
|
||||
];
|
||||
|
||||
@@ -989,7 +989,8 @@ fn toc_field_skips_nested_stories() {
|
||||
let mut zip = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let xml = String::from_utf8(zip.read("word/document.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
let boxes: Vec<(usize, usize)> = xml.match_indices("<w:txbxContent>").map(|(a, _)| (a, a + xml[a..].find("</w:txbxContent>").unwrap())).collect();
|
||||
assert_eq!(boxes.len(), 2, "{xml}");
|
||||
// Each text box is written twice: in the drawing and in its VML fallback.
|
||||
assert_eq!(boxes.len(), 4, "{xml}");
|
||||
let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i));
|
||||
for kind in ["begin", "separate", "end"] {
|
||||
let at: Vec<usize> = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect();
|
||||
@@ -997,7 +998,7 @@ fn toc_field_skips_nested_stories() {
|
||||
assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}");
|
||||
}
|
||||
let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap());
|
||||
assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
|
||||
assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1567,6 +1568,29 @@ fn attached_template_and_link_styles_round_trip() {
|
||||
assert!(!plain.settings.link_styles);
|
||||
}
|
||||
|
||||
/// Gutter position Top (`w:gutterAtTop`) is kept when a document is opened and saved again, and
|
||||
/// is not written when it is off.
|
||||
#[test]
|
||||
fn gutter_at_top_survives_open_and_save() {
|
||||
let settings_xml = |bytes: &[u8]| {
|
||||
let mut zip = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
String::from_utf8(zip.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let mut d = Document::new();
|
||||
d.settings.gutter_at_top = true;
|
||||
let first = wordcraft_docx::write(&d).expect("write");
|
||||
assert_eq!(settings_xml(&first).matches("<w:gutterAtTop/>").count(), 1);
|
||||
|
||||
let opened = wordcraft_docx::read(&first).expect("read");
|
||||
assert!(opened.settings.gutter_at_top);
|
||||
let saved = wordcraft_docx::write(&opened).expect("write again");
|
||||
assert_eq!(settings_xml(&saved).matches("<w:gutterAtTop/>").count(), 1);
|
||||
assert!(wordcraft_docx::read(&saved).expect("read again").settings.gutter_at_top);
|
||||
|
||||
let plain = wordcraft_docx::write(&Document::new()).expect("write plain");
|
||||
assert!(!settings_xml(&plain).contains("gutterAtTop"));
|
||||
}
|
||||
|
||||
/// #995: the zoom a document was saved at (`w:zoom`), One Page (`fullPage`) included, is read
|
||||
/// and written back.
|
||||
#[test]
|
||||
@@ -1922,8 +1946,21 @@ fn flat_opc_round_trip_equals_docx() {
|
||||
assert!(text.starts_with("<?xml") && text.contains("<?mso-application progid=\"Word.Document\"?>"));
|
||||
assert!(text.contains("pkg:name=\"/word/document.xml\"") && text.contains("<pkg:binaryData>"));
|
||||
assert_eq!(wordcraft_docx::sniff_xml(&xml), wordcraft_docx::XmlKind::FlatOpc);
|
||||
let back = wordcraft_docx::read_xml(&xml).expect("read flat");
|
||||
assert_eq!(back, rt(&d));
|
||||
let mut back = wordcraft_docx::read_xml(&xml).expect("read flat");
|
||||
// `pkg:xmlData` inlines a part without its XML declaration, so a kept XML part (the font
|
||||
// table) comes back without one; the markup is the same.
|
||||
let mut want = rt(&d);
|
||||
for doc in [&mut back, &mut want] {
|
||||
for v in doc.passthrough.values_mut() {
|
||||
if let Some(rest) =
|
||||
v.strip_prefix(b"<?xml").and_then(|r| r.iter().position(|&b| b == b'>').map(|e| r[e + 1..].trim_ascii_start().to_vec()))
|
||||
{
|
||||
*v = Arc::new(rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(back.passthrough.contains_key("word/fontTable.xml"));
|
||||
assert_eq!(back, want);
|
||||
assert_eq!(back.media.len(), 1);
|
||||
}
|
||||
|
||||
@@ -2398,6 +2435,10 @@ fn bibliography_sources_round_trip() {
|
||||
|
||||
assert_bibliography_parts(&bytes);
|
||||
assert_bibliography_sources_round_trip(&bytes);
|
||||
// Saved again after reading, the store keeps one relationship, from the main part.
|
||||
let again = wordcraft_docx::write(&wordcraft_docx::read(&bytes).expect("read")).expect("write again");
|
||||
assert_bibliography_parts(&again);
|
||||
assert_eq!(wordcraft_docx::read(&again).expect("read again").sources.len(), d.sources.len());
|
||||
}
|
||||
|
||||
/// #4848: a corporate author saves as Word's `b:Corporate`, in place of a name list (a role holds
|
||||
@@ -2438,9 +2479,12 @@ fn assert_bibliography_parts(bytes: &[u8]) {
|
||||
assert!(zip.contains("customXml/itemProps1.xml"));
|
||||
assert!(zip.contains("customXml/_rels/item1.xml.rels"));
|
||||
|
||||
let rels_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(rels_xml.contains("relationships/customXml"), "{rels_xml}");
|
||||
assert!(rels_xml.contains("Target=\"customXml/item1.xml\""), "{rels_xml}");
|
||||
// The sources' data store is related from the main part's relationships only.
|
||||
let rels_xml = String::from_utf8(zip.read("word/_rels/document.xml.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(rels_xml.matches("relationships/customXml\"").count(), 1, "{rels_xml}");
|
||||
assert!(rels_xml.contains("Target=\"../customXml/item1.xml\""), "{rels_xml}");
|
||||
let root_xml = String::from_utf8(zip.read("_rels/.rels", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(!root_xml.contains("relationships/customXml\""), "{root_xml}");
|
||||
|
||||
let ct_xml = String::from_utf8(zip.read("[Content_Types].xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(ct_xml.contains("PartName=\"/customXml/item1.xml\""), "{ct_xml}");
|
||||
|
||||
@@ -30,10 +30,16 @@ fn page_number_type_is_kept_even_when_it_only_repeats_the_defaults() {
|
||||
|
||||
#[test]
|
||||
fn page_number_type_with_a_start_and_format_still_round_trips() {
|
||||
let body = r#"<w:p><w:r><w:t>One</w:t></w:r></w:p><w:sectPr><w:pgNumType w:fmt="upperRoman" w:start="3"/></w:sectPr>"#;
|
||||
let d = wordcraft_docx::read(&docx(body)).unwrap();
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains(r#"w:fmt="upperRoman""#) && xml.contains(r#"w:start="3""#), "{xml}");
|
||||
for (format, start) in [("decimal", 0), ("upperRoman", 3)] {
|
||||
let page_number_type = format!(r#"<w:pgNumType w:fmt="{format}" w:start="{start}"/>"#);
|
||||
let body = format!(r#"<w:p><w:r><w:t>One</w:t></w:r></w:p><w:sectPr>{page_number_type}</w:sectPr>"#);
|
||||
let d = wordcraft_docx::read(&docx(&body)).unwrap();
|
||||
assert_eq!(d.last_section.page_num_start, Some(start));
|
||||
let saved = wordcraft_docx::write(&d).unwrap();
|
||||
let xml = document_xml(&saved);
|
||||
assert!(xml.contains(&page_number_type), "{xml}");
|
||||
assert_eq!(wordcraft_docx::read(&saved).unwrap().last_section.page_num_start, Some(start));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -261,5 +261,7 @@ fn story_shared_by_many_shapes_is_written_once() {
|
||||
}
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.len() < 2_000_000, "document.xml is {} bytes", xml.len());
|
||||
assert_eq!(xml.matches(text.as_str()).count(), 1);
|
||||
// The story is written for the first shape only: in its drawing and in that drawing's VML
|
||||
// fallback. The other shapes do not repeat it.
|
||||
assert_eq!(xml.matches(text.as_str()).count(), 2);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ workspace = true
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -58,6 +59,7 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-doc = { workspace = true, features = ["test-support"] }
|
||||
wordcraft-formats = { workspace = true, features = ["test-support"] }
|
||||
encoding_rs = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
cfb = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Typing timing: opens a document, types at the middle of it, and prints the layout time of
|
||||
//! each keystroke (the pagination every edit pays for).
|
||||
//!
|
||||
//! `cargo run --release -p wordcraft-engine --example typing_bench -- doc.docx [keys]`
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
fn main() -> Result<(), String> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let path = args.first().ok_or("usage: typing_bench doc.docx [keys]")?;
|
||||
let keys: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(40);
|
||||
let mut s = Session::new(wordcraft_engine::doc::Document::new());
|
||||
s.run("file.open", &json!({"path": path})).map_err(|e| e.to_string())?;
|
||||
let first = s.layout().ms;
|
||||
let mid = s.doc.body.len() / 2;
|
||||
let block = (mid..s.doc.body.len()).chain((0..mid).rev()).find(|&i| s.doc.body.get(i).and_then(|b| b.as_para()).is_some()).unwrap_or(mid);
|
||||
s.run("caret.set", &json!({"pos": {"story": "body", "path": [block], "off": 0}})).map_err(|e| e.to_string())?;
|
||||
let mut ms = Vec::with_capacity(keys);
|
||||
for _ in 0..keys {
|
||||
s.run("text.insert", &json!({"text": "a"})).map_err(|e| e.to_string())?;
|
||||
ms.push(s.layout().ms);
|
||||
}
|
||||
ms.sort_by(f64::total_cmp);
|
||||
let med = ms.get(ms.len() / 2).copied().unwrap_or(0.0);
|
||||
println!(
|
||||
"blocks {}, first layout {first:.1} ms, per key: median {med:.1} ms, min {:.1} ms",
|
||||
s.doc.body.len(),
|
||||
ms.first().copied().unwrap_or(0.0)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.when(has_canvas)
|
||||
.pure(),
|
||||
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
|
||||
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
|
||||
.params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#)
|
||||
.when(has_canvas),
|
||||
]
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult {
|
||||
result(&o)
|
||||
}
|
||||
|
||||
/// `canvas.member`: move, resize or remove one member; with no change, list the members.
|
||||
/// `canvas.member`: move, resize or remove one member; without index, list the members.
|
||||
fn member(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let pos = canvas_pos(s)?;
|
||||
let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else {
|
||||
|
||||
@@ -68,6 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Escape")
|
||||
.params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#)
|
||||
.pure(),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::chart::{ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES};
|
||||
use wordcraft_doc::chart::{ChartAxis, ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES, value_axis};
|
||||
use wordcraft_doc::graphic::{Graphic, GraphicKind};
|
||||
use wordcraft_doc::para::{Float, InlineObject};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
@@ -33,6 +33,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("chart.type", "Change Chart Type", "Chart Design › Type", |s, v| {
|
||||
let kind = chart_type(v)?.ok_or_else(|| CmdError::Params(format!("`type` is required: {TYPES}")))?;
|
||||
edit(s, |c| {
|
||||
// A scatter series is drawn as markers without a line; the other types draw it.
|
||||
if (c.kind == ChartType::Scatter) != (kind == ChartType::Scatter) {
|
||||
for series in &mut c.series {
|
||||
series.no_line = kind == ChartType::Scatter;
|
||||
if series.no_line && series.markers == Some(false) {
|
||||
series.markers = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pie and doughnut charts have a plain value axis and the other types a new
|
||||
// chart's value axis; an axis left as the old type had it takes the new type's.
|
||||
if c.kind.is_round() != kind.is_round() {
|
||||
let (from, to) = if kind.is_round() { (value_axis(), ChartAxis::default()) } else { (ChartAxis::default(), value_axis()) };
|
||||
if c.val_axis == from {
|
||||
c.val_axis = to;
|
||||
}
|
||||
}
|
||||
c.kind = kind;
|
||||
Ok(())
|
||||
})
|
||||
@@ -52,7 +69,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c.categories = cats.clone();
|
||||
}
|
||||
if let Some(series) = &series {
|
||||
c.series = series.clone();
|
||||
// Each series keeps the formatting of the one it replaces.
|
||||
c.series = series
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, values))| match c.series.get(i) {
|
||||
Some(old) => ChartSeries { name: name.clone(), values: values.clone(), ..old.clone() },
|
||||
None => ChartSeries::new(c.kind, name.clone(), values.clone()),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
@@ -99,6 +124,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let on = p::bool(v, "on").or_else(|| p::bool(v, "value"));
|
||||
edit(s, move |c| {
|
||||
c.data_labels = on.unwrap_or(!c.data_labels);
|
||||
// The chart's setting replaces each series' own.
|
||||
for series in &mut c.series {
|
||||
series.labels = None;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
@@ -152,7 +181,14 @@ fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let mut spec = ChartSpec::sample(kind);
|
||||
if let Some(d) = v.get("data") {
|
||||
spec.categories = d.get("categories").map(categories).transpose()?.unwrap_or_default();
|
||||
spec.series = d.get("series").map(series_list).transpose()?.unwrap_or_default();
|
||||
spec.series = d
|
||||
.get("series")
|
||||
.map(series_list)
|
||||
.transpose()?
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(name, values)| ChartSeries::new(kind, name, values))
|
||||
.collect();
|
||||
if spec.series.is_empty() {
|
||||
return Err(CmdError::Params(format!("`data.series` needs at least one series: {DATA}")));
|
||||
}
|
||||
@@ -220,8 +256,8 @@ fn cell_text(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Series from JSON: `[{"name", "values": [number|null|numeric string]}]`.
|
||||
fn series_list(v: &Value) -> Result<Vec<ChartSeries>, CmdError> {
|
||||
/// Series names and values from JSON: `[{"name", "values": [number|null|numeric string]}]`.
|
||||
fn series_list(v: &Value) -> Result<Vec<(String, Vec<Option<f64>>)>, CmdError> {
|
||||
let a = v.as_array().ok_or_else(|| CmdError::Params(format!("`series`: {DATA}")))?;
|
||||
a.iter()
|
||||
.take(MAX_SERIES)
|
||||
@@ -232,7 +268,7 @@ fn series_list(v: &Value) -> Result<Vec<ChartSeries>, CmdError> {
|
||||
None | Some(Value::Null) => Vec::new(),
|
||||
Some(_) => return Err(CmdError::Params("`values`: an array of numbers (null for none)".into())),
|
||||
};
|
||||
Ok(ChartSeries { name, values })
|
||||
Ok((name, values))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ mod sources;
|
||||
mod styles;
|
||||
|
||||
use cross_refs::cross_ref;
|
||||
pub(crate) use cross_refs::leading_breaks;
|
||||
pub use cross_refs::{caption_labels, ref_targets};
|
||||
#[cfg(test)]
|
||||
use generated::ENTRY_STYLE;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::generated::page_of;
|
||||
use super::{CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p};
|
||||
use crate::cmd::references::page_label;
|
||||
|
||||
pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let to = p::str(v, "to").unwrap_or("heading");
|
||||
@@ -10,9 +10,10 @@ pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let find = |ts: Vec<(String, Pos)>| ts.into_iter().find(|(t, _)| t == target || t.starts_with(target));
|
||||
let (text, pos) = find(targets).ok_or_else(|| CmdError::Params(format!("no {to} `{target}`")))?;
|
||||
let show = p::str(v, "show").unwrap_or("text");
|
||||
let page = page_of(s, &pos);
|
||||
let result = match show {
|
||||
"page" => page.to_string(),
|
||||
// The page the target's text starts on (after its leading page breaks), as its footer
|
||||
// shows it.
|
||||
"page" => page_label(s, &Pos { off: leading_breaks(&s.doc, &pos), ..pos.clone() }),
|
||||
"number" => text.split(':').next().unwrap_or(&text).trim().to_string(),
|
||||
"aboveBelow" => {
|
||||
if pos < s.sel.focus {
|
||||
@@ -152,6 +153,23 @@ pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> {
|
||||
targets
|
||||
}
|
||||
|
||||
/// The offset just past the page breaks at the start of the paragraph at `pos`, skipping bookmark
|
||||
/// marks among them (a `_Ref` bookmark may start before the breaks): its text starts there.
|
||||
pub(crate) fn leading_breaks(doc: &Document, pos: &Pos) -> usize {
|
||||
let Some(p) = doc.para(pos.story, &pos.path) else { return 0 };
|
||||
let mut after = 0;
|
||||
for (i, c) in p.text.char_indices() {
|
||||
if c == '\u{0C}' {
|
||||
after = i.saturating_add(c.len_utf8());
|
||||
} else if c != wordcraft_doc::para::OBJ
|
||||
|| !matches!(p.object_at(i), Some(InlineObject::BookmarkStart { .. } | InlineObject::BookmarkEnd { .. }))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
/// The hidden `_Ref` bookmark around the target paragraph at `pos` (its label and number only
|
||||
/// when `number_only`), reusing one already there. Returns its name and `at` moved past the
|
||||
/// bookmark marks inserted before it.
|
||||
@@ -159,16 +177,22 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R
|
||||
const MARK: usize = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let para = s.doc.para(pos.story, &pos.path).ok_or_else(|| CmdError::Params("cross-reference target is gone".into()))?;
|
||||
let end = if number_only { para.text.find(':').unwrap_or(para.len()) } else { para.len() };
|
||||
if let Some(InlineObject::BookmarkStart { name }) = para.object_at(0)
|
||||
&& name.starts_with("_Ref")
|
||||
{
|
||||
// Reuse it when it covers the same extent: up to the colon, or the whole paragraph.
|
||||
let same = para.object_offsets().into_iter().any(|o| {
|
||||
matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name)
|
||||
&& para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() })
|
||||
});
|
||||
if same {
|
||||
return Ok((name.clone(), at));
|
||||
// The bookmark starts after the leading page breaks, so `PAGEREF` reads the page the text is on.
|
||||
let start = leading_breaks(&s.doc, pos).min(end);
|
||||
// Reuse one that starts there or at the paragraph's start (before the breaks): the field's
|
||||
// result still reads the page the text is on.
|
||||
for from in [start, 0] {
|
||||
if let Some(InlineObject::BookmarkStart { name }) = para.object_at(from)
|
||||
&& name.starts_with("_Ref")
|
||||
{
|
||||
// Reuse it when it covers the same extent: up to the colon, or the whole paragraph.
|
||||
let same = para.object_offsets().into_iter().any(|o| {
|
||||
matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name)
|
||||
&& para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() })
|
||||
});
|
||||
if same {
|
||||
return Ok((name.clone(), at));
|
||||
}
|
||||
}
|
||||
}
|
||||
let next =
|
||||
@@ -176,11 +200,11 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R
|
||||
let name = format!("_Ref{next:09}");
|
||||
let props = CharProps::default();
|
||||
s.doc.insert_object(&Pos { off: end, ..pos.clone() }, InlineObject::BookmarkEnd { name: name.clone() }, &props)?;
|
||||
s.doc.insert_object(&Pos { off: 0, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?;
|
||||
s.doc.insert_object(&Pos { off: start, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?;
|
||||
if at.story == pos.story && at.path == pos.path {
|
||||
if at.off >= end {
|
||||
at.off = at.off.saturating_add(2 * MARK);
|
||||
} else if at.off > 0 {
|
||||
} else if at.off > start {
|
||||
at.off = at.off.saturating_add(MARK);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ use super::{
|
||||
Block, CharProps, CmdError, CmdResult, Document, FieldCode, InlineObject, Paragraph, Path, Pos, Session, SortKey, StoryRef, TabAlign, TabLeader,
|
||||
TabStop, Value, delete_selection, heading_letter, p, sel_result, sort_key,
|
||||
};
|
||||
use crate::cmd::references::{page_at, page_formats, page_text};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
/// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "<label>"` lists the
|
||||
/// captions that label's SEQ field numbers, `\a "<label>"` lists them without their label and
|
||||
@@ -331,9 +333,11 @@ fn add_entry_style(s: &mut Session) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn page_of(s: &mut Session, pos: &Pos) -> u32 {
|
||||
/// The page holding `pos`: its index in the layout (to order and deduplicate by) and its number
|
||||
/// in its section's format (`ii`), as the list writes it. Page "1" (index 0) when no page holds it.
|
||||
fn page_of(s: &mut Session, formats: &[NumFormat], pos: &Pos) -> (usize, String) {
|
||||
let l = s.layout();
|
||||
l.caret(pos).and_then(|c| l.pages.get(c.page)).map(|p| p.number).unwrap_or(1)
|
||||
page_at(&l, formats, pos).map_or_else(|| (0, "1".into()), |(i, n, fmt)| (i, page_text(n, fmt)))
|
||||
}
|
||||
|
||||
/// Entry lines (text, hanging indent) for a generated list.
|
||||
@@ -370,7 +374,7 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut with_pages: Vec<(String, u32)> = marks.into_iter().map(|(e, _)| (e, 0)).collect();
|
||||
let mut with_pages: Vec<(String, (usize, String))> = marks.into_iter().map(|(e, _)| (e, (0, String::new()))).collect();
|
||||
// Pages (layout once).
|
||||
let positions: Vec<Pos> = {
|
||||
let mut v = Vec::new();
|
||||
@@ -393,8 +397,9 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
}
|
||||
v
|
||||
};
|
||||
let formats = page_formats(s);
|
||||
for (i, pos) in positions.iter().enumerate() {
|
||||
let pg = page_of(s, pos);
|
||||
let pg = page_of(s, &formats, pos);
|
||||
if let Some(x) = with_pages.get_mut(i) {
|
||||
x.1 = pg;
|
||||
}
|
||||
@@ -403,14 +408,15 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
// `\n` without page numbers; `\p` the separator before them (a tab by default).
|
||||
let f = FieldCode::parse(kind);
|
||||
let sep = f.arg('p').unwrap_or("\t");
|
||||
return with_pages.into_iter().map(|(t, p)| (if f.has('n') { t } else { format!("{t}{sep}{p}") }, false)).collect();
|
||||
return with_pages.into_iter().map(|(t, p)| (if f.has('n') { t } else { format!("{t}{sep}{}", p.1) }, false)).collect();
|
||||
}
|
||||
// Index / TOA: group by entry, sort, list pages.
|
||||
let lang = crate::cmd::default_lang(s);
|
||||
let mut grouped: std::collections::BTreeMap<(SortKey, String), Vec<u32>> = Default::default();
|
||||
// Each page once, in page order (by its place in the layout, not its label: `ii` before `1`).
|
||||
let mut grouped: std::collections::BTreeMap<(SortKey, String), Vec<(usize, String)>> = Default::default();
|
||||
for (e, p) in with_pages {
|
||||
let pages = grouped.entry((sort_key(&e, lang.as_deref()), e)).or_default();
|
||||
if !pages.contains(&p) {
|
||||
if !pages.iter().any(|(i, _)| *i == p.0) {
|
||||
pages.push(p);
|
||||
}
|
||||
}
|
||||
@@ -424,7 +430,7 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
out.push((l, false));
|
||||
}
|
||||
}
|
||||
let list = pages.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let list = pages.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>().join(", ");
|
||||
out.push(if kind.starts_with("INDEX") { (format!("{e}, {list}"), true) } else { (format!("{e}\t{list}"), false) });
|
||||
}
|
||||
out
|
||||
|
||||
@@ -488,6 +488,32 @@ fn table_of_authorities_updates() {
|
||||
assert!(after.matches("Doe v. Roe").count() > t.matches("Doe v. Roe").count(), "{after}");
|
||||
}
|
||||
|
||||
/// #3856: the table of figures and the table of authorities write each page as its footer shows
|
||||
/// it, in the section's number format; the authority cited on pages i and ii lists both.
|
||||
#[test]
|
||||
fn figures_and_authorities_follow_the_page_number_format() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Smith v. Jones held it.\nSmith v. Jones again."));
|
||||
s.run("select.text", &json!({"text": "Smith v. Jones again"})).unwrap();
|
||||
s.run("caret.home", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "page"})).unwrap();
|
||||
s.run("references.caption", &json!({"label": "Figure", "text": "The court"})).unwrap();
|
||||
for occurrence in [1, 2] {
|
||||
s.run("select.text", &json!({"text": "Smith v. Jones", "occurrence": occurrence})).unwrap();
|
||||
s.run("references.markCitation", &json!({})).unwrap();
|
||||
}
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 1})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("references.tableOfFigures", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("references.tableOfAuthorities", &json!({})).unwrap();
|
||||
let t = s.doc.plain_text(StoryRef::Body);
|
||||
assert!(t.contains("Figure 1: The court\tii"), "{t}");
|
||||
assert!(t.contains("Smith v. Jones\ti, ii"), "{t}");
|
||||
}
|
||||
|
||||
/// Field instructions and results in the body, in order.
|
||||
fn fields(s: &Session) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
@@ -900,3 +926,42 @@ fn citation_refresh_source_lookup_work_scales_with_document_size() {
|
||||
let p = big.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert!(p.objects.iter().enumerate().all(|(i, o)| matches!(o, InlineObject::Field { result, .. } if result == &format!("[{}]", i + 1))));
|
||||
}
|
||||
|
||||
/// A heading that starts with a page break and has a `_Ref` bookmark from before the break: the
|
||||
/// page cross-reference reuses it and reads the heading's page, and still does after Update Field.
|
||||
#[test]
|
||||
fn a_ref_bookmark_before_a_page_break_reads_the_heading_page() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface"));
|
||||
s.run("select.text", &json!({"text": "Preface"})).unwrap();
|
||||
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.run("caret.home", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "page"})).unwrap();
|
||||
let path =
|
||||
s.doc.para_paths(StoryRef::Body).into_iter().find(|p| s.doc.para(StoryRef::Body, p).is_some_and(|p| p.text.contains("Preface"))).unwrap();
|
||||
let len = s.doc.para(StoryRef::Body, &path).unwrap().len();
|
||||
let props = CharProps::default();
|
||||
s.doc
|
||||
.insert_object(
|
||||
&Pos { story: StoryRef::Body, path: path.clone(), off: len },
|
||||
InlineObject::BookmarkEnd { name: "_Ref000000003".into() },
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
s.doc.insert_object(&Pos { story: StoryRef::Body, path, off: 0 }, InlineObject::BookmarkStart { name: "_Ref000000003".into() }, &props).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.crossReference", &json!({"to": "heading", "target": "Preface", "show": "page"})).unwrap();
|
||||
let pageref = |s: &Session| {
|
||||
s.doc
|
||||
.para_paths(StoryRef::Body)
|
||||
.into_iter()
|
||||
.flat_map(|p| s.doc.para(StoryRef::Body, &p).map(|p| p.objects.clone()).unwrap_or_default())
|
||||
.find_map(|o| match o {
|
||||
InlineObject::Field { instr, result, .. } if instr.starts_with("PAGEREF") => Some((instr, result)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(pageref(&s), ("PAGEREF _Ref000000003 \\h".to_string(), "2".to_string()));
|
||||
crate::cmd::references::update_fields_in(&mut s, true).unwrap();
|
||||
assert_eq!(pageref(&s).1, "2");
|
||||
}
|
||||
|
||||
@@ -63,7 +63,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?;
|
||||
set_accent(s, t.3[0]);
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"name": string (see design.themes)}"#),
|
||||
CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set)
|
||||
.params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#),
|
||||
CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing)
|
||||
|
||||
@@ -141,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp"))
|
||||
.params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#),
|
||||
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(
|
||||
r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#,
|
||||
),
|
||||
// Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening
|
||||
// it changes nothing, so it is its own command and never marks the document edited.
|
||||
CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| {
|
||||
@@ -172,7 +174,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("edit.formatPainter", "Format Painter", "Home › Clipboard", painter).params(r#"{"sticky"?: bool}"#).pure(),
|
||||
CommandSpec::new("edit.copyFormat", "Copy Formatting", "Home › Clipboard", |s, _| {
|
||||
painter_pick(s);
|
||||
// One format buffer, as in Word: Copy Formatting replaces an armed Format Painter.
|
||||
s.painter = None;
|
||||
s.copied_format = Some(picked_format(s));
|
||||
sel_result(s)
|
||||
})
|
||||
.key(copy_format_shortcut(cfg!(target_arch = "wasm32")))
|
||||
@@ -744,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let story = s.sel.focus.story;
|
||||
let results = search_full(s, story, true)?;
|
||||
let (a, b) = s.sel.ordered();
|
||||
// Replace the current match if selected, then move to the next.
|
||||
// Replace the current match if selected, then move to the next. The result says which
|
||||
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
|
||||
let mut replaced = 0;
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
|
||||
super::paste_text(s, &f.rep.unwrap_or_default())?;
|
||||
replaced = 1;
|
||||
}
|
||||
let _ = step(s, 1);
|
||||
Ok(json!({"remaining": search(s, story)?.len()}))
|
||||
let selected = match step(s, 1) {
|
||||
Ok(_) => {
|
||||
let (start, end) = s.sel.ordered();
|
||||
json!({"start": pos_json(&start), "end": pos_json(&end)})
|
||||
}
|
||||
Err(_) => Value::Null,
|
||||
};
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
@@ -832,11 +845,21 @@ fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
/// The character and paragraph formatting at the start of the selection.
|
||||
fn picked_format(s: &Session) -> (wordcraft_doc::props::CharProps, wordcraft_doc::props::ParaProps) {
|
||||
let f = s.sel.ordered().0;
|
||||
// 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();
|
||||
// Formatting only: not the source's hyperlink or revision marks (#5616).
|
||||
let chr = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone().without_symbol().formatting()).unwrap_or_default();
|
||||
let para = s.doc.para_at(&f).map(|p| p.props.clone().formatting()).unwrap_or_default();
|
||||
(chr, para)
|
||||
}
|
||||
|
||||
fn painter_pick(s: &mut Session) {
|
||||
let (chr, para) = picked_format(s);
|
||||
// One format buffer, as in Word: the pick is also what the next Paste Formatting applies,
|
||||
// and stays after the brush is used up or cancelled.
|
||||
s.copied_format = Some((chr.clone(), para.clone()));
|
||||
s.painter = Some((chr, para, false));
|
||||
}
|
||||
|
||||
@@ -852,9 +875,14 @@ fn painter(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"active": true}))
|
||||
}
|
||||
|
||||
/// Apply the format painter's formatting to the selection.
|
||||
/// Apply the format painter's formatting to the selection, or else what Copy Formatting picked
|
||||
/// up (which stays for the next Paste Formatting).
|
||||
fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let Some((chr, para, sticky)) = s.painter.clone() else { return Err(CmdError::Failed("no formatting copied".into())) };
|
||||
let (chr, para, sticky) = match (s.painter.clone(), s.copied_format.clone()) {
|
||||
(Some(brush), _) => brush,
|
||||
(None, Some((chr, para))) => (chr, para, true),
|
||||
(None, None) => return Err(CmdError::Failed("no formatting copied".into())),
|
||||
};
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b {
|
||||
// No selection: apply paragraph formatting (and word formatting like Word).
|
||||
@@ -864,15 +892,11 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
// Word selection includes trailing spaces; a painter click formats just the word,
|
||||
// matching the ordinary collapsed-caret formatting target.
|
||||
let word_end = pp.text.get(x..y).map(|word| x + word.trim_end().len()).unwrap_or(y);
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = chr.cleared().overlaid(&chr))?;
|
||||
s.doc.format_range(&Pos { off: x, ..f.clone() }, &Pos { off: word_end, ..f.clone() }, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
}
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
} else {
|
||||
s.doc.format_range(&a, &b, &|c| {
|
||||
let link = c.link.clone();
|
||||
*c = c.cleared().overlaid(&chr);
|
||||
c.link = link;
|
||||
})?;
|
||||
s.doc.format_range(&a, &b, &|c| *c = c.cleared().overlaid(&chr))?;
|
||||
if a.path != b.path || a.off == 0 {
|
||||
s.doc.format_paragraphs(&a, &b, &|p| *p = para.clone())?;
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> {
|
||||
fn set_code(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let code = p::req_str(v, "code")?.trim().to_string();
|
||||
if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) {
|
||||
return Err(CmdError::Params("bad field code".into()));
|
||||
return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into()));
|
||||
}
|
||||
let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) };
|
||||
with_field(s, &f.at, |o| match o {
|
||||
@@ -441,7 +441,10 @@ mod tests {
|
||||
s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap();
|
||||
let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default();
|
||||
assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report"));
|
||||
assert!(s.run("fields.setCode", &json!({"code": ""})).is_err());
|
||||
assert!(matches!(
|
||||
s.run("fields.setCode", &json!({"code": ""})),
|
||||
Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers"
|
||||
));
|
||||
|
||||
// A locked field keeps its result.
|
||||
s.run("fields.lock", &json!({})).unwrap();
|
||||
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(),
|
||||
CommandSpec::new("file.open", "Open", "File", open)
|
||||
.key("Mod+O / Mod+F12 / Mod+Alt+F2")
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#)
|
||||
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
|
||||
// to undo; it marks the document as changed itself.
|
||||
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
|
||||
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
|
||||
// No path (the command search, say): the app asks where to save, as File › Export
|
||||
@@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()}))
|
||||
}
|
||||
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved
|
||||
/// with from now on, or none.
|
||||
/// File › Info › Protect Document › Encrypt with Password: the password Word packages and
|
||||
/// OpenDocument text files (.odt, .ott) are saved with from now on, or none.
|
||||
fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let password = match v.get("password") {
|
||||
Some(Value::Null) => None,
|
||||
|
||||
@@ -198,9 +198,14 @@ fn special(query: &str, o: &Opts) -> (String, bool) {
|
||||
if (o.ignore_punct && is_punct(c)) || (o.ignore_space && is_space(c)) {
|
||||
continue;
|
||||
}
|
||||
// A keyboard apostrophe also finds text produced by smart quotes. Explicit character
|
||||
// codes above, and literal/regex/wildcard searches, keep exact character matching.
|
||||
atoms.push(if c == '\'' { "['‘’]".into() } else { lit(c) });
|
||||
// A keyboard apostrophe or double quote also finds text produced by smart quotes.
|
||||
// Explicit character codes above, and literal/regex/wildcard searches, keep exact
|
||||
// character matching.
|
||||
atoms.push(match c {
|
||||
'\'' => "['‘’]".into(),
|
||||
'"' => "[\"“”]".into(),
|
||||
_ => lit(c),
|
||||
});
|
||||
}
|
||||
let filler = match (o.ignore_punct, o.ignore_space) {
|
||||
(true, true) => r"[\p{P} \t\x{A0}]*",
|
||||
|
||||
@@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let Some(n) = v.get(k) else { return Ok(None) };
|
||||
let n = n.as_str().map(str::trim).unwrap_or("");
|
||||
if n.is_empty() || n.len() > 128 {
|
||||
return Err(CmdError::Params(format!("bad font name `{k}`")));
|
||||
return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes")));
|
||||
}
|
||||
Ok(Some(n.to_string()))
|
||||
};
|
||||
|
||||
@@ -10,7 +10,7 @@ use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
use wordcraft_doc::{Block, Paragraph, Path, Pos, StoryRef};
|
||||
|
||||
use super::references::{FieldCode, field_arg, leader};
|
||||
use super::references::{FieldCode, field_arg, leader, page_at, page_formats, page_text};
|
||||
use super::sel_result;
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
|
||||
@@ -162,6 +162,9 @@ fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// One page reference of an entry.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct PageRef {
|
||||
/// The page's index in the layout (the first page of a range): pages are told apart by it,
|
||||
/// not by their labels, which repeat across sections.
|
||||
at: usize,
|
||||
page: String,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
@@ -190,8 +193,10 @@ fn collect(s: &mut Session, lang: Option<&str>) -> BTreeMap<Vec<SortKey>, Node>
|
||||
}
|
||||
}
|
||||
}
|
||||
let formats = page_formats(s);
|
||||
let l = s.layout();
|
||||
let page = |pos: &Pos| l.caret(pos).and_then(|c| l.pages.get(c.page)).map(|p| p.number).unwrap_or(1);
|
||||
// A page's index in the layout and its number as its footer shows it (`ii`).
|
||||
let page = |pos: &Pos| page_at(&l, &formats, pos).map_or_else(|| (0, "1".to_string()), |(i, n, fmt)| (i, page_text(n, fmt)));
|
||||
let bookmark_end = |name: &str| {
|
||||
s.doc.para_paths(StoryRef::Body).into_iter().find_map(|path| {
|
||||
let p = s.doc.para(StoryRef::Body, &path)?;
|
||||
@@ -222,11 +227,12 @@ fn collect(s: &mut Session, lang: Option<&str>) -> BTreeMap<Vec<SortKey>, Node>
|
||||
}
|
||||
let range = f.arg('r').and_then(|bm| {
|
||||
let a = starts.iter().find(|(n, _)| n == bm).map(|(_, p)| page(p))?;
|
||||
let b = bookmark_end(bm).map(|p| page(&p)).unwrap_or(a);
|
||||
Some(if b > a { format!("{a}\u{2013}{b}") } else { a.to_string() })
|
||||
let b = bookmark_end(bm).map(|p| page(&p)).unwrap_or_else(|| a.clone());
|
||||
Some(if b.0 > a.0 { (a.0, format!("{}\u{2013}{}", a.1, b.1)) } else { a })
|
||||
});
|
||||
let r = PageRef { page: range.unwrap_or_else(|| page(&pos).to_string()), bold: f.has('b'), italic: f.has('i') };
|
||||
match node.pages.iter_mut().find(|x| x.page == r.page) {
|
||||
let (at, label) = range.unwrap_or_else(|| page(&pos));
|
||||
let r = PageRef { at, page: label, bold: f.has('b'), italic: f.has('i') };
|
||||
match node.pages.iter_mut().find(|x| x.at == r.at && x.page == r.page) {
|
||||
Some(x) => {
|
||||
x.bold |= r.bold;
|
||||
x.italic |= r.italic;
|
||||
|
||||
@@ -51,7 +51,7 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
},
|
||||
};
|
||||
if url.is_empty() || url.len() > 4096 {
|
||||
return Err(CmdError::Params("bad url".into()));
|
||||
return Err(CmdError::Params("`url` must be non-empty and at most 4096 UTF-8 bytes".into()));
|
||||
}
|
||||
let style = Some("Hyperlink".to_string());
|
||||
if s.sel.is_collapsed() {
|
||||
@@ -188,7 +188,9 @@ pub(super) fn delete_bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
pub(super) fn bookmark(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let name = p::req_str(v, "name")?.trim().to_string();
|
||||
if !bookmark_name_ok(&name) {
|
||||
return Err(CmdError::Params("bookmark names start with a letter, have no spaces and at most 40 characters".into()));
|
||||
return Err(CmdError::Params(
|
||||
"bookmark names start with a letter or underscore, contain only letters, numbers or underscores, and have at most 40 characters".into(),
|
||||
));
|
||||
}
|
||||
// Replace an existing bookmark of the same name.
|
||||
remove_bookmark(s, &name)?;
|
||||
|
||||
@@ -71,22 +71,7 @@ pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn base64_encode(b: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
|
||||
for ch in b.chunks(3) {
|
||||
let n =
|
||||
(ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32;
|
||||
for i in 0..4 {
|
||||
if i <= ch.len() {
|
||||
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub use craft_mime::transfer::base64 as base64_encode;
|
||||
|
||||
pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
|
||||
@@ -415,3 +415,22 @@ fn local_civil_date_follows_the_utc_offset() {
|
||||
assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_preserves_command_payload_bytes() {
|
||||
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
|
||||
assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded);
|
||||
}
|
||||
let bytes: Vec<u8> = (0..513).map(|i| (i % 256) as u8).collect();
|
||||
for len in 0..=bytes.len() {
|
||||
let encoded = super::objects::base64_encode(&bytes[..len]);
|
||||
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
|
||||
assert!(!encoded.contains(['\r', '\n']));
|
||||
assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec()));
|
||||
}
|
||||
assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///");
|
||||
// The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding.
|
||||
assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255]));
|
||||
assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec()));
|
||||
assert_eq!(super::objects::base64_decode("!!!!"), None);
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
apply_filter(s);
|
||||
filter_result(s)
|
||||
})
|
||||
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
|
||||
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; `sort` also accepts a field name, one key object or null; array entries may also be field names; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
|
||||
.when(has_list)
|
||||
.pure(),
|
||||
CommandSpec::new("mailings.sortRecipients", "Sort Recipients", "Mailings › Start Mail Merge › Edit Recipient List", |s, v| {
|
||||
@@ -118,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
apply_filter(s);
|
||||
filter_result(s)
|
||||
})
|
||||
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (no params: the list's own order)"#)
|
||||
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (`sort` also accepts a field name, one key object or null; array entries may also be field names; no params: the list's own order)"#)
|
||||
.when(has_list)
|
||||
.pure(),
|
||||
CommandSpec::new("mailings.insertField", "Insert Merge Field", "Mailings › Write & Insert Fields", |s, v| {
|
||||
@@ -192,6 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
refresh(s);
|
||||
Ok(json!({"record": idx + 1}))
|
||||
})
|
||||
.params(r#"{"text": string}"#)
|
||||
.when(has_recipients),
|
||||
CommandSpec::new("mailings.checkErrors", "Check for Errors", "Mailings › Finish", |s, _| {
|
||||
let mut missing = Vec::new();
|
||||
|
||||
@@ -255,7 +255,7 @@ pub(super) fn parse_sort(headers: &[String], v: Option<&Value>) -> Result<Vec<So
|
||||
None | Some(Value::Null) => return Ok(Vec::new()),
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(o @ (Value::Object(_) | Value::String(_))) => vec![o.clone()],
|
||||
Some(_) => return Err(CmdError::Params("`sort` must be an array of {field, descending}".into())),
|
||||
Some(_) => return Err(CmdError::Params("`sort` must be a field name, a {field, descending} object, an array of those, or null".into())),
|
||||
};
|
||||
if arr.len() > MAX_SORT_KEYS {
|
||||
return Err(CmdError::Params(format!("at most {MAX_SORT_KEYS} sort keys")));
|
||||
|
||||
@@ -107,7 +107,8 @@ fn condition(s: &Session, t: &str, row: usize) -> (bool, Vec<String>) {
|
||||
let op: String = rest.trim_start().chars().take_while(|c| matches!(c, '<'..='>')).collect();
|
||||
let mut texts = field_words(rest).into_iter().filter(|(_, q)| *q).map(|(w, _)| w);
|
||||
let cmp = texts.next().unwrap_or_default();
|
||||
let v = value(s, row, &field);
|
||||
let tested = t.split_once('{').and_then(|(_, r)| r.split('}').next()).unwrap_or("");
|
||||
let v = wordcraft_layout::fields::apply_case_switch(tested, value(s, row, &field));
|
||||
// Numbers compare as numbers (Word: "7" = "7.0"), everything else as text.
|
||||
let ord = match (v.trim().parse::<f64>(), cmp.trim().parse::<f64>()) {
|
||||
(Ok(a), Ok(b)) => a.partial_cmp(&b),
|
||||
@@ -134,7 +135,7 @@ fn keyword(instr: &str) -> String {
|
||||
fn act(s: &Session, instr: &str, row: usize) -> Option<Act> {
|
||||
let t = instr.trim();
|
||||
if let Some(n) = mergefield_name(t) {
|
||||
return Some(Act::Text(value(s, row, &n)));
|
||||
return Some(Act::Text(wordcraft_layout::fields::apply_case_switch(t, value(s, row, &n))));
|
||||
}
|
||||
Some(match keyword(t).as_str() {
|
||||
"ADDRESSBLOCK" => Act::Text(address_block(s, row)),
|
||||
|
||||
@@ -147,6 +147,33 @@ fn merge_field_types_ignore_case() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Alpha\nBeta (b)");
|
||||
}
|
||||
|
||||
/// A merge field's capitalization switch (`\* Upper`, `\* Lower`, `\* Caps`, `\* FirstCap`)
|
||||
/// applies to the record's value in Preview Results and Finish & Merge.
|
||||
#[test]
|
||||
fn merge_fields_apply_their_capitalization_switch() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("mailings.recipients", &json!({"rows": [{"City": "new york", "Name": "ADA lovelace"}]})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": r"MERGEFIELD City \* Upper \* MERGEFORMAT", "result": ""})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " "})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": r#"MERGEFIELD "Name" \* Lower"#, "result": ""})).unwrap();
|
||||
s.run("mailings.preview", &json!({"value": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace");
|
||||
s.run("mailings.finish", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "NEW YORK ada lovelace");
|
||||
}
|
||||
|
||||
/// An IF, NEXTIF or SKIPIF compares the tested merge field after its capitalization switch.
|
||||
#[test]
|
||||
fn rule_conditions_apply_the_tested_fields_capitalization_switch() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("mailings.recipients", &json!({"rows": [{"City": "new york"}, {"City": "paris"}]})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": r#"IF { MERGEFIELD City \* Upper } = "NEW YORK" "match" "other""#, "result": ""})).unwrap();
|
||||
s.run("mailings.preview", &json!({"value": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "match");
|
||||
s.run("mailings.next", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "other");
|
||||
}
|
||||
|
||||
/// An IF is a merge rule only when the field it tests is a MERGEFIELD: the word in a quoted
|
||||
/// value doesn't make `IF { PAGE } = "mergefield" …` one.
|
||||
#[test]
|
||||
@@ -590,7 +617,8 @@ fn recipients_from_an_xls_workbook() {
|
||||
let book = wordcraft_formats::sheet::xls_fixture(&[(
|
||||
"收件人",
|
||||
vec![row(&["姓名", "城市", "数量"]), row(&["张三", "北京", "12"]), row(&["李四", "上海", "2"])],
|
||||
)]);
|
||||
)])
|
||||
.unwrap();
|
||||
let mut s = Session::new(Document::new());
|
||||
let r = s.run("mailings.recipients", &json!({"path": "名单.xls", "data": b64(&book)})).unwrap();
|
||||
assert_eq!(r, json!({"fields": ["姓名", "城市", "数量"], "records": 2, "sheet": "收件人"}));
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("file.options", "Options", "File", options)
|
||||
.params(
|
||||
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: the system locations only), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
|
||||
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
|
||||
|
||||
@@ -274,7 +274,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
st.quick = on;
|
||||
}
|
||||
sel_result(s)
|
||||
}),
|
||||
})
|
||||
.params(r#"{"style": string (name or id), "value"?: bool (default true)}"#),
|
||||
// Advanced paragraph tools (#5043, as in WPS Office): conversions and cleanup over the
|
||||
// selection, or the whole document with `scope: "all"`. One undo step per command.
|
||||
CommandSpec::new("para.convertBreaks", "Convert Line Breaks to Paragraphs", "Home › Paragraph › Paragraph Tools", convert_breaks)
|
||||
|
||||
@@ -22,7 +22,7 @@ const MODES: [&str; 5] = ["none", "readOnly", "comments", "trackedChanges", "for
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("review.restrict", "Restrict Editing", "Review › Protect", restrict).params(
|
||||
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (start enforcing; "none" stops), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool, "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
|
||||
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (editing restriction; use "none" with "formatting": true for formatting-only protection), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool (true: stop protection), "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -431,7 +431,8 @@ enum HoleMode {
|
||||
/// run formatting and paragraph formatting outside the ranges `author` may edit, in every story,
|
||||
/// and the formatting of every table, row and cell that holds any of that protected content, and what
|
||||
/// reaches the whole document: page setup, the document defaults and the existing styles
|
||||
/// (applying a style may add one), the document's settings and its metadata.
|
||||
/// (applying a style may add one), the glossary's building blocks, the document's settings and
|
||||
/// its metadata.
|
||||
pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &str) -> bool {
|
||||
// Protection can't change mid-command (`protection_lifted` guards undo and redo).
|
||||
let mode = if Some("forms") == before.settings.protection.as_deref() { HoleMode::Controls } else { HoleMode::Perms(author.into()) };
|
||||
@@ -444,6 +445,7 @@ pub(crate) fn outside_unchanged(before: &Document, after: &Document, author: &st
|
||||
&& before.settings == after.settings
|
||||
&& before.core == after.core
|
||||
&& before.custom_props == after.custom_props
|
||||
&& before.glossary == after.glossary
|
||||
&& comments_unchanged(before, after)
|
||||
&& lists_unchanged(before, after)
|
||||
&& sources_unchanged(before, after)
|
||||
|
||||
@@ -428,6 +428,23 @@ fn the_post_check_compares_the_settings_and_the_metadata() {
|
||||
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged document isn't unchanged");
|
||||
}
|
||||
|
||||
/// The glossary's building blocks reach the whole document, so the post-check compares them.
|
||||
#[test]
|
||||
fn the_post_check_compares_the_glossary() {
|
||||
use wordcraft_doc::{BuildingBlock, CharProps, Paragraph};
|
||||
let mut before = Document::from_text("Some text.");
|
||||
before.glossary.push(BuildingBlock {
|
||||
name: "g".into(),
|
||||
blocks: vec![wordcraft_doc::para_block(Paragraph::with_text("Block", Default::default()))],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(super::outside_unchanged(&before, &before.clone(), "someone"), "an unchanged glossary is unchanged");
|
||||
let mut after = before.clone();
|
||||
after.glossary[0].blocks[0] =
|
||||
wordcraft_doc::para_block(Paragraph::with_text("Block", CharProps { lang: Some("fr-FR".into()), ..Default::default() }));
|
||||
assert!(!super::outside_unchanged(&before, &after, "someone"), "a relanguaged building block is a change");
|
||||
}
|
||||
|
||||
/// Read only, no exceptions: going to a header the document doesn't have doesn't create
|
||||
/// one, and loading or filtering recipients doesn't rewrite the merge fields' shown results
|
||||
/// (both used to change the document from a non-mutating command, #1327).
|
||||
|
||||
@@ -20,6 +20,7 @@ use fields::caption;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
use notes::{note, note_refs};
|
||||
pub use properties::{bookmark_text, date_picture};
|
||||
@@ -32,7 +33,7 @@ use toc::{insert_toc, remove_toc, toc_range};
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("references.toc", "Table of Contents", "References › Table of Contents", insert_toc).params(
|
||||
r#"{"levels"?: 1-9, "title"?: string, "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#,
|
||||
r#"{"levels"?: 1-9, "title"?: string (at most 1024 characters), "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#,
|
||||
),
|
||||
CommandSpec::new("references.updateToc", "Update Table", "References › Table of Contents", |s, _| {
|
||||
update_toc(s)?;
|
||||
|
||||
@@ -317,6 +317,45 @@ pub fn update_fields(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_fields_in(s, false)
|
||||
}
|
||||
|
||||
/// Each section's page number format (`w:pgNumType w:fmt`), by section index.
|
||||
pub(crate) fn page_formats(s: &Session) -> Vec<NumFormat> {
|
||||
s.doc.sections().into_iter().map(|(_, sec)| sec.page_num_format).collect()
|
||||
}
|
||||
|
||||
/// The page holding `pos` in `l`: its index in the layout, its number, and its section's page
|
||||
/// number format (`formats` from [`page_formats`]). `None` when no page holds it.
|
||||
pub(crate) fn page_at(l: &wordcraft_layout::DocLayout, formats: &[NumFormat], pos: &Pos) -> Option<(usize, u32, NumFormat)> {
|
||||
let c = l.caret(pos)?;
|
||||
let page = l.pages.get(c.page)?;
|
||||
Some((c.page, page.number, formats.get(page.section).copied().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// A page number as the page's footer shows it (`ii` in a lowerRoman section), as the `PAGE`
|
||||
/// and `PAGEREF` fields write it without a `\*` switch.
|
||||
pub(crate) fn page_text(number: u32, fmt: NumFormat) -> String {
|
||||
wordcraft_layout::fields::field_number("", fmt, number)
|
||||
}
|
||||
|
||||
/// The page number of the page holding `pos`, in its section's number format: what generated
|
||||
/// lists (TOC, index, tables of figures and authorities) and page cross-references write. Page
|
||||
/// "1" when no page holds it.
|
||||
pub(crate) fn page_label(s: &mut Session, pos: &Pos) -> String {
|
||||
let formats = page_formats(s);
|
||||
let l = s.layout();
|
||||
page_at(&l, &formats, pos).map_or_else(|| "1".into(), |(_, n, fmt)| page_text(n, fmt))
|
||||
}
|
||||
|
||||
/// Where `PAGEREF` reads bookmark `name` (starting at `pos`): a hidden `_Ref` bookmark from the
|
||||
/// start of a heading that starts with page breaks reads the page its text is on, as when its
|
||||
/// cross-reference was inserted.
|
||||
fn bookmark_page_pos(doc: &wordcraft_doc::Document, name: &str, pos: Pos) -> Pos {
|
||||
if pos.off == 0 && name.starts_with("_Ref") {
|
||||
let off = crate::cmd::citations::leading_breaks(doc, &pos);
|
||||
return Pos { off, ..pos };
|
||||
}
|
||||
pos
|
||||
}
|
||||
|
||||
/// [`update_fields`], or with `all` the whole document: the body (with SEQ, citations and TOC) and
|
||||
/// every part story, wherever the caret is (what printing needs).
|
||||
pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
@@ -326,18 +365,12 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
update_seq(s)?;
|
||||
}
|
||||
let mut pages: std::collections::HashMap<String, (u32, NumFormat)> = Default::default();
|
||||
let formats: Vec<NumFormat> = s.doc.sections().into_iter().map(|(_, sec)| sec.page_num_format).collect();
|
||||
let formats = page_formats(s);
|
||||
let marks = s.doc.bookmarks();
|
||||
for (name, pos) in marks {
|
||||
let pos = bookmark_page_pos(&s.doc, &name, pos);
|
||||
let l = s.layout();
|
||||
let page_info = l
|
||||
.caret(&pos)
|
||||
.and_then(|c| l.pages.get(c.page))
|
||||
.map(|p| {
|
||||
let format = formats.get(p.section).copied().unwrap_or_default();
|
||||
(p.number, format)
|
||||
})
|
||||
.unwrap_or((1, NumFormat::Decimal));
|
||||
let page_info = page_at(&l, &formats, &pos).map_or((1, NumFormat::Decimal), |(_, n, fmt)| (n, fmt));
|
||||
pages.entry(name).or_insert(page_info);
|
||||
}
|
||||
let stories: Vec<StoryRef> =
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
use super::properties::{new_property_value, text_result};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_toc_title_is_capped() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let before = s.doc.body.len();
|
||||
let long = "x".repeat(super::toc::MAX_TOC_TITLE + 1);
|
||||
let r = s.run("references.toc", &json!({"title": long}));
|
||||
assert!(matches!(r, Err(crate::CmdError::Params(_))), "{r:?}");
|
||||
assert_eq!(s.doc.body.len(), before, "a rejected title changes nothing");
|
||||
let at_cap = "x".repeat(super::toc::MAX_TOC_TITLE);
|
||||
s.run("references.toc", &json!({"title": at_cap})).unwrap();
|
||||
}
|
||||
|
||||
fn fields(s: &Session) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
use super::{
|
||||
Block, CharProps, CmdError, CmdResult, Counters, FieldCode, InlineObject, LevelSuffix, NumFormat, OBJ, Paragraph, Path, Pos, Selection, Session,
|
||||
StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, sel_result,
|
||||
StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, page_at, page_formats, page_text, sel_result,
|
||||
};
|
||||
|
||||
/// A table-of-contents title is a heading, not document body: longer titles are rejected
|
||||
/// instead of laying out megabytes of text (#3720).
|
||||
pub(super) const MAX_TOC_TITLE: usize = 1024;
|
||||
|
||||
fn checked_title(v: &Value) -> Result<Option<&str>, CmdError> {
|
||||
let Some(title) = p::str(v, "title") else { return Ok(None) };
|
||||
if title.chars().count() > MAX_TOC_TITLE {
|
||||
return Err(CmdError::Params(format!("`title` is longer than {MAX_TOC_TITLE} characters")));
|
||||
}
|
||||
Ok(Some(title))
|
||||
}
|
||||
|
||||
/// A level range such as `1-3` (or one level, `2`), clamped to 1–9.
|
||||
pub fn level_range(s: &str) -> Option<(u8, u8)> {
|
||||
let mut it = s.split('-').map(|x| x.trim().parse::<u8>().ok());
|
||||
@@ -67,13 +79,15 @@ pub fn toc_instr(v: &Value) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// A TOC entry: the paragraph it points at, its level (0-based), its text, and the leading page
|
||||
/// breaks of that paragraph (its page is where the text after them lands).
|
||||
/// A TOC entry: the paragraph it points at, its level (0-based), its text, the leading page
|
||||
/// breaks of that paragraph (its page is where the text after them lands), and, for a number
|
||||
/// followed by a tab, how far the heading's text starts after where its number starts.
|
||||
struct TocEntry {
|
||||
path: Path,
|
||||
level: u8,
|
||||
text: String,
|
||||
lead: usize,
|
||||
number_gap: Option<f32>,
|
||||
}
|
||||
|
||||
/// The headings of the body, in document order, as (body block, level 1–9, text, leading page
|
||||
@@ -117,9 +131,13 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
.and_then(|n| counters.next_label(&s.doc.numbering, n.num, n.level))
|
||||
.filter(|(label, def)| !label.is_empty() && !matches!(def.format, NumFormat::Bullet | NumFormat::None))
|
||||
.map(|(label, def)| match def.suffix {
|
||||
LevelSuffix::Tab => format!("{label}\t"),
|
||||
LevelSuffix::Space => format!("{label} "),
|
||||
LevelSuffix::Nothing => label,
|
||||
LevelSuffix::Tab => {
|
||||
let start = def.indent - def.hanging;
|
||||
let gap = def.tab.filter(|t| *t > start).unwrap_or(def.indent) - start;
|
||||
(format!("{label}\t"), Some(gap).filter(|g| g.is_finite() && *g > 0.0))
|
||||
}
|
||||
LevelSuffix::Space => (format!("{label} "), None),
|
||||
LevelSuffix::Nothing => (label, None),
|
||||
});
|
||||
let style = p.props.style.as_deref().unwrap_or("Normal");
|
||||
if style.starts_with("TOC") {
|
||||
@@ -144,8 +162,9 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
if let Some(l) = by_style.or(by_outline).or(if hidden { None } else { by_heading }) {
|
||||
let t = p.plain_text().replace(['\u{000C}', '\n', '\t'], " ").trim().to_string();
|
||||
if !t.is_empty() {
|
||||
let text = number.map_or_else(|| t.clone(), |n| format!("{n}{t}"));
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead });
|
||||
let text = number.as_ref().map_or_else(|| t.clone(), |(n, _)| format!("{n}{t}"));
|
||||
let number_gap = number.as_ref().and_then(|(_, g)| *g);
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead, number_gap });
|
||||
}
|
||||
}
|
||||
if let Some(id) = &tc {
|
||||
@@ -159,7 +178,7 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
|
||||
let l = c.arg('l').and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
|
||||
let text = c.args.first().map(|t| t.trim().to_string()).unwrap_or_default();
|
||||
if (id.is_empty() || *id == kind) && (tc_levels.0..=tc_levels.1).contains(&l) && !text.is_empty() {
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off });
|
||||
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off, number_gap: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -375,6 +394,7 @@ pub(super) fn cached_toc_tabs(s: &Session) -> Vec<(String, Vec<TabStop>)> {
|
||||
}
|
||||
|
||||
pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let title = checked_title(v)?.unwrap_or("Contents").to_string();
|
||||
let tabs = cached_toc_tabs(s);
|
||||
range_toc_to_field(s)?;
|
||||
let replace = v.as_object().is_some_and(|m| !m.is_empty());
|
||||
@@ -403,7 +423,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
None => delete_selection(s)?,
|
||||
};
|
||||
let title = p::str(v, "title").unwrap_or("Contents").to_string();
|
||||
if at.story != StoryRef::Body || at.path.depth() > 0 {
|
||||
return Err(CmdError::Failed("a table of contents goes in the main text".into()));
|
||||
}
|
||||
@@ -433,6 +452,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// (`title_above_break`): the field takes `v`'s settings, the title `v`'s `title` if one is given
|
||||
/// (otherwise it is kept, as Word's Insert Table of Contents keeps it), and the entries are rebuilt.
|
||||
fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(String, Vec<TabStop>)]) -> Result<(), CmdError> {
|
||||
let new_title = checked_title(v)?;
|
||||
let instr = toc_instr(v);
|
||||
let field = s.doc.para_mut(StoryRef::Body, &Path::top(start))?;
|
||||
for o in &mut field.objects {
|
||||
@@ -446,7 +466,7 @@ fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(St
|
||||
}
|
||||
}
|
||||
field.touch();
|
||||
if let (Some(title), Some(i)) = (p::str(v, "title"), start.checked_sub(1)) {
|
||||
if let (Some(title), Some(i)) = (new_title, start.checked_sub(1)) {
|
||||
let old = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
|
||||
let mut head = Paragraph::with_text(title, old.props_of_char(0).clone());
|
||||
head.props = old.props.clone();
|
||||
@@ -555,6 +575,7 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
};
|
||||
let no_pages = f.has('n').then(|| f.arg('n').and_then(level_range).unwrap_or((1, 9)));
|
||||
let sep = f.arg('p').map(str::to_string).unwrap_or_else(|| "\t".into());
|
||||
let formats = page_formats(s);
|
||||
for pass in 0..2 {
|
||||
// Pass 1 lays out with the entries in place, so headings below the TOC sit `entries.len()`
|
||||
// blocks further down and their pages account for the TOC's own length.
|
||||
@@ -574,8 +595,8 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
{
|
||||
*top = top.saturating_add(u32::try_from(shift).unwrap_or(u32::MAX));
|
||||
}
|
||||
let page =
|
||||
l.caret(&Pos { story: StoryRef::Body, path: target, off: e.lead }).and_then(|c| l.pages.get(c.page)).map(|pg| pg.number).unwrap_or(1);
|
||||
let page = page_at(&l, &formats, &Pos { story: StoryRef::Body, path: target, off: e.lead })
|
||||
.map_or_else(|| "1".into(), |(_, n, fmt)| page_text(n, fmt));
|
||||
let show_page = no_pages.is_none_or(|(a, b)| !(a..=b).contains(&(e.level + 1)));
|
||||
let link = links.get(k).cloned().flatten();
|
||||
// With a bookmark to point at, the page number is a `PAGEREF` field, as Word writes
|
||||
@@ -589,12 +610,22 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
let props = CharProps { link, ..Default::default() };
|
||||
let mut para = Paragraph::with_text(&text, props.clone()).styled(&format!("TOC{}", e.level + 1));
|
||||
if let Some(instr) = pageref {
|
||||
let field = InlineObject::Field { instr, result: page.to_string(), locked: false, dirty: false, code: false, form: String::new() };
|
||||
let field = InlineObject::Field { instr, result: page.clone(), locked: false, dirty: false, code: false, form: String::new() };
|
||||
para.insert_object(para.len(), field, &props)?;
|
||||
}
|
||||
para.mark = CharProps::default();
|
||||
if e.text.contains('\t') {
|
||||
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
|
||||
// Without a stop for the number (LibreOffice's Contents styles have only the page
|
||||
// number's right stop), its tab would run to the page number: the entry gets a
|
||||
// left stop as far after its indent as the heading's text is after its number.
|
||||
let style = s.doc.styles.resolve_para(¶.props);
|
||||
let has_stop =
|
||||
style.tabs.iter().any(|t| t.pos < width - 1.0 && matches!(t.align, TabAlign::Left | TabAlign::Center | TabAlign::Decimal));
|
||||
if let (None, false, Some(gap)) = (¶.props.tabs, has_stop, e.number_gap) {
|
||||
let pos = style.indent_left.max(0.0) + gap;
|
||||
para.props.tabs = (pos < width - 1.0).then(|| vec![TabStop { pos, align: TabAlign::Left, leader: TabLeader::None }]);
|
||||
}
|
||||
}
|
||||
if show_page && sep.contains('\t') {
|
||||
let right = TabStop { pos: width - 0.5, align: TabAlign::Right, leader };
|
||||
|
||||
@@ -28,12 +28,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("review.newComment", "New Comment", "Review › Comments", new_comment).key(super::mac_or("Mod+Alt+A / Mod+Alt+M", "Mod+Alt+M")).params(r#"{"text": string}"#),
|
||||
CommandSpec::new("review.reply", "Reply", "Review › Comments", reply)
|
||||
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
|
||||
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
|
||||
sel_result(s)
|
||||
})
|
||||
.params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
|
||||
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
|
||||
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
//! column, left of a row and along a cell's left edge inside it select the column, row or cell,
|
||||
//! and a drag from one selects every one up to the pointer; insert buttons left of a row border
|
||||
//! and above a column border add a row or column there; the move handle just past the table's
|
||||
//! top-left corner selects the table or, dragged, moves it (the table then floats where it's
|
||||
//! dropped, the text wrapping around it, as in Word); a double-click on a column border fits the
|
||||
//! column left of it to its contents. The app sends each click or finished drag here in page
|
||||
//! points, so each is one command (one undo step when it changes the document).
|
||||
//! top-left corner (top-right in a right-to-left table) selects the table or, dragged, moves it
|
||||
//! (the table then floats where it's dropped, the text wrapping around it, as in Word); a
|
||||
//! double-click on a column border fits the column left of it to its contents. The app sends
|
||||
//! each click or finished drag here in page points, so each is one command (one undo step when
|
||||
//! it changes the document).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -34,7 +35,7 @@ const INSERT_REACH: f32 = 3.5;
|
||||
const INSERT_OUT: f32 = 14.0;
|
||||
/// An insert button's centre sits this far out from the table's edge (points).
|
||||
const BUTTON_OUT: f32 = 8.0;
|
||||
/// The move handle's side and its gap from the table's top-left corner (points).
|
||||
/// The move handle's side and its gap from the table's top corner (points).
|
||||
const HANDLE: f32 = 8.0;
|
||||
const HANDLE_GAP: f32 = 2.0;
|
||||
/// The farthest a drag moves a table (points; Word's 22 inches).
|
||||
@@ -44,14 +45,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("table.selectAt", "Select Table Cells by Clicking", "Table Layout › Table › Select", select_at)
|
||||
.params(
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX"?: pt, "toY"?: pt, "reach"?: pt, "extend"?: bool, "anchorRow"?: n} (a click in page points, 0-based page, on a selection area of a table in the caret's story: just above a column selects the column, left of a row the row, along a cell's left edge inside it the cell, the move handle past the top-left corner the table; with toX/toY (a drag) every column, row or cell from there to that point; the page margin beside a table (its leading side: right for a right-to-left table) is a row area too, and `extend` (Shift+click) on one takes the rows from the selected ones' anchor, or from row `anchorRow` (0-based) when given, so a drag keeps its press's anchor. `reach` (default 3) is the column borders' resize reach, which the cell areas keep clear of.)"#,
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX"?: pt, "toY"?: pt, "reach"?: pt, "extend"?: bool, "anchorRow"?: n} (a click in page points, 0-based page, on a selection area of a table in the caret's story: just above a column selects the column, left of a row the row, along a cell's left edge inside it the cell, the move handle past the top-left corner (top-right in a right-to-left table) the table; with toX/toY (a drag) every column, row or cell from there to that point; the page margin beside a table (its leading side: right for a right-to-left table) is a row area too, and `extend` (Shift+click) on one takes the rows from the selected ones' anchor, or from row `anchorRow` (0-based) when given, so a drag keeps its press's anchor. `reach` (default 3) is the column borders' resize reach, which the cell areas keep clear of.)"#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("table.insertAt", "Insert Row or Column by Clicking", "Table Layout › Rows & Columns", insert_at).params(
|
||||
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a click on a table's insert button: left of a row border adds a row there, above a column border a column; the new row or column is selected, as in Word)"#,
|
||||
),
|
||||
CommandSpec::new("table.moveDrag", "Move Table by Dragging", "Table Layout › Table", move_drag).params(
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "reach"?: pt} (a drag from the move handle past a table's top-left corner: the table floats where it's dropped, the text wrapping around it; tables in the main text only)"#,
|
||||
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "reach"?: pt} (a drag from the move handle past a table's top-left corner (top-right in a right-to-left table): the table floats where it's dropped, the text wrapping around it; tables in the main text only)"#,
|
||||
),
|
||||
CommandSpec::new("table.fitColumn", "AutoFit Column by Double-Clicking", "Table Layout › Cell Size", fit_column).params(
|
||||
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
|
||||
@@ -67,7 +68,8 @@ pub enum Spot {
|
||||
/// The insert button of horizontal border `n` (0 = the table's top, `n` = the bottom of row
|
||||
/// `n - 1`).
|
||||
InsertRow(usize),
|
||||
/// The insert button of grid line `n` (0 = the table's left edge).
|
||||
/// The insert button of grid line `n` (0 = the table's left edge, or a right-to-left table's
|
||||
/// right edge).
|
||||
InsertColumn(usize),
|
||||
/// The selection area above grid column `n`.
|
||||
Column(usize),
|
||||
@@ -92,9 +94,11 @@ pub struct InsertMark {
|
||||
pub to: (f32, f32),
|
||||
}
|
||||
|
||||
/// The move handle's square (page points), just past the table's top-left corner.
|
||||
/// The move handle's square (page points), just past the table's top-left corner, or its
|
||||
/// top-right one when the table runs right to left (#6438).
|
||||
pub fn handle(geom: &ResizeTarget) -> Rect {
|
||||
Rect::new(geom.left() - HANDLE_GAP - HANDLE, geom.top() - HANDLE_GAP - HANDLE, HANDLE, HANDLE)
|
||||
let x = if geom.rtl { geom.right() + HANDLE_GAP } else { geom.left() - HANDLE_GAP - HANDLE };
|
||||
Rect::new(x, geom.top() - HANDLE_GAP - HANDLE, HANDLE, HANDLE)
|
||||
}
|
||||
|
||||
/// Whether the table's first row is on this page (its move handle is there).
|
||||
@@ -116,10 +120,12 @@ fn nearest(lines: impl Iterator<Item = (usize, f32)>, at: f32, reach: f32) -> Op
|
||||
lines.map(|(i, v)| (i, (at - v).abs())).filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// The grid column at page x `x` (the first or the last beyond the table).
|
||||
/// The grid column at page x `x` (the first or the last beyond the table); a right-to-left
|
||||
/// table's count from the right.
|
||||
fn column_at(geom: &ResizeTarget, x: f32) -> usize {
|
||||
let n = geom.cols.len().saturating_sub(1);
|
||||
geom.cols.iter().skip(1).take_while(|cx| **cx <= x).count().min(n.saturating_sub(1))
|
||||
let drawn = geom.cols.iter().skip(1).take_while(|cx| **cx <= x).count().min(n.saturating_sub(1));
|
||||
if geom.rtl { n.saturating_sub(1).saturating_sub(drawn) } else { drawn }
|
||||
}
|
||||
|
||||
/// The drawn row at page y `y` (the first or the last beyond the table).
|
||||
@@ -140,7 +146,7 @@ fn spot_in(geom: &ResizeTarget, cells: &[&CellBox], x: f32, y: f32, reach: f32,
|
||||
if y < top
|
||||
&& let Some(line) = nearest(lines, x, INSERT_REACH)
|
||||
{
|
||||
return Some(Spot::InsertColumn(line));
|
||||
return Some(Spot::InsertColumn(geom.grid_line(line)));
|
||||
}
|
||||
if y >= top - COLUMN_ABOVE && x >= left && x <= right {
|
||||
return Some(Spot::Column(column_at(geom, x)));
|
||||
@@ -230,7 +236,8 @@ pub fn handle_table(l: &DocLayout, doc: &Document, story: StoryRef, page: usize,
|
||||
.into_iter()
|
||||
.filter(|g| {
|
||||
let h = handle(g);
|
||||
g.story == story && starts_here(g) && x >= h.x - pad && x <= g.right() && y >= h.y - pad && y <= g.bottom()
|
||||
let (x0, x1) = if g.rtl { (g.left(), h.right() + pad) } else { (h.x - pad, g.right()) };
|
||||
g.story == story && starts_here(g) && x >= x0 && x <= x1 && y >= h.y - pad && y <= g.bottom()
|
||||
})
|
||||
.max_by_key(|g| g.table.0.len())
|
||||
}
|
||||
@@ -256,7 +263,7 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
|
||||
let Some(g) = table_resize::tables_on(l, doc, page).into_iter().find(|g| g.story == story && g.table == *table) else {
|
||||
return (None, None);
|
||||
};
|
||||
(first.then(|| handle(&g)), last.then(|| g.handle()))
|
||||
(first.then(|| handle(&g)), (last && g.resizable_columns()).then(|| g.handle()))
|
||||
}
|
||||
|
||||
/// The insert button a target is, if it's one.
|
||||
@@ -269,7 +276,7 @@ pub fn insert_mark(t: &Target) -> Option<InsertMark> {
|
||||
Some(InsertMark { center: (g.left() - BUTTON_OUT, y), from: (g.left(), y), to: (g.right(), y) })
|
||||
}
|
||||
Spot::InsertColumn(line) => {
|
||||
let x = g.cols.get(line).copied()?;
|
||||
let x = g.cols.get(g.grid_line(line)).copied()?;
|
||||
Some(InsertMark { center: (x, g.top() - BUTTON_OUT), from: (x, g.top()), to: (x, g.bottom()) })
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -379,6 +379,79 @@ fn dragging_the_handle_moves_the_table() {
|
||||
assert!(!movable(&nested));
|
||||
}
|
||||
|
||||
fn rtl_table_session(rows: usize, cols: usize) -> Session {
|
||||
let mut s = table_session(rows, cols);
|
||||
s.run("table.rtl", &json!({"value": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// #6438: a right-to-left table's first column is drawn at the right, and its move handle sits
|
||||
/// past its top-right corner, not by the first cell's left edge in the middle of the table. The
|
||||
/// pointer finds the table's edges where they are drawn; the handle selects it.
|
||||
#[test]
|
||||
fn a_right_to_left_tables_move_handle_is_past_its_top_right_corner() {
|
||||
let mut s = rtl_table_session(3, 4);
|
||||
let (first, last) = (cell_rect(&mut s, 0, 0), cell_rect(&mut s, 0, 3));
|
||||
assert!(first.x > last.right(), "the first column is drawn at the right: {first:?} {last:?}");
|
||||
let g = table_resize::tables_on(&s.layout(), &s.doc, 0)[0].clone();
|
||||
assert_eq!((g.left(), g.right()), (last.x, first.right()), "the table's drawn edges");
|
||||
let h = handle(&g);
|
||||
assert!(h.x > first.right() && h.bottom() < first.y, "past the top-right corner: {h:?}, {first:?}");
|
||||
assert_eq!(spot_at(&mut s, h.x + h.w / 2.0, h.y + h.h / 2.0), Some(Spot::Handle));
|
||||
assert_ne!(spot_at(&mut s, first.x - 6.0, first.y - 6.0), Some(Spot::Handle), "not by the first cell's left edge");
|
||||
// The caret's table shows it there, and the pointer finds it on its way there.
|
||||
let l = s.layout();
|
||||
assert_eq!(caret_handles(&l, &s.doc, StoryRef::Body, &table_path(&s), 0).0, Some(h));
|
||||
assert_eq!(handle_table(&l, &s.doc, StoryRef::Body, 0, h.right(), h.bottom(), REACH).map(|g| g.table), Some(table_path(&s)));
|
||||
s.run("table.selectAt", &json!({"page": 0, "x": h.x + 4.0, "y": h.y + 4.0})).unwrap();
|
||||
assert_eq!(s.cell_range().map(|r| (r.rows, r.cols)), Some(((0, 2), (0, 3))));
|
||||
}
|
||||
|
||||
/// #6438: dragging a right-to-left table's move handle moves the whole table as far as the
|
||||
/// pointer went, as with any table, instead of putting its left edge where its first cell's was
|
||||
/// (past the right margin, all but one column off the page). Dragged far right, it stays on the
|
||||
/// page.
|
||||
#[test]
|
||||
fn dragging_a_right_to_left_tables_handle_moves_the_whole_table() {
|
||||
let mut s = rtl_table_session(3, 4);
|
||||
let row = |s: &mut Session| (0..4).map(|c| cell_rect(s, 0, c)).collect::<Vec<_>>();
|
||||
let before = row(&mut s);
|
||||
let h = handle(&table_resize::tables_on(&s.layout(), &s.doc, 0)[0]);
|
||||
let (hx, hy) = (h.x + h.w / 2.0, h.y + h.h / 2.0);
|
||||
s.run("table.moveDrag", &json!({"page": 0, "x": hx, "y": hy, "toX": hx - 40.0, "toY": hy + 30.0})).unwrap();
|
||||
assert!(first_table(&s).props.float.is_some());
|
||||
for (a, b) in before.iter().zip(row(&mut s)) {
|
||||
assert!((b.x - (a.x - 40.0)).abs() < 0.5 && (b.y - (a.y + 30.0)).abs() < 0.5 && (b.w - a.w).abs() < 0.5, "{a:?} → {b:?}");
|
||||
}
|
||||
let h = handle(&table_resize::tables_on(&s.layout(), &s.doc, 0)[0]);
|
||||
let (hx, hy) = (h.x + h.w / 2.0, h.y + h.h / 2.0);
|
||||
s.run("table.moveDrag", &json!({"page": 0, "x": hx, "y": hy, "toX": hx + 1000.0, "toY": hy})).unwrap();
|
||||
let (moved, page_w) = (row(&mut s), s.layout().pages[0].w);
|
||||
assert!(moved[0].right() <= page_w + 0.5 && moved[0].right() > page_w - 1.0, "at the page's right edge: {moved:?}");
|
||||
assert!((moved[0].right() - moved[3].x - (before[0].right() - before[3].x)).abs() < 0.5, "the whole table: {moved:?}");
|
||||
}
|
||||
|
||||
/// A right-to-left table's columns are found where they are drawn: the area above its right
|
||||
/// column selects the first, above its left one the last; the insert button on the border left
|
||||
/// of the first cell adds the second column.
|
||||
#[test]
|
||||
fn a_right_to_left_tables_columns_are_found_where_they_are_drawn() {
|
||||
let mut s = rtl_table_session(2, 3);
|
||||
fill(&mut s);
|
||||
let (c0, c1, c2) = (cell_rect(&mut s, 0, 0), cell_rect(&mut s, 0, 1), cell_rect(&mut s, 0, 2));
|
||||
assert_eq!(spot_at(&mut s, c0.x + c0.w / 2.0, c0.y - 3.0), Some(Spot::Column(0)));
|
||||
assert_eq!(spot_at(&mut s, c2.x + c2.w / 2.0, c2.y - 3.0), Some(Spot::Column(2)));
|
||||
s.run("table.selectAt", &json!({"page": 0, "x": c2.x + c2.w / 2.0, "y": c2.y - 3.0})).unwrap();
|
||||
assert_eq!(s.selected_text(), "r0c2\nr1c2");
|
||||
s.run("table.selectAt", &json!({"page": 0, "x": c0.x + 20.0, "y": c0.y - 3.0, "toX": c1.x + 20.0, "toY": c1.y - 3.0})).unwrap();
|
||||
assert_eq!(s.cell_range().map(|r| r.cols), Some((0, 1)), "a drag from the first column to the second");
|
||||
assert_eq!(spot_at(&mut s, c0.x, c0.y - 8.0), Some(Spot::InsertColumn(1)));
|
||||
s.run("table.insertAt", &json!({"page": 0, "x": c0.x, "y": c0.y - 8.0})).unwrap();
|
||||
assert_eq!(first_table(&s).cols(), 4);
|
||||
assert!(para(&s, 0, 0).plain_text() == "r0c0" && para(&s, 0, 1).is_empty() && para(&s, 0, 2).plain_text() == "r0c1");
|
||||
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "it's selected");
|
||||
}
|
||||
|
||||
/// A double-click on a column border fits the column left of it to its text; as in Word, the
|
||||
/// columns right of it keep their widths and move along, so the table narrows. The right
|
||||
/// edge's column fits the same way.
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! only in their rows. The geometry comes from the layout (what is on the page, in
|
||||
//! page points), so the result is what the drag showed even when autofit or a percentage width
|
||||
//! made the drawn columns differ from the stored grid. The app sends each finished drag here,
|
||||
//! so every drag is one undo step.
|
||||
//! so every drag is one undo step. A right-to-left table's rows resize; its columns and corner
|
||||
//! don't yet (`ResizeTarget::resizable_columns`).
|
||||
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::props::{Align, HeightRule, VMerge};
|
||||
@@ -72,7 +73,8 @@ pub struct DrawnRow {
|
||||
pub row: usize,
|
||||
pub top: f32,
|
||||
pub bottom: f32,
|
||||
/// Grid lines that are cell borders in this row (a merged cell hides the ones it covers).
|
||||
/// Drawn grid lines (`ResizeTarget::cols`' indices) that are cell borders in this row (a
|
||||
/// merged cell hides the ones it covers).
|
||||
pub(crate) edges: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -82,12 +84,16 @@ pub struct ResizeTarget {
|
||||
pub edge: Edge,
|
||||
pub story: StoryRef,
|
||||
pub table: Path,
|
||||
/// Drawn grid lines, page x, left to right (columns + 1 of them).
|
||||
/// Drawn grid lines, page x, left to right (columns + 1 of them); a right-to-left table's
|
||||
/// grid runs the other way (`grid_line`).
|
||||
pub cols: Vec<f32>,
|
||||
/// Drawn rows on this page, top to bottom.
|
||||
pub rows: Vec<DrawnRow>,
|
||||
/// Whether the table's last row is on this page (the handle is shown only then).
|
||||
pub ends_here: bool,
|
||||
/// Whether the table runs right to left (`w:bidiVisual`): its first column is drawn at the
|
||||
/// right.
|
||||
pub rtl: bool,
|
||||
/// When cells of the table are selected and the column border is one of theirs
|
||||
/// (`limit_to_selection`): their rows, each with the grid lines its cells' borders are on.
|
||||
/// The border moves only there; empty, it moves in the whole column.
|
||||
@@ -131,6 +137,18 @@ impl ResizeTarget {
|
||||
pub fn handle(&self) -> Rect {
|
||||
Rect::new(self.right() + 1.0, self.bottom() + 1.0, HANDLE, HANDLE)
|
||||
}
|
||||
/// The grid line that drawn line `line` (`cols`' index) is, or the other way round: the same
|
||||
/// in a left-to-right table, counted from the other edge in a right-to-left one.
|
||||
pub fn grid_line(&self, line: usize) -> usize {
|
||||
if self.rtl { self.cols.len().saturating_sub(1).saturating_sub(line) } else { line }
|
||||
}
|
||||
/// Whether the table's column borders and resize handle are grabbed. Not a right-to-left
|
||||
/// table's: its grid runs from its right edge, and these drags, made for a grid running from
|
||||
/// the left, would put the new widths on the wrong columns. Mirrored ones aren't built yet
|
||||
/// (#6438).
|
||||
pub fn resizable_columns(&self) -> bool {
|
||||
!self.rtl
|
||||
}
|
||||
|
||||
/// The new widths and heights a drag that moved the pointer by (`dx`, `dy`) points gives;
|
||||
/// `share` says who makes up a column border's move (`true`: Shift is held).
|
||||
@@ -340,18 +358,23 @@ pub(crate) fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The drawn geometry of one table on a page, from its cells' boxes.
|
||||
/// The drawn geometry of one table on a page, from its cells' boxes: its grid lines as drawn,
|
||||
/// left to right, and its rows.
|
||||
fn geometry(t: &Table, boxes: &[&CellBox]) -> Option<(Vec<f32>, Vec<DrawnRow>)> {
|
||||
let n = t.cols();
|
||||
if n == 0 || n > wordcraft_doc::table::MAX_COLS || boxes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Lines are counted from the left as drawn. A right-to-left table's grid runs from its right
|
||||
// edge (`layout::table`), so a cell's left edge is the grid line it ends at, from the right.
|
||||
let rtl = t.props.bidi_visual;
|
||||
let mut lines: Vec<Option<f32>> = vec![None; n + 1];
|
||||
let mut rows: Vec<DrawnRow> = Vec::new();
|
||||
for b in boxes {
|
||||
let g = t.grid_col(b.row, b.cell);
|
||||
let span = t.rows.get(b.row).and_then(|r| r.cells.get(b.cell)).map_or(1, wordcraft_doc::Cell::span);
|
||||
let end = g.saturating_add(span).min(n);
|
||||
let (g, end) = if rtl { (n.saturating_sub(end), n.saturating_sub(g)) } else { (g, end) };
|
||||
if let Some(x) = lines.get_mut(g) {
|
||||
x.get_or_insert(b.rect.x);
|
||||
}
|
||||
@@ -371,7 +394,10 @@ fn geometry(t: &Table, boxes: &[&CellBox]) -> Option<(Vec<f32>, Vec<DrawnRow>)>
|
||||
}
|
||||
// A line no cell on this page ends at: between its drawn neighbours, as the grid shares it.
|
||||
let (first, last) = (lines.first().copied().flatten()?, lines.last().copied().flatten()?);
|
||||
let weight = |i: usize| t.grid.get(i).copied().filter(|w| t.grid.len() == n && w.is_finite() && *w > 0.0).unwrap_or(1.0);
|
||||
let weight = |i: usize| {
|
||||
let i = if rtl { n.saturating_sub(1).saturating_sub(i) } else { i };
|
||||
t.grid.get(i).copied().filter(|w| t.grid.len() == n && w.is_finite() && *w > 0.0).unwrap_or(1.0)
|
||||
};
|
||||
let mut cols = Vec::with_capacity(n + 1);
|
||||
let mut prev = (0usize, first);
|
||||
for i in 0..=n {
|
||||
@@ -418,14 +444,20 @@ pub(crate) fn tables_on(l: &DocLayout, doc: &Document, page: usize) -> Vec<Resiz
|
||||
let mine: Vec<&CellBox> = boxes.iter().filter(|b| b.story == story && b.table == *path).collect();
|
||||
let (cols, rows) = geometry(t, &mine)?;
|
||||
let ends_here = rows.last().is_some_and(|r| r.row + 1 == t.rows.len());
|
||||
Some(ResizeTarget { edge: Edge::Corner, story, table: path.clone(), cols, rows, ends_here, only: Vec::new() })
|
||||
let rtl = t.props.bidi_visual;
|
||||
Some(ResizeTarget { edge: Edge::Corner, story, table: path.clone(), cols, rows, ends_here, rtl, only: Vec::new() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn on_handle(t: &ResizeTarget, x: f32, y: f32, reach: f32) -> bool {
|
||||
let h = t.handle();
|
||||
t.ends_here && x >= h.x - reach / 2.0 && x <= h.right() + reach / 2.0 && y >= h.y - reach / 2.0 && y <= h.bottom() + reach / 2.0
|
||||
t.ends_here
|
||||
&& t.resizable_columns()
|
||||
&& x >= h.x - reach / 2.0
|
||||
&& x <= h.right() + reach / 2.0
|
||||
&& y >= h.y - reach / 2.0
|
||||
&& y <= h.bottom() + reach / 2.0
|
||||
}
|
||||
|
||||
/// The innermost table under page point (`x`, `y`) whose resize handle is on this page, or whose
|
||||
@@ -437,7 +469,11 @@ pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, r
|
||||
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
|
||||
tables_on(l, doc, page)
|
||||
.into_iter()
|
||||
.filter(|t| t.ends_here && ((x >= t.left() && x <= t.right() && y >= t.top() && y <= t.bottom()) || on_handle(t, x, y, reach)))
|
||||
.filter(|t| {
|
||||
t.ends_here
|
||||
&& t.resizable_columns()
|
||||
&& ((x >= t.left() && x <= t.right() && y >= t.top() && y <= t.bottom()) || on_handle(t, x, y, reach))
|
||||
})
|
||||
.max_by_key(|t| t.table.0.len())
|
||||
}
|
||||
|
||||
@@ -464,9 +500,12 @@ pub fn resize_target(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32,
|
||||
if x < left - reach || x > right + reach || y < top - reach || y > bottom + reach {
|
||||
continue;
|
||||
}
|
||||
// Column borders: in the row under the pointer, only lines that are cell borders there.
|
||||
// Column borders: in the row under the pointer, only lines that are cell borders there
|
||||
// (none of a right-to-left table's yet, `resizable_columns`).
|
||||
let row_here = target.rows.iter().find(|r| y >= r.top && y <= r.bottom).cloned();
|
||||
if let Some(r) = &row_here {
|
||||
if let Some(r) = &row_here
|
||||
&& target.resizable_columns()
|
||||
{
|
||||
for line in 0..target.cols.len() {
|
||||
// The table's left edge is grabbed from outside it (a point in, for the border's
|
||||
// width): inside starts the first cell.
|
||||
|
||||
@@ -128,6 +128,32 @@ fn the_corner_handle_scales_the_table() {
|
||||
assert!(((d1.bottom() - a1.y) - h * 2.0).abs() < 0.5, "{h} → {}", d1.bottom() - a1.y);
|
||||
}
|
||||
|
||||
/// #6438: a right-to-left table's columns run from its right edge, and mirrored drags for its
|
||||
/// column borders and corner aren't built yet: they aren't grabbed, so a drag leaves its columns
|
||||
/// alone (one used to squeeze all but the first to nothing). Its rows' borders resize as in any
|
||||
/// table.
|
||||
#[test]
|
||||
fn a_right_to_left_tables_columns_keep_their_widths() {
|
||||
let mut s = table_session(2, 3);
|
||||
s.run("table.rtl", &json!({"value": true})).unwrap();
|
||||
let start = first_table(&s);
|
||||
let (a, c) = (cell_rect(&mut s, 0, 0), cell_rect(&mut s, 1, 2));
|
||||
let y = a.y + a.h / 2.0;
|
||||
let l = s.layout();
|
||||
for x in [a.x, a.x + 1.0, a.x - 1.0, a.right(), c.x, c.right()] {
|
||||
assert!(resize_target(&l, &s.doc, 0, x, y, REACH).is_none_or(|t| !matches!(t.edge, Edge::Column(_))), "x {x}");
|
||||
let _ = s.run("table.resizeDrag", &json!({"page": 0, "x": x, "y": y, "toX": x - 30.0, "toY": y}));
|
||||
assert_eq!(first_table(&s), start, "x {x}");
|
||||
}
|
||||
let below = c.bottom() + 1.0 + HANDLE / 2.0;
|
||||
for (x, y) in [(a.right() + 1.0 + HANDLE / 2.0, below), (c.x - 1.0 - HANDLE / 2.0, below), (a.x + 10.0, y)] {
|
||||
assert!(table_under(&l, &s.doc, 0, x, y, REACH).is_none(), "no corner handle at {x}, {y}");
|
||||
}
|
||||
let x = a.x + a.w / 2.0;
|
||||
s.run("table.resizeDrag", &json!({"page": 0, "x": x, "y": a.bottom() + 1.0, "toX": x, "toY": a.bottom() + 21.0})).unwrap();
|
||||
assert!((cell_rect(&mut s, 0, 0).h - (a.h + 20.0)).abs() < 0.1, "the row border moves");
|
||||
}
|
||||
|
||||
/// A merged cell hides the border it covers: no column border to grab in its middle.
|
||||
#[test]
|
||||
fn merged_cells_have_no_border_inside() {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
|
||||
use wordcraft_doc::CharProps;
|
||||
|
||||
/// Options › Language › Set as default: only the saved default proofing language (what future
|
||||
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
|
||||
@@ -14,8 +15,19 @@ pub(super) fn preferred_language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Set Proofing Language: the selection's language and "do not check spelling or grammar",
|
||||
/// or (`default`) the document's default and the saved language for future blank documents;
|
||||
/// `detect` is the per-user detection preference.
|
||||
/// Nothing at all sets US English, as before.
|
||||
/// Nothing at all sets US English, as before. `scope: "document"` sets it for every story.
|
||||
pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Checked first, so a bad scope changes nothing (not even the detect preference).
|
||||
let whole_document = match v.get("scope") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::String(t)) if t == "selection" => false,
|
||||
Some(Value::String(t)) if t == "document" => true,
|
||||
Some(other) => return Err(CmdError::Params(format!("`scope` must be \"selection\" or \"document\", not {other}"))),
|
||||
};
|
||||
// Protection leaves only its exceptions editable, so the whole document can't be one.
|
||||
if whole_document && let Some(mode) = s.doc.settings.protection.as_deref() {
|
||||
return Err(CmdError::Disabled(format!("review.language: stop protection ({mode}) before changing the whole document's proofing language")));
|
||||
}
|
||||
let lang = match p::str(v, "lang") {
|
||||
Some(t) => Some(
|
||||
wordcraft_proof::lang::normalize_tag(t)
|
||||
@@ -45,20 +57,91 @@ pub(super) fn language(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if lang.is_none() && no_proof.is_none() {
|
||||
return Ok(json!({"detect": s.prefs.detect_language}));
|
||||
}
|
||||
let result = crate::cmd::format::apply(s, &|c| {
|
||||
let change = |c: &mut CharProps| {
|
||||
if let Some(l) = &lang {
|
||||
c.lang = Some(l.clone());
|
||||
}
|
||||
if let Some(np) = no_proof {
|
||||
c.no_proof = Some(np);
|
||||
}
|
||||
})?;
|
||||
};
|
||||
let result = if whole_document {
|
||||
let glossary_skipped = set_document_props(s, &change)?;
|
||||
// The same caret/selection result as the selection path (the selection is untouched).
|
||||
let mut r = sel_result(s)?;
|
||||
if let Some(m) = r.as_object_mut() {
|
||||
m.insert("scope".into(), json!("document"));
|
||||
if glossary_skipped {
|
||||
m.insert("glossarySkipped".into(), json!(true));
|
||||
}
|
||||
}
|
||||
r
|
||||
} else {
|
||||
crate::cmd::format::apply(s, &change)?
|
||||
};
|
||||
if p::bool(v, "default") == Some(true) {
|
||||
s.prefs.default_language = lang;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Apply `f` to the character formatting of every story of the document (Language dialog, "Apply
|
||||
/// to the whole document"): text and paragraph marks of the body, headers, footers, notes,
|
||||
/// comments, text boxes (all `Document::parts`), table cells, and the glossary's building blocks.
|
||||
/// The selection is untouched; formatting waiting for typing follows.
|
||||
///
|
||||
/// Glossary blocks are left alone while Track Changes and Track Formatting are both on: tracked
|
||||
/// formatting (`fmt_revisions::record`) compares only the body and the parts, so a glossary change
|
||||
/// would be an untracked edit. So those blocks keep their old language while tracking; the caller
|
||||
/// reports it (`glossarySkipped`). Returns whether the glossary was skipped.
|
||||
fn set_document_props(s: &mut Session, f: &dyn Fn(&mut CharProps)) -> Result<bool, CmdError> {
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for story in stories {
|
||||
for path in s.doc.para_paths(story) {
|
||||
let para = s.doc.para_mut(story, &path)?;
|
||||
let len = para.len();
|
||||
para.format(0, len, f)?;
|
||||
f(&mut para.mark);
|
||||
para.touch();
|
||||
}
|
||||
}
|
||||
let skipped = s.doc.settings.track_changes && s.prefs.markup.track_formatting;
|
||||
if !skipped {
|
||||
for block in &mut s.doc.glossary {
|
||||
format_blocks(&mut block.blocks, f, 0);
|
||||
}
|
||||
}
|
||||
if let Some(pend) = s.pending.as_mut() {
|
||||
f(pend);
|
||||
}
|
||||
Ok(skipped)
|
||||
}
|
||||
|
||||
/// [`set_document_props`] for a block list outside any story (depth-limited like `para_paths`).
|
||||
fn format_blocks(blocks: &mut wordcraft_doc::Blocks, f: &dyn Fn(&mut CharProps), depth: usize) {
|
||||
if depth > wordcraft_doc::PARA_WALK_DEPTH {
|
||||
return;
|
||||
}
|
||||
for blk in blocks.iter_mut() {
|
||||
match Arc::make_mut(blk) {
|
||||
wordcraft_doc::Block::Para(p) => {
|
||||
let len = p.len();
|
||||
// A range inside the paragraph can't fail; the mark is formatted regardless.
|
||||
let _ = p.format(0, len, f);
|
||||
f(&mut p.mark);
|
||||
p.touch();
|
||||
}
|
||||
wordcraft_doc::Block::Table(t) => {
|
||||
for row in &mut t.rows {
|
||||
for cell in &mut row.cells {
|
||||
format_blocks(&mut cell.blocks, f, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn macros(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(d) = v.get("define") {
|
||||
let name = d.get("name").and_then(Value::as_str).unwrap_or("Macro").to_string();
|
||||
|
||||
@@ -34,6 +34,7 @@ struct DiffCtx<'a> {
|
||||
opts: &'a CompareOptions,
|
||||
budget: &'a mut u64,
|
||||
char_fallbacks: &'a mut usize,
|
||||
plain_revised: bool,
|
||||
}
|
||||
|
||||
/// Changed paragraphs longer than this (in characters) are compared word by word even at
|
||||
@@ -48,10 +49,12 @@ const MAX_CHAR_DIFF: usize = 2000;
|
||||
/// [`MAX_CHAR_DIFF`] characters, it falls back to word-level diff for that paragraph, surfaces the
|
||||
/// fallback count in `"characterFallback"`, and includes `"level"` in `"notHonoured"`.
|
||||
pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let revised = if let Some(t) = p::str(v, "text") {
|
||||
Document::from_text(t)
|
||||
// A revised side given as plain text carries no real runs or properties; one opened from a
|
||||
// path does. The diff takes the revised formatting only in the latter case.
|
||||
let (revised, plain_revised) = if let Some(t) = p::str(v, "text") {
|
||||
(Document::from_text(t), true)
|
||||
} else if let Some(path) = p::str(v, "path") {
|
||||
crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)?
|
||||
(crate::io::open_path(std::path::Path::new(path)).map_err(CmdError::Failed)?, false)
|
||||
} else {
|
||||
return Err(CmdError::Params("`path` or `text` of the revised document is required".into()));
|
||||
};
|
||||
@@ -97,7 +100,7 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let mut budget = MAX_COMPARE_CELLS;
|
||||
let mut char_fallbacks = 0usize;
|
||||
let ops = lcs_ops(&old.iter().map(key).collect::<Vec<_>>(), &new.iter().map(key).collect::<Vec<_>>(), &mut budget);
|
||||
let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks };
|
||||
let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks, plain_revised };
|
||||
let mut out: Vec<Arc<Block>> = Vec::new();
|
||||
let (mut i, mut j) = (0usize, 0usize);
|
||||
let mut changes = 0usize;
|
||||
@@ -393,9 +396,11 @@ fn flatten_region(out: &mut Vec<Op>, region: &[(Op, usize, Kind)]) {
|
||||
|
||||
/// A token of a changed paragraph: a word (or character), or an inline object without text
|
||||
/// of its own (a text box anchor, a picture, a bookmark…), which is compared and kept whole.
|
||||
/// Each token also carries the byte range it came from in its source paragraph, so the output
|
||||
/// segment can take the formatting of the run it came from instead of the paragraph's first run.
|
||||
enum Tok<'a> {
|
||||
Text(String),
|
||||
Obj(&'a InlineObject),
|
||||
Text(String, std::ops::Range<usize>),
|
||||
Obj(&'a InlineObject, std::ops::Range<usize>),
|
||||
}
|
||||
|
||||
/// What a comparison sees of a token: the text as the options say, an object with the text of
|
||||
@@ -421,52 +426,131 @@ fn same_objects(doc: &Document, a: &Paragraph, b: &Paragraph) -> bool {
|
||||
}
|
||||
|
||||
/// Words with the spaces after them ("The ", "cat "), or single characters, and the objects
|
||||
/// between them. Objects with text (fields, equations…) count as their text.
|
||||
/// between them. Objects with text (fields, equations…) count as their text. Each token records
|
||||
/// the byte range it came from in `p`, so its output segment can take that source run's
|
||||
/// formatting. An object's flattened text (or a broken marker's placeholder) maps to the marker's
|
||||
/// own range, which is the nearest formatting the object has.
|
||||
fn tokens(p: &Paragraph, characters: bool) -> Vec<Tok<'_>> {
|
||||
fn push(v: &mut Vec<Tok<'_>>, cur: &mut String, c: char, characters: bool) {
|
||||
fn push(v: &mut Vec<Tok<'_>>, cur: &mut String, start: usize, end: usize, c: char, characters: bool) {
|
||||
cur.push(c);
|
||||
if characters || c == ' ' {
|
||||
v.push(Tok::Text(std::mem::take(cur)));
|
||||
v.push(Tok::Text(std::mem::take(cur), start..end));
|
||||
}
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut cur_start = 0usize;
|
||||
let mut objects = p.objects.iter();
|
||||
for c in p.text.chars() {
|
||||
for (i, c) in p.text.char_indices() {
|
||||
let marker = i..i + OBJ.len_utf8();
|
||||
if c != OBJ {
|
||||
push(&mut v, &mut cur, c, characters);
|
||||
if cur.is_empty() {
|
||||
cur_start = i;
|
||||
}
|
||||
push(&mut v, &mut cur, cur_start, i + c.len_utf8(), c, characters);
|
||||
continue;
|
||||
}
|
||||
match objects.next() {
|
||||
Some(o) if o.plain_text().is_empty() => {
|
||||
if !cur.is_empty() {
|
||||
v.push(Tok::Text(std::mem::take(&mut cur)));
|
||||
v.push(Tok::Text(std::mem::take(&mut cur), cur_start..i));
|
||||
}
|
||||
v.push(Tok::Obj(o, marker));
|
||||
}
|
||||
Some(o) => {
|
||||
for c in o.plain_text().chars() {
|
||||
if cur.is_empty() {
|
||||
cur_start = i;
|
||||
}
|
||||
push(&mut v, &mut cur, cur_start, marker.end, c, characters);
|
||||
}
|
||||
v.push(Tok::Obj(o));
|
||||
}
|
||||
Some(o) => o.plain_text().chars().for_each(|c| push(&mut v, &mut cur, c, characters)),
|
||||
None => {
|
||||
// A marker without its object (a broken paragraph): kept as a visible
|
||||
// placeholder, so the loss shows in the result instead of vanishing.
|
||||
log::warn!("compare: an object marker without its object");
|
||||
push(&mut v, &mut cur, char::REPLACEMENT_CHARACTER, characters);
|
||||
if cur.is_empty() {
|
||||
cur_start = i;
|
||||
}
|
||||
push(&mut v, &mut cur, cur_start, marker.end, char::REPLACEMENT_CHARACTER, characters);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
v.push(Tok::Text(cur));
|
||||
v.push(Tok::Text(cur, cur_start..p.text.len()));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// One side's run formatting for `word_diff`: the paragraph's run ranges (from
|
||||
/// [`Paragraph::run_ranges`]), walked with a forward cursor. `word_diff` consumes each side's
|
||||
/// tokens in increasing offset order, so the cursor makes a token's lookup amortised O(1)
|
||||
/// instead of rescanning the runs from the start for every token; an out-of-order offset falls
|
||||
/// back to a binary search, so the lookup stays correct for any offset.
|
||||
struct SideProps<'a> {
|
||||
ranges: Vec<(std::ops::Range<usize>, &'a CharProps)>,
|
||||
mark: &'a CharProps,
|
||||
cursor: usize,
|
||||
}
|
||||
|
||||
impl<'a> SideProps<'a> {
|
||||
fn new(p: &'a Paragraph) -> Self {
|
||||
SideProps { ranges: p.run_ranges().collect(), mark: &p.mark, cursor: 0 }
|
||||
}
|
||||
|
||||
/// The props of the run holding byte `off`: that run's props, or the paragraph mark when
|
||||
/// `off` is past the last run — the same answer `Paragraph::props_of_char` gives.
|
||||
fn run_props(&mut self, off: usize) -> &'a CharProps {
|
||||
while self.cursor < self.ranges.len() && self.ranges[self.cursor].0.end <= off {
|
||||
self.cursor += 1;
|
||||
}
|
||||
if let Some((range, props)) = self.ranges.get(self.cursor)
|
||||
&& range.contains(&off)
|
||||
{
|
||||
return props;
|
||||
}
|
||||
let idx = self.ranges.partition_point(|(r, _)| r.start <= off);
|
||||
match idx.checked_sub(1).and_then(|i| self.ranges.get(i)) {
|
||||
Some((range, props)) if range.contains(&off) => props,
|
||||
_ => self.mark,
|
||||
}
|
||||
}
|
||||
|
||||
/// The formatting of the source run a token came from: the run holding the token's first
|
||||
/// byte, with the revision metadata stripped. `ins`, `del` and `fmt_change` are indices into
|
||||
/// the *source* document's own revision table, and the rebuilt paragraph lives in the result
|
||||
/// document, whose table is a different one, so a source mark can never be carried across;
|
||||
/// `word_diff` stamps the compare's own `ins`/`del` on the segments it marks. The consequence
|
||||
/// is plain: a pre-existing pending revision inside a changed paragraph (say another author's
|
||||
/// deletion) is superseded by the compare result rather than preserved. The hyperlink is
|
||||
/// kept, because Reject restores it on a deleted run (at token granularity: the link is taken
|
||||
/// from the token's first byte, so a token that starts unlinked can lose a mid-token link).
|
||||
fn props_of(&mut self, t: &Tok<'_>) -> CharProps {
|
||||
let off = match t {
|
||||
Tok::Text(_, range) | Tok::Obj(_, range) => range.start,
|
||||
};
|
||||
let c = self.run_props(off);
|
||||
CharProps { ins: None, del: None, fmt_change: None, ..c.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The props of an output token: those of the source run it came from, or — never expected, since
|
||||
/// [`tokens`] and [`lcs_ops`] consume both sides in step — the given fallback. A miss is loud.
|
||||
fn output_props(side: &mut SideProps<'_>, t: Option<&Tok<'_>>, fallback: &CharProps) -> CharProps {
|
||||
if t.is_none() {
|
||||
log::warn!("compare: a token range lookup missed; `tokens` and `lcs_ops` are out of step");
|
||||
}
|
||||
t.map(|t| side.props_of(t)).unwrap_or_else(|| fallback.clone())
|
||||
}
|
||||
|
||||
/// Add a token at the end of `p` with `props`.
|
||||
fn put(p: &mut Paragraph, t: Option<&Tok<'_>>, props: &CharProps) {
|
||||
let at = p.len();
|
||||
match t {
|
||||
Some(Tok::Text(t)) => {
|
||||
Some(Tok::Text(t, _)) => {
|
||||
let _ = p.insert_text(at, t, props);
|
||||
}
|
||||
Some(Tok::Obj(o)) => {
|
||||
Some(Tok::Obj(o, _)) => {
|
||||
let _ = p.insert_object(at, (*o).clone(), props);
|
||||
}
|
||||
None => {}
|
||||
@@ -500,10 +584,12 @@ fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let plain_revised = ctx.plain_revised;
|
||||
let (ta, tb) = (tokens(a, chars), tokens(b, chars));
|
||||
let (mut a_props, mut b_props) = (SideProps::new(a), SideProps::new(b));
|
||||
let key = |t: &Tok<'_>| match t {
|
||||
Tok::Text(t) => Key::Text(ctx.opts.key(t)),
|
||||
Tok::Obj(o) => obj_key(doc, o),
|
||||
Tok::Text(t, _) => Key::Text(ctx.opts.key(t)),
|
||||
Tok::Obj(o, _) => obj_key(doc, o),
|
||||
};
|
||||
let ops = lcs_ops(&ta.iter().map(key).collect::<Vec<_>>(), &tb.iter().map(key).collect::<Vec<_>>(), ctx.budget);
|
||||
// Only at character granularity: a matched whole word almost never happens by coincidence,
|
||||
@@ -511,23 +597,46 @@ fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>
|
||||
// a short interior match need folding back into its surrounding edit.
|
||||
let ops = if chars { collapse_noise_matches(&ops) } else { ops };
|
||||
let mut p = Paragraph::new();
|
||||
p.props = b.props.clone();
|
||||
let base = a.runs.first().map(|r| r.props.clone()).unwrap_or_default();
|
||||
// The revised paragraph's properties are used with its revision bookkeeping stripped, like runs
|
||||
// (`SideProps::props_of`) and the mark, because `fmt_change`/`num_change` are indices into the revised
|
||||
// document's own revision table and are meaningless in the result document. A plain-text
|
||||
// revised side, which carries no paragraph properties of its own, falls back to the original's,
|
||||
// stripped the same way, so pre-existing revision state never leaks into the rebuilt paragraph.
|
||||
p.props = if plain_revised && b.props.is_empty() { a.props.formatting() } else { b.props.formatting() };
|
||||
// The paragraph mark (the formatting typing into the paragraph's end would get) is the revised
|
||||
// paragraph's when it comes from a document, and the original's when the revised side is plain
|
||||
// text and has no mark of its own. Its own revision bookkeeping (`ins`, `del`, `fmt_change`)
|
||||
// is cleared because those indices belong to another document's revision table.
|
||||
p.mark = if plain_revised {
|
||||
CharProps { ins: None, del: None, fmt_change: None, ..a.mark.clone() }
|
||||
} else {
|
||||
CharProps { ins: None, del: None, fmt_change: None, ..b.mark.clone() }
|
||||
};
|
||||
let fallback = a.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default();
|
||||
let fallback_b = b.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default();
|
||||
let (mut i, mut j) = (0, 0);
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Same => {
|
||||
// Equal as compared (perhaps up to case or spacing): the revised text.
|
||||
put(&mut p, tb.get(j), &base);
|
||||
// Equal as compared (perhaps up to case or spacing): the revised text, but the
|
||||
// formatting of the run it stands for. For a document revised side that is the
|
||||
// revised run, as issue #3749 prescribes ("Copy unchanged tokens from the revised
|
||||
// paragraph with their own properties"); a plain-text revised side has no runs to
|
||||
// speak of, so the original run's formatting is kept instead.
|
||||
let props =
|
||||
if plain_revised { output_props(&mut a_props, ta.get(i), &fallback) } else { output_props(&mut b_props, tb.get(j), &fallback_b) };
|
||||
put(&mut p, tb.get(j), &props);
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
Op::Del => {
|
||||
put(&mut p, ta.get(i), &CharProps { del: Some(ctx.del), ..base.clone() });
|
||||
let props = output_props(&mut a_props, ta.get(i), &fallback);
|
||||
put(&mut p, ta.get(i), &CharProps { del: Some(ctx.del), ..props });
|
||||
i += 1;
|
||||
}
|
||||
Op::Ins => {
|
||||
put(&mut p, tb.get(j), &CharProps { ins: Some(ctx.ins), ..base.clone() });
|
||||
let props = tb.get(j).map(|t| b_props.props_of(t)).unwrap_or_else(|| fallback.clone());
|
||||
put(&mut p, tb.get(j), &CharProps { ins: Some(ctx.ins), ..props });
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,7 +340,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.params(r#"{"format": "decimal|upperRoman|lowerLetter…", "text"?: "%1.", "start"?: n}"#),
|
||||
CommandSpec::new("review.language", "Language", "Review › Language", language).params(
|
||||
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents)}"#,
|
||||
r#"{"lang"?: "en-US|en-GB|pl-PL|fr-FR|…" (BCP 47; default en-US), "noProof"?: bool, "detect"?: bool (detect language automatically, a preference), "default"?: bool (also the document's default and the saved language for future blank documents), "scope"?: "selection" (default) | "document" (every run and paragraph mark of every story: body, headers, footers, notes, comments, text boxes, tables, glossary (skipped while Track Changes and Track Formatting are on); one undo step, selection unchanged; returns the caret, "scope":"document" and "glossarySkipped":true when the glossary was skipped)}"#,
|
||||
),
|
||||
CommandSpec::new("review.language.preferred", "Set as Default Language", "File › Options › Language", preferred_language)
|
||||
.params(r#"{"lang": "en-US|en-GB|pl-PL|nl-NL|…" (BCP 47)} — only the saved default proofing language, what future blank documents are written in, as Options › Language › Set as default does; the open document, the selection and the undo history don't change. Returns {"preferred": tag}."#)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use super::*;
|
||||
|
||||
mod compare_stage0;
|
||||
|
||||
#[test]
|
||||
fn compare_marks_changes() {
|
||||
let mut s = Session::new(Document::from_text("The cat sat.\nKeep this.\nOld line."));
|
||||
@@ -903,3 +905,150 @@ fn inspect_removals_work_when_the_document_does_not_track_changes() {
|
||||
assert!(!text.contains("Hidden"), "the hidden text is still there: {text}");
|
||||
assert!(text.contains("Visible text."), "{text}");
|
||||
}
|
||||
|
||||
/// #3518: every run and paragraph mark of a story, as (story, path, lang, noProof) rows.
|
||||
fn proofing_rows(s: &Session) -> Vec<(StoryRef, Option<String>, Option<bool>)> {
|
||||
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
|
||||
let mut out = Vec::new();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st) {
|
||||
let Some(p) = s.doc.para(st, &path) else { continue };
|
||||
out.push((st, p.mark.lang.clone(), p.mark.no_proof));
|
||||
out.extend(p.runs.iter().map(|r| (st, r.props.lang.clone(), r.props.no_proof)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A document with its text in German in the body, a table cell, a header, a footnote, a comment
|
||||
/// and a text box, as a Word DOCX keeps a `w:lang` on each run, plus a glossary entry.
|
||||
fn multi_story_doc() -> Session {
|
||||
use wordcraft_doc::{Block, BuildingBlock, CharProps, Paragraph, PartKind, Table};
|
||||
let de = || CharProps { lang: Some("de-DE".into()), ..Default::default() };
|
||||
let blk = |t: &str| Arc::new(Block::Para(Paragraph::with_text(t, de())));
|
||||
let mut d = Document::from_text("Guten Tag");
|
||||
d.body = vec![blk("Guten Tag")];
|
||||
let mut t = Table::new(1, 2, 200.0);
|
||||
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
|
||||
c.blocks = vec![blk("Zelle")];
|
||||
}
|
||||
d.body.push(Arc::new(Block::Table(t)));
|
||||
d.body.push(blk("Ende"));
|
||||
for kind in [PartKind::Header, PartKind::Footnote, PartKind::Comment, PartKind::TextBox] {
|
||||
d.add_part(kind, vec![blk("Teil")]);
|
||||
}
|
||||
d.glossary.push(BuildingBlock { name: "g".into(), blocks: vec![blk("Baustein")], ..Default::default() });
|
||||
Session::new(d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_document_sets_every_story() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
let (sel, before) = (s.sel.clone(), s.doc.clone());
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.len() >= 10 && rows.iter().any(|r| r.1.as_deref() == Some("de-DE")));
|
||||
s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
// Runs that had their own language, the paragraph marks and the empty cell: all French.
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.iter().all(|r| r.1.as_deref() == Some("fr-FR")), "{rows:?}");
|
||||
for kind_story in s.doc.parts.keys() {
|
||||
assert!(rows.iter().any(|r| r.0 == StoryRef::Part(*kind_story)));
|
||||
}
|
||||
assert!(s.doc.plain_text(StoryRef::Body).contains("Zelle"));
|
||||
let g = &s.doc.glossary[0].blocks;
|
||||
assert_eq!(g[0].as_para().map(|p| p.runs[0].props.lang.clone()), Some(Some("fr-FR".into())));
|
||||
assert_eq!(g[0].as_para().map(|p| p.mark.lang.clone()), Some(Some("fr-FR".into())));
|
||||
// The selection stays; the document is modified.
|
||||
assert_eq!(s.sel, sel);
|
||||
assert!(s.doc != before);
|
||||
// One undo restores everything.
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc == before);
|
||||
assert_eq!(s.sel, sel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_scope_document_no_proof_and_pending() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.language", &json!({"noProof": true, "scope": "document"})).unwrap();
|
||||
assert!(proofing_rows(&s).iter().all(|r| r.2 == Some(true)));
|
||||
// The language itself wasn't asked for and stays.
|
||||
assert!(proofing_rows(&s).iter().any(|r| r.1.as_deref() == Some("de-DE")));
|
||||
// Formatting waiting for typing follows.
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "pl-PL", "scope": "document"})).unwrap();
|
||||
assert_eq!(s.pending.as_ref().and_then(|p| p.lang.as_deref()), Some("pl-PL"));
|
||||
}
|
||||
|
||||
/// Document scope returns the caret/selection like the selection path, plus the scope.
|
||||
#[test]
|
||||
fn language_scope_document_returns_the_selection_result() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert_eq!(out["scope"], "document");
|
||||
assert_eq!(out["anchor"], crate::cmd::pos_json(&s.sel.anchor), "{out}");
|
||||
assert_eq!(out["focus"], crate::cmd::pos_json(&s.sel.focus), "{out}");
|
||||
}
|
||||
|
||||
/// Tracked formatting records only the body and parts, so while it is on the glossary (outside
|
||||
/// any story) is left alone instead of changing untracked; with tracking off it changes.
|
||||
#[test]
|
||||
fn language_scope_document_skips_glossary_while_tracking_formatting() {
|
||||
let gloss = |s: &Session| s.doc.glossary[0].blocks[0].as_para().map(|p| (p.runs[0].props.lang.clone(), p.mark.lang.clone()));
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackFormatting": true})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert_eq!(out["glossarySkipped"], true, "{out}");
|
||||
assert_eq!(gloss(&s), Some((Some("de-DE".into()), Some("de-DE".into()))));
|
||||
assert!(proofing_rows(&s).iter().all(|r| r.1.as_deref() == Some("fr-FR")));
|
||||
assert!(s.doc.revisions.iter().any(|r| r.kind == wordcraft_doc::RevisionKind::Format), "the body change is tracked");
|
||||
let mut s = multi_story_doc();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("review.trackingOptions", &json!({"trackFormatting": false})).unwrap();
|
||||
let out = s.run("review.language", &json!({"lang": "fr-FR", "scope": "document"})).unwrap();
|
||||
assert!(out.get("glossarySkipped").is_none(), "{out}");
|
||||
assert_eq!(gloss(&s), Some((Some("fr-FR".into()), Some("fr-FR".into()))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_default_scope_is_selection_only() {
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "fr-FR"})).unwrap();
|
||||
let rows = proofing_rows(&s);
|
||||
assert!(rows.iter().any(|r| r.1.as_deref() == Some("fr-FR")));
|
||||
assert!(rows.iter().filter(|r| r.1.as_deref() == Some("fr-FR")).count() < rows.len() / 2);
|
||||
let mut s = multi_story_doc();
|
||||
s.run("select.text", &json!({"text": "Guten"})).unwrap();
|
||||
s.run("review.language", &json!({"lang": "fr-FR", "scope": "selection"})).unwrap();
|
||||
assert_eq!(proofing_rows(&s), rows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_bad_scope_is_a_params_error() {
|
||||
let mut s = multi_story_doc();
|
||||
let before = s.doc.clone();
|
||||
for bad in [json!("everything"), json!(1), json!(true), json!(["document"])] {
|
||||
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": bad})).unwrap_err();
|
||||
assert!(matches!(e, CmdError::Params(_)), "{e:?}");
|
||||
}
|
||||
assert!(s.doc == before);
|
||||
assert!(s.prefs.detect_language);
|
||||
}
|
||||
|
||||
/// Document scope is refused under editing protection, before anything changes.
|
||||
#[test]
|
||||
fn language_document_scope_is_refused_under_protection() {
|
||||
for mode in ["readOnly", "comments", "forms"] {
|
||||
let mut s = multi_story_doc();
|
||||
s.doc.settings.protection = Some(mode.into());
|
||||
let before = s.doc.clone();
|
||||
let e = s.run("review.language", &json!({"lang": "fr-FR", "detect": false, "scope": "document"})).unwrap_err();
|
||||
assert!(matches!(e, CmdError::Disabled(_)), "{mode}: {e:?}");
|
||||
assert!(s.doc == before, "{mode}: nothing changed");
|
||||
assert!(s.prefs.detect_language, "{mode}: the detect preference is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
//! Regression tests for #3749 Stage 0: formatting-preserving compare.
|
||||
//!
|
||||
//! `word_diff` carries source byte ranges through tokenization, so every output segment takes its
|
||||
//! `CharProps` from the run it came from instead of stamping the original paragraph's first run on
|
||||
//! everything. The revised side decides which run each segment follows: when the revised side is a
|
||||
//! real document, Same/Ins take the revised run and Del takes the original run; when it is plain
|
||||
//! text (with no runs of its own), Same/Del take the original run and Ins takes the (default)
|
||||
//! revised run. The paragraph mark and `ParaProps` follow the revised side for a document, and fall
|
||||
//! back to the original's for plain text.
|
||||
//!
|
||||
//! The ins/del segmentation for text-only paragraphs is unchanged: the goldens below were captured
|
||||
//! from the pre-fix binary (`review.compare` over a plain original and a plain revised text, word
|
||||
//! and character level) and must keep matching.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A run signature: its text, and whether it is marked inserted / deleted.
|
||||
fn run_sig(p: &Paragraph) -> Vec<(String, bool, bool)> {
|
||||
p.run_ranges().map(|(r, c)| (p.text[r].to_string(), c.ins.is_some(), c.del.is_some())).collect()
|
||||
}
|
||||
|
||||
/// The first run whose text contains `needle`.
|
||||
fn run_with<'a>(p: &'a Paragraph, needle: &str) -> (&'a str, &'a CharProps) {
|
||||
p.run_ranges()
|
||||
.find(|(r, _)| p.text[r.clone()].contains(needle))
|
||||
.map(|(r, c)| (&p.text[r], c))
|
||||
.unwrap_or_else(|| panic!("no run contains {needle:?} in {:?}", p.text))
|
||||
}
|
||||
|
||||
// --- mixed character formatting -----------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn mixed_formatting_is_preserved_per_range() {
|
||||
let mut s = Session::new(Document::from_text("alpha beta gamma"));
|
||||
s.run("select.text", &json!({"text": "alpha"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("select.text", &json!({"text": "gamma"})).unwrap();
|
||||
s.run("format.italic", &json!({})).unwrap();
|
||||
s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
// The deleted text stays in the tracked paragraph; the visible result is what Accept shows.
|
||||
assert_eq!(p.plain_text(), "alpha beta delta gamma");
|
||||
assert_eq!(p.final_text(), "alpha delta gamma");
|
||||
let (_, alpha) = run_with(p, "alpha");
|
||||
assert_eq!(alpha.bold, Some(true), "unchanged `alpha` keeps the original's bold");
|
||||
assert_ne!(alpha.italic, Some(true));
|
||||
let (_, gamma) = run_with(p, "gamma");
|
||||
assert_eq!(gamma.italic, Some(true), "unchanged `gamma` keeps the original's italic");
|
||||
assert_ne!(gamma.bold, Some(true));
|
||||
let (_, delta) = run_with(p, "delta");
|
||||
assert!(delta.ins.is_some(), "inserted `delta` is marked inserted");
|
||||
assert_ne!(delta.bold, Some(true), "inserted text does not inherit the original's bold");
|
||||
assert_ne!(delta.italic, Some(true), "inserted text does not inherit the original's italic");
|
||||
let (_, beta) = run_with(p, "beta");
|
||||
assert!(beta.del.is_some(), "removed `beta` is marked deleted");
|
||||
assert_ne!(beta.bold, Some(true));
|
||||
}
|
||||
|
||||
// --- byte-range props lookup --------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn change_point_on_a_multibyte_char_takes_its_own_run() {
|
||||
// The change point is the second character, `ä` (2 bytes). The byte-range lookup must land on
|
||||
// `ä`'s own run; a character count used as a byte offset would land inside the preceding `é`
|
||||
// and stamp its bold on the deleted `ä`.
|
||||
let mut s = Session::new(Document::from_text("éä"));
|
||||
s.run("select.text", &json!({"text": "é"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("select.text", &json!({"text": "ä"})).unwrap();
|
||||
s.run("format.italic", &json!({})).unwrap();
|
||||
s.run("review.compare", &json!({"text": "éö", "level": "character"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.plain_text(), "éäö", "deleted `ä` and inserted `ö`");
|
||||
let (_, ae) = run_with(p, "ä");
|
||||
assert!(ae.del.is_some(), "the changed multi-byte char is deleted");
|
||||
assert_eq!(ae.italic, Some(true), "it takes its own run");
|
||||
assert_ne!(ae.bold, Some(true), "and not the preceding multi-byte run's props");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_run_at_a_token_start_does_not_shadow_its_props() {
|
||||
let mut s = Session::new(Document::from_text("alpha beta gamma"));
|
||||
s.run("select.text", &json!({"text": "beta"})).unwrap();
|
||||
s.run("format.italic", &json!({})).unwrap();
|
||||
{
|
||||
let mut p = s.doc.body[0].as_para().unwrap().clone();
|
||||
let at = p.text.find("beta").unwrap();
|
||||
let mut idx = 0usize;
|
||||
let mut start = 0usize;
|
||||
for (i, r) in p.runs.iter().enumerate() {
|
||||
if start == at {
|
||||
idx = i;
|
||||
break;
|
||||
}
|
||||
start += r.len;
|
||||
}
|
||||
// An empty run with different props exactly at "beta"'s start.
|
||||
p.runs.insert(idx, wordcraft_doc::para::Run { len: 0, props: CharProps { bold: Some(true), ..CharProps::default() } });
|
||||
s.doc.body[0] = std::sync::Arc::new(Block::Para(p));
|
||||
}
|
||||
s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, beta) = run_with(p, "beta");
|
||||
assert!(beta.del.is_some());
|
||||
assert_eq!(beta.italic, Some(true), "the token takes the run after the empty one");
|
||||
assert_ne!(beta.bold, Some(true), "an empty run at the token's start must not shadow the next run's props");
|
||||
}
|
||||
|
||||
// --- hyperlinks ---------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn middle_run_hyperlink_survives_and_reject_restores_it() {
|
||||
let mut s = Session::new(Document::from_text("click here now"));
|
||||
s.run("select.text", &json!({"text": "here"})).unwrap();
|
||||
s.run("insert.link", &json!({"url": "https://example.com"})).unwrap();
|
||||
s.run("review.compare", &json!({"text": "click there now"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, here) = run_with(p, "here");
|
||||
assert!(here.del.is_some(), "the removed word is deleted");
|
||||
assert_eq!(here.link.as_deref(), Some("https://example.com"), "the deleted run keeps its hyperlink");
|
||||
let (_, there) = run_with(p, "there");
|
||||
assert!(there.ins.is_some());
|
||||
assert_eq!(there.link, None, "inserted text takes the revised run's formatting (no link)");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "click here now");
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, here) = run_with(p, "here");
|
||||
assert_eq!(here.link.as_deref(), Some("https://example.com"), "Reject restores the hyperlink at token level");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_run_hyperlink_does_not_leak_onto_inserted_text() {
|
||||
let mut s = Session::new(Document::from_text("here click now"));
|
||||
s.run("select.text", &json!({"text": "here"})).unwrap();
|
||||
s.run("insert.link", &json!({"url": "https://example.com"})).unwrap();
|
||||
s.run("review.compare", &json!({"text": "here there click now"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, here) = run_with(p, "here");
|
||||
assert_eq!(here.link.as_deref(), Some("https://example.com"), "the unchanged first run keeps its link");
|
||||
let (_, there) = run_with(p, "there");
|
||||
assert!(there.ins.is_some());
|
||||
assert_eq!(there.link, None, "the first run's link must not leak onto inserted text");
|
||||
}
|
||||
|
||||
// --- reject restores formatting -----------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn deleted_segment_keeps_formatting_so_reject_restores_it() {
|
||||
let mut s = Session::new(Document::from_text("alpha beta gamma"));
|
||||
s.run("select.text", &json!({"text": "alpha"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("select.text", &json!({"text": "beta"})).unwrap();
|
||||
s.run("format.italic", &json!({})).unwrap();
|
||||
s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "alpha beta gamma");
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, alpha) = run_with(p, "alpha");
|
||||
assert_eq!(alpha.bold, Some(true));
|
||||
let (_, beta) = run_with(p, "beta");
|
||||
assert_eq!(beta.italic, Some(true), "the deleted token kept its italic, so Reject restores it at token level");
|
||||
}
|
||||
|
||||
// --- text-only segmentation identity (goldens from the pre-fix binary) --------------------------
|
||||
|
||||
#[test]
|
||||
fn text_only_segmentation_matches_pre_fix_golden() {
|
||||
// (original, revised, level, expected (text, ins, del) runs)
|
||||
let cases: &[(&str, &str, &str, &[(&str, bool, bool)])] = &[
|
||||
("The dog sat.", "The cat sat.", "word", &[("The ", false, false), ("dog ", false, true), ("cat ", true, false), ("sat.", false, false)]),
|
||||
("a cat ran", "a dog ran", "word", &[("a ", false, false), ("cat ", false, true), ("dog ", true, false), ("ran", false, false)]),
|
||||
("colour", "color", "word", &[("colour", false, true), ("color", true, false)]),
|
||||
(
|
||||
"zawarta w dniu 01.09.2026 pomiędzy:",
|
||||
"zawarta w dniu 19.10.2026 pomiędzy:",
|
||||
"word",
|
||||
&[("zawarta w dniu ", false, false), ("01.09.2026 ", false, true), ("19.10.2026 ", true, false), ("pomiędzy:", false, false)],
|
||||
),
|
||||
("The dog sat.", "The cat sat.", "character", &[("The ", false, false), ("dog", false, true), ("cat", true, false), (" sat.", false, false)]),
|
||||
("a cat ran", "a dog ran", "character", &[("a ", false, false), ("cat", false, true), ("dog", true, false), (" ran", false, false)]),
|
||||
("colour", "color", "character", &[("colo", false, false), ("u", false, true), ("r", false, false)]),
|
||||
(
|
||||
"zawarta w dniu 01.09.2026 pomiędzy:",
|
||||
"zawarta w dniu 19.10.2026 pomiędzy:",
|
||||
"character",
|
||||
&[("zawarta w dniu ", false, false), ("01.09", false, true), ("19.10", true, false), (".2026 pomiędzy:", false, false)],
|
||||
),
|
||||
];
|
||||
for (orig, rev, level, want) in cases {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": rev, "level": level})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let want: Vec<(String, bool, bool)> = want.iter().map(|(t, i, d)| ((*t).to_string(), *i, *d)).collect();
|
||||
assert_eq!(run_sig(p), want, "{orig:?} -> {rev:?} [{level}]");
|
||||
}
|
||||
}
|
||||
|
||||
// --- paragraph mark and paragraph properties ----------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn paragraph_mark_is_preserved() {
|
||||
let mut s = Session::new(Document::from_text("alpha beta gamma"));
|
||||
{
|
||||
let mut p = s.doc.body[0].as_para().unwrap().clone();
|
||||
p.mark.bold = Some(true);
|
||||
s.doc.body[0] = std::sync::Arc::new(Block::Para(p));
|
||||
}
|
||||
s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.mark.bold, Some(true), "the rebuilt paragraph keeps the original paragraph mark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_props_kept_when_revised_is_plain() {
|
||||
let mut s = Session::new(Document::from_text("alpha beta gamma"));
|
||||
s.run("para.style", &json!({"style": "Heading1"})).unwrap();
|
||||
s.run("para.alignCenter", &json!({})).unwrap();
|
||||
s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.props.style.as_deref(), Some("Heading1"), "the original style survives a plain revised side");
|
||||
assert!(p.props.align.is_some(), "the original alignment survives a plain revised side");
|
||||
}
|
||||
|
||||
// --- object pass-through (not flattened away by the rebuild) -------------------------------------
|
||||
|
||||
/// A session whose single paragraph is `alpha beta gamma` with a picture after "beta ", already
|
||||
/// compared against `alpha delta gamma`: the picture's anchor sits in a deleted run.
|
||||
fn compared_with_picture() -> Session {
|
||||
let mut s = Session::new(Document::from_text("alpha beta gamma"));
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, "alpha beta ".len())})).unwrap();
|
||||
let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
|
||||
s.run("insert.picture", &json!({"data": png})).unwrap();
|
||||
assert_eq!(s.doc.body[0].as_para().unwrap().objects.len(), 1, "the picture was inserted");
|
||||
s.run("review.compare", &json!({"text": "alpha delta gamma"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_anchor_survives_a_changed_paragraph() {
|
||||
let s = compared_with_picture();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.objects.len(), 1, "the changed paragraph's picture anchor survives the rebuild");
|
||||
let off = p.object_offsets().first().copied().expect("the picture anchor is in the text");
|
||||
assert!(p.props_of_char(off).del.is_some(), "the picture anchor sits in a deleted run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_removes_the_deleted_picture_and_rejecting_restores_it() {
|
||||
let mut accepted = compared_with_picture();
|
||||
accepted.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(accepted.doc.body[0].as_para().unwrap().objects.len(), 0, "accepting the deletion removes the picture");
|
||||
|
||||
let mut rejected = compared_with_picture();
|
||||
rejected.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(rejected.doc.body[0].as_para().unwrap().objects.len(), 1, "rejecting the deletion restores the picture");
|
||||
}
|
||||
|
||||
// --- document revised side: unchanged tokens follow the revised formatting (#3749) --------------
|
||||
|
||||
#[test]
|
||||
fn unchanged_word_takes_the_revised_formatting_document_path() {
|
||||
let rev = Session::new(Document::from_text("Read the manual now."));
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-s0-rev-bold-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev.doc).unwrap();
|
||||
|
||||
let mut s = Session::new(Document::from_text("Read the manual today."));
|
||||
s.run("select.text", &json!({"text": "manual"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, manual) = run_with(p, "manual");
|
||||
assert_ne!(manual.bold, Some(true), "the unchanged word takes the revised side's formatting, not the original's bold");
|
||||
let (_, today) = run_with(p, "today.");
|
||||
assert!(today.del.is_some(), "the removed word is deleted");
|
||||
let (_, now) = run_with(p, "now.");
|
||||
assert!(now.ins.is_some(), "the added word is inserted");
|
||||
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.plain_text(), "Read the manual now.");
|
||||
let (_, manual) = run_with(p, "manual");
|
||||
assert_ne!(manual.bold, Some(true), "accepting leaves the revised (unbolded) formatting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_style_change_is_not_masked_document_path() {
|
||||
let rev = Session::new(Document::from_text("Introduction to X"));
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-s0-style-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev.doc).unwrap();
|
||||
|
||||
let mut s = Session::new(Document::from_text("Introduction"));
|
||||
s.run("para.style", &json!({"style": "Heading1"})).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy(), "level": "character"})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_ne!(p.props.style.as_deref(), Some("Heading1"), "the revised paragraph's empty properties win, so the style change isn't masked");
|
||||
assert!(p.run_ranges().any(|(_, c)| c.ins.is_some()), "the text was diffed, not wholesale replaced");
|
||||
let (_, intro) = run_with(p, "Introduction");
|
||||
assert!(intro.ins.is_none() && intro.del.is_none(), "the unchanged text survives unmarked");
|
||||
let (_, added) = run_with(p, " to X");
|
||||
assert!(added.ins.is_some(), "only the added text is insertion-marked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_word_gains_the_revised_formatting_document_path() {
|
||||
let mut rev = Session::new(Document::from_text("Read the manual now."));
|
||||
rev.run("select.text", &json!({"text": "manual"})).unwrap();
|
||||
rev.run("format.bold", &json!({})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-s0-rev-gains-bold-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev.doc).unwrap();
|
||||
|
||||
let mut s = Session::new(Document::from_text("Read the manual today."));
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, manual) = run_with(p, "manual");
|
||||
assert_eq!(manual.bold, Some(true), "the unchanged word takes the revised side's bold");
|
||||
let (_, today) = run_with(p, "today.");
|
||||
assert!(today.del.is_some(), "the removed word is deleted");
|
||||
let (_, now) = run_with(p, "now.");
|
||||
assert!(now.ins.is_some(), "the added word is inserted");
|
||||
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
assert_eq!(p.plain_text(), "Read the manual now.");
|
||||
let (_, manual) = run_with(p, "manual");
|
||||
assert_eq!(manual.bold, Some(true), "accepting leaves the revised (bolded) formatting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_hyperlink_on_an_unchanged_word_follows_the_revised_side_document_path() {
|
||||
let rev = Session::new(Document::from_text("Read the manual now."));
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-s0-link-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev.doc).unwrap();
|
||||
|
||||
let mut s = Session::new(Document::from_text("Read the manual today."));
|
||||
s.run("select.text", &json!({"text": "manual"})).unwrap();
|
||||
s.run("insert.link", &json!({"url": "https://example.com"})).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
let p = s.doc.body[0].as_para().unwrap();
|
||||
let (_, manual) = run_with(p, "manual");
|
||||
assert_eq!(manual.link, None, "the unchanged word takes the revised side's run, which dropped the link");
|
||||
}
|
||||
@@ -464,7 +464,7 @@ pub fn save_bytes_opts(name: &str, doc: &Document, opts: &ExportOptions) -> Resu
|
||||
}
|
||||
|
||||
/// [`save_bytes`], encrypted with `password` when there is one and the format is a Word package
|
||||
/// (other formats are copies and are written as they are).
|
||||
/// or OpenDocument text file (.odt, .ott); other formats are copies and are written as they are.
|
||||
pub fn save_bytes_with(name: &str, doc: &Document, password: Option<&str>, opts: &ExportOptions) -> Result<Vec<u8>, String> {
|
||||
let bytes = save_bytes_opts(name, doc, opts)?;
|
||||
match password {
|
||||
|
||||
@@ -16,10 +16,11 @@ pub fn open(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Opti
|
||||
// that state no size.
|
||||
other => wordcraft_formats::import_on(other, bytes, page).map(|r| {
|
||||
r.map(|mut doc| {
|
||||
if !matches!(other, "odt" | "ott" | "fodt") {
|
||||
let odf = matches!(other, "odt" | "ott" | "fodt");
|
||||
if !odf {
|
||||
crate::io::fit_pictures(&mut doc);
|
||||
}
|
||||
draw_charts(&mut doc);
|
||||
draw_charts(&mut doc, odf);
|
||||
doc
|
||||
})
|
||||
}),
|
||||
@@ -27,8 +28,9 @@ pub fn open(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Opti
|
||||
}
|
||||
|
||||
/// Draw the charts a reader left undrawn (ODT charts come as their chart model alone): in the
|
||||
/// document's theme colours, at their size.
|
||||
fn draw_charts(doc: &mut Document) {
|
||||
/// document's theme colours, at their size. With `odf`, scatter series are set to markers without
|
||||
/// a line first (see `markers_only_scatter`).
|
||||
pub(crate) fn draw_charts(doc: &mut Document, odf: bool) {
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
/// Groups nest at most this deep here (the readers flatten deeper ones).
|
||||
const DEPTH: usize = 16;
|
||||
@@ -39,16 +41,41 @@ fn draw_charts(doc: &mut Document) {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn draw(o: &mut InlineObject, theme: &[wordcraft_doc::Rgb], depth: usize) {
|
||||
fn draw(o: &mut InlineObject, theme: &[wordcraft_doc::Rgb], odf: bool, depth: usize) {
|
||||
match o {
|
||||
InlineObject::Group { children, .. } if depth < DEPTH => children.iter_mut().for_each(|c| draw(&mut c.obj, theme, depth + 1)),
|
||||
o if undrawn(o, depth) => crate::cmd::chart::redraw(o, theme),
|
||||
InlineObject::Group { children, .. } if depth < DEPTH => children.iter_mut().for_each(|c| draw(&mut c.obj, theme, odf, depth + 1)),
|
||||
o if undrawn(o, depth) => {
|
||||
if odf {
|
||||
markers_only_scatter(o);
|
||||
}
|
||||
crate::cmd::chart::redraw(o, theme)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// The ODF reader does not read a scatter chart's line setting, so every scatter series of an
|
||||
// opened ODF file is set to markers without a line, as the ODF writer writes them. A series
|
||||
// with its markers turned off gets them back, as Change Chart Type does, so it is still drawn.
|
||||
fn markers_only_scatter(o: &mut InlineObject) {
|
||||
if let InlineObject::Graphic { graphic, .. } = o
|
||||
&& let Some(spec) = graphic.chart.as_deref()
|
||||
&& spec.kind == wordcraft_doc::chart::ChartType::Scatter
|
||||
&& spec.series.iter().any(|s| !s.no_line || s.markers == Some(false))
|
||||
{
|
||||
let mut spec = spec.clone();
|
||||
for series in &mut spec.series {
|
||||
series.no_line = true;
|
||||
if series.markers == Some(false) {
|
||||
series.markers = None;
|
||||
}
|
||||
}
|
||||
std::sync::Arc::make_mut(graphic).chart = Some(std::sync::Arc::new(spec));
|
||||
}
|
||||
}
|
||||
let theme = doc.settings.theme_colors.clone();
|
||||
// (Drawing them doesn't change the document: markup kept as read for them still is.)
|
||||
doc.fill_objects(&|o| undrawn(o, 0), &mut |o| draw(o, &theme, 0));
|
||||
// (Markup kept as read for these charts is still written as read after they are drawn,
|
||||
// scatter charts included.)
|
||||
doc.fill_objects(&|o| undrawn(o, 0), &mut |o| draw(o, &theme, odf, 0));
|
||||
}
|
||||
|
||||
/// Save to a format other than plain text / JSON.
|
||||
|
||||
@@ -39,7 +39,7 @@ pub struct Prefs {
|
||||
pub region: Option<String>,
|
||||
/// A folder searched for Hunspell dictionaries before the system locations (File › Options ›
|
||||
/// Language, #1063): an app started from Finder or the Dock doesn't see
|
||||
/// `WORDCRAFT_DICTIONARIES`. `None` searches the system locations only.
|
||||
/// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder.
|
||||
pub dictionaries_folder: Option<String>,
|
||||
/// The user templates folder File › New lists personal templates from and Save as Word
|
||||
/// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's
|
||||
|
||||
@@ -15,6 +15,9 @@ const MAX_FILES: usize = 16;
|
||||
const DISK_BUDGET: u64 = 2 << 30;
|
||||
/// Times a record lock held for a moment (by a process being started) is tried again.
|
||||
const LOCK_RETRIES: u32 = 10;
|
||||
/// How many times, 10 ms apart, a record's emptied folder is removed again while it isn't empty
|
||||
/// yet ([`remove_record_dir`]).
|
||||
const REMOVE_RETRIES: u32 = 100;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -347,11 +350,25 @@ impl Store {
|
||||
self.entries.remove(id);
|
||||
self.locks.remove(id);
|
||||
fs::remove_file(dir.join("owner.lock")).map_err(|e| e.to_string())?;
|
||||
fs::remove_dir(&dir).map_err(|e| e.to_string())?;
|
||||
remove_record_dir(&dir, |d| fs::remove_dir(d)).map_err(|e| e.to_string())?;
|
||||
sync_dir(&self.root).map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Removes a record's emptied folder `dir` with `remove`. On Windows a file just deleted stays in
|
||||
/// its folder, pending deletion, while another process still has it open (an antivirus scanner
|
||||
/// or a search indexer looking at a file just written), so the folder isn't empty yet and
|
||||
/// removing it fails ("The directory is not empty", os error 145): wait that out, retrying
|
||||
/// [`REMOVE_RETRIES`] times 10 ms apart, as [`Store::lock`] waits out a lock held for a moment.
|
||||
fn remove_record_dir(dir: &Path, mut remove: impl FnMut(&Path) -> io::Result<()>) -> io::Result<()> {
|
||||
for _ in 0..REMOVE_RETRIES {
|
||||
match remove(dir) {
|
||||
Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => std::thread::sleep(Duration::from_millis(10)),
|
||||
done => return done,
|
||||
}
|
||||
}
|
||||
remove(dir)
|
||||
}
|
||||
struct Limited<W> {
|
||||
inner: W,
|
||||
remaining: u64,
|
||||
|
||||
@@ -619,3 +619,37 @@ fn finish_recovery_covers_every_open_document() {
|
||||
s.finish_recovery();
|
||||
assert_eq!(records(&t.0), [dirty]);
|
||||
}
|
||||
|
||||
/// Removing a record's emptied folder waits out a file Windows hasn't finished deleting (another
|
||||
/// process, such as an antivirus scanner, still has it open, so the folder isn't empty yet: os
|
||||
/// error 145), which made saving with a password, and discarding a closed document's copy, fail
|
||||
/// now and then. It doesn't wait on other errors, nor forever.
|
||||
#[test]
|
||||
fn removing_a_record_folder_waits_for_files_still_being_deleted() {
|
||||
let not_empty = || io::Error::from(io::ErrorKind::DirectoryNotEmpty);
|
||||
let mut pending = 3;
|
||||
let removed = remove_record_dir(Path::new("record"), |_| {
|
||||
if pending > 0 {
|
||||
pending -= 1;
|
||||
Err(not_empty())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
assert!(removed.is_ok(), "{removed:?}");
|
||||
assert_eq!(pending, 0);
|
||||
let mut calls = 0;
|
||||
let stuck = remove_record_dir(Path::new("record"), |_| {
|
||||
calls += 1;
|
||||
Err(not_empty())
|
||||
});
|
||||
assert_eq!(stuck.map_err(|e| e.kind()), Err(io::ErrorKind::DirectoryNotEmpty));
|
||||
assert_eq!(calls, REMOVE_RETRIES + 1);
|
||||
let mut calls = 0;
|
||||
let denied = remove_record_dir(Path::new("record"), |_| {
|
||||
calls += 1;
|
||||
Err(io::Error::from(io::ErrorKind::PermissionDenied))
|
||||
});
|
||||
assert_eq!(denied.map_err(|e| e.kind()), Err(io::ErrorKind::PermissionDenied));
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
|
||||
@@ -88,6 +88,10 @@ pub struct Session {
|
||||
pub initials: String,
|
||||
/// Format painter: copied formatting waiting to be applied (and whether it stays on).
|
||||
pub painter: Option<(CharProps, wordcraft_doc::props::ParaProps, bool)>,
|
||||
/// Formatting picked up by Copy Formatting (Mod+Shift+C): Paste Formatting applies it as often
|
||||
/// as asked, as in Word, until the next Copy Formatting. A Format Painter pick is stored here
|
||||
/// as well.
|
||||
pub copied_format: Option<(CharProps, wordcraft_doc::props::ParaProps)>,
|
||||
/// Last message for the status bar / agents.
|
||||
pub status: String,
|
||||
/// Headers/footers `insert.createHeader`/`insert.createFooter` made for a page that had none
|
||||
|
||||
@@ -259,6 +259,7 @@ impl Session {
|
||||
author: _,
|
||||
initials: _,
|
||||
painter: _,
|
||||
copied_format: _,
|
||||
// What the drawn window knows of the others: its front end sets it as it draws.
|
||||
windows: _,
|
||||
status: _,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl Session {
|
||||
author: "WordCraft User".into(),
|
||||
initials: String::new(),
|
||||
painter: None,
|
||||
copied_format: None,
|
||||
status: String::new(),
|
||||
new_header_parts,
|
||||
hf_return,
|
||||
|
||||
@@ -92,6 +92,7 @@ impl Session {
|
||||
author: _,
|
||||
initials: _,
|
||||
painter: _,
|
||||
copied_format: _,
|
||||
status: _,
|
||||
// Headers just created to edit: closing checks they still exist and are empty.
|
||||
new_header_parts: _,
|
||||
|
||||
@@ -5,6 +5,7 @@ mod czech_test_dict;
|
||||
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use wordcraft_doc::props::BorderStyle;
|
||||
use wordcraft_doc::{Pos, StoryRef};
|
||||
|
||||
@@ -17,6 +18,7 @@ mod fit_one_page;
|
||||
mod font_sizes;
|
||||
mod fonts;
|
||||
mod ime_noop;
|
||||
mod page_number_formats_in_lists;
|
||||
mod para_tools;
|
||||
mod revision_checks;
|
||||
mod typing;
|
||||
@@ -1108,6 +1110,26 @@ fn replace_under_track_changes_skips_deleted_text() {
|
||||
assert_eq!(text(&s), "one dog two dog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_reports_whether_it_replaced_and_what_it_selected() {
|
||||
// Replace follows Word's button: the first call only selects a match. Agents read
|
||||
// `remaining` alone as done (#6877), so the result says whether anything was replaced.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "alpha XX beta XX gamma XX"}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let calls: Vec<_> = (0..5).map(|_| run(&mut s, "edit.replace", json!({"text": "XX", "with": "YY"}))).collect();
|
||||
let replaced: Vec<_> = calls.iter().map(|r| r["replaced"].clone()).collect();
|
||||
assert_eq!(replaced, [json!(0), json!(1), json!(1), json!(1), json!(0)]);
|
||||
let remaining: Vec<_> = calls.iter().map(|r| r["remaining"].clone()).collect();
|
||||
assert_eq!(remaining, [json!(3), json!(2), json!(1), json!(0), json!(0)]);
|
||||
let selected: Vec<_> = calls.iter().map(|r| (r["selected"]["start"]["off"].clone(), r["selected"]["end"]["off"].clone())).collect();
|
||||
assert_eq!(selected[0], (json!(6), json!(8)));
|
||||
assert_eq!(selected[1], (json!(14), json!(16)));
|
||||
assert_eq!(selected[2], (json!(23), json!(25)));
|
||||
assert!(calls[3]["selected"].is_null() && calls[4]["selected"].is_null(), "no match is left to select");
|
||||
assert_eq!(text(&s), "alpha YY beta YY gamma YY");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_reads_the_text_around_tracked_deletions() {
|
||||
// `edits` are (start, end) byte ranges deleted with Track Changes on, last first.
|
||||
@@ -5164,6 +5186,74 @@ fn hostile_file_params_never_panic() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// Large parameters must return and lay out within a generous wall-clock budget, so a regression
|
||||
/// that loops or allocates without a cap fails here with its command id (#3720).
|
||||
#[test]
|
||||
fn hostile_large_params_stay_bounded() {
|
||||
const BUDGET: Duration = Duration::from_secs(5);
|
||||
let reg = cmd::registry();
|
||||
// 1 MiB makes an uncapped copy or a quadratic scan visible without making the test itself
|
||||
// expensive; the counts are large enough that an uncapped loop takes seconds.
|
||||
let big = "x".repeat(1 << 20);
|
||||
let mut deep = json!([]);
|
||||
for _ in 0..64 {
|
||||
deep = json!([deep]);
|
||||
}
|
||||
let junk = [
|
||||
json!({
|
||||
"text": big, "name": big, "label": big, "find": big, "replace": big,
|
||||
"title": big, "author": big, "path": big,
|
||||
}),
|
||||
json!({
|
||||
"count": 1_000_000_000u64, "copies": 1_000_000_000u64, "times": 1_000_000_000u64,
|
||||
"cols": 1_000_000_000u64, "rows": 1_000_000_000u64, "level": 1_000_000_000u64,
|
||||
"page": 1_000_000_000u64, "from": 1_000_000_000u64, "to": 1_000_000_000u64,
|
||||
"id": 1_000_000_000u64,
|
||||
}),
|
||||
json!({"width": 3e38, "height": 3e38, "top": -3e38, "left": 3e38}),
|
||||
json!({"path": deep}),
|
||||
];
|
||||
for spec in reg.all() {
|
||||
if spec.id.starts_with("file.") || spec.id == "insert.picture" || spec.id == "insert.textFromFile" {
|
||||
continue;
|
||||
}
|
||||
for j in &junk {
|
||||
let mut s = Session::new(crate::sample::sample_document());
|
||||
assert_ne!(s.read_aloud.backend, crate::speech::Backend::System, "tests must never start real speech");
|
||||
let start = Instant::now();
|
||||
let r = s.run(spec.id, j);
|
||||
let elapsed = start.elapsed();
|
||||
assert!(!caught_panic(®, &r), "{} panicked on large params: {r:?}", spec.id);
|
||||
assert_within_budget(spec.id, elapsed, BUDGET);
|
||||
// Laying the result out is not part of the command's budget; the layout tests
|
||||
// cover long text separately. It still runs so a bad parameter reaches the layout.
|
||||
s.clamp_selection();
|
||||
let _ = s.layout();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_within_budget(id: &str, elapsed: Duration, budget: Duration) {
|
||||
assert!(elapsed <= budget, "{id} took {elapsed:?} (budget {budget:?})");
|
||||
}
|
||||
|
||||
/// The budget above fires: a command that runs past it is named, not ignored (#3720).
|
||||
#[test]
|
||||
#[should_panic(expected = "test.slow took")]
|
||||
fn hostile_large_param_budget_flags_a_slow_command() {
|
||||
let budget = Duration::from_millis(1);
|
||||
let mut s = Session::new(crate::sample::sample_document());
|
||||
let slow = crate::CommandSpec::new("test.slow", "Slow", "", |_, _| {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
Ok(json!({}))
|
||||
})
|
||||
.pure();
|
||||
s.registry = Arc::new(crate::Registry::new(vec![slow]));
|
||||
let start = Instant::now();
|
||||
let _ = s.run("test.slow", &json!({}));
|
||||
assert_within_budget("test.slow", start.elapsed(), budget);
|
||||
}
|
||||
|
||||
/// A panic that `Session::run`'s guard turned into an error, in a command or one it ran: still a
|
||||
/// crash path (#3718). Only the guard's own `"{id} panicked: "` counts, not an error that echoes
|
||||
/// those words.
|
||||
@@ -7674,6 +7764,81 @@ fn chart_edits_are_one_undo_step_each() {
|
||||
assert_eq!((*w, graphic.w, graphic.h), (300.0, 300.0, 150.0));
|
||||
}
|
||||
|
||||
/// Scatter series are drawn as markers without a line: inserted with data, changed to scatter
|
||||
/// and back, and added by Edit Data. Edit Data keeps each replaced series' formatting.
|
||||
#[test]
|
||||
fn scatter_chart_series_have_no_line_and_edit_data_keeps_formatting() {
|
||||
let no_lines = |s: &Session| first_chart(&s.doc).unwrap().series.iter().map(|x| x.no_line).collect::<Vec<_>>();
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.chart", json!({"type": "scatter", "data": {"categories": [1, 2], "series": [{"name": "A", "values": [1, 2]}]}}));
|
||||
assert_eq!(no_lines(&s), [true]);
|
||||
run(&mut s, "chart.type", json!({"type": "line"}));
|
||||
assert_eq!(no_lines(&s), [false]);
|
||||
run(&mut s, "chart.type", json!({"type": "scatter"}));
|
||||
assert_eq!(no_lines(&s), [true]);
|
||||
|
||||
// Formatting read from a file, set on the chart's model.
|
||||
let set = |s: &mut Session, f: &dyn Fn(&mut wordcraft_doc::chart::ChartSpec)| {
|
||||
let mut spec = first_chart(&s.doc).unwrap();
|
||||
f(&mut spec);
|
||||
let pos = Pos::body(0, 0);
|
||||
let p = s.doc.para_mut(pos.story, &pos.path).unwrap();
|
||||
let off = p.object_offsets()[0];
|
||||
if let Some(wordcraft_doc::para::InlineObject::Graphic { graphic, .. }) = p.object_at_mut(off) {
|
||||
std::sync::Arc::make_mut(graphic).chart = Some(std::sync::Arc::new(spec));
|
||||
}
|
||||
};
|
||||
|
||||
// A series' formatting stays through Edit Data; a new series gets the type's default.
|
||||
set(&mut s, &|c| c.series[0].fill = Some(wordcraft_doc::props::Rgb(0x12, 0x34, 0x56)));
|
||||
run(&mut s, "chart.editData", json!({"data": {"series": [{"name": "B", "values": [3, 4]}, {"name": "C", "values": [5, 6]}]}}));
|
||||
let c = first_chart(&s.doc).unwrap();
|
||||
assert_eq!(c.series[0].fill, Some(wordcraft_doc::props::Rgb(0x12, 0x34, 0x56)));
|
||||
assert_eq!((c.series[0].name.as_str(), c.series[1].name.as_str()), ("B", "C"));
|
||||
assert_eq!(no_lines(&s), [true, true]);
|
||||
|
||||
// A line-only series made a scatter series again gets its markers back, so it stays visible.
|
||||
set(&mut s, &|c| c.series[0].markers = Some(false));
|
||||
run(&mut s, "chart.type", json!({"type": "line"}));
|
||||
run(&mut s, "chart.type", json!({"type": "scatter"}));
|
||||
assert_eq!(first_chart(&s.doc).unwrap().series[0].markers, None);
|
||||
|
||||
// The chart's Data Labels setting replaces a series' own.
|
||||
set(&mut s, &|c| c.series[1].labels = Some(true));
|
||||
run(&mut s, "chart.dataLabels", json!({"on": false}));
|
||||
let c = first_chart(&s.doc).unwrap();
|
||||
assert!(!c.data_labels && c.series.iter().all(|x| x.labels.is_none()));
|
||||
}
|
||||
|
||||
/// A pie chart changed to a column chart gets a new column chart's value axis, and back; an
|
||||
/// axis that was changed stays as it is.
|
||||
#[test]
|
||||
fn chart_type_between_round_and_axis_charts_sets_the_value_axis() {
|
||||
use wordcraft_doc::chart::{ChartAxis, value_axis};
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.chart", json!({"type": "pie"}));
|
||||
assert_eq!(first_chart(&s.doc).unwrap().val_axis, ChartAxis::default());
|
||||
run(&mut s, "chart.type", json!({"type": "column"}));
|
||||
assert_eq!(first_chart(&s.doc).unwrap().val_axis, value_axis());
|
||||
run(&mut s, "chart.type", json!({"type": "doughnut"}));
|
||||
assert_eq!(first_chart(&s.doc).unwrap().val_axis, ChartAxis::default());
|
||||
|
||||
let mut s = self::s();
|
||||
run(&mut s, "insert.chart", json!({"type": "column"}));
|
||||
let pos = Pos::body(0, 0);
|
||||
let p = s.doc.para_mut(pos.story, &pos.path).unwrap();
|
||||
let off = p.object_offsets()[0];
|
||||
if let Some(wordcraft_doc::para::InlineObject::Graphic { graphic, .. }) = p.object_at_mut(off) {
|
||||
let g = std::sync::Arc::make_mut(graphic);
|
||||
let mut spec = (**g.chart.as_ref().unwrap()).clone();
|
||||
spec.val_axis.max = Some(50.0);
|
||||
g.chart = Some(std::sync::Arc::new(spec));
|
||||
}
|
||||
run(&mut s, "chart.type", json!({"type": "pie"}));
|
||||
run(&mut s, "chart.type", json!({"type": "bar"}));
|
||||
assert_eq!(first_chart(&s.doc).unwrap().val_axis, ChartAxis { max: Some(50.0), ..value_axis() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_chart_data_is_capped() {
|
||||
use wordcraft_doc::chart::{MAX_CELLS, MAX_POINTS, MAX_SERIES, MAX_TEXT};
|
||||
@@ -13079,6 +13244,80 @@ fn an_odt_charts_paragraph_is_written_as_read_after_drawing_it() {
|
||||
assert!(content.contains(r#"draw:name="Chart1""#) && !content.contains("wcChart"), "{content}");
|
||||
}
|
||||
|
||||
/// A scatter chart saved as ODT (or flat ODT) and opened again is still drawn as markers without
|
||||
/// lines, and its paragraph is still written as read.
|
||||
#[test]
|
||||
fn an_odt_scatter_chart_reopens_without_lines() {
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.chart", json!({"type": "scatter"}));
|
||||
let odt = wordcraft_formats::odt::export(&s.doc).unwrap();
|
||||
let fodt = wordcraft_formats::odt::export_flat(&s.doc).unwrap();
|
||||
for (name, bytes) in [("t.odt", odt), ("t.fodt", fodt)] {
|
||||
let doc = crate::io::open_bytes(name, &bytes).unwrap();
|
||||
let c = first_chart(&doc).expect("the chart has its model");
|
||||
assert_eq!(c.kind, wordcraft_doc::chart::ChartType::Scatter);
|
||||
assert!(!c.series.is_empty() && c.series.iter().all(|x| x.no_line), "{name}: {:?}", c.series);
|
||||
// The drawn items are the markers-only drawing, not the one with lines between points.
|
||||
let p = doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
let (items, w, h) = p
|
||||
.object_offsets()
|
||||
.into_iter()
|
||||
.find_map(|off| match p.object_at(off) {
|
||||
Some(InlineObject::Graphic { graphic, w, h, .. }) if graphic.chart.is_some() => Some((graphic.items.clone(), *w, *h)),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the chart is drawn");
|
||||
let theme = &doc.settings.theme_colors;
|
||||
assert_eq!(items, crate::cmd::chart::chart_graphic(c.clone(), theme, w, h).items, "{name}");
|
||||
let mut lines = c.clone();
|
||||
lines.series.iter_mut().for_each(|x| x.no_line = false);
|
||||
assert_ne!(items, crate::cmd::chart::chart_graphic(lines, theme, w, h).items, "{name}");
|
||||
}
|
||||
let doc = crate::io::open_bytes("t.odt", &wordcraft_formats::odt::export(&s.doc).unwrap()).unwrap();
|
||||
let again = wordcraft_formats::odt::export(&doc).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&again, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
let content = String::from_utf8(z.read("content.xml", 16 << 20).unwrap().unwrap()).unwrap();
|
||||
assert!(content.contains(r#"draw:name="Chart1""#) && !content.contains("wcChart"), "{content}");
|
||||
}
|
||||
|
||||
/// An undrawn scatter series with its markers turned off is not left with neither a line nor
|
||||
/// markers when an opened ODF file's scatter charts are set to markers only; other formats keep
|
||||
/// their series as read.
|
||||
#[test]
|
||||
fn an_opened_odf_scatter_series_keeps_its_markers() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.chart", json!({"type": "scatter"}));
|
||||
let undrawn = |doc: &wordcraft_doc::Document| {
|
||||
let mut doc = doc.clone();
|
||||
doc.fill_objects(&|o| matches!(o, InlineObject::Graphic { graphic, .. } if graphic.chart.is_some()), &mut |o| {
|
||||
if let InlineObject::Graphic { graphic, .. } = o {
|
||||
let g = Arc::make_mut(graphic);
|
||||
if let Some(spec) = g.chart.as_deref() {
|
||||
let mut spec = spec.clone();
|
||||
for series in &mut spec.series {
|
||||
series.no_line = false;
|
||||
series.markers = Some(false);
|
||||
}
|
||||
g.chart = Some(Arc::new(spec));
|
||||
}
|
||||
g.items.clear();
|
||||
}
|
||||
});
|
||||
doc
|
||||
};
|
||||
let mut odf = undrawn(&s.doc);
|
||||
crate::io_ext::draw_charts(&mut odf, true);
|
||||
let c = first_chart(&odf).expect("the chart has its model");
|
||||
assert!(!c.series.is_empty() && c.series.iter().all(|x| x.no_line && x.markers.is_none()), "{:?}", c.series);
|
||||
let mut other = undrawn(&s.doc);
|
||||
crate::io_ext::draw_charts(&mut other, false);
|
||||
let c = first_chart(&other).expect("the chart has its model");
|
||||
assert!(c.series.iter().all(|x| !x.no_line && x.markers == Some(false)), "{:?}", c.series);
|
||||
}
|
||||
|
||||
/// A picture an OpenDocument file makes wider than the text (a rule across the whole page) stays
|
||||
/// that wide, and its paragraph is written as read: opening a file changes nothing in it.
|
||||
#[test]
|
||||
@@ -13472,3 +13711,173 @@ fn resolving_away_an_empty_paragraph_with_a_section_break_keeps_the_next_paragra
|
||||
assert_eq!(s.doc.last_section.margin_left, 72.0, "{cmd}: the following section's setup stays");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5616: Copy Formatting's formatting stays for every Paste Formatting, as in Word; it doesn't
|
||||
/// arm the one-shot Format Painter brush.
|
||||
#[test]
|
||||
fn copied_formatting_pastes_again_and_again() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
assert!(s.painter.is_none());
|
||||
for word in ["one", "two"] {
|
||||
run(&mut s, "select.text", json!({"text": word}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true), "{word}");
|
||||
}
|
||||
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Bold one two");
|
||||
}
|
||||
|
||||
/// #5616: Copy Formatting and the Format Painter share one format buffer: each replaces the other,
|
||||
/// so a used-up brush never hands over to older copied formatting.
|
||||
#[test]
|
||||
fn copy_formatting_and_the_format_painter_replace_each_other() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
assert!(s.painter.is_some());
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
assert!(s.painter.is_none(), "Copy Formatting clears an armed brush");
|
||||
assert!(s.copied_format.is_some());
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
assert!(s.painter.is_some());
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert!(s.painter.is_none(), "a used-up brush is gone");
|
||||
assert!(s.copied_format.is_some(), "its pick stays for Paste Formatting");
|
||||
}
|
||||
|
||||
/// #5616: arming and cancelling the Format Painter leaves Copy Formatting's pick; a brush's pick
|
||||
/// is what Paste Formatting applies next.
|
||||
#[test]
|
||||
fn cancelling_the_format_painter_keeps_the_copied_formatting() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bold one two"}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
assert!(s.painter.is_none());
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
|
||||
// A brush picked from plain text replaces the bold pick.
|
||||
run(&mut s, "select.text", json!({"text": "two"}));
|
||||
run(&mut s, "edit.formatPainter", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "Bold"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert_ne!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
|
||||
}
|
||||
|
||||
/// #5616: copied formatting carries no tracked paragraph formatting or numbering change.
|
||||
#[test]
|
||||
fn copied_paragraph_formatting_carries_no_tracked_changes() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "one\ntwo"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
run(&mut s, "para.alignCenter", json!({}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": false}));
|
||||
run(&mut s, "select.text", json!({"text": "one"}));
|
||||
let f = s.sel.focus.clone();
|
||||
assert!(s.doc.para_at(&f).unwrap().props.fmt_change.is_some(), "the source paragraph has a tracked formatting change");
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
let (_, para) = s.copied_format.clone().unwrap();
|
||||
assert!(para.fmt_change.is_none() && para.num_change.is_none());
|
||||
run(&mut s, "select.text", json!({"text": "two"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let f = s.sel.focus.clone();
|
||||
let p = s.doc.para_at(&f).unwrap().props.clone();
|
||||
assert!(p.fmt_change.is_none() && p.num_change.is_none());
|
||||
}
|
||||
|
||||
/// #5616: copied formatting carries no hyperlink or revision marks, even into a collapsed caret.
|
||||
#[test]
|
||||
fn copied_formatting_carries_no_hyperlink() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "source target"}));
|
||||
run(&mut s, "select.text", json!({"text": "source"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
|
||||
run(&mut s, "select.text", json!({"text": "so"}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
let (chr, _) = s.copied_format.clone().unwrap();
|
||||
assert_eq!(chr.bold, Some(true));
|
||||
assert!(chr.link.is_none() && chr.ins.is_none() && chr.del.is_none() && chr.fmt_change.is_none());
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "select.collapse", json!({}));
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let f = s.sel.focus.clone();
|
||||
let link = s.doc.para_at(&f).map(|p| p.props_of_char(f.off).link.clone());
|
||||
assert_eq!(link, Some(None), "the target didn't become a link");
|
||||
}
|
||||
|
||||
/// #5616: Paste Formatting at a bare caret keeps the word's own hyperlink and tracked insertion.
|
||||
#[test]
|
||||
fn a_caret_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "source target"}));
|
||||
run(&mut s, "select.text", json!({"text": "source"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
|
||||
run(&mut s, "select.collapse", json!({}));
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let at_caret = |s: &Session| {
|
||||
let f = s.sel.focus.clone();
|
||||
s.doc.para_at(&f).map(|p| p.props_of_char(f.off).clone()).unwrap_or_default()
|
||||
};
|
||||
let c = at_caret(&s);
|
||||
assert!(c.link.is_some(), "the target kept its hyperlink");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
// A tracked insertion stays tracked.
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "text.insert", json!({"text": " added"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": false}));
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
assert!(at_caret(&s).ins.is_some(), "the insertion is tracked before");
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
assert!(at_caret(&s).ins.is_some(), "Paste Formatting kept the insertion mark");
|
||||
}
|
||||
|
||||
/// #5616: Paste Formatting over a selection keeps the target's hyperlink and tracked marks too.
|
||||
#[test]
|
||||
fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "source target"}));
|
||||
run(&mut s, "select.text", json!({"text": "source"}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
run(&mut s, "edit.copyFormat", json!({}));
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.com/"}));
|
||||
run(&mut s, "select.text", json!({"text": "target"}));
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let (a, _) = s.sel.ordered();
|
||||
let c = s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default();
|
||||
assert!(c.link.is_some(), "the target kept its hyperlink");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
// A tracked insertion selected as a range stays tracked.
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": true}));
|
||||
run(&mut s, "text.insert", json!({"text": " added"}));
|
||||
run(&mut s, "review.trackChanges", json!({"value": false}));
|
||||
run(&mut s, "select.text", json!({"text": "added"}));
|
||||
let at_start = |s: &Session| {
|
||||
let (a, _) = s.sel.ordered();
|
||||
s.doc.para_at(&a).map(|p| p.props_of_char(a.off).clone()).unwrap_or_default()
|
||||
};
|
||||
assert!(at_start(&s).ins.is_some(), "the insertion is tracked before");
|
||||
run(&mut s, "edit.pasteFormat", json!({}));
|
||||
let c = at_start(&s);
|
||||
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
}
|
||||
|
||||
@@ -46,3 +46,49 @@ fn normal_apostrophe_search_keeps_exact_modes_and_original_byte_ranges() {
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), original);
|
||||
}
|
||||
|
||||
/// A keyboard double quote finds the curly ones smart quotes type, as a keyboard apostrophe does.
|
||||
#[test]
|
||||
fn keyboard_double_quote_finds_smart_quoted_typing() {
|
||||
let mut s = s();
|
||||
for ch in "\"hi\"".chars() {
|
||||
run(&mut s, "text.insert", json!({"text": ch.to_string()}));
|
||||
}
|
||||
assert_eq!(text(&s), "“hi”");
|
||||
for (query, count) in [("\"", 2), ("\"hi", 1), ("hi\"", 1), ("\"hi\"", 1), ("\"HI\"", 1)] {
|
||||
assert_eq!(run(&mut s, "edit.find", json!({"text": query}))["count"], count, "{query}");
|
||||
}
|
||||
assert_eq!(run(&mut s, "edit.find", json!({"text": "\"HI\"", "matchCase": true}))["count"], 0);
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"hi\"", "with": "[^&]"}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "[“hi”]");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), "“hi”");
|
||||
}
|
||||
|
||||
/// Straight and curly double quotes: only a typed `"` in a normal search reads as all three.
|
||||
#[test]
|
||||
fn normal_double_quote_search_keeps_exact_modes_and_original_byte_ranges() {
|
||||
let mut s = s();
|
||||
let original = "🙂 \"hi\" “hi” ”hi“ 'hi' ″hi″";
|
||||
run(&mut s, "document.setText", json!({"text": original}));
|
||||
let found = run(&mut s, "edit.find", json!({"text": "\"hi\""}));
|
||||
assert_eq!(found["count"], 3);
|
||||
let ranges: Vec<_> =
|
||||
found["matches"].as_array().unwrap().iter().map(|m| (m["start"]["off"].as_u64().unwrap(), m["end"]["off"].as_u64().unwrap())).collect();
|
||||
assert_eq!(ranges, [(5, 9), (10, 18), (19, 27)]);
|
||||
assert_eq!(run(&mut s, "edit.find", json!({"text": "\""}))["count"], 6);
|
||||
for options in [json!({"special": false}), json!({"wildcards": true}), json!({"regex": true})] {
|
||||
let mut exact = super::s();
|
||||
run(&mut exact, "document.setText", json!({"text": original}));
|
||||
let mut params = options;
|
||||
params["text"] = json!("\"hi\"");
|
||||
assert_eq!(run(&mut exact, "edit.find", params)["count"], 1);
|
||||
}
|
||||
for query in ["^034hi^034", "^u8220hi^u8221", "“hi”", "”hi“"] {
|
||||
assert_eq!(run(&mut s, "edit.find", json!({"text": query}))["count"], 1, "{query}");
|
||||
}
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"hi\"", "with": "<^&>"}))["replaced"], 3);
|
||||
assert_eq!(text(&s), "🙂 <\"hi\"> <“hi”> <”hi“> 'hi' ″hi″");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), original);
|
||||
}
|
||||
|
||||
@@ -5,13 +5,40 @@ use wordcraft_doc::props::CharProps;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Creates a document with `lines` lines of text.
|
||||
/// The bundled face the fixtures are set in. Their page counts are exact to a line, so they must
|
||||
/// not depend on the face the host substitutes for the default Aptos: at 11 pt, Arial and
|
||||
/// Liberation Sans fit 28 of these lines on a page and DejaVu Sans, the only candidate on a bare
|
||||
/// FreeBSD system, fits 27. Inter is the bundled face whose metrics give each 0.5 pt step its own
|
||||
/// page boundary at this page size.
|
||||
const FIXTURE_FONT: &str = "Inter";
|
||||
|
||||
/// Creates a document with `lines` lines of text in [`FIXTURE_FONT`]. Inter fits 25 lines on a
|
||||
/// page at 12 pt, 26 at 11.5 pt and 27 at 11 pt.
|
||||
fn create_multiline_doc(lines: usize) -> Session {
|
||||
let mut text = String::new();
|
||||
for i in 1..=lines {
|
||||
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
|
||||
}
|
||||
Session::new(Document::from_text(&text))
|
||||
let mut doc = Document::from_text(&text);
|
||||
std::sync::Arc::make_mut(&mut doc.styles).default_chr.font = Some(FIXTURE_FONT.into());
|
||||
Session::new(doc)
|
||||
}
|
||||
|
||||
/// Asserts the body is laid out in the bundled [`FIXTURE_FONT`], not a substitute.
|
||||
fn assert_fixture_font(s: &mut Session) {
|
||||
let layout = s.layout();
|
||||
let mut runs = 0;
|
||||
for page in &layout.pages {
|
||||
for item in &page.items {
|
||||
if let wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, para, .. } = item {
|
||||
for style in ¶.styles {
|
||||
runs += 1;
|
||||
assert_eq!(style.face.family, FIXTURE_FONT, "the fixture must not fall back to another family");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(runs > 0, "the font check must inspect laid-out body text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -39,7 +66,7 @@ fn fit_one_page_fails_on_hard_page_break() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_refuses_page_break_before_before_search() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[1]) {
|
||||
p.props.page_break_before = Some(true);
|
||||
@@ -74,7 +101,7 @@ fn fit_one_page_fails_on_next_page_section_break() {
|
||||
#[test]
|
||||
fn fit_one_page_condenses_slight_overflow_and_undoes() {
|
||||
// Find the boundary where the document just spills onto page 2
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -102,7 +129,7 @@ fn fit_one_page_condenses_slight_overflow_and_undoes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_max_delta() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document");
|
||||
|
||||
let doc_backup = s.doc.clone();
|
||||
@@ -117,11 +144,7 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
let mut text = String::new();
|
||||
for i in 1..=28 {
|
||||
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
|
||||
}
|
||||
let mut s = Session::new(Document::from_text(&text));
|
||||
let mut s = create_multiline_doc(27);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
@@ -131,6 +154,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
}
|
||||
}
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
|
||||
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
|
||||
@@ -147,7 +171,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_allows_spacing_only_at_font_floor() {
|
||||
let mut lines = 35;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_font = |s: &mut Session| {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -178,7 +202,7 @@ fn fit_one_page_allows_spacing_only_at_font_floor() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() {
|
||||
let mut lines = 35;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_font = |s: &mut Session| {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -208,7 +232,7 @@ fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_bounds_fine_step_loop() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -224,7 +248,7 @@ fn fit_one_page_bounds_fine_step_loop() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_supports_max_delta_above_2pt() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -244,7 +268,7 @@ fn fit_one_page_supports_max_delta_above_2pt() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_anti_compound_guard_prevents_repeated_invocations() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
loop {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -314,7 +338,7 @@ fn fit_one_page_already_fits_wins_over_exhausted_budget() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_checks_complex_script_font_floor() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -340,7 +364,7 @@ fn fit_one_page_checks_complex_script_font_floor() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_checks_editable_text_box_font_floor() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -386,7 +410,7 @@ fn fit_one_page_checks_editable_text_box_font_floor() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_when_overflow_exceeds_limits() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
@@ -566,7 +590,7 @@ fn fit_one_page_fails_with_failed_cmd_error() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_never_populates_custom_props() {
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -582,7 +606,7 @@ fn fit_one_page_never_populates_custom_props() {
|
||||
fn fit_one_page_allows_subsequent_fit_after_typography_reset() {
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -625,7 +649,7 @@ fn fit_one_page_allows_subsequent_fit_after_typography_reset() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() {
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -646,7 +670,7 @@ fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_small_comment_font_never_blocks_body_fit() {
|
||||
let mut lines = 30;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 2;
|
||||
@@ -666,7 +690,7 @@ fn fit_one_page_small_comment_font_never_blocks_body_fit() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_anti_compound_caps_total_reduction_across_runs() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Initial fit with -0.5 pt font reduction (spacing disabled so font budget is exercised)
|
||||
@@ -688,7 +712,7 @@ fn fit_one_page_anti_compound_caps_total_reduction_across_runs() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
// Add a 9.0 pt run to the first paragraph alongside 11.0 pt runs
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[0]) {
|
||||
p.runs.push(wordcraft_doc::para::Run { len: 5, props: CharProps { size: Some(9.0), ..Default::default() } });
|
||||
@@ -725,7 +749,7 @@ fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_allows_spill_with_bottom_placed_footnote() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -751,7 +775,7 @@ fn fit_one_page_allows_spill_with_bottom_placed_footnote() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_with_final_page_footnote() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -784,7 +808,7 @@ fn fit_one_page_with_final_page_footnote() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_skips_deleted_text_when_markup_hidden() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Insert a deleted text run with small font (e.g. 6.0 pt, below the 8.5 pt floor)
|
||||
@@ -815,7 +839,7 @@ fn fit_one_page_skips_deleted_text_when_markup_hidden() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
let styles_before = s.doc.styles.clone();
|
||||
|
||||
@@ -853,8 +877,9 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
// Apply fit
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
|
||||
@@ -900,7 +925,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() {
|
||||
s.touch();
|
||||
s.relayout();
|
||||
};
|
||||
let mut lines = 27;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
set_font(&mut s);
|
||||
while s.layout().pages.len() < 2 && lines < 120 {
|
||||
@@ -924,7 +949,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_skips_hidden_text_when_hidden_marks_off() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Insert a hidden text run with small font (6.0 pt, below the 8.5 pt floor) into an existing paragraph
|
||||
@@ -958,7 +983,7 @@ fn fit_one_page_skips_hidden_text_when_hidden_marks_off() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_accounts_for_vertical_alignment_padding() {
|
||||
let mut s = create_multiline_doc(26);
|
||||
let mut s = create_multiline_doc(25);
|
||||
let extra_p = wordcraft_doc::Paragraph::with_text("Spill line on page 2.", CharProps::default());
|
||||
s.doc.body.push(wordcraft_doc::para_block(extra_p));
|
||||
|
||||
@@ -977,7 +1002,7 @@ fn fit_one_page_accounts_for_vertical_alignment_padding() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_accounts_for_note_separator_decor_story() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
while s.layout().pages.len() < 2 && lines < 80 {
|
||||
lines += 1;
|
||||
@@ -1012,7 +1037,7 @@ fn fit_one_page_accounts_for_note_separator_decor_story() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() {
|
||||
let mut lines = 28;
|
||||
let mut lines = 20;
|
||||
let mut s = create_multiline_doc(lines);
|
||||
let set_spacing = |s: &mut Session| {
|
||||
for b in &mut s.doc.body {
|
||||
@@ -1053,7 +1078,7 @@ fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Calling with zero maxDeltaPt and adjustSpacing: false produces no candidate steps
|
||||
@@ -1068,23 +1093,24 @@ fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() {
|
||||
let mut lines = 33;
|
||||
let enable_line_numbers = |s: &mut Session| {
|
||||
s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default());
|
||||
s.touch();
|
||||
s.relayout();
|
||||
};
|
||||
let mut s = create_multiline_doc(lines);
|
||||
enable_line_numbers(&mut s);
|
||||
while s.layout().pages.len() < 2 && lines < 60 {
|
||||
lines += 1;
|
||||
s = create_multiline_doc(lines);
|
||||
enable_line_numbers(&mut s);
|
||||
}
|
||||
let mut s = create_multiline_doc(33);
|
||||
s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default());
|
||||
s.touch();
|
||||
s.relayout();
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// Every body line on the final page also places a line-number decoration. Counting those as
|
||||
// content would double the final-page line count and refuse before any candidate is tried.
|
||||
// content would double the final-page line count and refuse before any candidate is tried:
|
||||
// between 7 and 12 body lines are within the 12-line limit, and twice as many are not.
|
||||
let body_lines: usize = s.layout().pages[1]
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| match item {
|
||||
wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, l0, l1, .. } => l1 - l0,
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
assert!((7..=12).contains(&body_lines), "the final page must carry 7 to 12 body lines, has {body_lines}");
|
||||
let decorated = s.layout().pages[1]
|
||||
.items
|
||||
.iter()
|
||||
@@ -1099,7 +1125,7 @@ fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_counts_side_by_side_footnote_cells_once() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
|
||||
// A footnote table whose row's cells sit side by side: their text occupies one vertical
|
||||
@@ -1134,7 +1160,7 @@ fn fit_one_page_counts_side_by_side_footnote_cells_once() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_refuses_when_formatting_changes_cannot_be_tracked() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
let mut s = create_multiline_doc(26);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
s.doc.settings.track_changes = true;
|
||||
s.prefs.markup.track_formatting = true;
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Generated lists and page cross-references write a page as its footer shows it: in the number
|
||||
//! format of the page's section (`w:pgNumType w:fmt`), as Word does (#3856). The front matter is
|
||||
//! numbered i, ii; the body restarts at 1.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, v: Value) {
|
||||
s.run(id, &v).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
|
||||
/// Page i: "Front"; page ii: "Preface" (Heading 1); next-page section break; page 1: "Chapter one"
|
||||
/// (Heading 1). Section 1 lowerRoman from 1, section 2 decimal from 1.
|
||||
fn two_sections() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface\nChapter one"));
|
||||
for h in ["Preface", "Chapter one"] {
|
||||
run(&mut s, "select.text", json!({"text": h}));
|
||||
run(&mut s, "styles.apply", json!({"style": "Heading 1"}));
|
||||
}
|
||||
run(&mut s, "select.text", json!({"text": "Preface"}));
|
||||
run(&mut s, "caret.home", json!({}));
|
||||
run(&mut s, "layout.break", json!({"kind": "page"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "caret.home", json!({}));
|
||||
run(&mut s, "layout.break", json!({"kind": "nextPage"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "decimal", "start": 1}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "lowerRoman", "start": 1}));
|
||||
s
|
||||
}
|
||||
|
||||
fn styled(s: &Session, prefix: &str) -> Vec<String> {
|
||||
s.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.filter(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with(prefix) && st != "TOCHeading"))
|
||||
.map(|p| p.plain_text())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn field_results(s: &Session, name: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
for o in &s.doc.para(StoryRef::Body, &path).unwrap().objects {
|
||||
if let InlineObject::Field { instr, result, .. } = o
|
||||
&& instr.trim_start().starts_with(name)
|
||||
{
|
||||
out.push(result.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_page_numbers_follow_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": false, "rightAlign": false}));
|
||||
assert_eq!(styled(&s, "TOC1"), ["Preface ii", "Chapter one 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_pageref_results_follow_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": true, "rightAlign": false}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["ii", "1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_upper_roman_and_letters() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "upperRoman", "start": 4}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "lowerLetter", "start": 3}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": false, "rightAlign": false}));
|
||||
// Preface is the section's 2nd page: 4 + 1 = 5 = V; Chapter one starts at 3 = c.
|
||||
assert_eq!(styled(&s, "TOC1"), ["Preface V", "Chapter one c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_pages_follow_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "select.text", json!({"text": "Preface"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Preface"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Chapter"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
let text = s.doc.plain_text(StoryRef::Body);
|
||||
// The index is the last thing in the document: its lines start with the entry.
|
||||
let entry = |name: &str| text.lines().rfind(|l| l.starts_with(name)).unwrap_or_default().to_string();
|
||||
let preface = entry("Preface");
|
||||
assert!(preface.ends_with("ii"), "index line {preface:?} in {text:?}");
|
||||
let chapter = entry("Chapter");
|
||||
assert!(chapter.ends_with('1') && chapter != "Chapter one", "index line {chapter:?} in {text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_cross_reference_follows_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
// Before this change the field was inserted with "1", not even the decimal 2: find out which
|
||||
// page it reads, too.
|
||||
run(&mut s, "insert.crossReference", json!({"to": "heading", "target": "Preface", "show": "page"}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["ii"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_fields_still_agree() {
|
||||
// F9 already formats PAGEREF by the section; inserting must give the same as updating.
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": true, "rightAlign": false}));
|
||||
let inserted = field_results(&s, "PAGEREF");
|
||||
crate::cmd::references::update_fields_in(&mut s, true).unwrap();
|
||||
assert_eq!(field_results(&s, "PAGEREF"), inserted);
|
||||
}
|
||||
|
||||
// PR #5971 review: a decimal-only guard, `1, 1` across two sections, index page ranges and
|
||||
// `_Ref` bookmark reuse.
|
||||
|
||||
/// "Front" / page break / "Preface" (Heading 1) / page break / "Chapter one" (Heading 1), one
|
||||
/// decimal section: pages 1, 2, 3.
|
||||
fn decimal_only() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface\nChapter one"));
|
||||
for h in ["Preface", "Chapter one"] {
|
||||
run(&mut s, "select.text", json!({"text": h}));
|
||||
run(&mut s, "styles.apply", json!({"style": "Heading 1"}));
|
||||
run(&mut s, "caret.home", json!({}));
|
||||
run(&mut s, "layout.break", json!({"kind": "page"}));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The last line of the body's text that starts with `name` (the index is at the end).
|
||||
fn index_line(s: &Session, name: &str) -> String {
|
||||
let text = s.doc.plain_text(StoryRef::Body);
|
||||
text.lines().rfind(|l| l.starts_with(name)).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// The body paragraph whose text contains `text`, and the byte offset where `text` starts in it.
|
||||
fn find(s: &Session, text: &str) -> (wordcraft_doc::Path, usize) {
|
||||
s.doc
|
||||
.para_paths(StoryRef::Body)
|
||||
.into_iter()
|
||||
.find_map(|path| s.doc.para(StoryRef::Body, &path).and_then(|p| p.text.find(text)).map(|o| (path, o)))
|
||||
.unwrap_or_else(|| panic!("no paragraph with {text:?}"))
|
||||
}
|
||||
|
||||
fn add_mark(s: &mut Session, path: &wordcraft_doc::Path, off: usize, obj: InlineObject) {
|
||||
let at = wordcraft_doc::Pos { story: StoryRef::Body, path: path.clone(), off };
|
||||
s.doc.insert_object(&at, obj, &wordcraft_doc::CharProps::default()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_only_documents_keep_plain_page_numbers() {
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": false, "rightAlign": false}));
|
||||
assert_eq!(styled(&s, "TOC1"), ["Preface 2", "Chapter one 3"]);
|
||||
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": true, "rightAlign": false}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["2", "3"]);
|
||||
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "insert.crossReference", json!({"to": "heading", "target": "Preface", "show": "page"}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["2"]);
|
||||
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "select.text", json!({"text": "Preface"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Preface"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Chapter"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
let (preface, chapter) = (index_line(&s, "Preface"), index_line(&s, "Chapter"));
|
||||
assert!(preface.ends_with('2') && !preface.ends_with("12"), "{preface:?}");
|
||||
assert!(chapter.ends_with('3') && chapter != "Chapter one", "{chapter:?}");
|
||||
}
|
||||
|
||||
/// The same entry on page 1 of two sections lists both pages: the index merges pages by layout
|
||||
/// page, not by the number shown.
|
||||
#[test]
|
||||
fn the_same_label_on_two_pages_is_listed_twice() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "decimal", "start": 1}));
|
||||
for t in ["Front", "Chapter one"] {
|
||||
run(&mut s, "select.text", json!({"text": t}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Topic"}));
|
||||
}
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
let line = index_line(&s, "Topic");
|
||||
assert!(line.ends_with("1, 1"), "{line:?}");
|
||||
}
|
||||
|
||||
/// An index entry for bookmark `Span` (`XE \r`), the bookmark from "Preface" (page ii) to `end`.
|
||||
fn range_entry(end: Option<(&str, bool)>) -> String {
|
||||
let mut s = two_sections();
|
||||
let (path, off) = find(&s, "Preface");
|
||||
// The end first, so the start's offset stays put when both are in one paragraph.
|
||||
if let Some((text, at_end_of_para)) = end {
|
||||
let (epath, eoff) = find(&s, text);
|
||||
let eoff = if at_end_of_para { s.doc.para(StoryRef::Body, &epath).unwrap().len() } else { eoff + text.len() };
|
||||
add_mark(&mut s, &epath, eoff, InlineObject::BookmarkEnd { name: "Span".into() });
|
||||
}
|
||||
add_mark(&mut s, &path, off, InlineObject::BookmarkStart { name: "Span".into() });
|
||||
run(&mut s, "select.text", json!({"text": "Front"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Span", "bookmark": "Span"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
index_line(&s, "Span")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_range_across_sections_uses_each_ends_format() {
|
||||
let line = range_entry(Some(("Chapter one", true)));
|
||||
assert!(line.ends_with("ii\u{2013}1"), "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_range_on_one_page_is_one_page() {
|
||||
let line = range_entry(Some(("Preface", false)));
|
||||
assert!(line.ends_with("ii") && !line.contains('\u{2013}'), "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_range_without_its_end_is_the_start_page() {
|
||||
let line = range_entry(None);
|
||||
assert!(line.ends_with("ii") && !line.contains('\u{2013}'), "{line:?}");
|
||||
}
|
||||
|
||||
/// A heading that starts with a page break and already has a `_Ref` bookmark around it from
|
||||
/// offset 0: a page cross-reference reuses it and reads the heading's page.
|
||||
#[test]
|
||||
fn a_ref_bookmark_before_the_page_break_is_reused() {
|
||||
let mut s = two_sections();
|
||||
let (path, _) = find(&s, "Preface");
|
||||
let len = s.doc.para(StoryRef::Body, &path).unwrap().len();
|
||||
add_mark(&mut s, &path, len, InlineObject::BookmarkEnd { name: "_Ref000000007".into() });
|
||||
add_mark(&mut s, &path, 0, InlineObject::BookmarkStart { name: "_Ref000000007".into() });
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "insert.crossReference", json!({"to": "heading", "target": "Preface", "show": "page"}));
|
||||
let refs: Vec<String> = s.doc.bookmarks().into_iter().map(|b| b.0).filter(|n| n.starts_with("_Ref")).collect();
|
||||
assert_eq!(refs, ["_Ref000000007"], "no second _Ref bookmark");
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["ii"]);
|
||||
}
|
||||
@@ -4031,3 +4031,25 @@ fn issues_1281_1045_english_dialects_proof_typed_text() {
|
||||
let words: Vec<&str> = issues.as_array().unwrap().iter().filter(|i| i["kind"] == "spelling").filter_map(|i| i["text"].as_str()).collect();
|
||||
assert_eq!(words, ["21th"]);
|
||||
}
|
||||
|
||||
/// #6788: Enter in a paragraph with a drop cap makes a normal paragraph; only the first keeps
|
||||
/// the cap (Word behaviour), for a dropped cap and one in the margin.
|
||||
#[test]
|
||||
fn enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph() {
|
||||
for position in ["dropped", "margin"] {
|
||||
let mut s = typed("Sugar and knowledge");
|
||||
run(&mut s, "insert.dropCap", json!({"position": position, "lines": 3, "distance": 4.0, "font": "Liberation Mono"}));
|
||||
let first_has_cap = s.doc.body.first().and_then(|b| b.as_para()).is_some_and(|p| p.props.drop_cap == Some(3));
|
||||
assert!(first_has_cap, "{position}: the cap is set");
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 10}, "focus": {"block": 0, "off": 10}}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
let paras: Vec<_> = s.doc.body.iter().filter_map(|b| b.as_para()).collect();
|
||||
assert_eq!(paras.len(), 2, "{position}");
|
||||
let (first, second) = (¶s[0].props, ¶s[1].props);
|
||||
assert_eq!(first.drop_cap, Some(3), "{position}: the first paragraph keeps its cap");
|
||||
assert_eq!(second.drop_cap, None, "{position}");
|
||||
assert_eq!(second.drop_cap_margin, None, "{position}");
|
||||
assert_eq!(second.drop_cap_distance, None, "{position}");
|
||||
assert_eq!(second.drop_cap_font, None, "{position}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,3 +103,58 @@ fn an_odt_bibliography_updates_from_its_citations_sources() {
|
||||
assert!(text.iter().any(|t| t.contains("Kilns and Fire")), "{text:?}");
|
||||
assert!(!text.iter().any(|t| t.contains("stale")), "{text:?}");
|
||||
}
|
||||
|
||||
/// #6486: LibreOffice numbers headings through its outline style, the number followed by a tab,
|
||||
/// and its Contents styles carry only the right-aligned dotted stop for the page number. After
|
||||
/// Update Table, the tab after an entry's number stops near the number, not at the page-number
|
||||
/// stop: the title stays at the left and each entry stays on one line.
|
||||
#[test]
|
||||
fn an_odt_toc_with_numbered_headings_keeps_its_entries_on_one_line() {
|
||||
let outline = |level: u8, cm: f32| {
|
||||
format!(
|
||||
r#"<text:outline-level-style text:level="{level}" style:num-format="1" style:num-suffix="." text:display-levels="{level}"><style:list-level-properties text:list-level-position-and-space-mode="label-alignment"><style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="{cm}cm" fo:text-indent="-{cm}cm" fo:margin-left="{cm}cm"/></style:list-level-properties></text:outline-level-style>"#
|
||||
)
|
||||
};
|
||||
let contents = |n: u8, indent: f32| {
|
||||
format!(
|
||||
r#"<style:style style:name="Contents_20_{n}" style:display-name="Contents {n}" style:family="paragraph"><style:paragraph-properties fo:margin-left="{indent}cm"><style:tab-stops><style:tab-stop style:position="16.99cm" style:type="right" style:leader-style="dotted" style:leader-text="."/></style:tab-stops></style:paragraph-properties></style:style>"#
|
||||
)
|
||||
};
|
||||
let styles = format!(
|
||||
r#"<office:document-styles {NS}><office:styles>{}{}<text:outline-style style:name="Outline">{}{}</text:outline-style></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" fo:margin-left="2cm" fo:margin-right="2cm" fo:margin-top="2cm" fo:margin-bottom="2cm"/></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#,
|
||||
contents(1, 0.0),
|
||||
contents(2, 0.499),
|
||||
outline(1, 0.762),
|
||||
outline(2, 1.016)
|
||||
);
|
||||
let content = format!(
|
||||
r#"<office:document-content {NS}><office:body><office:text>
|
||||
<text:table-of-content text:name="T"><text:table-of-content-source text:outline-level="2"/><text:index-body><text:p text:style-name="Contents_20_1">1. Planning<text:tab/>1</text:p><text:p text:style-name="Contents_20_2">1.1. Budget<text:tab/>1</text:p></text:index-body></text:table-of-content>
|
||||
<text:h text:outline-level="1">Planning</text:h><text:p>Text.</text:p>
|
||||
<text:h text:outline-level="2">Budget</text:h><text:p>More text.</text:p>
|
||||
</office:text></office:body></office:document-content>"#
|
||||
);
|
||||
let mut z = craft_zip::Writer::new();
|
||||
for (name, data) in [("mimetype", "application/vnd.oasis.opendocument.text"), ("styles.xml", styles.as_str()), ("content.xml", content.as_str())]
|
||||
{
|
||||
z.add(name, data.as_bytes(), craft_zip::Compression::Stored).unwrap();
|
||||
}
|
||||
let mut s = Session::new(io::open_bytes("toc.odt", &z.finish().unwrap()).unwrap());
|
||||
s.run("references.updateToc", &json!({})).unwrap();
|
||||
let layout = s.layout();
|
||||
let mut checked = 0;
|
||||
for (i, b) in s.doc.body.iter().enumerate() {
|
||||
let Some(p) = b.as_para().filter(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC") && st != "TOCHeading")) else {
|
||||
continue;
|
||||
};
|
||||
let Some(tab) = p.text.find('\t') else { continue };
|
||||
let pos = |off| wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(i), off };
|
||||
let title = layout.caret(&pos(tab + 1)).unwrap();
|
||||
let end = layout.caret(&pos(p.len())).unwrap();
|
||||
assert!(p.plain_text().contains("Planning") || p.plain_text().contains("Budget"), "{:?}", p.text);
|
||||
assert_eq!((title.page, title.top), (end.page, end.top), "{:?} wraps", p.text);
|
||||
assert!(title.x < 200.0, "{:?}: the title starts at {}", p.text, title.x);
|
||||
checked += 1;
|
||||
}
|
||||
assert_eq!(checked, 2);
|
||||
}
|
||||
|
||||
@@ -67,6 +67,11 @@ pub struct FontFace {
|
||||
/// values).
|
||||
pub cap_height: f64,
|
||||
pub x_height: f64,
|
||||
/// Average character width in font units (`OS/2.xAvgCharWidth`), half the em for an East
|
||||
/// Asian font, whose average a platform's text metrics report as its half-width cell rather
|
||||
/// than the full-width figure in the table. Word's automatic spacing between East Asian and
|
||||
/// Latin text is half of it (see `wordcraft_layout::para::grid::auto_space`).
|
||||
pub avg_char_width: f64,
|
||||
pub shaper: harfrust::ShaperData,
|
||||
/// Variable fonts: the named instance's axis settings (user units; empty = default instance),
|
||||
/// the normalised location and the shaper's view of it.
|
||||
|
||||
@@ -14,6 +14,20 @@ pub(super) fn east_asian_font(f: &skrifa::FontRef<'_>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The font's average character width in font units: `OS/2.xAvgCharWidth`, or half the em when
|
||||
/// the table is missing or says nothing. An East Asian font gets half the em whatever its table
|
||||
/// says, because a platform's text metrics report a double-byte font's average as the width of
|
||||
/// its half-width cell, not the full-width figure the table carries (Yu Gothic says 1972 of
|
||||
/// 2048, and Word spaces it as 1024).
|
||||
fn avg_char_width(f: &skrifa::FontRef<'_>, upem: f64) -> f64 {
|
||||
use skrifa::raw::TableProvider;
|
||||
let half = upem / 2.0;
|
||||
if east_asian_font(f) {
|
||||
return half;
|
||||
}
|
||||
f.os2().ok().map(|t| f64::from(t.x_avg_char_width())).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(half).min(upem)
|
||||
}
|
||||
|
||||
/// A family name in another language, from a font's `name` table.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LocalName {
|
||||
@@ -371,6 +385,7 @@ pub(super) fn make_face(
|
||||
.map(|v| v >= 0.5)
|
||||
.or(axis(b"slnt").map(|v| v.abs() > 0.1))
|
||||
.unwrap_or(!matches!(a.style, skrifa::attribute::Style::Normal) || style_italic(&style));
|
||||
let upem = m.units_per_em.max(1) as f64;
|
||||
Some(FontFace {
|
||||
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
|
||||
family,
|
||||
@@ -381,11 +396,12 @@ pub(super) fn make_face(
|
||||
postscript: coords.is_empty().then(|| name(&f, &[StringId::POSTSCRIPT_NAME])).flatten(),
|
||||
weight,
|
||||
italic,
|
||||
upem: m.units_per_em.max(1) as f64,
|
||||
upem,
|
||||
ascent: m.ascent as f64,
|
||||
descent: -(m.descent as f64),
|
||||
cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),
|
||||
x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),
|
||||
avg_char_width: avg_char_width(&f, upem),
|
||||
shaper,
|
||||
coords,
|
||||
location,
|
||||
|
||||
@@ -579,6 +579,24 @@ fn east_asian_fonts_are_listed_for_the_asian_text_font_box() {
|
||||
assert_eq!(listed(&db), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_east_asian_faces_average_character_width_is_its_half_width_cell() {
|
||||
// #6583: Word's automatic space beside East Asian text is half the average character width
|
||||
// of the face before it, and a platform's text metrics report a double-byte font's average
|
||||
// as the width of its half-width cell, not the full-width figure its OS/2 table carries. The
|
||||
// two faces here share one OS/2 table and differ only in their code pages.
|
||||
let dir = font_dir("avgcharwidth");
|
||||
let song = with_family_names("SourceSans3-Regular.ttf", &[(0x0409, "Songti Width")]);
|
||||
std::fs::write(dir.join("song.ttf"), with_code_pages(&song, 1 << 18)).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir]);
|
||||
let latin = db.face(FAMILY, "Regular");
|
||||
let asian = db.face("Songti Width", "Regular");
|
||||
assert!(latin.upem > 0.0 && !latin.is_east_asian() && asian.is_east_asian());
|
||||
// The Latin face keeps the table's figure, which is not half the em.
|
||||
assert!(latin.avg_char_width > latin.upem / 2.0, "{} of {}", latin.avg_char_width, latin.upem);
|
||||
assert_eq!(asian.avg_char_width, asian.upem / 2.0);
|
||||
}
|
||||
|
||||
/// #848: browsing the font list drew each family's name in its own face, loading every family
|
||||
/// shown for good (tens of megabytes per trip through the Font box). Preview faces are read for
|
||||
/// the preview alone: however many families are previewed, the database keeps no font data, and
|
||||
|
||||
@@ -63,7 +63,13 @@ impl std::fmt::Display for UserFontError {
|
||||
match self {
|
||||
UserFontError::Empty => write!(f, "the font file is empty"),
|
||||
UserFontError::TooLarge { bytes } => {
|
||||
write!(f, "the font file is too large ({} MB; at most {} MB)", bytes.div_ceil(1 << 20), MAX_FONT_FILE_BYTES >> 20)
|
||||
write!(
|
||||
f,
|
||||
"the font is too large ({} MB; file limit {} MB, unpacked limit {} MB)",
|
||||
bytes.div_ceil(1 << 20),
|
||||
MAX_FONT_FILE_BYTES >> 20,
|
||||
MAX_DECODED_BYTES >> 20
|
||||
)
|
||||
}
|
||||
UserFontError::NotAFont => write!(f, "not a font file (TrueType, OpenType, TTC, WOFF or WOFF2)"),
|
||||
UserFontError::BadWebFont(e) => write!(f, "the web font couldn't be read: {e}"),
|
||||
|
||||
@@ -210,7 +210,9 @@ fn woff1_claiming(orig: u32) -> Vec<u8> {
|
||||
fn a_woff_claiming_a_huge_table_is_refused_before_inflating() {
|
||||
// #3703: the decoder sizes a table's buffer from the directory before inflating it.
|
||||
for orig in [200 << 20, u32::MAX] {
|
||||
assert!(matches!(decode_font_file(&woff1_claiming(orig)), Err(UserFontError::TooLarge { .. })), "{orig}");
|
||||
let error = decode_font_file(&woff1_claiming(orig)).unwrap_err();
|
||||
assert!(matches!(&error, UserFontError::TooLarge { .. }), "{orig}");
|
||||
assert!(error.to_string().contains("unpacked limit 128 MB"), "{error}");
|
||||
}
|
||||
// A small claim reaches the decoder, which finds the data doesn't inflate to it.
|
||||
assert!(matches!(decode_font_file(&woff1_claiming(64)), Err(UserFontError::BadWebFont(_))));
|
||||
@@ -311,7 +313,9 @@ fn junk_is_rejected_without_adding_anything() {
|
||||
assert_eq!(db.families().len(), n + db.user_fonts().iter().map(|u| u.families().len()).sum::<usize>());
|
||||
let mut big = regular.clone();
|
||||
big.resize(MAX_FONT_FILE_BYTES + 1, 0);
|
||||
assert!(matches!(db.install_font("big.ttf", &big), Err(UserFontError::TooLarge { .. })));
|
||||
let error = db.install_font("big.ttf", &big).unwrap_err();
|
||||
assert!(matches!(&error, UserFontError::TooLarge { .. }));
|
||||
assert!(error.to_string().contains("file limit 50 MB"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,6 +8,11 @@ description = "WordCraft import/export: plain text, Markdown, HTML, RTF, OpenDoc
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# `sheet::xls_fixture`, the binary workbook builder other crates' tests share; turned on only as a
|
||||
# dev-dependency, so never built into the app.
|
||||
test-support = ["craft-xls/test-support"]
|
||||
|
||||
[dependencies]
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-docx = { workspace = true }
|
||||
|
||||
@@ -109,9 +109,10 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
|
||||
Err("not an Excel or OpenDocument spreadsheet".into())
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[doc(hidden)]
|
||||
pub fn xls_fixture(sheets: &[(&str, Vec<Vec<String>>)]) -> Vec<u8> {
|
||||
craft_xls::testing::workbook(sheets)
|
||||
pub fn xls_fixture(sheets: &[(&str, Vec<Vec<String>>)]) -> Result<Vec<u8>, String> {
|
||||
craft_xls::testing::workbook(sheets).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn field_names(row: &[String]) -> Vec<String> {
|
||||
|
||||
@@ -10,9 +10,10 @@ workspace = true
|
||||
|
||||
[features]
|
||||
# Picture decoding within a memory budget (`picture`), for the crates that decode pictures.
|
||||
image = ["dep:image", "dep:craft-image-codecs"]
|
||||
image = ["dep:image", "dep:craft-image-codecs", "dep:craft-tiff"]
|
||||
|
||||
[dependencies]
|
||||
craft-image-codecs = { workspace = true, optional = true }
|
||||
craft-tiff = { workspace = true, optional = true }
|
||||
image = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
+236
-37
@@ -1,5 +1,4 @@
|
||||
//! WordCraft geometry and units.
|
||||
//!
|
||||
//! Layout works in **points** (1/72 inch, `f32`). File formats use other units: OOXML uses
|
||||
//! twentieths of a point (twips) for most lengths, half-points for font sizes, eighths of a point
|
||||
//! for borders and English Metric Units (EMU, 914 400 per inch) for drawings. The conversions live
|
||||
@@ -25,26 +24,32 @@ pub const EMU_PER_PT: f32 = 12_700.0;
|
||||
pub const PT_PER_CM: f32 = 72.0 / 2.54;
|
||||
|
||||
/// Twips → points.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn twips(v: i64) -> f32 {
|
||||
v as f32 / TWIPS_PER_PT
|
||||
}
|
||||
/// Points → twips (rounded).
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_twips(pt: f32) -> i64 {
|
||||
finite(pt * TWIPS_PER_PT).round() as i64
|
||||
}
|
||||
/// EMU → points.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn emu(v: i64) -> f32 {
|
||||
v as f32 / EMU_PER_PT
|
||||
}
|
||||
/// Points → EMU (rounded).
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_emu(pt: f32) -> i64 {
|
||||
(finite(pt) as f64 * EMU_PER_PT as f64).round() as i64
|
||||
(f64::from(finite(pt)) * f64::from(EMU_PER_PT)).round() as i64
|
||||
}
|
||||
/// Half-points (OOXML font sizes) → points.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
|
||||
pub fn half_points(v: i64) -> f32 {
|
||||
v as f32 / 2.0
|
||||
}
|
||||
/// Points → half-points (rounded).
|
||||
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
|
||||
pub fn to_half_points(pt: f32) -> i64 {
|
||||
(finite(pt) * 2.0).round() as i64
|
||||
}
|
||||
@@ -58,15 +63,21 @@ pub fn finite(v: f32) -> f32 {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Unit {
|
||||
/// Inches (the default).
|
||||
#[default]
|
||||
Inches,
|
||||
/// Centimetres.
|
||||
Centimeters,
|
||||
/// Millimetres.
|
||||
Millimeters,
|
||||
/// Points (1/72 inch).
|
||||
Points,
|
||||
/// Picas (12 points).
|
||||
Picas,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
/// The suffix shown after a number in this unit (`"` for inches, ` cm`, ` pt`, …).
|
||||
pub fn suffix(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Inches => "\"",
|
||||
@@ -76,6 +87,7 @@ impl Unit {
|
||||
Unit::Picas => " pi",
|
||||
}
|
||||
}
|
||||
/// How many points one of this unit is.
|
||||
pub fn pt_per_unit(self) -> f32 {
|
||||
match self {
|
||||
Unit::Inches => PT_PER_IN,
|
||||
@@ -99,15 +111,34 @@ impl Unit {
|
||||
let s = format!("{v:.2}");
|
||||
let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s };
|
||||
let s = if s == "-0" { "0" } else { s };
|
||||
s.replace('.', &decimal.to_string())
|
||||
let mut buf = [0u8; 4];
|
||||
let sep: &str = decimal.encode_utf8(&mut buf);
|
||||
s.replace('.', sep)
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps the digits and decimal separators of other scripts to their ASCII forms: Arabic-Indic
|
||||
/// (`٠`–`٩`, `٫`), Extended Arabic-Indic (`۰`–`۹`) and full-width (`0`–`9`, `.`, `,`).
|
||||
fn fold_digit(c: char) -> char {
|
||||
match c {
|
||||
'\u{0660}'..='\u{0669}' => char::from(b'0' + (c as u32 - 0x0660) as u8),
|
||||
'\u{06F0}'..='\u{06F9}' => char::from(b'0' + (c as u32 - 0x06F0) as u8),
|
||||
'\u{FF10}'..='\u{FF19}' => char::from(b'0' + (c as u32 - 0xFF10) as u8),
|
||||
'\u{066B}' | '\u{FF0E}' => '.',
|
||||
'\u{FF0C}' => ',',
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a measurement typed by a user: `1"`, `1 in`, `2.5cm`, `12pt`, `3 pi`, `10 mm`, `1.5 li`
|
||||
/// (lines are 12 pt). A bare number is in `default`. Returns points. Either decimal separator
|
||||
/// works (`2,5 cm` and `2.5 cm`), whatever the region.
|
||||
/// (lines are 12 pt), `8 px` (pixels are 0.75 pt). A bare number is in `default`. Returns points,
|
||||
/// or `None` for anything unreadable or whose result does not fit in an `f32`.
|
||||
///
|
||||
/// Either decimal separator works (`2,5 cm` and `2.5 cm`), whatever the region, so a thousands
|
||||
/// separator is *not* understood: `1,000 pt` is 1 pt, not 1000. Arabic-Indic and full-width digits
|
||||
/// are accepted like ASCII ones. Scientific notation is not: the number ends at the `e`.
|
||||
pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
|
||||
let t = s.trim().to_ascii_lowercase().replace('\u{2212}', "-");
|
||||
let t = s.trim().chars().map(fold_digit).collect::<String>().to_ascii_lowercase().replace('\u{2212}', "-");
|
||||
if t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -123,8 +154,7 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
|
||||
"cm" => PT_PER_CM,
|
||||
"mm" => PT_PER_CM / 10.0,
|
||||
"pt" | "pts" | "point" | "points" => 1.0,
|
||||
"pi" | "pc" | "pica" | "picas" => 12.0,
|
||||
"li" | "line" | "lines" => 12.0,
|
||||
"pi" | "pc" | "pica" | "picas" | "li" | "line" | "lines" => 12.0,
|
||||
"px" => 0.75,
|
||||
_ => return None,
|
||||
};
|
||||
@@ -138,50 +168,98 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
|
||||
/// A point in page space (points, y down).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)]
|
||||
pub struct Point {
|
||||
/// Distance from the left edge.
|
||||
pub x: f32,
|
||||
/// Distance from the top edge.
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
/// A point at (`x`, `y`).
|
||||
pub const fn new(x: f32, y: f32) -> Self {
|
||||
Point { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
/// An axis-aligned rectangle (points, y down). `w`/`h` are never negative when built with [`Rect::new`].
|
||||
/// An axis-aligned rectangle (points, y down). `w`/`h` are finite and never negative, whether the
|
||||
/// rectangle was built with [`Rect::new`] or deserialized (both go through the same checks).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)]
|
||||
#[serde(from = "RectRaw")]
|
||||
pub struct Rect {
|
||||
/// Left edge.
|
||||
pub x: f32,
|
||||
/// Top edge.
|
||||
pub y: f32,
|
||||
/// Width.
|
||||
pub w: f32,
|
||||
/// Height.
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
/// The unchecked shape of a [`Rect`] on the wire; converting it applies [`Rect::new`]'s rules.
|
||||
#[derive(Deserialize)]
|
||||
struct RectRaw {
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
}
|
||||
|
||||
impl From<RectRaw> for Rect {
|
||||
fn from(r: RectRaw) -> Self {
|
||||
Rect::new(r.x, r.y, r.w, r.h)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where two crossed edges meet: both land on their midpoint.
|
||||
fn collapse(lo: f32, hi: f32) -> (f32, f32) {
|
||||
if hi < lo {
|
||||
let m = lo * 0.5 + hi * 0.5;
|
||||
(m, m)
|
||||
} else {
|
||||
(lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
/// A rectangle with NaN and infinities replaced by 0 and a negative size clamped to 0.
|
||||
pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
|
||||
Rect { x: finite(x), y: finite(y), w: finite(w).max(0.0), h: finite(h).max(0.0) }
|
||||
}
|
||||
/// The right edge.
|
||||
pub fn right(&self) -> f32 {
|
||||
self.x + self.w
|
||||
}
|
||||
/// The bottom edge.
|
||||
pub fn bottom(&self) -> f32 {
|
||||
self.y + self.h
|
||||
}
|
||||
/// Whether `p` is inside or on the edge. Edges are *included*, unlike [`Rect::intersects`],
|
||||
/// so a point on an edge shared by two rectangles is in both.
|
||||
pub fn contains(&self, p: Point) -> bool {
|
||||
p.x >= self.x && p.x <= self.right() && p.y >= self.y && p.y <= self.bottom()
|
||||
}
|
||||
/// Whether the interiors overlap. Rectangles that only touch along an edge do *not* intersect.
|
||||
pub fn intersects(&self, o: &Rect) -> bool {
|
||||
self.x < o.right() && o.x < self.right() && self.y < o.bottom() && o.y < self.bottom()
|
||||
}
|
||||
/// The smallest rectangle covering both. An empty rectangle still counts: `Rect::default()`
|
||||
/// sits at the origin, so accumulating bounds from it always stretches to (0, 0). Start from
|
||||
/// the first real rectangle instead.
|
||||
pub fn union(&self, o: &Rect) -> Rect {
|
||||
let x = self.x.min(o.x);
|
||||
let y = self.y.min(o.y);
|
||||
Rect::new(x, y, self.right().max(o.right()) - x, self.bottom().max(o.bottom()) - y)
|
||||
}
|
||||
/// Shrunk by `l`, `t`, `r`, `b` on the left, top, right and bottom (grown for negative values).
|
||||
/// If the edges cross, the result has zero size at the middle of where they crossed.
|
||||
pub fn inset(&self, l: f32, t: f32, r: f32, b: f32) -> Rect {
|
||||
Rect::new(self.x + l, self.y + t, self.w - l - r, self.h - t - b)
|
||||
let (l, t, r, b) = (finite(l), finite(t), finite(r), finite(b));
|
||||
let (x0, x1) = collapse(self.x + l, self.right() - r);
|
||||
let (y0, y1) = collapse(self.y + t, self.bottom() - b);
|
||||
Rect::new(x0, y0, x1 - x0, y1 - y0)
|
||||
}
|
||||
/// Grown by `d` on every side (shrunk for negative `d`, down to zero size).
|
||||
/// Grown by `d` on every side (shrunk for negative `d`, down to zero size at the centre).
|
||||
pub fn expand(&self, d: f32) -> Rect {
|
||||
self.inset(-d, -d, -d, -d)
|
||||
}
|
||||
@@ -198,12 +276,15 @@ pub fn normalize_degrees(deg: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// How a drawing is turned about its centre: mirrored first (`flip_h` left to right, `flip_v` top
|
||||
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as DrawingML's `a:xfrm`
|
||||
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as `DrawingML`'s `a:xfrm`
|
||||
/// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub struct Spin {
|
||||
/// Clockwise rotation in degrees.
|
||||
pub deg: f32,
|
||||
/// Mirrored left to right.
|
||||
pub flip_h: bool,
|
||||
/// Mirrored top to bottom.
|
||||
pub flip_v: bool,
|
||||
}
|
||||
|
||||
@@ -219,7 +300,7 @@ impl Spin {
|
||||
}
|
||||
|
||||
/// The linear part (a, b, c, d: x' = a·x + c·y, y' = b·x + d·y).
|
||||
fn linear(&self) -> [f32; 4] {
|
||||
fn linear(self) -> [f32; 4] {
|
||||
let r = normalize_degrees(self.deg).to_radians();
|
||||
let (s, c) = r.sin_cos();
|
||||
let fx = if self.flip_h { -1.0 } else { 1.0 };
|
||||
@@ -237,17 +318,17 @@ impl Spin {
|
||||
|
||||
/// Where point (`x`, `y`) goes when turned about (`cx`, `cy`).
|
||||
pub fn apply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (u, v) = (x - cx, y - cy);
|
||||
(cx + a * u + c * v, cy + b * u + d * v)
|
||||
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
|
||||
let (relative_x, relative_y) = (x - cx, y - cy);
|
||||
(cx + x_from_x * relative_x + x_from_y * relative_y, cy + y_from_x * relative_x + y_from_y * relative_y)
|
||||
}
|
||||
|
||||
/// The point that [`Spin::apply`] takes to (`x`, `y`).
|
||||
pub fn unapply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
|
||||
// The linear part is orthogonal: its inverse is its transpose.
|
||||
let [a, b, c, d] = self.linear();
|
||||
let (u, v) = (x - cx, y - cy);
|
||||
(cx + a * u + b * v, cy + c * u + d * v)
|
||||
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
|
||||
let (relative_x, relative_y) = (x - cx, y - cy);
|
||||
(cx + x_from_x * relative_x + y_from_x * relative_y, cy + x_from_y * relative_x + y_from_y * relative_y)
|
||||
}
|
||||
|
||||
/// The axis-aligned box `r` covers once turned about its centre.
|
||||
@@ -258,10 +339,10 @@ impl Spin {
|
||||
|
||||
/// The width and height of the box a `w` × `h` rectangle covers once turned.
|
||||
pub fn extent(&self, w: f32, h: f32) -> (f32, f32) {
|
||||
let (w, h) = (finite(w).abs(), finite(h).abs());
|
||||
let r = normalize_degrees(self.deg).to_radians();
|
||||
let (s, c) = (r.sin().abs(), r.cos().abs());
|
||||
(w * c + h * s, w * s + h * c)
|
||||
let (width, height) = (finite(w).abs(), finite(h).abs());
|
||||
let radians = normalize_degrees(self.deg).to_radians();
|
||||
let (sine, cosine) = (radians.sin().abs(), radians.cos().abs());
|
||||
(width * cosine + height * sine, width * sine + height * cosine)
|
||||
}
|
||||
|
||||
/// This spin applied inside `outer` (a group member's own spin within its group's): the one
|
||||
@@ -307,13 +388,15 @@ pub fn paper_by_name(name: &str) -> Option<(&'static str, f32, f32)> {
|
||||
/// How a page is placed on other paper when printing with "Scale to paper size" (#2108).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PaperFit {
|
||||
/// The sheet, turned to the page's orientation (points).
|
||||
/// The sheet's width, turned to the page's orientation (points).
|
||||
pub paper_w: f32,
|
||||
/// The sheet's height, turned to the page's orientation (points).
|
||||
pub paper_h: f32,
|
||||
/// Page points to sheet points.
|
||||
pub k: f32,
|
||||
/// Where the page's top-left corner lands on the sheet (the page is centred).
|
||||
/// Where the page's left edge lands on the sheet (the page is centred).
|
||||
pub dx: f32,
|
||||
/// Where the page's top edge lands on the sheet (the page is centred).
|
||||
pub dy: f32,
|
||||
}
|
||||
|
||||
@@ -323,7 +406,7 @@ pub struct PaperFit {
|
||||
/// page as it is (scale 1 on paper of its own size).
|
||||
pub fn fit_to_paper(page_w: f32, page_h: f32, paper_w: f32, paper_h: f32) -> PaperFit {
|
||||
let ok = |v: f32| v.is_finite() && v >= 1.0;
|
||||
let as_is = PaperFit { paper_w: page_w, paper_h: page_h, k: 1.0, dx: 0.0, dy: 0.0 };
|
||||
let as_is = PaperFit { paper_w: finite(page_w), paper_h: finite(page_h), k: 1.0, dx: 0.0, dy: 0.0 };
|
||||
if !(ok(page_w) && ok(page_h) && ok(paper_w) && ok(paper_h)) {
|
||||
return as_is;
|
||||
}
|
||||
@@ -341,13 +424,17 @@ pub fn fit_to_paper(page_w: f32, page_h: f32, paper_w: f32, paper_h: f32) -> Pap
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn close(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < 1e-3
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_round_trips() {
|
||||
assert_eq!(twips(1440), 72.0);
|
||||
assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits());
|
||||
assert_eq!(to_twips(72.0), 1440);
|
||||
assert_eq!(emu(914_400), 72.0);
|
||||
assert_eq!(emu(914_400).to_bits(), 72.0f32.to_bits());
|
||||
assert_eq!(to_emu(72.0), 914_400);
|
||||
assert_eq!(half_points(24), 12.0);
|
||||
assert_eq!(half_points(24).to_bits(), 12.0f32.to_bits());
|
||||
assert_eq!(to_half_points(10.5), 21);
|
||||
assert_eq!(to_twips(f32::NAN), 0);
|
||||
}
|
||||
@@ -359,6 +446,7 @@ mod tests {
|
||||
assert_eq!(parse_measure("12pt", Unit::Inches), Some(12.0));
|
||||
assert_eq!(parse_measure("2", Unit::Inches), Some(144.0));
|
||||
assert_eq!(parse_measure("1,5 li", Unit::Inches), Some(18.0));
|
||||
assert_eq!(parse_measure("8 px", Unit::Inches), Some(6.0));
|
||||
let cm = parse_measure("2.54 cm", Unit::Inches).unwrap();
|
||||
assert!((cm - 72.0).abs() < 0.01);
|
||||
assert_eq!(parse_measure("abc", Unit::Inches), None);
|
||||
@@ -371,19 +459,29 @@ mod tests {
|
||||
assert_eq!(parse_measure("1.5\"", Unit::Centimeters), Some(108.0));
|
||||
assert_eq!(parse_measure("\u{2212}1 in", Unit::Points), Some(-72.0));
|
||||
assert_eq!(parse_measure("1,2,3", Unit::Inches), None);
|
||||
// Overflowing values during unit conversion return None (#1359).
|
||||
// A comma is a decimal separator, never a thousands separator.
|
||||
assert_eq!(parse_measure("1,000 pt", Unit::Inches), Some(1.0));
|
||||
// Scientific notation is not accepted: the number stops at the `e`, leaving an unknown
|
||||
// unit. (Overflow itself is covered by `parse_measure_rejects_overflow_to_infinity`.)
|
||||
assert_eq!(parse_measure("1e3 pt", Unit::Points), None);
|
||||
assert_eq!(parse_measure("3.4e38 in", Unit::Points), None);
|
||||
assert_eq!(parse_measure("-3.4e38 in", Unit::Points), None);
|
||||
assert_eq!(parse_measure("3.4e38 cm", Unit::Points), None);
|
||||
assert_eq!(parse_measure("3.4e38 mm", Unit::Points), None);
|
||||
assert_eq!(parse_measure("3.4e38 pi", Unit::Points), None);
|
||||
assert_eq!(parse_measure("3.4e38 li", Unit::Points), None);
|
||||
assert_eq!(parse_measure("3.4e38", Unit::Inches), None);
|
||||
assert_eq!(parse_measure("1e39 pt", Unit::Points), None);
|
||||
assert_eq!(parse_measure("inf", Unit::Points), None);
|
||||
assert_eq!(parse_measure("nan", Unit::Points), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_digits_of_other_scripts() {
|
||||
let two_cm = parse_measure("2 cm", Unit::Inches).unwrap();
|
||||
assert_eq!(parse_measure("\u{0662} cm", Unit::Inches), Some(two_cm)); // Arabic-Indic ٢
|
||||
assert_eq!(parse_measure("\u{06F2} cm", Unit::Inches), Some(two_cm)); // Extended ۲
|
||||
assert_eq!(parse_measure("\u{FF12} cm", Unit::Inches), Some(two_cm)); // Full-width 2
|
||||
let two_and_half = parse_measure("2.5 cm", Unit::Inches).unwrap();
|
||||
assert_eq!(parse_measure("\u{0662}\u{066B}\u{0665} cm", Unit::Inches), Some(two_and_half)); // ٢٫٥
|
||||
assert_eq!(parse_measure("\u{FF12}\u{FF0E}\u{FF15}cm", Unit::Inches), Some(two_and_half)); // 2.5
|
||||
assert_eq!(parse_measure("\u{0663}", Unit::Points), Some(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_measure_rejects_overflow_to_infinity() {
|
||||
// Finite inputs whose scaled result overflows `f32` must be rejected,
|
||||
@@ -420,6 +518,10 @@ mod tests {
|
||||
assert_eq!(Unit::Inches.format_with(108.0, ','), "1,5\"");
|
||||
assert_eq!(Unit::Points.format_with(720.0, ','), "720 pt");
|
||||
assert_eq!(Unit::Inches.format_with(f32::NAN, ','), "0\"");
|
||||
// A tiny negative value must not print as "-0".
|
||||
assert_eq!(Unit::Points.format(-0.001), "0 pt");
|
||||
// Any character can be the separator.
|
||||
assert_eq!(Unit::Inches.number(108.0, '\u{066B}'), "1\u{066B}5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -429,10 +531,106 @@ mod tests {
|
||||
assert!(a.intersects(&b));
|
||||
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 15.0, 15.0));
|
||||
assert!(a.contains(Point::new(5.0, 5.0)));
|
||||
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w, 0.0);
|
||||
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w.to_bits(), 0.0f32.to_bits());
|
||||
assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_edges_are_in_contains_but_not_intersects() {
|
||||
let a = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
let b = Rect::new(10.0, 0.0, 10.0, 10.0); // shares the edge x = 10
|
||||
assert!(!a.intersects(&b));
|
||||
assert!(a.contains(Point::new(10.0, 5.0)) && b.contains(Point::new(10.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inset_past_zero_collapses_to_center() {
|
||||
let r = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
assert_eq!(r.inset(8.0, 8.0, 8.0, 8.0), Rect::new(5.0, 5.0, 0.0, 0.0));
|
||||
assert_eq!(r.expand(-8.0), Rect::new(5.0, 5.0, 0.0, 0.0));
|
||||
assert_eq!(r.expand(-20.0), Rect::new(5.0, 5.0, 0.0, 0.0));
|
||||
// Only one axis crosses: the other keeps its size.
|
||||
assert_eq!(r.inset(0.0, 8.0, 0.0, 8.0), Rect::new(0.0, 5.0, 10.0, 0.0));
|
||||
// Growing still works, and hostile insets are ignored rather than poisoning the result.
|
||||
assert_eq!(r.expand(1.0), Rect::new(-1.0, -1.0, 12.0, 12.0));
|
||||
assert_eq!(r.inset(f32::NAN, 0.0, 0.0, 0.0), r);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_from_raw_is_sanitised() {
|
||||
// Deserialization goes through this conversion (`#[serde(from = "RectRaw")]`).
|
||||
let r = Rect::from(RectRaw { x: f32::NAN, y: 1.0, w: -4.0, h: f32::INFINITY });
|
||||
assert_eq!(r, Rect::new(0.0, 1.0, 0.0, 0.0));
|
||||
let ok = Rect::from(RectRaw { x: 1.0, y: 2.0, w: 3.0, h: 4.0 });
|
||||
assert_eq!(ok, Rect::new(1.0, 2.0, 3.0, 4.0));
|
||||
}
|
||||
#[test]
|
||||
fn rects_are_cleaned_when_deserialized() {
|
||||
use serde::de::value::{Error, MapDeserializer};
|
||||
let fields = [("x", f32::NAN), ("y", 1.0), ("w", -5.0), ("h", 2.0)];
|
||||
let parsed: Result<Rect, Error> = Rect::deserialize(MapDeserializer::new(fields.into_iter()));
|
||||
assert!(parsed.is_ok());
|
||||
assert_eq!(parsed.unwrap_or_default(), Rect::new(0.0, 1.0, 0.0, 2.0));
|
||||
}
|
||||
#[test]
|
||||
fn spin_apply_and_unapply_are_inverse() {
|
||||
for spin in [
|
||||
Spin::new(0.0, false, false),
|
||||
Spin::new(37.0, false, false),
|
||||
Spin::new(90.0, true, false),
|
||||
Spin::new(215.0, false, true),
|
||||
Spin::new(300.0, true, true),
|
||||
] {
|
||||
let (x, y) = spin.apply(50.0, 40.0, 70.0, 10.0);
|
||||
let (bx, by) = spin.unapply(50.0, 40.0, x, y);
|
||||
assert!(close(bx, 70.0) && close(by, 10.0), "{spin:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_turn_is_clockwise_in_page_space() {
|
||||
// y points down, so the point to the right of the centre goes below it.
|
||||
let (x, y) = Spin::new(90.0, false, false).apply(0.0, 0.0, 10.0, 0.0);
|
||||
assert!(x.abs() < 1e-4 && (y - 10.0).abs() < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn within_equals_applying_both_spins() {
|
||||
let (outer, inner) = (Spin::new(30.0, true, false), Spin::new(75.0, false, true));
|
||||
let (ix, iy) = inner.apply(0.0, 0.0, 12.0, -7.0);
|
||||
let (ex, ey) = outer.apply(0.0, 0.0, ix, iy);
|
||||
let (bx, by) = inner.within(outer).apply(0.0, 0.0, 12.0, -7.0);
|
||||
assert!(close(ex, bx) && close(ey, by));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spin_matrix_agrees_with_apply() {
|
||||
let spin = Spin::new(37.0, true, false);
|
||||
let [a, b, c, d, e, f] = spin.matrix(50.0, 40.0);
|
||||
let (x, y) = spin.apply(50.0, 40.0, 70.0, 10.0);
|
||||
assert!(close(a * 70.0 + c * 10.0 + e, x) && close(b * 70.0 + d * 10.0 + f, y));
|
||||
// The centre stays where it is.
|
||||
let (cx, cy) = spin.apply(50.0, 40.0, 50.0, 40.0);
|
||||
assert!(close(cx, 50.0) && close(cy, 40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spin_bounds_and_identity() {
|
||||
assert!(Spin::default().is_identity());
|
||||
assert!(Spin::new(360.0, false, false).is_identity());
|
||||
assert!(!Spin::new(0.0, true, false).is_identity());
|
||||
let b = Spin::new(90.0, false, false).bounds(Rect::new(0.0, 0.0, 10.0, 20.0));
|
||||
assert!(close(b.x, -5.0) && close(b.y, 5.0) && close(b.w, 20.0) && close(b.h, 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalises_degrees() {
|
||||
assert_eq!(normalize_degrees(370.0), 10.0);
|
||||
assert_eq!(normalize_degrees(-90.0), 270.0);
|
||||
assert_eq!(normalize_degrees(f32::NAN), 0.0);
|
||||
assert!((0.0..360.0).contains(&normalize_degrees(-1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_names() {
|
||||
assert_eq!(paper_name(612.0, 792.0), Some("Letter"));
|
||||
@@ -468,6 +666,7 @@ mod tests {
|
||||
{
|
||||
let f = fit_to_paper(a, b, c, d);
|
||||
assert_eq!((f.k, f.dx, f.dy), (1.0, 0.0, 0.0));
|
||||
assert!(f.paper_w.is_finite() && f.paper_h.is_finite());
|
||||
}
|
||||
assert!(fit_to_paper(1.0, 1.0, f32::MAX, f32::MAX).k.is_finite());
|
||||
}
|
||||
|
||||
+29
-33
@@ -20,9 +20,9 @@ pub enum Refusal {
|
||||
NotAPicture,
|
||||
/// A kind of picture that is never decoded, because its decoder can't be held to a budget.
|
||||
Unsupported(&'static str),
|
||||
/// Decoding it would take more memory than the budget.
|
||||
/// Decoding would exceed the memory budget or size arithmetic overflowed.
|
||||
TooLarge { width: u32, height: u32 },
|
||||
/// The header or the data is damaged.
|
||||
/// The header or data is damaged, or the decoder rejects the input.
|
||||
Broken(String),
|
||||
}
|
||||
|
||||
@@ -179,11 +179,19 @@ pub struct Probe<'a> {
|
||||
}
|
||||
|
||||
/// TIFF compressions decoded within the caller's limits: none, CCITT Group 4, LZW, Deflate (both
|
||||
/// codes) and PackBits. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
|
||||
/// codes) and `PackBits`. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
|
||||
/// default limits, whatever size the TIFF declares, so such a TIFF is not decoded (#3645).
|
||||
const TIFF_COMPRESSIONS: [u16; 6] = [1, 4, 5, 8, 32946, 32773];
|
||||
|
||||
/// Read a picture's header: PNG, JPEG, GIF, WebP, BMP or TIFF.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::NotAPicture` for an unsupported format, `Refusal::Unsupported` for a TIFF
|
||||
/// whose compression cannot be read or budgeted (including truncation that prevents reading
|
||||
/// its compression metadata), `Refusal::TooLarge`
|
||||
/// on size arithmetic overflow, and `Refusal::Broken` for other header or inspection errors,
|
||||
/// including TIFF errors after compression metadata is accepted.
|
||||
pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
|
||||
let codec_fmt = detect(bytes).ok_or(Refusal::NotAPicture)?;
|
||||
let format = from_codec_format(codec_fmt).ok_or(Refusal::NotAPicture)?;
|
||||
@@ -287,6 +295,11 @@ fn dib_to_bmp(dib: &[u8]) -> Vec<u8> {
|
||||
/// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds
|
||||
/// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see
|
||||
/// [`dib_layout`]).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic
|
||||
/// overflow.
|
||||
pub fn probe_dib(dib: Vec<u8>) -> Result<Probe<'static>, Refusal> {
|
||||
let dib = dib_layout(dib);
|
||||
let bmp = dib_to_bmp(&dib);
|
||||
@@ -349,6 +362,12 @@ impl Probe<'_> {
|
||||
|
||||
/// Decode, refused before anything is allocated when the peak would pass `budget` bytes. The
|
||||
/// decoder is held to the header's size and to `budget` as well.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Refusal::TooLarge` when the picture does not fit `budget` or the decoder
|
||||
/// exceeds its limits, `Refusal::NotAPicture` for an unsupported format, and
|
||||
/// `Refusal::Broken` for other decoding or pixel-conversion errors.
|
||||
pub fn decode(&self, budget: u64) -> Result<DynamicImage, Refusal> {
|
||||
if !self.fits(budget) {
|
||||
return Err(Refusal::TooLarge { width: self.width, height: self.height });
|
||||
@@ -364,6 +383,10 @@ impl Probe<'_> {
|
||||
}
|
||||
|
||||
/// [`probe`], then [`Probe::decode`] within `budget` bytes.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the probing or decoding `Refusal`; see [`probe`] and [`Probe::decode`].
|
||||
pub fn decode(bytes: &[u8], budget: u64) -> Result<DynamicImage, Refusal> {
|
||||
probe(bytes)?.decode(budget)
|
||||
}
|
||||
@@ -516,36 +539,7 @@ fn worst_coefficients(bytes: &[u8]) -> u64 {
|
||||
/// tag is missing. None when the header can't be read, or when the tag appears more than once:
|
||||
/// the decoder keeps the last copy, so a harmless first one must not hide a JPEG one after it.
|
||||
fn tiff_compression(bytes: &[u8]) -> Option<u16> {
|
||||
let le = match bytes.get(..4)? {
|
||||
b"II*\0" => true,
|
||||
b"MM\0*" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let u16_at = |at: usize| -> Option<u16> {
|
||||
let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?];
|
||||
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
|
||||
};
|
||||
let u32_at = |at: usize| -> Option<u32> {
|
||||
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
|
||||
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
|
||||
};
|
||||
let ifd = usize::try_from(u32_at(4)?).ok()?;
|
||||
let mut found = None;
|
||||
for i in 0..usize::from(u16_at(ifd)?) {
|
||||
let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?;
|
||||
if u16_at(entry)? != 259 {
|
||||
continue;
|
||||
}
|
||||
if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 {
|
||||
return None;
|
||||
}
|
||||
found = Some(match u16_at(entry.checked_add(2)?)? {
|
||||
3 => u16_at(entry.checked_add(8)?)?,
|
||||
4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?,
|
||||
_ => return None,
|
||||
});
|
||||
}
|
||||
Some(found.unwrap_or(1))
|
||||
craft_tiff::probe::first_image_compression(bytes)
|
||||
}
|
||||
|
||||
/// A DIB with a V4 or V5 header in the layout the decoder reads. A 32-bit one whose alpha mask
|
||||
@@ -722,6 +716,7 @@ mod tests {
|
||||
let mut s = vec![8];
|
||||
s.extend(h.to_be_bytes());
|
||||
s.extend(w.to_be_bytes());
|
||||
#[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")]
|
||||
s.push((comps.len() / 3) as u8);
|
||||
s.extend(comps);
|
||||
s
|
||||
@@ -736,6 +731,7 @@ mod tests {
|
||||
// A marker walk over SOI, an APP0 segment, SOF2, then the scan.
|
||||
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2];
|
||||
let f = sof(64, 64, &[1, 0x11, 0]);
|
||||
#[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")]
|
||||
jpeg.extend(((f.len() + 2) as u16).to_be_bytes());
|
||||
jpeg.extend(&f);
|
||||
jpeg.extend([0xFF, 0xDA]);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user