mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-04 19:56:58 -06:00
Compare commits
403
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ffbe57ebe | ||
|
|
551463ca51 | ||
|
|
bd69ff6e73 | ||
|
|
c867a329be | ||
|
|
ba68b13b19 | ||
|
|
b0fd8cbfe9 | ||
|
|
c6bceddb93 | ||
|
|
5a71494219 | ||
|
|
b2adf0f456 | ||
|
|
255309155b | ||
|
|
daa74a4fda | ||
|
|
ec687a6876 | ||
|
|
1e2e0cf217 | ||
|
|
ba01027379 | ||
|
|
61953d5fa9 | ||
|
|
ae35ca4fd8 | ||
|
|
c7d2d85a86 | ||
|
|
7c74a5fa93 | ||
|
|
89e336f645 | ||
|
|
18c7cfd8d6 | ||
|
|
8670496a46 | ||
|
|
2895ab88d4 | ||
|
|
5288ef3255 | ||
|
|
8527081bc2 | ||
|
|
342931078a | ||
|
|
6c47d77c19 | ||
|
|
0eed1a0d15 | ||
|
|
820742d5dc | ||
|
|
5cc4702ca8 | ||
|
|
1f73bb9486 | ||
|
|
017af2f3f9 | ||
|
|
72afcbd32d | ||
|
|
72ef3083e7 | ||
|
|
27672b2448 | ||
|
|
67d5297c08 | ||
|
|
4c1dfa6367 | ||
|
|
ccf405de52 | ||
|
|
da072c3e74 | ||
|
|
c013dff332 | ||
|
|
e976e6aa69 | ||
|
|
1580f46cee | ||
|
|
f03da28fb5 | ||
|
|
48f0ad7496 | ||
|
|
ab58acfa09 | ||
|
|
d48ca8d3ec | ||
|
|
425f6d990d | ||
|
|
e3878d2b83 | ||
|
|
a1b04eaa52 | ||
|
|
f98d9c2515 | ||
|
|
d8f1a821c7 | ||
|
|
b400a7bbb8 | ||
|
|
c84c1b9e44 | ||
|
|
bee380b2e8 | ||
|
|
dc266c5e55 | ||
|
|
95bfd5af43 | ||
|
|
c7bb1c9636 | ||
|
|
463552ac36 | ||
|
|
870bbffddf | ||
|
|
a2d8bbdb4d | ||
|
|
98e617806b | ||
|
|
4f6dbbb5fd | ||
|
|
882bacb858 | ||
|
|
3487354a1b | ||
|
|
991b590021 | ||
|
|
549748efec | ||
|
|
bf7ce2509c | ||
|
|
f5c9da1b70 | ||
|
|
c8c78e0fab | ||
|
|
dd42e032fc | ||
|
|
438223240c | ||
|
|
6c80ff1de1 | ||
|
|
6585dbbfca | ||
|
|
83a2e63257 | ||
|
|
e3a913a4d3 | ||
|
|
25f126f48b | ||
|
|
ba8bc15d89 | ||
|
|
30792edab8 | ||
|
|
2094505e3a | ||
|
|
7db2784719 | ||
|
|
cbea96e5e9 | ||
|
|
0d04e94422 | ||
|
|
e26c73df7a | ||
|
|
ed33f21784 | ||
|
|
6b021d557d | ||
|
|
5bfdfc3bf6 | ||
|
|
2ed77bdb93 | ||
|
|
d01c843aa2 | ||
|
|
cde21126d2 | ||
|
|
42f157b53f | ||
|
|
34a93e9123 | ||
|
|
9f7fcb88a7 | ||
|
|
da69216eeb | ||
|
|
a668eba449 | ||
|
|
b7c34c3e1e | ||
|
|
3ec85eeb81 | ||
|
|
3c9c0219b8 | ||
|
|
b185aaf839 | ||
|
|
03439ff33f | ||
|
|
93573f56e6 | ||
|
|
cb1c530240 | ||
|
|
dc5f5852dd | ||
|
|
b4cb84ea5d | ||
|
|
faebf07b9a | ||
|
|
acc1233da0 | ||
|
|
c1a0484d81 | ||
|
|
f6f7e9414e | ||
|
|
1de5a93974 | ||
|
|
9f43aa6ec1 | ||
|
|
f2e2c78c4b | ||
|
|
fe22b29c5f | ||
|
|
7f86031339 | ||
|
|
10fcb05b15 | ||
|
|
1a05479d99 | ||
|
|
fc0acd93b9 | ||
|
|
5c2e7eb296 | ||
|
|
cc7f9e2688 | ||
|
|
d885a9d997 | ||
|
|
a67df42aa8 | ||
|
|
27dea96335 | ||
|
|
1fd3163fcc | ||
|
|
3c5aeef936 | ||
|
|
b29d85119e | ||
|
|
4158ed794d | ||
|
|
b5b6300036 | ||
|
|
4fcdd74b9f | ||
|
|
bcf2aa3b03 | ||
|
|
9dad9fca5f | ||
|
|
1bd422a454 | ||
|
|
0a7bf74427 | ||
|
|
f3d88f5da3 | ||
|
|
87d5e537e2 | ||
|
|
175d2eabe6 | ||
|
|
585cc90953 | ||
|
|
53cd405269 | ||
|
|
5991c5b7e4 | ||
|
|
7d0a1f897b | ||
|
|
f1c93ad7c7 | ||
|
|
c17448f4d5 | ||
|
|
2f16864552 | ||
|
|
902838c7b8 | ||
|
|
395eb4d8ff | ||
|
|
b8535745a0 | ||
|
|
e5bc372a0c | ||
|
|
16c803ecfd | ||
|
|
206ed0fcd4 | ||
|
|
7220765c02 | ||
|
|
257bdec953 | ||
|
|
ed757d0cdf | ||
|
|
1ab6d78010 | ||
|
|
7c6fbc0681 | ||
|
|
3afd70cf3d | ||
|
|
b741bbac9a | ||
|
|
fd948e2015 | ||
|
|
612e92e6c5 | ||
|
|
5ae937d8e3 | ||
|
|
c07395d712 | ||
|
|
1b9b8b1bf3 | ||
|
|
ea5d48b18c | ||
|
|
03b54b043f | ||
|
|
e2588d8d35 | ||
|
|
026803c4bf | ||
|
|
51ba3b8382 | ||
|
|
48e07fbcd1 | ||
|
|
72e54545d8 | ||
|
|
28d2dac6fd | ||
|
|
209db57e2c | ||
|
|
481eb1e79b | ||
|
|
4b5ad59b01 | ||
|
|
f22123dbaf | ||
|
|
df475fac83 | ||
|
|
1405e7e8cb | ||
|
|
cf8b64ffae | ||
|
|
aea7330f43 | ||
|
|
951e6b230d | ||
|
|
f55fabaac6 | ||
|
|
faa032ec12 | ||
|
|
989a377de9 | ||
|
|
b8362fc62d | ||
|
|
c14183a0a0 | ||
|
|
78b0a6929c | ||
|
|
870bec1839 | ||
|
|
e819a03435 | ||
|
|
77c0a29922 | ||
|
|
cc438cb369 | ||
|
|
5a22d2d4ae | ||
|
|
d66a7d3bf9 | ||
|
|
5efc89e5ea | ||
|
|
010134fb8e | ||
|
|
08b8d71ece | ||
|
|
940b64273c | ||
|
|
a1fa8b1a13 | ||
|
|
d05c629fc0 | ||
|
|
e8c3216cad | ||
|
|
8027b35f8d | ||
|
|
f33b5f8551 | ||
|
|
4bac1b4da0 | ||
|
|
e862c6ad51 | ||
|
|
3035dda6d4 | ||
|
|
6b0c47d2a8 | ||
|
|
1a8e4ac2d3 | ||
|
|
647e726179 | ||
|
|
c2f7c65e9c | ||
|
|
8d9eb6fc0f | ||
|
|
93abd12f9f | ||
|
|
f722a2f80b | ||
|
|
6b8f63e207 | ||
|
|
678e813ec4 | ||
|
|
afba11d6e0 | ||
|
|
2b30b235d8 | ||
|
|
1f682738fd | ||
|
|
423c58523d | ||
|
|
e076e47529 | ||
|
|
f87e9cd6ba | ||
|
|
17a13fd901 | ||
|
|
50c7b1963f | ||
|
|
b4eff8d494 | ||
|
|
79b3b88edd | ||
|
|
3820b9b206 | ||
|
|
e874c67147 | ||
|
|
605df8c165 | ||
|
|
8d7ed624ec | ||
|
|
aeba356814 | ||
|
|
ce54605a04 | ||
|
|
592d3cb902 | ||
|
|
fd81fadba7 | ||
|
|
17ae08d4b8 | ||
|
|
8edbfcdeef | ||
|
|
0f30f776bb | ||
|
|
0c7ad0e0f0 | ||
|
|
91cb502355 | ||
|
|
19947b9170 | ||
|
|
3de53ecf4e | ||
|
|
faec3ecbde | ||
|
|
d46ecf3ab1 | ||
|
|
5945ca3cae | ||
|
|
14111658d1 | ||
|
|
8286638f79 | ||
|
|
eeac0d3322 | ||
|
|
cac0dd2ee0 | ||
|
|
dd2d40a5f5 | ||
|
|
3e5c6ce405 | ||
|
|
3fe111cc9f | ||
|
|
8aa24886da | ||
|
|
2114b003ef | ||
|
|
c70411808d | ||
|
|
e129211603 | ||
|
|
91a52f278c | ||
|
|
80c5151ab3 | ||
|
|
b4b41e038d | ||
|
|
6637fb7bbf | ||
|
|
5e8c7cb7cb | ||
|
|
ee05e88fa0 | ||
|
|
81aae389b3 | ||
|
|
8803a95a2d | ||
|
|
2c08518c6f | ||
|
|
4a4b37c255 | ||
|
|
adef1253bb | ||
|
|
ff271a34e8 | ||
|
|
676fe0ee9b | ||
|
|
52d50bd830 | ||
|
|
6ebd483b14 | ||
|
|
16ec8d91ce | ||
|
|
be2d9021bf | ||
|
|
6078524793 | ||
|
|
3f9fc816bf | ||
|
|
d729387c8c | ||
|
|
c7b21e5d02 | ||
|
|
273d2ed225 | ||
|
|
bdf3c54189 | ||
|
|
6a445b341a | ||
|
|
958dd78ceb | ||
|
|
0b7bdee856 | ||
|
|
8be58e3a21 | ||
|
|
8654ed1319 | ||
|
|
8e7fca10b4 | ||
|
|
b83864e0f4 | ||
|
|
e39281dce7 | ||
|
|
60ec8580cd | ||
|
|
ac306cf704 | ||
|
|
0ac9cbfba9 | ||
|
|
488f75b6e0 | ||
|
|
dd3d3040ac | ||
|
|
03da178335 | ||
|
|
8ee16cc876 | ||
|
|
7777eba6e4 | ||
|
|
b1958ac483 | ||
|
|
dfbeffd34a | ||
|
|
4722d7d2fe | ||
|
|
81a367be13 | ||
|
|
989fa17544 | ||
|
|
eccf146bca | ||
|
|
1a0b33f671 | ||
|
|
523c905c6d | ||
|
|
ce2f7789f4 | ||
|
|
539d9ce9d6 | ||
|
|
ccf6340262 | ||
|
|
41f4118d0e | ||
|
|
41e2164cd0 | ||
|
|
861bed3fdd | ||
|
|
6010893891 | ||
|
|
8427de0edb | ||
|
|
1789fd7b4d | ||
|
|
83676d584a | ||
|
|
ec29711caf | ||
|
|
2bce6ed613 | ||
|
|
b922877d1f | ||
|
|
03b20a6ca9 | ||
|
|
e27a3bbdfc | ||
|
|
c93359d997 | ||
|
|
0ef496019a | ||
|
|
2d3e10a693 | ||
|
|
2e9699c519 | ||
|
|
514a95b80f | ||
|
|
4afcb2812f | ||
|
|
834c8054cf | ||
|
|
540bd57931 | ||
|
|
11790205d1 | ||
|
|
741d74b3fa | ||
|
|
b73210feeb | ||
|
|
0837c9dac5 | ||
|
|
b92b7a40ad | ||
|
|
01b9ce4b81 | ||
|
|
af9dca95de | ||
|
|
6eb03bf4ea | ||
|
|
9d005a6a40 | ||
|
|
0bef53685f | ||
|
|
f0b5298dc4 | ||
|
|
95d1c1b4be | ||
|
|
b946229d38 | ||
|
|
5c9c343e46 | ||
|
|
b664721fb1 | ||
|
|
1abb47e788 | ||
|
|
9e8732bd85 | ||
|
|
2c7df2fb96 | ||
|
|
4c0b520a53 | ||
|
|
370489a59b | ||
|
|
783d2ce93e | ||
|
|
f2c9880298 | ||
|
|
1392290eec | ||
|
|
afaea9484c | ||
|
|
b2964c2c1c | ||
|
|
6f7b6f2d87 | ||
|
|
609aa80e5e | ||
|
|
cdec6b459f | ||
|
|
3310e9f5ee | ||
|
|
554a7d689e | ||
|
|
2c32076416 | ||
|
|
19b8dfece6 | ||
|
|
0b1117c87f | ||
|
|
110852a379 | ||
|
|
17b26e39cc | ||
|
|
82567c2c61 | ||
|
|
376a714e73 | ||
|
|
37caf16978 | ||
|
|
9a81b9a88d | ||
|
|
100dfb3c42 | ||
|
|
e88b44df12 | ||
|
|
a03571dea8 | ||
|
|
bc0c9e4da5 | ||
|
|
8ac3002653 | ||
|
|
7f8283a77f | ||
|
|
833082618a | ||
|
|
c7b4310dc1 | ||
|
|
778ccf6db3 | ||
|
|
da295eb0c5 | ||
|
|
022be202c1 | ||
|
|
824a5e2c1d | ||
|
|
a620ad3587 | ||
|
|
7612fe17db | ||
|
|
0345dd28f3 | ||
|
|
959bc54505 | ||
|
|
791e144fd7 | ||
|
|
6ce224d4b3 | ||
|
|
20b8ce57a8 | ||
|
|
f4862c6b0e | ||
|
|
7fd2dc9127 | ||
|
|
f420ef4d6a | ||
|
|
6a35fc23a7 | ||
|
|
cf0f6876b9 | ||
|
|
40810c50de | ||
|
|
979077101f | ||
|
|
9f34d3790e | ||
|
|
c120c09423 | ||
|
|
c37ee263ce | ||
|
|
07e4b515fc | ||
|
|
f438ec2943 | ||
|
|
61ef4aab3c | ||
|
|
1336bc27cb | ||
|
|
a525210f48 | ||
|
|
892235af06 | ||
|
|
e14f85661b | ||
|
|
021269b675 | ||
|
|
b395c45437 | ||
|
|
68c5dfe8c7 | ||
|
|
eac757af34 | ||
|
|
3c159e2331 | ||
|
|
6997afcc34 | ||
|
|
d3096ed0fb | ||
|
|
0074cb6ac6 | ||
|
|
3c44fc6443 | ||
|
|
dc515b6128 | ||
|
|
6e783bdc6e | ||
|
|
aea58b38b8 |
Generated
+111
-268
File diff suppressed because it is too large
Load Diff
+54
-58
@@ -37,30 +37,26 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
thiserror = "2"
|
||||
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4"
|
||||
clap_mangen = "0.2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
quick-xml = "0.41"
|
||||
@@ -89,28 +85,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e", 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"
|
||||
@@ -178,27 +174,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "98a66a56550b027cc8cdcd689ab7d3239c71427e" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07b014397ff2ff86a3570e472552d527be9e588a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ Command line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert report.docx report.pdf # docx, pdf, odt, rtf, html, md, tex, txt, png
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 1, no file, if a character or picture would be left out
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 3, no file, if a character or picture would be left out
|
||||
wordcraft-cli text report.docx # plain text
|
||||
wordcraft-cli inspect report.docx # structure as JSON
|
||||
wordcraft-cli run --template sample \
|
||||
@@ -165,27 +165,16 @@ wordcraft-cli run --template sample \
|
||||
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
|
||||
```
|
||||
|
||||
`wordcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
|
||||
(command-line conventions); `wordcraft-cli --help` and `<subcommand> --help` are the reference for every flag. Exit status:
|
||||
0 success, 1 the command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that conflict or that a
|
||||
subcommand doesn't take, all checked before any file is opened), and 128 plus the signal number when a signal ends the
|
||||
process. Errors are `error: <message>` on stderr; results are on stdout. `--version`/`-V` work on every subcommand and there
|
||||
is no `version` subcommand. `WORDCRAFT_PASSWORD` is read by `--password` (a flag wins, an empty variable counts as unset,
|
||||
and `--help` never shows its value); `WORDCRAFT_REGION` sets the paper. The Linux packages (deb, rpm and tar.gz) and the
|
||||
FreeBSD package install the man pages and the bash, zsh and fish completions.
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 1
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 3
|
||||
and write nothing if the output would draw a character no font has (an empty box) or leave out a
|
||||
picture. Exit codes are 0 (written) and 1 (unreadable input or a strict refusal); `--strict` with another
|
||||
output type is a usage error (2), checked before the input is read. On a strict refusal, stderr has one
|
||||
`error: strict: …` line per kind, then one JSON line. (Before RFC-0018 a strict refusal exited 3; RFC-0018 has no code 3.)
|
||||
`validate` exits 0 for PASS and 1 for FAIL, INCOMPLETE or a file it can't read: the verdict is the first line of the report
|
||||
(`verdict` with `--json`).
|
||||
picture. Exit codes are 0 (written), 1 (unreadable input, usage error, or `--strict` with another
|
||||
output type, checked before the input is read) and 3 (strict refusal). On exit 3, stderr has one
|
||||
`wordcraft-cli: strict: …` line per kind, then one JSON line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert in.docx out.pdf --strict
|
||||
# error: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# error: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# wordcraft-cli: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# wordcraft-cli: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# {"schema":1,"strict":"failed","missing_glyphs":[{"cp":"U+2D30","count":3}],"missing_pictures":[{"part":"word/media/image2.bin","source_part":"word/header2.xml","reason":"unsupported_format"}],"truncated":false,"total_missing_glyphs":1,"total_missing_pictures":1,"glyphs_truncated":false,"pictures_truncated":false}
|
||||
```
|
||||
|
||||
|
||||
@@ -6,9 +6,6 @@ license.workspace = true
|
||||
publish = false
|
||||
description = "WordCraft command line: convert, inspect, render, run commands, MCP server"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "wordcraft-cli"
|
||||
path = "src/main.rs"
|
||||
@@ -25,14 +22,9 @@ wordcraft-zotero = { workspace = true }
|
||||
wordcraft-validate = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
thiserror = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
|
||||
clap_complete = { workspace = true }
|
||||
clap_mangen = { workspace = true }
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
//! Writes wordcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `wordcraft-cli.1` and one per subcommand, such as
|
||||
//! `wordcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (see `packaging/`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p wordcraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Also run by the tests.
|
||||
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = wordcraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "wordcraft-cli", dir)?;
|
||||
}
|
||||
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
|
||||
// which `clap_mangen` would otherwise give pages of its own (`wordcraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(wordcraft_cli::command(), dir)
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string; what
|
||||
//! clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The end of every subcommand's `--help`.
|
||||
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// The top-level `--help` ends with the environment and the exit status.
|
||||
const TOP_NOTES: &str = "A password-protected Word file is opened with --password PASS, --password-file PATH or the WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by every other process, so the other two are better. A file opened with a password is written with it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.\n\nPaper: documents created here, and HTML, Markdown and text files (which give no page size), use the system region's paper (A4, or Letter in the US and other Letter regions), read from LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the same output on every machine.\n\nEnvironment:\n WORDCRAFT_PASSWORD the password of a protected Word file, when neither --password nor --password-file is given\n WORDCRAFT_REGION the paper and region to use instead of the system's (a tag such as en-US)\n\nExit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// WordCraft from the command line: convert, inspect, render, run commands, validate, serve MCP
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "wordcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum Command {
|
||||
/// Convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png, xml)
|
||||
///
|
||||
/// `--update-fields` refreshes unlocked fields before saving (if protection blocks updates, they are skipped with a
|
||||
/// warning). An .xml file is a Word XML Document (Flat OPC), or with `--format wordml2003` a Word 2003 XML Document.
|
||||
/// `--markup` (Print Markup) puts comments beside each page and tracked changes in pdf/png, and a comment list in
|
||||
/// html/md/txt. `--strict` (pdf or png output only) writes nothing and exits 1 if a character can't be drawn or a
|
||||
/// picture is missing or undecodable; the report is on stderr, with one JSON line.
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Convert(ConvertArgs),
|
||||
/// Pages, words, paragraphs and properties (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Info(FileArgs),
|
||||
/// The plain text
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Text(FileArgs),
|
||||
/// The document structure (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Inspect(FileArgs),
|
||||
/// Render one page to a PNG
|
||||
///
|
||||
/// `--strict` writes nothing and exits 1 if a character on the page can't be drawn or a picture is missing or
|
||||
/// undecodable (the report is on stderr, as for `convert --strict`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Render(RenderArgs),
|
||||
/// Run commands headlessly, then save
|
||||
///
|
||||
/// `--script` runs a JSON file (`-` is stdin) first: {"file"?, "template"?, "commands": [{"command": id, "params"?:
|
||||
/// {…}} | id, …], "save"?: [OUT, …]}; save formats follow the extension (docx and pdf in one run); relative paths
|
||||
/// resolve against the script's folder. `file.new` and `file.open` open another document and make it active; later
|
||||
/// commands and the saves work on the active one; `view.switchWindows` lists the open documents and with {"id": N}
|
||||
/// makes one active. PNG saves use `--page` (1-based, default 1) and `--scale` (default 2).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Run(RunArgs),
|
||||
/// List every command
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Commands(JsonArgs),
|
||||
/// Feature-catalog parity
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Parity(ParityArgs),
|
||||
/// Structural integrity check
|
||||
///
|
||||
/// Exit 0 for PASS; 1 for FAIL, INCOMPLETE or a file that can't be read (the verdict is the first line of the report,
|
||||
/// and `verdict` in `--json`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Validate(ValidateArgs),
|
||||
/// MCP server on stdio, with a headless session
|
||||
///
|
||||
/// Both roots are required: the agent's commands read files (open, insert text or picture, mail-merge data,
|
||||
/// templates…) only inside the read root and write them (save, export, merge output…) only inside the write root,
|
||||
/// links followed; the same folder may be both. `--connect` (bridge to the running app) is refused until the app
|
||||
/// confines its control channel (#3695, #5819).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Mcp(McpArgs),
|
||||
/// Run a Zotero command on a document (Zotero must be running)
|
||||
///
|
||||
/// The commands are addEditCitation, addEditBibliography, addNote, refresh, removeCodes and setDocPrefs; `--cmd`
|
||||
/// runs first (for example `--cmd caret.docEnd`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Zotero(ZoteroArgs),
|
||||
}
|
||||
|
||||
/// How a password-protected Word file is opened.
|
||||
#[derive(Args, Debug, Default)]
|
||||
pub(crate) struct Password {
|
||||
/// The password (readable by every other process on the machine; prefer --password-file)
|
||||
#[arg(long, value_name = "PASS", env = "WORDCRAFT_PASSWORD", hide_env_values = true)]
|
||||
pub(crate) password: Option<String>,
|
||||
/// Read the password from this file (a trailing newline is dropped)
|
||||
#[arg(long = "password-file", value_name = "PATH")]
|
||||
pub(crate) password_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct FileArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
pub(crate) enum XmlFormat {
|
||||
/// A Word 2003 XML Document
|
||||
Wordml2003,
|
||||
/// A Word XML Document (Flat OPC), the default
|
||||
Flatopc,
|
||||
}
|
||||
|
||||
impl XmlFormat {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
XmlFormat::Wordml2003 => "wordml2003",
|
||||
XmlFormat::Flatopc => "flatopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ConvertArgs {
|
||||
/// The document to read
|
||||
pub(crate) input: PathBuf,
|
||||
/// The file to write; its extension names the format
|
||||
pub(crate) output: PathBuf,
|
||||
/// Print Markup: comments beside each page and tracked changes
|
||||
#[arg(long)]
|
||||
pub(crate) markup: bool,
|
||||
/// Refresh unlocked fields before saving
|
||||
#[arg(long = "update-fields")]
|
||||
pub(crate) update_fields: bool,
|
||||
/// For pdf or png output: write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
/// The kind of .xml file to write
|
||||
#[arg(long, value_enum, value_name = "KIND")]
|
||||
pub(crate) format: Option<XmlFormat>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RenderArgs {
|
||||
/// The document
|
||||
pub(crate) input: PathBuf,
|
||||
/// The PNG to write
|
||||
pub(crate) output: PathBuf,
|
||||
/// The page, from 1
|
||||
#[arg(long, value_name = "N", value_parser = page, default_value = "1")]
|
||||
pub(crate) page: u64,
|
||||
/// Device pixels per point
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale, default_value = "2")]
|
||||
pub(crate) scale: f64,
|
||||
/// Write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
/// One `--cmd ID[=JSON]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Cmd {
|
||||
pub(crate) id: String,
|
||||
pub(crate) params: Value,
|
||||
}
|
||||
|
||||
fn cmd(text: &str) -> Result<Cmd, UsageError> {
|
||||
match text.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
let params = serde_json::from_str(p).map_err(|e| UsageError::CmdJson { id: id.to_owned(), why: e.to_string() })?;
|
||||
Ok(Cmd { id: id.to_owned(), params })
|
||||
}
|
||||
None => Ok(Cmd { id: text.to_owned(), params: json!({}) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn page(text: &str) -> Result<u64, UsageError> {
|
||||
match text.parse::<u64>() {
|
||||
Ok(0) => Err(UsageError::Page("invalid --page `0`: page numbers start at 1".to_owned())),
|
||||
Ok(n) => Ok(n),
|
||||
Err(_) => Err(UsageError::Page(format!("invalid --page `{text}`: not a valid integer"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(text: &str) -> Result<f64, UsageError> {
|
||||
let n = text.parse::<f64>().map_err(|_| UsageError::Scale(format!("invalid --scale `{text}`: not a number")))?;
|
||||
if n.is_finite() && n > 0.0 { Ok(n) } else { Err(UsageError::Scale(format!("invalid --scale `{text}`: scale must be a finite positive number"))) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RunArgs {
|
||||
/// Open this document first
|
||||
#[arg(long, value_name = "F", conflicts_with = "template")]
|
||||
pub(crate) file: Option<PathBuf>,
|
||||
/// Start from this template
|
||||
#[arg(long, value_name = "T")]
|
||||
pub(crate) template: Option<String>,
|
||||
/// A script to run first (`-` is stdin)
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) script: Option<PathBuf>,
|
||||
/// Run one command, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the result here (the extension names the format)
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// The page of a PNG save, from 1 (default 1)
|
||||
#[arg(long, value_name = "N", value_parser = page)]
|
||||
pub(crate) page: Option<u64>,
|
||||
/// The scale of a PNG save (default 2)
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale)]
|
||||
pub(crate) scale: Option<f64>,
|
||||
/// Print each command's result
|
||||
#[arg(long)]
|
||||
pub(crate) print: bool,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct JsonArgs {
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ParityArgs {
|
||||
/// Markdown instead of JSON
|
||||
#[arg(long)]
|
||||
pub(crate) markdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ValidateArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// The folder the agent may read in (links followed); the same folder may be the write root
|
||||
#[arg(long = "automation-read-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) read_root: Option<PathBuf>,
|
||||
/// The folder the agent may write in (links followed)
|
||||
#[arg(long = "automation-write-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) write_root: Option<PathBuf>,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
/// Refused for now: the desktop app does not confine its control channel to automation roots yet
|
||||
#[arg(long, value_name = "HOST:PORT")]
|
||||
pub(crate) connect: Option<String>,
|
||||
}
|
||||
|
||||
fn folder(text: &str) -> Result<PathBuf, UsageError> {
|
||||
if text.is_empty() { Err(UsageError::EmptyFolder) } else { Ok(PathBuf::from(text)) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ZoteroArgs {
|
||||
/// The Zotero command (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)
|
||||
#[arg(value_parser = zotero_command)]
|
||||
pub(crate) command: String,
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// Run one command first, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the document here afterwards
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// Show the calls to and from Zotero on stderr
|
||||
#[arg(long)]
|
||||
pub(crate) trace: bool,
|
||||
/// Zotero's port
|
||||
#[arg(long, value_name = "P")]
|
||||
pub(crate) port: Option<u16>,
|
||||
}
|
||||
|
||||
fn zotero_command(text: &str) -> Result<String, UsageError> {
|
||||
if wordcraft_zotero::Command::from_name(text).is_some() { Ok(text.to_owned()) } else { Err(UsageError::Zotero(text.to_owned())) }
|
||||
}
|
||||
|
||||
/// A mistake in the command line that clap can't see by itself.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub(crate) enum UsageError {
|
||||
#[error("{0}")]
|
||||
Page(String),
|
||||
#[error("{0}")]
|
||||
Scale(String),
|
||||
#[error("--cmd {id}: bad JSON params: {why}")]
|
||||
CmdJson { id: String, why: String },
|
||||
#[error("a folder is needed, not an empty name")]
|
||||
EmptyFolder,
|
||||
#[error("unknown Zotero command `{0}` (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)")]
|
||||
Zotero(String),
|
||||
}
|
||||
|
||||
/// The clap definition of the whole command line (completions and man pages are generated from it).
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
}
|
||||
|
||||
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("wordcraft-cli")).chain(args.iter().cloned()))?;
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
if let Some((name, sub)) = matches.subcommand() {
|
||||
password_precedence(&mut cli.command, sub, name);
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// `--password`, `--password-file`, then `WORDCRAFT_PASSWORD`: a password file named on the command line beats the
|
||||
/// variable, which clap would otherwise read into `--password`.
|
||||
fn password_precedence(command: &mut Command, sub: &ArgMatches, _name: &str) {
|
||||
let open = match command {
|
||||
Command::Convert(a) => &mut a.open,
|
||||
Command::Info(a) | Command::Text(a) | Command::Inspect(a) => &mut a.open,
|
||||
Command::Render(a) => &mut a.open,
|
||||
Command::Run(a) => &mut a.open,
|
||||
_ => return,
|
||||
};
|
||||
let from_env = sub.value_source("password") == Some(clap::parser::ValueSource::EnvVariable);
|
||||
if from_env && open.password_file.is_some() {
|
||||
open.password = None;
|
||||
}
|
||||
// A blank variable counts as unset.
|
||||
if from_env && open.password.as_deref() == Some("") {
|
||||
open.password = None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
|
||||
//! flag must not silently remove a root and leave the server unconfined.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct AutomationArgs {
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
read_given: bool,
|
||||
write_given: bool,
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
|
||||
Self { read_root, write_root, read_given: false, write_given: false }
|
||||
}
|
||||
|
||||
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
|
||||
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
|
||||
let (root, given) = match flag {
|
||||
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
|
||||
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if *given {
|
||||
return Err(format!("{flag} given twice"));
|
||||
}
|
||||
let value = match inline {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if value.starts_with('-') {
|
||||
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
|
||||
}
|
||||
value
|
||||
}
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!("{flag} needs a non-empty folder"));
|
||||
}
|
||||
*root = Some(value.into());
|
||||
*given = true;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roots_are_taken_once_and_other_arguments_are_left() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
let mut args = ["a folder".to_owned(), "report.docx".to_owned()].into_iter();
|
||||
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
|
||||
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
|
||||
assert!(!roots.consume("--author", &mut args).unwrap());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
assert_eq!(roots.write_root, Some("out".into()));
|
||||
assert_eq!(args.next().as_deref(), Some("report.docx"));
|
||||
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_operands_leave_roots_unchanged() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
|
||||
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
|
||||
let mut args = operand.map(str::to_owned).into_iter();
|
||||
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
|
||||
assert_eq!(roots.read_root, Some("read".into()));
|
||||
assert_eq!(roots.write_root, Some("write".into()));
|
||||
}
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
|
||||
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
|
||||
assert_eq!(roots.read_root, Some("-folder".into()));
|
||||
assert_eq!(roots.write_root, Some("./-folder".into()));
|
||||
}
|
||||
}
|
||||
@@ -1,620 +0,0 @@
|
||||
//! The subcommands: each takes its parsed arguments and the output streams, and returns the exit status.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::{CmdError, Session};
|
||||
|
||||
use crate::args::{self, Command, ConvertArgs, FileArgs, JsonArgs, McpArgs, ParityArgs, Password, RenderArgs, RunArgs, ValidateArgs, ZoteroArgs};
|
||||
use crate::error::CliError;
|
||||
use crate::script;
|
||||
use crate::{Io, errln};
|
||||
|
||||
type Result<T> = std::result::Result<T, CliError>;
|
||||
|
||||
fn engine_error(e: impl std::fmt::Display) -> CliError {
|
||||
CliError::Failed(escape_text(&e.to_string(), false))
|
||||
}
|
||||
|
||||
/// Open a document for a subcommand. A password-protected Word file needs its password
|
||||
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
|
||||
/// `convert` does not quietly write a copy the password no longer protects.
|
||||
fn open(path: &Path, password: Option<&str>) -> Result<Session> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, ®ion).map_err(engine_error)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The password for a protected Word file: `--password`, `--password-file` or `WORDCRAFT_PASSWORD` (clap reads the
|
||||
/// variable into `--password`; a blank one counts as unset). The file form exists because a password on a command line
|
||||
/// is readable by every other process on the machine; a trailing newline is dropped so a file written by `echo` works.
|
||||
/// Never logged, and never named in an error.
|
||||
pub(crate) fn password_from(open: &Password) -> Result<Option<String>> {
|
||||
if let Some(password) = &open.password {
|
||||
return Ok(Some(password.clone()));
|
||||
}
|
||||
if let Some(path) = &open.password_file {
|
||||
let raw =
|
||||
std::fs::read_to_string(path).map_err(|e| CliError::Failed(escape_text(&format!("--password-file {}: {e}", path.display()), false)))?;
|
||||
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A path the engine takes as text: output paths must be valid Unicode (only the opened file may not be, #1440).
|
||||
fn unicode(path: &Path) -> Result<&str> {
|
||||
path.to_str().ok_or_else(|| CliError::Failed(format!("{}: the file name is not valid Unicode", path.display().to_string().escape_debug())))
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
let mut s = Session::new(doc);
|
||||
s.system_region = system_region();
|
||||
s
|
||||
}
|
||||
|
||||
/// The system region, read as the app reads it (locale variables, else the platform's locale).
|
||||
fn system_region() -> wordcraft_engine::Region {
|
||||
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
|
||||
fn listed_text(doc: &wordcraft_doc::Document) -> std::result::Result<String, String> {
|
||||
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
|
||||
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
|
||||
}
|
||||
|
||||
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
|
||||
/// The command also checks whether the open document is protected: this name determines which
|
||||
/// named editing exceptions the session can use, so the flag must not bypass that check.
|
||||
fn set_author(s: &mut Session, name: &str) -> std::result::Result<(), String> {
|
||||
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
|
||||
}
|
||||
|
||||
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
|
||||
/// process to the same roots first (`confine_process`), which a test must not do.
|
||||
fn headless_mcp(
|
||||
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
|
||||
author: Option<&str>,
|
||||
) -> std::result::Result<wordcraft_mcp::Headless, String> {
|
||||
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
|
||||
if let Some(name) = author {
|
||||
set_author(&mut headless.session, name)?;
|
||||
}
|
||||
Ok(headless)
|
||||
}
|
||||
|
||||
/// A failed `--strict` export: a strict refusal becomes [`CliError::Strict`] carrying what stderr
|
||||
/// shows (each line of the report as `error: …`, then its JSON on one line, from
|
||||
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
|
||||
/// failure.
|
||||
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> CliError {
|
||||
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
|
||||
return engine_error(e);
|
||||
}
|
||||
let mut params = json!({"markup": markup});
|
||||
if let Some(page) = page {
|
||||
params["page"] = json!(page);
|
||||
}
|
||||
CliError::Strict(match s.run("file.strictReport", ¶ms).map_err(|e| e.to_string()) {
|
||||
Ok(json) => {
|
||||
let mut text = String::new();
|
||||
for line in report_lines(&json) {
|
||||
text += &format!("error: {}\n", escape_peer(&line));
|
||||
}
|
||||
text + &json_line_safe(&json.to_string())
|
||||
}
|
||||
Err(e) => format!("error: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
|
||||
fn report_lines(json: &Value) -> Vec<String> {
|
||||
wordcraft_engine::strict::lines_from_json(json)
|
||||
}
|
||||
|
||||
/// Explicitly update unlocked fields in a session before saving the document.
|
||||
///
|
||||
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
|
||||
/// stderr and continues conversion rather than aborting. Other command failures are converted to
|
||||
/// [`CliError`] via [`engine_error`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Err(CliError)` if the command fails with an error other than `CmdError::Disabled`.
|
||||
fn update_fields(s: &mut Session, io: &mut Io) -> Result<()> {
|
||||
if let Err(e) = s.run("references.updateFields", &json!({})) {
|
||||
if matches!(e, CmdError::Disabled(_)) {
|
||||
errln!(io, "warning: {e}");
|
||||
} else {
|
||||
return Err(engine_error(e));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
|
||||
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
|
||||
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
|
||||
/// terminal or pass for other output.
|
||||
fn escape_peer(s: &str) -> String {
|
||||
escape_text(s, true)
|
||||
}
|
||||
|
||||
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
|
||||
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
|
||||
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
|
||||
fn is_unsafe_char(c: char) -> bool {
|
||||
c.is_control()
|
||||
|| matches!(
|
||||
c,
|
||||
'\u{00ad}'
|
||||
| '\u{061c}'
|
||||
| '\u{200b}'..='\u{200f}'
|
||||
| '\u{2028}'..='\u{202e}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{feff}'
|
||||
| '\u{e0000}'..='\u{e007f}'
|
||||
)
|
||||
}
|
||||
|
||||
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
|
||||
/// paths, and a backslash can't forge or hide anything).
|
||||
fn escape_text(s: &str, backslash: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' if backslash => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
|
||||
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
|
||||
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
|
||||
/// can't drive or spoof a terminal.
|
||||
fn json_line_safe(json: &str) -> String {
|
||||
let mut out = String::with_capacity(json.len());
|
||||
for c in json.chars() {
|
||||
if is_unsafe_char(c) {
|
||||
for unit in c.encode_utf16(&mut [0u16; 2]) {
|
||||
out.push_str(&format!("\\u{unit:04x}"));
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parity_markdown(p: &Value) -> String {
|
||||
let mut s = String::from(
|
||||
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
|
||||
);
|
||||
s += &format!(
|
||||
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
|
||||
p["live"], p["total"], p["percent"]
|
||||
);
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
let h = &p["headless"];
|
||||
s += &format!(
|
||||
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
|
||||
h["yes"],
|
||||
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
|
||||
h["no"]["window"],
|
||||
h["no"]["os"],
|
||||
h["no"]["engine-gap"],
|
||||
h["partial"],
|
||||
h["unknown"]
|
||||
);
|
||||
s += "\n## Missing\n\n";
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
let m = t["missing"].as_array().cloned().unwrap_or_default();
|
||||
if m.is_empty() {
|
||||
continue;
|
||||
}
|
||||
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
|
||||
for x in m {
|
||||
s += &format!("- {}\n", x.as_str().unwrap_or(""));
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Write a `validate` report for people: the verdict, then one line per finding
|
||||
/// (`SEVERITY RULE [part] message`), then the coverage notes.
|
||||
fn write_validate_report(o: &mut dyn Write, report: &wordcraft_validate::Report) -> std::io::Result<()> {
|
||||
o.write_all(render_validate_report(report).as_bytes())
|
||||
}
|
||||
|
||||
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
|
||||
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
|
||||
/// terminal; printable text, including Unicode, is left as written.
|
||||
///
|
||||
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
|
||||
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
|
||||
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
|
||||
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
|
||||
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
|
||||
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
|
||||
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
|
||||
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
|
||||
/// why its escaping is left to `serde_json`.
|
||||
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
|
||||
let mut out = format!("{}\n", verdict_label(report.verdict));
|
||||
for f in &report.findings {
|
||||
let severity = severity_label(f.severity);
|
||||
match &f.part {
|
||||
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
|
||||
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
|
||||
}
|
||||
}
|
||||
for note in &report.coverage_notes {
|
||||
out.push_str(&format!("note: {}\n", escape_report_text(note)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
|
||||
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
|
||||
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
|
||||
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
|
||||
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
|
||||
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
|
||||
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
|
||||
/// injective.
|
||||
fn escape_report_text(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if c.is_control() || is_invisible_format(c) {
|
||||
out.extend(c.escape_debug());
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
|
||||
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
|
||||
fn is_invisible_format(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Map a validation verdict enum to its human-readable uppercase display label.
|
||||
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
|
||||
match v {
|
||||
wordcraft_validate::Verdict::Pass => "PASS",
|
||||
wordcraft_validate::Verdict::Fail => "FAIL",
|
||||
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a validation severity enum to its human-readable uppercase display label.
|
||||
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
|
||||
match s {
|
||||
wordcraft_validate::Severity::Corrupt => "CORRUPT",
|
||||
wordcraft_validate::Severity::Error => "ERROR",
|
||||
wordcraft_validate::Severity::Warning => "WARNING",
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
|
||||
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
|
||||
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
|
||||
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
|
||||
--automation-read-root DIR --automation-write-root DIR";
|
||||
|
||||
/// Run one parsed subcommand; the result is the exit status.
|
||||
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<u8> {
|
||||
match command {
|
||||
Command::Convert(a) => convert(a, io).map(|()| 0),
|
||||
Command::Info(a) => info(a, io).map(|()| 0),
|
||||
Command::Text(a) => text(a, io).map(|()| 0),
|
||||
Command::Inspect(a) => inspect(a, io).map(|()| 0),
|
||||
Command::Render(a) => render(a, io).map(|()| 0),
|
||||
Command::Run(a) => run_script(a, io).map(|()| 0),
|
||||
Command::Commands(a) => commands(a, io).map(|()| 0),
|
||||
Command::Parity(a) => parity(a, io).map(|()| 0),
|
||||
Command::Validate(a) => validate(a, io),
|
||||
Command::Mcp(a) => mcp(a, io).map(|()| 0),
|
||||
Command::Zotero(a) => zotero(a, io).map(|()| 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to stdout and flush. A closed stdout comes back as [`CliError::StdoutClosed`] instead of a panic.
|
||||
fn write_stdout(io: &mut Io, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write(&mut *io.out)?;
|
||||
io.out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert(a: ConvertArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
// Before the input is opened: a wrong output type is a usage error, not a file error.
|
||||
let to_png = o.to_ascii_lowercase().ends_with(".png");
|
||||
if a.strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
return Err(CliError::Usage("convert: --strict needs a .pdf or .png output".into()));
|
||||
}
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
if a.update_fields {
|
||||
update_fields(&mut s, io)?;
|
||||
}
|
||||
let r = if to_png {
|
||||
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": a.markup, "strict": a.strict}))
|
||||
} else {
|
||||
let mut params = json!({"path": o, "markup": a.markup, "strict": a.strict});
|
||||
if let Some(f) = a.format {
|
||||
params["format"] = json!(f.name());
|
||||
}
|
||||
s.run("file.save", ¶ms)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
return Err(if a.strict { refusal(&mut s, e, a.markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
errln!(io, "wrote {o}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_file(a: &FileArgs) -> Result<Session> {
|
||||
let password = password_from(&a.open)?;
|
||||
open(&a.file, password.as_deref())
|
||||
}
|
||||
|
||||
fn info(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{info}"))
|
||||
}
|
||||
|
||||
fn text(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let s = open_file(&a)?;
|
||||
let text = listed_text(&s.doc)?;
|
||||
write_stdout(io, |o| writeln!(o, "{text}"))
|
||||
}
|
||||
|
||||
fn inspect(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{tree}"))
|
||||
}
|
||||
|
||||
fn render(a: RenderArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
let mut params = json!({"path": o, "page": a.page, "scale": a.scale, "strict": a.strict});
|
||||
if a.strict {
|
||||
// The check and its report must see the page as it is written.
|
||||
params["markup"] = json!(false);
|
||||
}
|
||||
let r = match s.run("file.exportPng", ¶ms) {
|
||||
Ok(r) => r,
|
||||
Err(e) if a.strict => return Err(refusal(&mut s, e, false, Some(a.page))),
|
||||
Err(e) => return Err(engine_error(e)),
|
||||
};
|
||||
write_stdout(io, |o| writeln!(o, "{r}"))
|
||||
}
|
||||
|
||||
fn load_run_script(path: Option<&Path>) -> Result<Option<script::Script>> {
|
||||
path.map(|p| script::load(p).map_err(engine_error)).transpose()
|
||||
}
|
||||
|
||||
fn run_script(a: RunArgs, io: &mut Io) -> Result<()> {
|
||||
let password = password_from(&a.open)?;
|
||||
let script = load_run_script(a.script.as_deref())?;
|
||||
// A source named on the command line wins over both of the script's.
|
||||
let (mut from_file, mut from_template) = (a.file.clone(), a.template.clone());
|
||||
if from_file.is_none() && from_template.is_none() {
|
||||
from_file = script.as_ref().and_then(|loaded| loaded.file.as_deref().map(std::path::PathBuf::from));
|
||||
from_template = script.as_ref().and_then(|loaded| loaded.template.clone());
|
||||
}
|
||||
let mut s = match (from_file, from_template) {
|
||||
(Some(f), _) => open(&f, password.as_deref())?,
|
||||
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
|
||||
// `file.new` opens beside the session's first document, which is then closed: the
|
||||
// run starts with one open document.
|
||||
(None, t) => {
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
let first = s.document_id();
|
||||
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
|
||||
s.run("file.new", ¶ms).map_err(engine_error)?;
|
||||
s.close_document(first).map_err(engine_error)?;
|
||||
s
|
||||
}
|
||||
};
|
||||
if let Some(name) = &a.author {
|
||||
set_author(&mut s, name).map_err(CliError::Failed)?;
|
||||
}
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
let mut outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).collect();
|
||||
if let Some(save) = &a.save {
|
||||
outputs.push(unicode(save)?.to_owned());
|
||||
}
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
if let Some(p) = parent.filter(|p| !p.is_dir()) {
|
||||
return Err(format!("{out}: folder {} does not exist", p.display()).into());
|
||||
}
|
||||
if Path::new(out).is_dir() {
|
||||
return Err(format!("{out}: is a folder, not a file").into());
|
||||
}
|
||||
if !out.to_ascii_lowercase().ends_with(".png") {
|
||||
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
|
||||
}
|
||||
}
|
||||
for out in outputs {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = a.page {
|
||||
v["page"] = json!(n);
|
||||
}
|
||||
if let Some(k) = a.scale {
|
||||
v["scale"] = json!(k);
|
||||
}
|
||||
s.run("file.exportPng", &v)
|
||||
} else {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commands(a: JsonArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
if a.json {
|
||||
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{list}"))
|
||||
} else {
|
||||
write_stdout(io, |o| {
|
||||
for c in s.registry.all() {
|
||||
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
|
||||
}
|
||||
writeln!(o, "{:<32} Structural integrity check", "validate")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parity(a: ParityArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
let p = wordcraft_engine::catalog::parity(&s.registry);
|
||||
if a.markdown {
|
||||
write_stdout(io, |o| write!(o, "{}", parity_markdown(&p)))
|
||||
} else {
|
||||
write_stdout(io, |o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(a: McpArgs, io: &mut Io) -> Result<()> {
|
||||
if a.connect.is_some() {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. clap requires both roots.
|
||||
let roots = wordcraft_engine::file_access::AutomationRoots::new(a.read_root.as_deref(), a.write_root.as_deref())
|
||||
.map_err(|e| CliError::Failed(format!("mcp: {e}")))?;
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(CliError::Usage("mcp: give both --automation-read-root DIR and --automation-write-root DIR".into()));
|
||||
};
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
errln!(io, "files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, a.author.as_deref()).map_err(CliError::Failed)?);
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), &mut *io.out)?)
|
||||
}
|
||||
|
||||
fn zotero(a: ZoteroArgs, io: &mut Io) -> Result<()> {
|
||||
let command =
|
||||
wordcraft_zotero::Command::from_name(&a.command).ok_or_else(|| CliError::Usage(format!("unknown Zotero command `{}`", a.command)))?;
|
||||
let mut s = open(&a.file, None)?;
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
}
|
||||
let mut opts = wordcraft_zotero::client::Options::default();
|
||||
if let Some(p) = a.port {
|
||||
opts.addr.set_port(p);
|
||||
}
|
||||
let mut bridge = wordcraft_zotero::Bridge::new();
|
||||
let mut host = wordcraft_zotero::Headless::default();
|
||||
let mut trace = Vec::new();
|
||||
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
|
||||
let r = bridge.handle(&mut s, &mut host, call);
|
||||
if a.trace {
|
||||
trace.push(format!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string()))));
|
||||
trace.push(format!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r))))));
|
||||
}
|
||||
r
|
||||
})
|
||||
.map_err(engine_error)?;
|
||||
for line in &trace {
|
||||
errln!(io, "{line}");
|
||||
}
|
||||
for alert in &host.alerts {
|
||||
errln!(io, "Zotero: {}", escape_peer(alert));
|
||||
}
|
||||
errln!(io, "{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = &a.save {
|
||||
let o = unicode(o)?;
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
errln!(io, "wrote {o}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `validate`: 0 for PASS, 1 for any other verdict or a file that can't be read (RFC-0018 rule 1.2 has no other code;
|
||||
/// the verdict is in the report).
|
||||
fn validate(a: ValidateArgs, io: &mut Io) -> Result<u8> {
|
||||
let report =
|
||||
wordcraft_validate::validate_path(&a.file).map_err(|e| CliError::Failed(escape_text(&format!("{}: {e}", a.file.display()), false)))?;
|
||||
let written = if a.json {
|
||||
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{json}"))
|
||||
} else {
|
||||
write_stdout(io, |o| write_validate_report(o, &report))
|
||||
};
|
||||
match written {
|
||||
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
|
||||
Ok(()) | Err(CliError::StdoutClosed) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
Ok(match report.verdict {
|
||||
wordcraft_validate::Verdict::Pass => 0,
|
||||
wordcraft_validate::Verdict::Fail | wordcraft_validate::Verdict::Incomplete => 1,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,37 +0,0 @@
|
||||
//! What stops a command, and how each case exits.
|
||||
|
||||
/// Why a CLI run stopped early.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub enum CliError {
|
||||
/// The command failed (exit 1); the text is already safe to print.
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
/// A mistake in the command line found after parsing (exit 2).
|
||||
#[error("{0}")]
|
||||
Usage(String),
|
||||
/// A strict export refused (exit 1): the report's lines, then its JSON line, ready for stderr.
|
||||
#[error("{0}")]
|
||||
Strict(String),
|
||||
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): nobody is left to write to, so a quiet
|
||||
/// exit 0 (`validate` keeps its verdict's status).
|
||||
#[error("stdout closed")]
|
||||
StdoutClosed,
|
||||
}
|
||||
|
||||
impl From<String> for CliError {
|
||||
fn from(e: String) -> Self {
|
||||
CliError::Failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CliError {
|
||||
fn from(e: &str) -> Self {
|
||||
CliError::Failed(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for CliError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
if e.kind() == std::io::ErrorKind::BrokenPipe { CliError::StdoutClosed } else { CliError::Failed(e.to_string()) }
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//! Headless WordCraft (`wordcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
|
||||
//! through the binary; `wordcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
|
||||
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
|
||||
|
||||
mod args;
|
||||
mod commands;
|
||||
mod error;
|
||||
mod script;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
|
||||
use error::CliError;
|
||||
|
||||
pub use args::command;
|
||||
|
||||
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
|
||||
pub(crate) struct Io<'a> {
|
||||
pub(crate) out: &'a mut dyn Write,
|
||||
pub(crate) err: &'a mut dyn Write,
|
||||
}
|
||||
|
||||
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
|
||||
macro_rules! errln {
|
||||
($io:expr, $($arg:tt)*) => {
|
||||
drop(writeln!($io.err, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use errln;
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
let arg = arg.to_string_lossy();
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
|
||||
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
|
||||
/// to `out`, exit 0.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
let _ = writeln!(err, "error: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match args::parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
let _ = write!(to, "{}", e.render());
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
let mut io = Io { out, err };
|
||||
// Language packs installed in the suite's font store are used; `proof.installPack` installs
|
||||
// only while the person has turned downloading on in the app.
|
||||
wordcraft_engine::packs::use_font_store(false);
|
||||
if let Some(source) = wordcraft_engine::packs::index_override() {
|
||||
errln!(io, "Language packs come from a test source: {source}");
|
||||
}
|
||||
match commands::dispatch(cli.command, &mut io) {
|
||||
Ok(code) => i32::from(code),
|
||||
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
|
||||
Err(CliError::StdoutClosed) => 0,
|
||||
Err(CliError::Usage(e)) => {
|
||||
errln!(io, "error: {e}");
|
||||
2
|
||||
}
|
||||
// The report's lines already start with `error:`.
|
||||
Err(CliError::Strict(report)) => {
|
||||
errln!(io, "{report}");
|
||||
1
|
||||
}
|
||||
Err(e) => {
|
||||
errln!(io, "error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
+1083
-5
File diff suppressed because it is too large
Load Diff
+506
-280
@@ -1,285 +1,5 @@
|
||||
use super::*;
|
||||
use crate::launcher_profile_flag;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A failed in-process run: the exit code and what stderr said (without its `error: ` prefix).
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Fail {
|
||||
code: i32,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Fail {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the whole CLI in this process, as the binary does.
|
||||
fn exec<S: AsRef<OsStr>>(args: &[S]) -> (i32, String, String) {
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = crate::run(args.iter().map(|a| a.as_ref().to_owned()), &mut out, &mut err);
|
||||
(code, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned())
|
||||
}
|
||||
|
||||
/// `Ok` for exit 0, else the exit code and message.
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> std::result::Result<(), Fail> {
|
||||
let (code, _, err) = exec(args);
|
||||
if code == 0 { Ok(()) } else { Err(Fail { code, text: err.trim_end().strip_prefix("error: ").unwrap_or(err.trim_end()).to_owned() }) }
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
/// A usage error: exit 2, the message on stderr, nothing on stdout, and no work done.
|
||||
fn usage(argv: &[&str]) -> String {
|
||||
let (code, out, err) = exec(argv);
|
||||
assert_eq!((code, out.as_str()), (2, ""), "{argv:?}: {err}");
|
||||
err
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_and_scale_are_checked_before_any_file_is_opened() {
|
||||
for sub in [vec!["render", "missing.docx", "out.png"], vec!["run", "--template", "sample", "--save", "out.png"]] {
|
||||
let with = |extra: &[&str]| usage(&[&sub[..], extra].concat());
|
||||
for missing in [&["--page"][..], &["--scale"], &["--page", "--scale", "2"], &["--scale", "--page", "1"]] {
|
||||
with(missing);
|
||||
}
|
||||
assert!(with(&["--page", "banana"]).contains("invalid --page `banana`: not a valid integer"));
|
||||
assert!(with(&["--page", "0"]).contains("invalid --page `0`: page numbers start at 1"));
|
||||
with(&["--page", "-1"]);
|
||||
assert!(with(&["--scale", "banana"]).contains("invalid --scale `banana`: not a number"));
|
||||
for bad in ["0", "-2", "NaN", "inf"] {
|
||||
assert!(with(&["--scale", bad]).contains(&format!("invalid --scale `{bad}`: scale must be a finite positive number")));
|
||||
}
|
||||
with(&["--page", "1", "--page", "2"]);
|
||||
with(&["--scale", "1", "--scale", "2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_repeated_and_conflicting_options_are_usage_errors_before_file_access() {
|
||||
assert!(usage(&["info", "missing.docx", "--passwrod", "x"]).contains("--passwrod"));
|
||||
assert!(usage(&["render", "missing.docx", "out.png", "--sclae", "2"]).contains("--sclae"));
|
||||
assert!(usage(&["zotero", "refresh", "missing.docx", "--prot", "1"]).contains("--prot"));
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "--markup"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "flatopc", "--format", "wordml2003"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.xml", "--format", "docx"]).contains("wordml2003"));
|
||||
usage(&["convert", "missing.docx"]);
|
||||
usage(&["convert", "a.docx", "b.docx", "c.docx"]);
|
||||
usage(&["run", "--file", "a.docx", "--template", "blank"]);
|
||||
usage(&["info"]);
|
||||
usage(&["frobnicate"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.docx", "--strict"]).contains("--strict needs a .pdf or .png output"));
|
||||
// A valid single value reaches file access, rather than an option error.
|
||||
let (code, _, err) = exec(&["convert", "missing.docx", "out.xml", "--format", "flatopc"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: missing.docx:"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_and_script_values_are_checked_by_the_parser() {
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--script", "--cmd", "caret.docEnd"],
|
||||
] {
|
||||
usage(&argv);
|
||||
}
|
||||
assert!(usage(&["run", "--cmd", "text.insert={nope"]).contains("bad JSON params"));
|
||||
assert_eq!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_author_flag_names_the_headless_session() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert_eq!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])), Ok(()));
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_or_a_file_and_never_shows_in_an_error() {
|
||||
let open = |password: Option<&str>, file: Option<&str>| Password { password: password.map(Into::into), password_file: file.map(PathBuf::from) };
|
||||
assert_eq!(password_from(&open(None, None)), Ok(None));
|
||||
assert_eq!(password_from(&open(Some("s3cret"), None)), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the file.
|
||||
assert_eq!(password_from(&open(Some("a"), Some("/nonexistent"))), Ok(Some("a".into())));
|
||||
let path = std::env::temp_dir().join(format!("wordcraft-cli-password-test-{}.txt", std::process::id()));
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&open(None, path.to_str()));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())), "only the trailing newline is lost");
|
||||
let err = password_from(&open(None, Some("/nonexistent/secret.txt"))).unwrap_err().to_string();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
/// A password file on the command line beats the variable, a blank variable is unset, and `--help` shows neither value.
|
||||
#[test]
|
||||
fn the_password_variable_is_read_by_the_flag_and_hidden() {
|
||||
let parse = |argv: &[&str]| crate::args::parse(&argv.iter().map(OsString::from).collect::<Vec<_>>());
|
||||
let help = parse(&["info", "--help"]).unwrap_err().render().to_string();
|
||||
assert!(help.contains("WORDCRAFT_PASSWORD") || help.contains("--password"), "{help}");
|
||||
let Err(e) = parse(&["info", "--password"]) else { panic!("a missing value must not parse") };
|
||||
assert_eq!(e.exit_code(), 2);
|
||||
let top = parse(&["--help"]).unwrap_err().render().to_string();
|
||||
assert!(top.contains("WORDCRAFT_PASSWORD") && top.contains("WORDCRAFT_REGION") && top.contains("Exit status"), "{top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_needs_both_roots_and_refuses_connect() {
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec!["mcp".to_string()], given].concat();
|
||||
let err = usage(&line.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
assert!(err.contains("--automation-read-root") || err.contains("--automation-write-root"), "{line:?}: {err}");
|
||||
}
|
||||
let missing = usage(&["mcp", "--automation-read-root", "a", "--automation-read-root=b", "--automation-write-root", "c"]);
|
||||
assert!(missing.contains("--automation-read-root"), "{missing}");
|
||||
usage(&["mcp", "--automation-read-root=", "--automation-write-root=x"]);
|
||||
// A folder that does not exist is an error, not a server that quietly runs unconfined.
|
||||
let (code, _, err) = exec(&["mcp", "--automation-read-root", "/definitely/not/a/folder", "--automation-write-root", "/definitely/not/a/folder"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: mcp: cannot open the automation read root"), "{err}");
|
||||
// `--connect` is refused whether or not it has roots, before anything connects (#3695, #5819).
|
||||
let dir = base.to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect=127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let (code, _, err) = exec(&line);
|
||||
assert_eq!(code, 1, "{line:?}");
|
||||
assert!(err.contains("--connect") && err.contains("#3695") && err.contains("#5819"), "{line:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_opening_subcommand_reaches_the_open_with_a_non_unicode_name_but_not_an_output() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
for argv in [
|
||||
vec![OsString::from("convert"), latin1(), "out.pdf".into()],
|
||||
vec!["info".into(), latin1()],
|
||||
vec!["text".into(), latin1()],
|
||||
vec!["inspect".into(), latin1()],
|
||||
vec!["render".into(), latin1(), "out.png".into()],
|
||||
vec!["run".into(), "--file".into(), latin1()],
|
||||
vec!["zotero".into(), "refresh".into(), latin1()],
|
||||
] {
|
||||
let (code, _, err) = exec(&argv);
|
||||
assert_eq!(code, 1, "{argv:?}: {err}");
|
||||
assert!(err.contains("No such file"), "{argv:?}: {err}");
|
||||
}
|
||||
// An output the engine takes as text must be Unicode: a failure, and nothing opened.
|
||||
let out = OsString::from_vec(b"caf\xe9.png".to_vec());
|
||||
let (code, _, err) = exec(&["render".into(), OsString::from("in.docx"), out]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.contains("not valid Unicode"), "{err}");
|
||||
// Elsewhere clap refuses it as usage.
|
||||
assert_eq!(exec(&["run".into(), OsString::from("--template"), OsString::from_vec(b"caf\xe9".to_vec())]).0, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// `validate`: PASS is 0; FAIL, INCOMPLETE and a file that can't be read are 1 (RFC-0018 rule 1.2); usage is 2.
|
||||
#[test]
|
||||
fn validate_exits_0_for_pass_1_for_anything_else_and_2_for_usage() {
|
||||
let dir = script_dir("validate-exit");
|
||||
let good = dir.join("good.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &good.to_string_lossy()])).unwrap();
|
||||
let good = good.to_string_lossy().into_owned();
|
||||
let (code, out, _) = exec(&["validate", &good]);
|
||||
assert_eq!((code, out.lines().next()), (0, Some("PASS")));
|
||||
let (code, out, _) = exec(&["validate", "--json", &good]);
|
||||
assert_eq!(code, 0);
|
||||
assert!(out.contains("\"verdict\""), "{out}");
|
||||
let broken = dir.join("broken.docx");
|
||||
std::fs::write(&broken, b"not a zip").unwrap();
|
||||
let (code, out, _) = exec(&["validate".to_string(), broken.to_string_lossy().into_owned()]);
|
||||
assert_eq!(code, 1, "{out}");
|
||||
assert!(out.starts_with("FAIL") || out.starts_with("INCOMPLETE"), "{out}");
|
||||
let (code, _, err) = exec(&["validate", "/definitely/not/there.docx"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: /definitely/not/there.docx:"), "{err}");
|
||||
usage(&["validate"]);
|
||||
usage(&["validate", &good, &good]);
|
||||
usage(&["validate", &good, "--bogus"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_go_to_stdout_with_exit_0() {
|
||||
for argv in [vec!["--version"], vec!["-V"], vec!["--help"], vec!["-h"], vec!["help"], vec!["convert", "--help"], vec!["help", "validate"]] {
|
||||
let (code, out, err) = exec(&argv);
|
||||
assert_eq!((code, err.as_str()), (0, ""), "{argv:?}");
|
||||
assert!(out.contains("wordcraft-cli"), "{argv:?}: {out}");
|
||||
}
|
||||
let (_, out, _) = exec(&["--version"]);
|
||||
assert_eq!(out.trim(), format!("wordcraft-cli {}", env!("CARGO_PKG_VERSION")));
|
||||
// The version is not a subcommand; with no arguments the help is shown as an error, exit 2.
|
||||
usage(&["version"]);
|
||||
assert_eq!(exec::<&str>(&[]).0, 2);
|
||||
// Every subcommand's help ends with the exit status.
|
||||
for sub in crate::command().get_subcommands().map(|c| c.get_name().to_owned()).filter(|n| n != "help") {
|
||||
let (code, out, _) = exec(&[sub.as_str(), "--help"]);
|
||||
assert_eq!(code, 0, "{sub}");
|
||||
assert!(out.contains("Exit status"), "{sub}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_bootstrap_exits_2_before_anything_runs() {
|
||||
let err = usage(&["--launch-profile=nightly-v1", "info", "x.docx"]);
|
||||
assert!(err.starts_with("error: --launch-profile and --profile-root"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_stdout_ends_quietly_and_other_write_errors_fail() {
|
||||
struct Closed(std::io::ErrorKind);
|
||||
impl Write for Closed {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::BrokenPipe), &mut err), 0);
|
||||
assert!(err.is_empty());
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::PermissionDenied), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_strict_and_render_strict_refusals_exit_1() {
|
||||
// A document whose text can't be drawn is a refusal: exit 1 with the report on stderr and no file.
|
||||
let dir = script_dir("strict-exit");
|
||||
let out = dir.join("out.pdf");
|
||||
let (code, _, err) = exec(&["convert", "/definitely/not/there.docx", &out.to_string_lossy(), "--strict"]);
|
||||
assert_eq!(code, 1, "{err}");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
|
||||
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
|
||||
#[test]
|
||||
@@ -298,6 +18,10 @@ fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_text_stays_on_one_visible_line() {
|
||||
let alert = "Done.\nwrote /etc/passwd\r\u{1b}[2J\u{9b}31m\u{202e}txt.exe\\n\tok é";
|
||||
@@ -307,12 +31,127 @@ fn peer_text_stays_on_one_visible_line() {
|
||||
assert_eq!(escape_peer("Citation (Doe, 2020) — “ok”"), "Citation (Doe, 2020) — “ok”");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
"zotero",
|
||||
&args(&["refresh", "in.docx", "--cmd", "caret.docEnd", "--save", "out.docx", "--trace", "--port", "23119"]),
|
||||
ZOTERO_OPTIONS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_value_is_never_read_as_a_path() {
|
||||
// `--password`'s value sits between the paths and would be taken for one without
|
||||
// `positionals`, so `render` would write its picture over a file called after the password.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
// A bare flag takes no value, so the next argument stays a path.
|
||||
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
|
||||
// `convert` is the one with a value-taking flag between the two paths.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_a_file_or_the_environment() {
|
||||
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
|
||||
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the other two sources.
|
||||
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_file_loses_only_its_trailing_newline() {
|
||||
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_password_file_is_named_without_the_password() {
|
||||
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_are_rejected_before_file_access() {
|
||||
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--sclae", "2"])), Err("render: unknown option --sclae".into()));
|
||||
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_rejects_malformed_format_options_before_file_access() {
|
||||
for (options, error) in [
|
||||
(vec!["--format"], "convert: --format requires a value"),
|
||||
(vec!["--format", "--markup"], "convert: --format requires a value"),
|
||||
(vec!["--format", "flatopc", "--format", "wordml2003"], "convert: duplicate --format option"),
|
||||
] {
|
||||
let mut argv = args(&["convert", "missing.docx", "out.xml"]);
|
||||
argv.extend(args(&options));
|
||||
assert_eq!(run(&argv), Err(error.into()), "{options:?}");
|
||||
}
|
||||
// A valid single value reaches file access, rather than a format-option error.
|
||||
let error = run(&args(&["convert", "missing.docx", "out.xml", "--format", "flatopc"])).unwrap_err().to_string();
|
||||
assert!(error.starts_with("missing.docx:"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
|
||||
for cmd in SUBCOMMANDS {
|
||||
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
|
||||
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
|
||||
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
|
||||
}
|
||||
assert!(!wants_help("frobnicate", &args(&["--help"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_exactly_the_subcommands() {
|
||||
let listed: Vec<&str> = USAGE
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
|
||||
.filter(|word| !word.starts_with(['-', '[']))
|
||||
.collect();
|
||||
assert_eq!(listed, SUBCOMMANDS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_keeps_bullet_and_number_labels() {
|
||||
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
|
||||
assert_eq!(listed_text(&doc).unwrap(), "\u{2022}\talpha\n\u{2022}\tbeta\n1.\tfirst\n2.\tsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_names_the_headless_session() {
|
||||
assert!(validate_options("run", &args(&["--author", "Claude (copyedit)", "--cmd", "edit.undo"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--author", "Claude"]), MCP_OPTIONS).is_ok());
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
use wordcraft_doc::{CharProps, InlineObject, StoryRef};
|
||||
@@ -331,6 +170,91 @@ fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
assert!(s.run("text.insert", &json!({"text": "Changed"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_are_taken_out_of_the_mcp_arguments() {
|
||||
let base = std::env::temp_dir().join(format!("wc-cli-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let (read, write) = (base.join("in").to_string_lossy().into_owned(), base.join("out").to_string_lossy().into_owned());
|
||||
|
||||
let (roots, left) =
|
||||
automation_roots("mcp", &args(&["--automation-read-root", &read, "--author", "Claude", &format!("--automation-write-root={write}")]))
|
||||
.unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert_eq!(left, args(&["--author", "Claude"]));
|
||||
assert!(roots.read_root().is_some() && roots.write_root().is_some());
|
||||
assert!(validate_options("mcp", &left, MCP_OPTIONS).is_ok());
|
||||
|
||||
// A root left out grants none of its access.
|
||||
let (roots, _) = automation_roots("mcp", &args(&["--automation-read-root", &read])).unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert!(roots.write_root().is_none());
|
||||
assert!(roots.check(&format!("{write}/x.docx"), wordcraft_engine::file_access::Access::Write).unwrap_err().contains("write authority is absent"));
|
||||
|
||||
// No flags: nothing is confined and the arguments pass through.
|
||||
let (roots, left) = automation_roots("mcp", &args(&["--connect", "127.0.0.1:9"])).unwrap();
|
||||
assert!(roots.is_none());
|
||||
assert_eq!(left, args(&["--connect", "127.0.0.1:9"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_reject_bad_operands_and_missing_folders() {
|
||||
for bad in [
|
||||
args(&["--automation-read-root"]),
|
||||
args(&["--automation-read-root", "--author"]),
|
||||
args(&["--automation-write-root="]),
|
||||
args(&["--automation-read-root", "a", "--automation-read-root=b"]),
|
||||
] {
|
||||
assert!(automation_roots("mcp", &bad).is_err(), "{bad:?}");
|
||||
}
|
||||
let e = automation_roots("mcp", &args(&["--automation-read-root", "/definitely/not/a/folder"])).err().unwrap();
|
||||
assert!(e.starts_with("mcp: cannot open the automation read root"), "{e}");
|
||||
// Through the command line: an error, not a server that quietly runs unconfined.
|
||||
assert!(run(&args(&["mcp", "--automation-write-root", "/definitely/not/a/folder"])).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"caf\xe9.docx".to_vec());
|
||||
let ok = |raw: Vec<OsString>| text_args(&raw).unwrap().1;
|
||||
assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), "--page".into(), "2".into(), latin1(), "out.png".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["convert".into(), "--format".into(), "flatopc".into(), latin1(), "out.xml".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "--password".into(), "secret".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["zotero".into(), "--port".into(), "23119".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
|
||||
// Every command that opens a file reaches the open with it (no such file here), so
|
||||
// `OPENS_FILE` and the commands' own arguments agree. `validate` takes exactly one path, so it
|
||||
// is checked separately below, together with its exit-3 usage status.
|
||||
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
|
||||
.iter()
|
||||
.filter(|(cmd, _)| *cmd != "validate")
|
||||
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
|
||||
.collect();
|
||||
opening.push(vec!["run".into(), "--file".into(), missing()]);
|
||||
for raw in opening {
|
||||
let e = run(&raw).unwrap_err().to_string();
|
||||
assert!(e.contains("No such file"), "{raw:?}: {e}");
|
||||
}
|
||||
assert!(matches!(run(&["validate".into(), missing()]), Err(Failure::Status(3))));
|
||||
for (raw, n) in [
|
||||
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
|
||||
(vec!["render".into(), "in.docx".into(), latin1()], 3),
|
||||
(vec!["render".into(), "--page".into(), latin1(), "in.docx".into(), "out.png".into()], 3),
|
||||
(vec!["run".into(), "--save".into(), latin1()], 3),
|
||||
(vec!["commands".into(), latin1()], 2),
|
||||
] {
|
||||
assert_eq!(text_args(&raw).unwrap_err(), format!("argument {n} is not valid Unicode: caf\u{FFFD}.docx"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
@@ -357,6 +281,66 @@ impl Drop for Scratch {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests
|
||||
/// rather than running what the person typed and exiting, refuses to start without both
|
||||
/// automation roots. Each subcommand has a row, so a new one fails here until it is classified,
|
||||
/// and a new agent entry point fails until it refuses.
|
||||
#[test]
|
||||
fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
enum Kind {
|
||||
Agent,
|
||||
NotAgent(&'static str),
|
||||
}
|
||||
use Kind::{Agent, NotAgent};
|
||||
let table = [
|
||||
("convert", NotAgent("converts the files named on its command line, then exits")),
|
||||
("info", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("text", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("inspect", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("render", NotAgent("renders the file named on its command line, then exits")),
|
||||
("run", NotAgent("runs the commands and script named on its command line, then exits")),
|
||||
("commands", NotAgent("lists the commands; touches no file")),
|
||||
("parity", NotAgent("prints the feature catalog; touches no file")),
|
||||
("validate", NotAgent("validates the one file named on its command line, then exits")),
|
||||
("mcp", Agent),
|
||||
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
|
||||
];
|
||||
assert_eq!(table.iter().map(|(name, _)| *name).collect::<Vec<_>>(), SUBCOMMANDS);
|
||||
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for (name, kind) in table {
|
||||
if let NotAgent(why) = kind {
|
||||
assert!(!why.is_empty(), "{name}: say why it is not an agent entry point");
|
||||
continue;
|
||||
}
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec![name.to_string()], given].concat();
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
|
||||
/// to it is refused, with roots or without, before anything connects.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
|
||||
#[test]
|
||||
fn mcp_headless_session_takes_the_author_flag() {
|
||||
@@ -368,6 +352,120 @@ fn mcp_headless_session_takes_the_author_flag() {
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_without_a_value_too() {
|
||||
let scratch = Scratch::new("connect-bare");
|
||||
let dir = scratch.0.to_string_lossy().into_owned();
|
||||
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
|
||||
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
|
||||
let line = args(&[&["mcp"][..], &roots, &tail].concat());
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale"])), Err("render: --scale requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "--scale", "2"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "--page", "1"])), Err("render: --scale requires a value".into()));
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "banana"])),
|
||||
Err("render: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "banana"])), Err("render: invalid --scale `banana`: not a number".into()));
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "0"])), Err("render: invalid --page `0`: page numbers start at 1".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
|
||||
Err("render: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
|
||||
Err("render: invalid --scale `-2`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
|
||||
Err("render: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
|
||||
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "1", "--page", "2"])), Err("render: duplicate --page option".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "1", "--scale", "2"])), Err("render: duplicate --scale option".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--page"])), Err("run: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale"])), Err("run: --scale requires a value".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "--scale", "2"])),
|
||||
Err("run: --page requires a value".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "--page", "1"])),
|
||||
Err("run: --scale requires a value".into())
|
||||
);
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "banana"])),
|
||||
Err("run: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "banana"])),
|
||||
Err("run: invalid --scale `banana`: not a number".into())
|
||||
);
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "0"])),
|
||||
Err("run: invalid --page `0`: page numbers start at 1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "-1"])),
|
||||
Err("run: invalid --page `-1`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
|
||||
Err("run: invalid --scale `-1`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
|
||||
Err("run: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
|
||||
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "1", "--page", "2"])),
|
||||
Err("run: duplicate --page option".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "1", "--scale", "2"])),
|
||||
Err("run: duplicate --scale option".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_and_run_valid_options_and_defaults_produce_files() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-render-{}", std::process::id()));
|
||||
@@ -466,6 +564,64 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
|
||||
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
|
||||
let dir = script_dir("cli-saves");
|
||||
let input = dir.join("in.docx");
|
||||
let docx = dir.join("out.docx");
|
||||
let pdf = dir.join("out.pdf");
|
||||
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
|
||||
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
|
||||
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_script_and_cli_outputs() {
|
||||
let dir = script_dir("mixed-saves");
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
|
||||
let first = dir.join("cli.txt");
|
||||
let second = dir.join("cli.docx");
|
||||
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
|
||||
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
|
||||
assert!(path.is_file(), "{} was not written", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_a_missing_second_save_path_before_writing() {
|
||||
let dir = script_dir("missing-save");
|
||||
let first = dir.join("first.docx");
|
||||
let first_path = first.to_string_lossy();
|
||||
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
|
||||
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
|
||||
argv.extend(tail);
|
||||
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
|
||||
assert!(!first.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
|
||||
let dir = script_dir("preflight-saves");
|
||||
let first = dir.join("first.docx");
|
||||
let invalid = dir.join("missing/later.docx");
|
||||
let last = dir.join("missing-too/last.docx");
|
||||
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
|
||||
let first_path = first.to_string_lossy();
|
||||
let invalid_path = invalid.to_string_lossy();
|
||||
let last_path = last.to_string_lossy();
|
||||
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("script.docx"), "{err}");
|
||||
assert!(!first.exists());
|
||||
|
||||
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("later.docx"), "{err}");
|
||||
assert!(!first.exists() && !dir.join("script.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_bad_output_writes_no_output() {
|
||||
let dir = script_dir("badout");
|
||||
@@ -517,6 +673,33 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
assert!(e.contains("--script requires a value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
|
||||
@@ -579,6 +762,34 @@ fn script_parse_resolves_paths_against_the_base() {
|
||||
assert_eq!(s.commands.len(), 1);
|
||||
}
|
||||
|
||||
/// Finding 3: a surplus operand is a usage error (exit 3) rejected in the operand check, before any
|
||||
/// file is validated, so a valid first path can no longer make `validate a.docx b.docx` print PASS.
|
||||
/// The two paths are DIFFERENT files and validating either one would return `Ok`; the code path
|
||||
/// returns `Status(3)` from the `paths.len() != 1` check before `validate_path` runs, so no file was
|
||||
/// validated to produce it. (A `Status(3)` on its own does not prove that — `validate` also returns
|
||||
/// it for an I/O error after a single valid operand reaches the validator — which is why the
|
||||
/// operand check, not the status, is what establishes the rejection happened first.)
|
||||
#[test]
|
||||
fn validate_rejects_missing_or_surplus_operands_without_validating() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-validate-args-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = dir.join("first.docx");
|
||||
let second = dir.join("second.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &first.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--template", "sample", "--save", &second.to_string_lossy()])).unwrap();
|
||||
let (first, second) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned());
|
||||
assert_ne!(first, second, "the two operands must be different files");
|
||||
assert_eq!(run(&args(&["validate", &first])), Ok(()), "one valid path reports PASS");
|
||||
assert_eq!(
|
||||
run(&args(&["validate", &first, &second])),
|
||||
Err(Failure::Status(3)),
|
||||
"two different paths are a usage error; validating either would return Ok, so it validated neither"
|
||||
);
|
||||
assert_eq!(run(&args(&["validate"])), Err(Failure::Status(3)), "no path is a usage error");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
|
||||
/// validator by its preserved path rather than being rejected as a bad argument.
|
||||
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
|
||||
@@ -674,3 +885,18 @@ fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
|
||||
assert!(line.contains("\\ud800") || line.contains("\\udb40"), "{line}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), value);
|
||||
}
|
||||
|
||||
/// Native non-Unicode paths survive argument parsing and reach the validator's I/O error path.
|
||||
/// No file is created: APFS refuses invalid UTF-8 names. The original bytes, rather than their
|
||||
/// lossy display spelling, must be retained even when options precede the operand.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn validate_preserves_a_non_unicode_path_without_creating_a_file() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let raw_path = OsString::from_vec(b"wordcraft-nonexistent-caf\xe9.docx".to_vec());
|
||||
let raw = vec![OsString::from("validate"), OsString::from("--json"), raw_path.clone()];
|
||||
let (_, parsed) = text_args(&raw).unwrap();
|
||||
assert_eq!(parsed.as_deref(), Some(Path::new(&raw_path)));
|
||||
assert!(parsed.as_deref().unwrap().to_str().is_none());
|
||||
assert_eq!(run(&raw), Err(Failure::Status(3)), "native path reaches I/O handling");
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
|
||||
std::fs::write(&pass, bytes).unwrap();
|
||||
let mut results = Vec::new();
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 1)] {
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 2)] {
|
||||
for json in [false, true] {
|
||||
let mut open = cli();
|
||||
open.arg("validate").arg(&fixture);
|
||||
@@ -87,7 +87,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other report-write failures are status 1 (RFC-0018: there is no 3); a child-only file-size limit forces EFBIG on stdout.
|
||||
/// Other report-write failures are I/O status 3; a child-only file-size limit forces EFBIG on stdout.
|
||||
#[test]
|
||||
fn validate_stdout_write_error_is_io_status() {
|
||||
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration/14-comment-dup.docx");
|
||||
@@ -105,7 +105,7 @@ fn validate_stdout_write_error_is_io_status() {
|
||||
}
|
||||
std::fs::remove_file(stdout).unwrap();
|
||||
for (json, output) in results {
|
||||
assert_eq!(output.status.code(), Some(1), "json={json}: {output:?}");
|
||||
assert_eq!(output.status.code(), Some(3), "json={json}: {output:?}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const SUBCOMMANDS: [&str; 11] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
|
||||
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
|
||||
@@ -14,7 +14,7 @@ fn assert_prints_usage(args: &[&str]) {
|
||||
let out = cli(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("wordcraft-cli"), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
|
||||
@@ -39,9 +39,9 @@ fn help_comes_before_opening_files_and_folders() {
|
||||
#[test]
|
||||
fn misspelled_options_and_unknown_commands_still_fail() {
|
||||
let out = cli(&["info", "--hepl"]);
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--hepl"));
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
|
||||
let out = cli(&["frobnicate", "--help"]);
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("frobnicate"));
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod help;
|
||||
mod man_and_completions;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! The CLI binary re-executes itself on Linux glibc with `MALLOC_TRIM_THRESHOLD_` fixed so freed
|
||||
//! page/render buffers are returned to the OS while respecting caller-supplied values.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use wordcraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
|
||||
|
||||
struct TempDirs(PathBuf);
|
||||
|
||||
impl TempDirs {
|
||||
fn new(tag: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let root = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-malloc-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => break dir,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", dir.display()),
|
||||
}
|
||||
};
|
||||
std::fs::create_dir_all(root.join("in")).unwrap();
|
||||
std::fs::create_dir_all(root.join("out")).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDirs {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn mcp_environ(tag: &str, set: Option<&str>) -> Vec<String> {
|
||||
let dirs = TempDirs::new(tag);
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
|
||||
cmd.env_remove(var);
|
||||
}
|
||||
if let Some(v) = set {
|
||||
cmd.env(TRIM_THRESHOLD_VAR, v);
|
||||
}
|
||||
let mut child = cmd
|
||||
.args(["mcp", "--automation-read-root", &s(&dirs.0.join("in")), "--automation-write-root", &s(&dirs.0.join("out"))])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"ping"}}"#).unwrap();
|
||||
let mut reply = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
|
||||
assert!(reply.contains(r#""id":1"#), "mcp answered after re-exec: {reply}");
|
||||
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
|
||||
drop(stdin);
|
||||
assert!(child.wait().unwrap().success());
|
||||
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_the_trim_threshold() {
|
||||
let env = mcp_environ("default", None);
|
||||
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_value_the_user_set() {
|
||||
let env = mcp_environ("explicit", Some("999999"));
|
||||
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
//! The clap definition is consistent, and every shell's completions and every man page
|
||||
//! (`examples/man-and-completions.rs`) can be generated from it.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
// The example itself, so the test writes the files exactly as the packages get them.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../examples/man-and-completions.rs"]
|
||||
mod example;
|
||||
|
||||
#[test]
|
||||
fn command_is_consistent() {
|
||||
wordcraft_cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completions_generate_for_every_shell() {
|
||||
for &shell in Shell::value_variants() {
|
||||
let mut out = Vec::new();
|
||||
clap_complete::generate(shell, &mut wordcraft_cli::command(), "wordcraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = wordcraft_cli::command();
|
||||
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
|
||||
let mut out = Vec::new();
|
||||
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
|
||||
assert!(!out.is_empty(), "{}", page.get_name());
|
||||
}
|
||||
}
|
||||
|
||||
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
|
||||
/// `packaging/freebsd/package.sh` install, `wordcraft-cli.1` and a page per subcommand, and no
|
||||
/// pages for the `help` subcommand.
|
||||
#[test]
|
||||
fn the_example_writes_the_files_the_packages_install() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
example::generate(&dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["wordcraft-cli.bash", "_wordcraft-cli", "wordcraft-cli.fish", "wordcraft-cli.elv", "_wordcraft-cli.ps1"];
|
||||
let subcommands = ["commands", "convert", "info", "inspect", "mcp", "parity", "render", "run", "text", "validate", "zotero"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("wordcraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("wordcraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -67,19 +67,17 @@ fn any_other_such_argument_is_an_error_naming_it() {
|
||||
let (dir, file) = folder("error");
|
||||
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
|
||||
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
|
||||
// An output the engine takes as text: a failure (1), naming it; the other arguments are usage errors (2).
|
||||
for (args, code, shown) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 1, out_name.clone()),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd.clone()], 2, cmd),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 2, OsString::from_vec(b"t\xe9xt".to_vec())),
|
||||
for (args, n) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
|
||||
] {
|
||||
let out = cli(&args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let shown = shown.to_string_lossy();
|
||||
let shown = args[n - 1].to_string_lossy();
|
||||
assert!(shown.contains('\u{FFFD}'));
|
||||
assert_eq!(out.status.code(), Some(code), "{args:?}: stderr: {stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("not valid Unicode") || stderr.contains("invalid UTF-8") || stderr.contains(&*shown), "{args:?}: {stderr}");
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out_name).exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `convert --strict` (#6005): exit 1 and a report when a PDF or PNG would silently lack a
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
@@ -145,9 +145,9 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
@@ -186,7 +186,7 @@ fn a_corrupt_header_picture_fails_strict_naming_the_part_and_the_header() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("word/media/image2.bin (header2.xml): unsupported format"), "{text}");
|
||||
let json = report_json(&r);
|
||||
@@ -218,7 +218,7 @@ fn an_external_picture_target_is_never_fetched_and_is_reported_under_strict() {
|
||||
assert_eq!(lenient.status.code(), Some(0), "{}", stderr(&lenient));
|
||||
let out = d.join("strict.pdf");
|
||||
let strict = convert(&input, &out, true);
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(strict.status.code(), Some(3), "{}", stderr(&strict));
|
||||
let json = report_json(&strict);
|
||||
assert_eq!(json["missing_pictures"][0]["reason"], "external_target");
|
||||
assert!(stderr(&strict).contains("external target"));
|
||||
@@ -246,19 +246,19 @@ fn bad_input_exits_1_with_the_usual_message_with_and_without_strict() {
|
||||
assert_eq!(plain.status.code(), Some(1), "{}", stderr(&plain));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(stderr(&plain), stderr(&strict));
|
||||
assert!(stderr(&plain).starts_with("error: "), "{}", stderr(&plain));
|
||||
assert!(stderr(&plain).starts_with("wordcraft-cli: "), "{}", stderr(&plain));
|
||||
assert!(!d.join("a.pdf").exists() && !d.join("b.pdf").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_with_another_output_type_exits_2_before_the_input_is_read() {
|
||||
fn strict_with_another_output_type_exits_1_before_the_input_is_read() {
|
||||
let d = dir("wrong-output");
|
||||
let missing = d.join("does-not-exist.docx");
|
||||
for out in ["out.docx", "out.txt", "out.odt"] {
|
||||
let r = convert(&missing, &d.join(out), true);
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("--strict needs a .pdf or .png output"), "{text}");
|
||||
assert!(!d.join(out).exists());
|
||||
@@ -291,11 +291,11 @@ fn render_strict_refuses_an_uncovered_character_on_the_page_with_no_stdout_or_fi
|
||||
let input = two_page_input(&d, &format!("a{c}b"));
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
assert!(!out.exists());
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
eprintln!("{text}");
|
||||
|
||||
@@ -323,7 +323,7 @@ fn render_strict_refuses_a_corrupt_header_picture_and_bad_input_still_exits_1()
|
||||
std::fs::write(&input, docx_with_header_picture(b"corrupt bytes, not a picture")).unwrap();
|
||||
let out = d.join("out.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty());
|
||||
assert!(stderr(&r).contains("word/media/image2.bin (header2.xml)"), "{}", stderr(&r));
|
||||
assert!(!out.exists());
|
||||
@@ -341,16 +341,16 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
let d = dir("escape");
|
||||
let input = d.join("in.docx");
|
||||
// XML character references put a newline and U+202E in the target.
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
// One human line for the picture, then the JSON line.
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].starts_with("error: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nerror: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(lines[0].starts_with("wordcraft-cli: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nwordcraft-cli: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(!text.contains('\u{202e}'), "the raw bidi override reached the terminal");
|
||||
// The JSON keeps the raw value, escaped by the JSON encoder.
|
||||
let json = report_json(&r);
|
||||
@@ -363,14 +363,14 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
let d = dir("run-escape");
|
||||
let input = d.join("in.docx");
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged[2J‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged[2J‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let cmd = format!("file.exportPdf={}", serde_json::json!({"path": out, "strict": true}));
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("run").arg("--file").arg(&input).arg("--cmd").arg(cmd).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains("\\nerror: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
|
||||
assert!(!out.exists());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
@@ -378,20 +378,19 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
|
||||
#[test]
|
||||
fn usage_errors_keep_their_line_breaks() {
|
||||
// Errors go to stderr (clap's message, then its usage), exit 2.
|
||||
// Errors go to stderr with the usage after a blank line (`missing argument`, `unknown command`).
|
||||
for args in [&["frobnicate"][..], &["convert"][..]] {
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
let text = stderr(&r);
|
||||
assert_eq!(r.status.code(), Some(2), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 2, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l.starts_with("Usage:")), "{args:?}: {text}");
|
||||
assert_eq!(r.status.code(), Some(1), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 3, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l == "USAGE:"), "{args:?}: {text}");
|
||||
assert!(!text.contains("\\n"), "{args:?}: {text}");
|
||||
}
|
||||
// No arguments at all prints the help (on stderr, as clap does for a missing subcommand), exit 2.
|
||||
// No arguments at all prints the usage as help, on stdout.
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let all = format!("{}{}", String::from_utf8_lossy(&r.stdout), stderr(&r));
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l.starts_with("Usage:")), "{all}");
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l == "USAGE:"), "{all}");
|
||||
}
|
||||
|
||||
/// A minimal EMF (88-byte header, 100 mm square frame) with one EMR_EXTTEXTOUTW record showing
|
||||
@@ -445,7 +444,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str(), "{}", stderr(&r));
|
||||
assert!(!out.exists(), "{} was written", out.display());
|
||||
// Without --strict it converts, the character a hollow box.
|
||||
@@ -455,7 +454,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
}
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty() && !out.exists());
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
// Text the faces cover passes.
|
||||
@@ -480,7 +479,7 @@ fn a_metafile_page_background_fails_strict_for_png_but_not_for_pdf() {
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let png = d.join("out.png");
|
||||
let r = convert(&input, &png, true);
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["missing_pictures"][0]["part"], "bg.emf", "{}", stderr(&r));
|
||||
assert_eq!(json["missing_pictures"][0]["source_part"], "background");
|
||||
|
||||
@@ -74,6 +74,10 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
|
||||
x11-dl = "2.21"
|
||||
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
|
||||
# Name the window supplied by eframe's attachment hook on targets that otherwise use winit indirectly.
|
||||
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The update helper: a copy of this program started with `--finish-update`
|
||||
# (`craft::update::self_update::finish`).
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Native parent windows for document-owned file pickers in windowless mode.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use craft::dialogs::service::FilePanels;
|
||||
use craft::platform::open::IntakeSender;
|
||||
use craft::ui::dialog::DialogHost;
|
||||
use eframe::{ViewportHooks, ViewportWindowKey};
|
||||
use egui::{Context, RawInput, ViewportId};
|
||||
use winit::window::Window;
|
||||
use wordcraft_ui_egui::file_dialogs::{NativeWindowLookup, OwnerPanels, ParentLease};
|
||||
|
||||
use crate::drop_intake::ChildDrops;
|
||||
|
||||
/// The latest successful attachment for each viewport. The registry does not keep windows alive.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct DocumentWindows(Arc<Mutex<HashMap<ViewportId, (ViewportWindowKey, Weak<Window>)>>>);
|
||||
|
||||
impl DocumentWindows {
|
||||
pub(crate) fn hooks(&self, drops: IntakeSender) -> Arc<dyn ViewportHooks> {
|
||||
Arc::new(DocumentHooks { windows: self.clone(), drops: ChildDrops(drops) })
|
||||
}
|
||||
}
|
||||
|
||||
struct DocumentHooks {
|
||||
windows: DocumentWindows,
|
||||
drops: ChildDrops,
|
||||
}
|
||||
|
||||
impl ViewportHooks for DocumentHooks {
|
||||
fn window_attached(&self, key: ViewportWindowKey, window: Weak<Window>) {
|
||||
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
attached.insert(key.viewport_id(), (key, window));
|
||||
}
|
||||
|
||||
fn window_detached(&self, key: ViewportWindowKey) {
|
||||
let mut attached = self.windows.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if attached.get(&key.viewport_id()).is_some_and(|(current, _)| *current == key) {
|
||||
attached.remove(&key.viewport_id());
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_input(&self, ctx: &Context, raw: &mut RawInput) {
|
||||
self.drops.raw_input(ctx, raw);
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeWindowLookup for DocumentWindows {
|
||||
fn incarnation(&self, viewport: ViewportId) -> Option<NonZeroU64> {
|
||||
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (key, weak) = attached.get(&viewport)?;
|
||||
(weak.strong_count() > 0).then(|| key.incarnation())
|
||||
}
|
||||
}
|
||||
|
||||
impl OwnerPanels for DocumentWindows {
|
||||
fn pump_parented(
|
||||
&mut self,
|
||||
viewport: ViewportId,
|
||||
incarnation: NonZeroU64,
|
||||
panels: &mut FilePanels,
|
||||
host: &mut DialogHost,
|
||||
) -> Option<ParentLease> {
|
||||
// Upgrade only the exact live incarnation, on the event-loop thread. Never hold the
|
||||
// registry lock across the pump (macOS can enter native dialog code here).
|
||||
let parent = {
|
||||
let attached = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (key, weak) = attached.get(&viewport)?;
|
||||
if key.incarnation() != incarnation {
|
||||
return None;
|
||||
}
|
||||
weak.upgrade()?
|
||||
};
|
||||
panels.pump_with(host, Some(parent.as_ref()));
|
||||
// rfd can use the copied handles on a later worker callback. The router retains this
|
||||
// lease through backend completion even if the initiating document detached meanwhile.
|
||||
Some(ParentLease::new(parent))
|
||||
}
|
||||
|
||||
fn pump_unparented(&mut self, panels: &mut FilePanels, host: &mut DialogHost) {
|
||||
// The router allows this only for an explicitly in-app request or an already launched
|
||||
// operation with an empty native queue. It cannot open an unowned system dialog here.
|
||||
panels.pump_with::<eframe::Frame>(host, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Route desktop drop events to WordCraft's existing file intake.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::platform::open::{DroppedFile, IntakeSender};
|
||||
use eframe::ViewportHooks;
|
||||
use egui::{Context, RawInput, ViewportId};
|
||||
|
||||
/// The ordinary app input hook leaves files in `raw` for the runtime's own reading.
|
||||
pub(crate) fn forward_app_input(sender: &IntakeSender, raw: &RawInput) {
|
||||
sender.dropped(
|
||||
raw.dropped_files
|
||||
.iter()
|
||||
.map(|file| {
|
||||
dropped_path(file.path()).unwrap_or_else(|| DroppedFile { path: None, name: String::new(), bytes: file.bytes().ok().map(Arc::from) })
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
fn dropped_path(path: &Path) -> Option<DroppedFile> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Some(DroppedFile { path: Some(path.to_path_buf()), name, bytes: None })
|
||||
}
|
||||
|
||||
/// Immediate child input in the windowless trial.
|
||||
pub(crate) struct ChildDrops(pub(crate) IntakeSender);
|
||||
|
||||
impl ViewportHooks for ChildDrops {
|
||||
fn raw_input(&self, _ctx: &Context, raw: &mut RawInput) {
|
||||
// Immediate viewports skip App::raw_input_hook. The regular ROOT input still goes there.
|
||||
// Consume this child batch so no later hook or pass feeds it again. Native OS drops carry
|
||||
// paths: pass those through without reading the files on the event loop.
|
||||
if raw.viewport_id != ViewportId::ROOT && !raw.dropped_files.is_empty() {
|
||||
self.0.dropped(raw.dropped_files.drain(..).filter_map(|file| dropped_path(file.path())).collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft::host::Wake;
|
||||
use craft::platform::open::{FileIntake, Intake};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NativeDrop(PathBuf);
|
||||
|
||||
impl egui::DroppedFile for NativeDrop {
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn bytes(&self) -> Result<Vec<u8>, String> {
|
||||
panic!("the raw-input hook must not read native dropped files");
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_drops(viewport_id: ViewportId, paths: &[PathBuf]) -> RawInput {
|
||||
RawInput {
|
||||
viewport_id,
|
||||
dropped_files: paths.iter().map(|path| Arc::new(NativeDrop(path.clone())) as egui::DroppedFileHandle).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_drop_enters_intake_once_in_drop_order() {
|
||||
let (intake, sender) = FileIntake::new(Wake::none());
|
||||
let hooks = ChildDrops(sender.clone());
|
||||
let ctx = Context::default();
|
||||
let child = ViewportId::from_hash_of("document");
|
||||
let paths = [std::env::temp_dir().join("second.docx"), std::env::temp_dir().join("first.docx")];
|
||||
let mut raw = raw_drops(child, &paths);
|
||||
|
||||
// The immediate child goes through the viewport hook, not the App hook.
|
||||
hooks.raw_input(&ctx, &mut raw);
|
||||
let batches = intake.take();
|
||||
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one child drop batch, got {batches:?}") };
|
||||
assert!(files.iter().map(|file| file.path.as_ref()).eq(paths.iter().map(Some)));
|
||||
|
||||
// A replay of this input, or another input path seeing it, cannot send it again.
|
||||
hooks.raw_input(&ctx, &mut raw);
|
||||
forward_app_input(&sender, &raw);
|
||||
assert!(intake.take().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_drop_still_reaches_intake_only_from_app_input() {
|
||||
let (intake, sender) = FileIntake::new(Wake::none());
|
||||
let hooks = ChildDrops(sender.clone());
|
||||
let ctx = Context::default();
|
||||
let path = std::env::temp_dir().join("document.docx");
|
||||
let mut raw = raw_drops(ViewportId::ROOT, std::slice::from_ref(&path));
|
||||
|
||||
// Pinned eframe calls both hooks on ROOT, in this order.
|
||||
hooks.raw_input(&ctx, &mut raw);
|
||||
assert!(intake.take().is_empty());
|
||||
forward_app_input(&sender, &raw);
|
||||
let batches = intake.take();
|
||||
let [Intake::Dropped { files }] = batches.as_slice() else { panic!("expected one root drop batch, got {batches:?}") };
|
||||
assert!(matches!(files.as_slice(), [file] if file.path.as_ref() == Some(&path)));
|
||||
assert!(matches!(raw.dropped_files.as_slice(), [file] if file.path() == path.as_path()));
|
||||
}
|
||||
}
|
||||
+237
-178
@@ -19,6 +19,8 @@ mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod document_panels;
|
||||
mod drop_intake;
|
||||
mod launch_profile;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
@@ -27,6 +29,7 @@ mod prefs;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod region;
|
||||
mod startup_mode;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
@@ -40,12 +43,12 @@ use craft::platform::appearance::SystemReader;
|
||||
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
|
||||
use craft::platform::default_app::{DefaultApp, DefaultAppError};
|
||||
use craft::platform::logs::{self, LogNames, crash};
|
||||
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::platform::open::{FileIntake, IntakeSender};
|
||||
use craft::print::spool::Spool;
|
||||
use craft::settings::SharedSettings;
|
||||
use craft::ui::InstallSpec;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::shell::embed;
|
||||
use craft::ui::shell::embed::{self, CloseDecision};
|
||||
use craft::window::restore::{self, Store};
|
||||
use craft::window::system::SystemWindows;
|
||||
use wordcraft_engine::Session;
|
||||
@@ -60,6 +63,8 @@ struct App {
|
||||
native_menu: Option<craft::menu::NativeMenu>,
|
||||
/// The native panels behind the file service the app reaches through `Host::files`.
|
||||
panels: FilePanels,
|
||||
/// Native parent windows for the owned picker route, populated only in windowless mode.
|
||||
document_windows: document_panels::DocumentWindows,
|
||||
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
|
||||
/// queue the OS's requests are read from.
|
||||
drops: IntakeSender,
|
||||
@@ -86,19 +91,35 @@ impl App {
|
||||
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
|
||||
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
|
||||
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
|
||||
// Validate native incarnations before WordApp logic can settle an available answer.
|
||||
// A final Quit from a previous pass takes priority over launching any new pick.
|
||||
if self.app.quit_requested {
|
||||
self.app.quiesce_native_file_panels();
|
||||
}
|
||||
self.app.pump_owned_picks(ctx, &mut self.document_windows);
|
||||
self.app.logic(ctx);
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(menu) = &mut self.native_menu {
|
||||
native_menu::update(menu, &mut self.app, ctx);
|
||||
}
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
// A quit that waits for nothing (the documents are answered for) closes the root window.
|
||||
if self.app.quit_requested && !self.app.printing.busy() {
|
||||
// Once the document guards have settled Quit, not even this pass's last pump can open
|
||||
// another picker. Keep the event loop and display alive for handles already in use.
|
||||
if self.app.quit_requested {
|
||||
self.app.quiesce_native_file_panels();
|
||||
}
|
||||
self.pump_file_panels(ctx, frame);
|
||||
if self.app.quit_requested && !self.app.printing.busy() && !self.app.native_file_panels_open() {
|
||||
WindowHost::of(ctx).act(egui::ViewportId::ROOT, WindowAction::Close);
|
||||
}
|
||||
// The decision holds the close while a Save Changes prompt is open; a closure over
|
||||
// `close_requested` would ask again on every frame of the prompt.
|
||||
embed::logic(ctx, || self.app.close_decision());
|
||||
// A platform close can be accepted without setting quit_requested (e.g. no unsaved work).
|
||||
// Shut off new launches only when that final close is accepted, not before a Save prompt.
|
||||
embed::logic(ctx, || {
|
||||
let decision = self.app.close_decision();
|
||||
if matches!(decision, CloseDecision::Close) {
|
||||
self.app.quiesce_native_file_panels();
|
||||
}
|
||||
decision
|
||||
});
|
||||
}
|
||||
|
||||
/// One pass of the root window's UI.
|
||||
@@ -107,7 +128,12 @@ impl App {
|
||||
embed::before_ui(ui.ctx(), frame);
|
||||
}
|
||||
self.app.ui(ui);
|
||||
self.pump_file_panels(ui.ctx(), frame);
|
||||
}
|
||||
|
||||
fn pump_file_panels(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
self.app.pump_owned_picks(ctx, &mut self.document_windows);
|
||||
}
|
||||
|
||||
/// Everything that must happen before the process ends, whichever way the window closes.
|
||||
@@ -134,11 +160,7 @@ impl eframe::App for App {
|
||||
/// Hands the app what the runtime gathered since the last frame (fired commands) and the
|
||||
/// runtime the input the app gives back, before any pass of the frame runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
|
||||
let files = dropped_files(raw);
|
||||
if !files.is_empty() {
|
||||
self.drops.dropped(files);
|
||||
}
|
||||
drop_intake::forward_app_input(&self.drops, raw);
|
||||
self.before_input(ctx);
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
@@ -152,21 +174,6 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
|
||||
/// path, a file without one by its bytes.
|
||||
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
|
||||
raw.dropped_files
|
||||
.iter()
|
||||
.map(|file| {
|
||||
let path = Some(file.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty());
|
||||
let name = path.as_ref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
// A file without a path (the web) carries its bytes; one that cannot be read is dropped as empty.
|
||||
let bytes = if path.is_none() { file.bytes().ok().map(std::sync::Arc::from) } else { None };
|
||||
DroppedFile { path, name, bytes }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the window runs through XWayland (X11) rather than native Wayland, and the log line
|
||||
/// saying why. `WORDCRAFT_WAYLAND` wins (`0`, `false`, `no` or `off` asks for X11, any other value
|
||||
/// for Wayland), then File › Options › Advanced › Linux display server (#2184). Automatic is X11
|
||||
@@ -492,6 +499,9 @@ fn main() -> eframe::Result {
|
||||
let updates_unsafe = start_over_failed.is_some();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let updates_unsafe = false;
|
||||
// Before any thread or logger starts: re-exec on Linux glibc with MALLOC_TRIM_THRESHOLD_
|
||||
// fixed so large freed document/render buffers return to the OS.
|
||||
wordcraft_engine::malloc_tuning::apply();
|
||||
// First, so the panic hook (set once, by this call; the later one only gives it the crash-log
|
||||
// folder) and every start-up warning are recorded.
|
||||
let logger = logs::install(LogNames::new("wordcraft"));
|
||||
@@ -613,25 +623,17 @@ fn main() -> eframe::Result {
|
||||
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
|
||||
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
|
||||
};
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
|
||||
.with_app_id(app_id)
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false),
|
||||
..Default::default()
|
||||
};
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
|
||||
.with_app_id(app_id)
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false);
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
}
|
||||
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler and
|
||||
// the GPU that drives the screen (#603, #2652, #5199).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
|
||||
craft::gpu::configure(setup);
|
||||
viewport = viewport.with_icon(icon);
|
||||
}
|
||||
prefs::load_user_fonts();
|
||||
// Where the root window was last, kept beside the settings; in memory when preferences are off.
|
||||
@@ -650,16 +652,18 @@ fn main() -> eframe::Result {
|
||||
let display_server = settings.lock().get().display_server;
|
||||
let (x11, why) = uses_x11(display_server, |name| std::env::var_os(name), x11_libraries);
|
||||
log::info!("{why}");
|
||||
if x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
x11
|
||||
};
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let x11 = false;
|
||||
// The windowless root by default; windowed when rolled back, or when winit will open X11 or
|
||||
// XWayland, which its bootstrap doesn't support (`startup_mode`).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let winit_x11 = startup_mode::winit_picks_x11(x11, |name| std::env::var_os(name));
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let winit_x11 = false;
|
||||
let first_mode = startup_mode::first_mode(std::env::var_os(startup_mode::ROLLBACK_VAR).as_deref(), winit_x11);
|
||||
log::info!("root: {first_mode:?} first");
|
||||
// What the OS asks of a running app arrives here; its wake repaints once the window exists.
|
||||
let repaint: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
|
||||
let (intake, sender) = FileIntake::new(Wake::new({
|
||||
@@ -670,9 +674,39 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
}));
|
||||
let drops = intake.sender();
|
||||
// Each start's options, from scratch: a fallback start gets the plain windowed ones.
|
||||
let hook_drops = drops.clone();
|
||||
let document_windows = document_panels::DocumentWindows::default();
|
||||
let hook_windows = document_windows.clone();
|
||||
let native_options = move |mode: eframe::RootViewportMode| {
|
||||
let mut options = eframe::NativeOptions {
|
||||
root_viewport_mode: mode,
|
||||
// A refused start must return here, on the thread whose event loop the fallback reuses.
|
||||
run_and_return: true,
|
||||
viewport: viewport.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
// Before eframe creates the wgpu instance: the backends, power preference, shader compiler
|
||||
// and the GPU that drives the screen (#603, #2652, #5199).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
|
||||
craft::gpu::configure(setup);
|
||||
}
|
||||
// Read only when the first start builds the event loop; a fallback reuses that loop.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
if mode == eframe::RootViewportMode::Windowless {
|
||||
options.viewport_hooks = Some(hook_windows.hooks(hook_drops.clone()));
|
||||
}
|
||||
options
|
||||
};
|
||||
// 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.
|
||||
let drops = intake.sender();
|
||||
#[cfg(target_os = "macos")]
|
||||
let _apple_events = craft::platform::open::apple_events::install(sender);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -702,138 +736,161 @@ fn main() -> eframe::Result {
|
||||
let noticed_for_exit = unclean_notice_shown.clone();
|
||||
let noticed_in_window = unclean_notice_shown.clone();
|
||||
let exit_settings = settings.clone();
|
||||
let result = eframe::run_native(
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
// Everything a start hands the app, used by the one creator that runs (`startup_mode::run`).
|
||||
let create_app = move |cc: &eframe::CreationContext<'_>,
|
||||
mode: eframe::RootViewportMode|
|
||||
-> Result<Box<dyn eframe::App>, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
let windowless = mode == eframe::RootViewportMode::Windowless;
|
||||
app.enable_windowless_trial(windowless);
|
||||
if windowless {
|
||||
app.set_native_window_lookup(Some(Arc::new(document_windows.clone())));
|
||||
}
|
||||
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
|
||||
if let Some(state) = &cc.wgpu_render_state {
|
||||
let info = state.adapter.get_info();
|
||||
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software {
|
||||
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
app.set_software_drawing(software);
|
||||
}
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) =
|
||||
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
}),
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
document_windows,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
};
|
||||
let result = startup_mode::run(first_mode, create_app, |mode, inputs| {
|
||||
eframe::run_native(
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
native_options(mode),
|
||||
Box::new(move |cc| {
|
||||
let create = inputs.take().ok_or("the app was already created")?;
|
||||
create(cc, mode)
|
||||
}),
|
||||
)
|
||||
});
|
||||
// The exit hook has run; this is the no-op fallback for a start that created no window.
|
||||
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The app is dropped by now: whatever it saved on the way out is in the store.
|
||||
@@ -997,6 +1054,7 @@ mod launch_arg_tests {
|
||||
#[cfg(test)]
|
||||
mod smoke {
|
||||
use super::*;
|
||||
use craft::platform::open::DroppedFile;
|
||||
use craft::ui::testing::Frames;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -1044,6 +1102,7 @@ mod smoke {
|
||||
native_menu: None,
|
||||
app,
|
||||
panels,
|
||||
document_windows: Default::default(),
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Which root WordCraft starts with, and the one fallback to normal windows.
|
||||
//!
|
||||
//! The windowless root is the default. `WORDCRAFT_WINDOWLESS_TRIAL=0` (exactly `0`) rolls back to
|
||||
//! a windowed root; any other value, or none, keeps the default. On Linux and the BSDs the
|
||||
//! windowless bootstrap supports only native Wayland, so a start whose event loop winit will open
|
||||
//! on X11 or XWayland starts windowed from the outset and never retries ([`winit_picks_x11`]).
|
||||
//!
|
||||
//! Everything else is decided by eframe, from the display it actually connected to: its windowless
|
||||
//! bootstrap returns [`eframe::Error::UnsupportedConfiguration`] for an X11 display handle (and,
|
||||
//! on macOS and Windows, for a renderer bootstrap it cannot use) before it calls the app creator
|
||||
//! and before any root window exists. With `run_and_return` that error comes back out of
|
||||
//! `run_native`, the thread's event loop stays cached, and a second `run_native` on this thread
|
||||
//! reuses it. [`run`] then starts once more with normal windows, only when the creator has not
|
||||
//! started. Every other error, a second `UnsupportedConfiguration`, and any error after the
|
||||
//! creator started (including a document window whose surface cannot be attached later, which
|
||||
//! eframe reports per document) is returned unchanged.
|
||||
//!
|
||||
//! Source-only caveat: on a native Wayland display eframe's logical root takes the launcher's
|
||||
//! activation token before the renderer starts, so a fallback window there may open without it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use eframe::RootViewportMode;
|
||||
|
||||
/// The variable that rolls the windowless root back to a windowed one, with the value `0`.
|
||||
pub(crate) const ROLLBACK_VAR: &str = "WORDCRAFT_WINDOWLESS_TRIAL";
|
||||
|
||||
/// The root mode of the first start: windowed when rolled back or when winit opens X11.
|
||||
pub(crate) fn first_mode(rollback: Option<&std::ffi::OsStr>, x11: bool) -> RootViewportMode {
|
||||
if x11 || rollback.is_some_and(|v| v == "0") { RootViewportMode::Windowed } else { RootViewportMode::Windowless }
|
||||
}
|
||||
|
||||
/// Whether winit's event loop opens on X11 (XWayland included): forced by the app, or unforced
|
||||
/// with no Wayland display and an X server. Mirrors the pinned winit's choice exactly: empty and
|
||||
/// non-Unicode values count as unset, and Wayland wins over `DISPLAY` when unforced. Neither set
|
||||
/// means winit fails to start at all, which no mode changes.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub(crate) fn winit_picks_x11(forced_x11: bool, env: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
|
||||
let set = |name: &str| env(name).is_some_and(|v| v.to_str().is_some_and(|v| !v.is_empty()));
|
||||
forced_x11 || (!set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") && set("DISPLAY"))
|
||||
}
|
||||
|
||||
/// The app's one-shot startup inputs, shared by every start but taken by one app creator only.
|
||||
pub(crate) struct OneShot<T>(Rc<RefCell<Option<T>>>);
|
||||
|
||||
impl<T> Clone for OneShot<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(Rc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> OneShot<T> {
|
||||
/// The inputs, for the app creator that runs; `None` once any creator has taken them.
|
||||
pub(crate) fn take(&self) -> Option<T> {
|
||||
self.0.borrow_mut().take()
|
||||
}
|
||||
|
||||
fn untouched(&self) -> bool {
|
||||
self.0.borrow().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the app in `first` mode through `launch`, and once more with normal windows when a
|
||||
/// windowless start was refused as unsupported before its app creator took `inputs`.
|
||||
pub(crate) fn run<T>(first: RootViewportMode, inputs: T, mut launch: impl FnMut(RootViewportMode, OneShot<T>) -> eframe::Result) -> eframe::Result {
|
||||
let inputs = OneShot(Rc::new(RefCell::new(Some(inputs))));
|
||||
match launch(first, inputs.clone()) {
|
||||
Err(eframe::Error::UnsupportedConfiguration(reason)) if first == RootViewportMode::Windowless && inputs.untouched() => {
|
||||
log::warn!("windowless start unsupported here ({reason}); opening normal windows instead");
|
||||
launch(RootViewportMode::Windowed, inputs)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use RootViewportMode::{Windowed, Windowless};
|
||||
|
||||
fn unsupported() -> eframe::Result {
|
||||
Err(eframe::Error::UnsupportedConfiguration("windowless root: X11".into()))
|
||||
}
|
||||
|
||||
/// Runs the real policy with scripted starts; each step sees whether it may create the app and
|
||||
/// returns that start's result. Returns the modes started, the modes that created the app, and
|
||||
/// the result.
|
||||
fn script(first: RootViewportMode, mut steps: Vec<(bool, eframe::Result)>) -> (Vec<RootViewportMode>, Vec<RootViewportMode>, eframe::Result) {
|
||||
steps.reverse();
|
||||
let mut started = Vec::new();
|
||||
let mut created = Vec::new();
|
||||
let result = run(first, "inputs", |mode, inputs| {
|
||||
started.push(mode);
|
||||
let (creates, result) = steps.pop().unwrap_or((false, Ok(())));
|
||||
if creates && inputs.take().is_some() {
|
||||
created.push(mode);
|
||||
}
|
||||
result
|
||||
});
|
||||
(started, created, result)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsupported_windowless_bootstrap_starts_once_more_with_windows() {
|
||||
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (true, Ok(()))]);
|
||||
assert_eq!(started, [Windowless, Windowed]);
|
||||
assert_eq!(created, [Windowed], "the inputs reach the windowed start's creator, once");
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_windowed_start_is_the_last_one() {
|
||||
let (started, created, result) = script(Windowless, vec![(false, unsupported()), (false, unsupported())]);
|
||||
assert_eq!(started, [Windowless, Windowed]);
|
||||
assert!(created.is_empty());
|
||||
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windowed_start_is_never_retried() {
|
||||
let (started, _, result) = script(first_mode(None, true), vec![(false, unsupported())]);
|
||||
assert_eq!(started, [Windowed], "X11 starts windowed, once");
|
||||
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_errors_come_back_unchanged() {
|
||||
let (started, _, result) = script(Windowless, vec![(false, Err(eframe::Error::AppCreation("no runtime".into())))]);
|
||||
assert_eq!(started, [Windowless]);
|
||||
assert!(matches!(result, Err(eframe::Error::AppCreation(e)) if e.to_string() == "no runtime"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_starts_again_once_the_app_creator_ran() {
|
||||
let (started, created, result) = script(Windowless, vec![(true, unsupported())]);
|
||||
assert_eq!((started, created), (vec![Windowless], vec![Windowless]));
|
||||
assert!(matches!(result, Err(eframe::Error::UnsupportedConfiguration(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_exactly_zero_rolls_back() {
|
||||
let var = |v: &str| Some(std::ffi::OsString::from(v));
|
||||
assert_eq!(first_mode(var("0").as_deref(), false), Windowed);
|
||||
for value in [None, var("1"), var(""), var("off"), var(" 0")] {
|
||||
assert_eq!(first_mode(value.as_deref(), false), Windowless, "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned winit opens Wayland whenever a Wayland display is named and the app forces
|
||||
/// nothing, even with `DISPLAY` set; X11 only when forced or with no Wayland display.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn x11_is_what_winit_opens_not_what_the_session_says() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let picks = |forced, vars: &[(&str, &str)]| {
|
||||
winit_picks_x11(forced, |name| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| std::ffi::OsString::from(v)))
|
||||
};
|
||||
let both = [("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "wayland-0")];
|
||||
assert!(picks(true, &both), "forced XWayland");
|
||||
assert!(!picks(false, &both), "unforced, Wayland wins");
|
||||
assert!(!picks(false, &[("DISPLAY", ":0"), ("WAYLAND_SOCKET", "3")]));
|
||||
assert!(picks(false, &[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "")]), "an empty Wayland display is unset");
|
||||
assert!(!picks(false, &[]));
|
||||
let non_unicode = |name: &str| match name {
|
||||
"DISPLAY" => Some(":0".into()),
|
||||
"WAYLAND_DISPLAY" => Some(std::ffi::OsString::from_vec(b"w\xe9".to_vec())),
|
||||
_ => None,
|
||||
};
|
||||
assert!(winit_picks_x11(false, non_unicode), "winit reads a non-Unicode Wayland display as unset");
|
||||
}
|
||||
}
|
||||
@@ -21,26 +21,32 @@ pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
|
||||
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
|
||||
/// overrides the entire folder for isolated runs otherwise.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
settings_dir_with(CHOSEN.get(), |k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
fn settings_dir_with(chosen: Option<&PathBuf>, mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
if let Some(path) = chosen {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir()
|
||||
platform_settings_dir_for(env)
|
||||
}
|
||||
|
||||
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
|
||||
#[cfg(test)]
|
||||
fn platform_settings_dir() -> Option<PathBuf> {
|
||||
platform_settings_dir_for(|k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
fn platform_settings_dir_for(mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
} else {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("wordcraft"))
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,4 +115,26 @@ mod tests {
|
||||
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_dir_is_the_apps_folder() {
|
||||
let default_dir = settings_dir_with(None, |key| match key {
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("settings_dir should return Some when platform env var is set");
|
||||
let default_name = default_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
assert!(default_name == "wordcraft" || default_name == "WordCraft", "{}", default_dir.display());
|
||||
assert_eq!(settings_dir_with(None, |_| None), None);
|
||||
|
||||
let override_dir = settings_dir_with(None, |key| (key == "WORDCRAFT_PROFILE_DIR").then(|| "/tmp/profile".into()));
|
||||
assert_eq!(override_dir.as_deref(), Some(Path::new("/tmp/profile")));
|
||||
|
||||
let empty_override = settings_dir_with(None, |key| match key {
|
||||
"WORDCRAFT_PROFILE_DIR" => Some("".into()),
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(empty_override, Some(default_dir));
|
||||
}
|
||||
}
|
||||
|
||||
+52
-3
@@ -230,10 +230,26 @@ impl ChartAxis {
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters.
|
||||
/// characters. A trailing space stays when it is part of the code: the character after `_`,
|
||||
/// `*` or `\`, or text inside quotes.
|
||||
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()
|
||||
let chars: Vec<char> = s.chars().take(MAX_FMT * 4).skip_while(|c| c.is_whitespace() || c.is_control()).take(MAX_FMT).collect();
|
||||
let mut keep = 0;
|
||||
let mut quoted = false;
|
||||
let mut operand = false;
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if !c.is_control() && (!c.is_whitespace() || operand || quoted) {
|
||||
keep = i + 1;
|
||||
}
|
||||
if operand {
|
||||
operand = false;
|
||||
} else if c == '"' {
|
||||
quoted = !quoted;
|
||||
} else if !quoted && matches!(c, '_' | '*' | '\\') {
|
||||
operand = true;
|
||||
}
|
||||
}
|
||||
chars[..keep].iter().map(|&c| if c.is_control() { ' ' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// A chart WordCraft can edit.
|
||||
@@ -512,4 +528,37 @@ mod tests {
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_keeps_a_trailing_space_that_is_an_operand() {
|
||||
// `_`, `*` and `\` take the next character, so a final space after one is part of the code.
|
||||
assert_eq!(clean_fmt("0_ "), "0_ ");
|
||||
assert_eq!(clean_fmt("#,##0_ "), "#,##0_ ");
|
||||
assert_eq!(clean_fmt("0* "), "0* ");
|
||||
assert_eq!(clean_fmt("0\\ "), "0\\ ");
|
||||
assert_eq!(clean_fmt("0_ \n "), "0_ ");
|
||||
assert_eq!(clean_fmt("0\"a "), "0\"a ", "a space inside quotes is text");
|
||||
// Other spaces at the ends, and control characters, still go.
|
||||
assert_eq!(clean_fmt(" 0.00 \t"), "0.00");
|
||||
assert_eq!(clean_fmt("0_\n"), "0_");
|
||||
assert_eq!(clean_fmt("0\"a\" "), "0\"a\"");
|
||||
assert_eq!(clean_fmt("\\_ "), "\\_", "an escaped `_` takes no operand");
|
||||
assert_eq!(clean_fmt("0\u{1}0"), "0 0");
|
||||
assert_eq!(clean_fmt("_\u{1}"), "_");
|
||||
assert_eq!(clean_fmt(" \n "), "");
|
||||
let long = format!("{}_ ", "0".repeat(MAX_FMT - 2));
|
||||
assert_eq!(clean_fmt(&long), long, "a code of exactly MAX_FMT characters keeps its operand");
|
||||
|
||||
// Axis and series formats both go through the cleaner.
|
||||
let mut a = ChartAxis { fmt: Some("0_ ".into()), ..Default::default() };
|
||||
a.sanitize();
|
||||
assert_eq!(a.fmt.as_deref(), Some("0_ "));
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], fmt: Some("#,##0_ ".into()), ..Default::default() }],
|
||||
categories: vec!["a".into()],
|
||||
..Default::default()
|
||||
};
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].fmt.as_deref(), Some("#,##0_ "));
|
||||
}
|
||||
}
|
||||
|
||||
+17
-1
@@ -619,7 +619,8 @@ impl Paragraph {
|
||||
/// The word around `off` (double-click): (start, end) without trailing space.
|
||||
pub fn word_at(&self, off: usize) -> (usize, usize) {
|
||||
let off = self.clamp(off);
|
||||
let is_w = |c: char| crate::bidi::is_word_char(c);
|
||||
// Word's word unit takes a typographic apostrophe (’) like `'`, at either end too (#6517).
|
||||
let is_w = |c: char| crate::bidi::is_word_char(c) || c == '’';
|
||||
let mut a = off;
|
||||
for (i, c) in self.text.get(..off).unwrap_or("").char_indices().rev() {
|
||||
if !is_w(c) {
|
||||
@@ -852,6 +853,21 @@ mod tests {
|
||||
assert_eq!(p.prev_boundary(0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_at_takes_a_typographic_apostrophe_like_a_straight_one() {
|
||||
// Byte offsets: `’` is three bytes. Word: `don’t ` (#6517).
|
||||
let p = Paragraph::with_text("don’t stop", CharProps::default());
|
||||
assert_eq!(p.word_at(1), (0, 8));
|
||||
assert_eq!(p.word_at(2), (0, 8));
|
||||
let p = Paragraph::with_text("the dogs’ bone", CharProps::default());
|
||||
assert_eq!(p.word_at(5), (4, 12));
|
||||
let p = Paragraph::with_text("’tis here", CharProps::default());
|
||||
assert_eq!(p.word_at(3), (0, 7));
|
||||
assert_eq!(p.word_at(4), (0, 7));
|
||||
let p = Paragraph::with_text("well-known", CharProps::default());
|
||||
assert_eq!(p.word_at(1), (0, 4));
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn edits_keep_runs_consistent(ops in proptest::collection::vec((0u8..4, 0usize..40, 0usize..40, "[a-zé ]{0,5}"), 0..40)) {
|
||||
|
||||
@@ -177,6 +177,19 @@ fn glossary_value_from_shared(
|
||||
})
|
||||
}
|
||||
|
||||
fn note_separators_from_shared(
|
||||
source: craft_wordmodel::NoteSeparators,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::NoteSeparators, DocxError> {
|
||||
let craft_wordmodel::NoteSeparators { separator, continuation_separator, continuation_notice } = source;
|
||||
let mut blocks = |b: Option<craft_wordmodel::Blocks>| b.map(|b| blocks_from_shared(b, graphics)).transpose();
|
||||
Ok(wordcraft_doc::NoteSeparators {
|
||||
separator: blocks(separator)?,
|
||||
continuation_separator: blocks(continuation_separator)?,
|
||||
continuation_notice: blocks(continuation_notice)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn missing_pictures_from_shared(source: craft_wordmodel::MissingPictures) -> Result<wordcraft_doc::MissingPictures, DocxError> {
|
||||
let mut target = wordcraft_doc::MissingPictures::default();
|
||||
target.truncated = source.truncated;
|
||||
@@ -239,8 +252,8 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
document.core = convert(core)?;
|
||||
document.sources = convert(sources)?;
|
||||
document.custom_props = convert(custom_props)?;
|
||||
document.footnote_separators = convert(footnote_separators)?;
|
||||
document.endnote_separators = convert(endnote_separators)?;
|
||||
document.footnote_separators = note_separators_from_shared(footnote_separators, &mut graphics)?;
|
||||
document.endnote_separators = note_separators_from_shared(endnote_separators, &mut graphics)?;
|
||||
document.media = media;
|
||||
document.passthrough = passthrough;
|
||||
document.glossary = glossary.into_iter().map(|g| glossary_value_from_shared(g, &mut graphics)).collect::<Result<_, _>>()?;
|
||||
|
||||
@@ -2444,6 +2444,36 @@ fn note_separators_and_continuation_notice_round_trip() {
|
||||
check(&wordcraft_docx::read(&out).unwrap());
|
||||
}
|
||||
|
||||
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
|
||||
/// in the body, instead of failing the whole document. (The test name dates from when the body
|
||||
/// opened this shape as a rectangle.)
|
||||
#[test]
|
||||
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
|
||||
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
|
||||
let notes = |root: &str, item: &str| {
|
||||
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
|
||||
};
|
||||
let footnotes = notes("footnotes", "footnote");
|
||||
let endnotes = notes("endnotes", "endnote");
|
||||
let bytes = docx(
|
||||
&format!("<w:p>{frame}</w:p>"),
|
||||
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
|
||||
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
|
||||
);
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
|
||||
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
|
||||
};
|
||||
let in_body = shapes(d.body[0].as_para().unwrap());
|
||||
assert_eq!(in_body.len(), 1, "{in_body:?}");
|
||||
assert_eq!(in_body[0].1, 40.0);
|
||||
assert_eq!(in_body[0].0, ShapeKind::Frame);
|
||||
for separators in [&d.footnote_separators, &d.endnote_separators] {
|
||||
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
|
||||
assert_eq!(shapes(sep), in_body);
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #534: East Asian number formats are read, labelled and written back as they were; a
|
||||
/// value the format doesn't define is decimal, and a level without `w:ind` has no indent.
|
||||
#[test]
|
||||
|
||||
@@ -362,10 +362,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
|
||||
if !copied {
|
||||
return Err(CmdError::Failed("the member vanished".into()));
|
||||
}
|
||||
s.clipboard_text = f.clipboard_text();
|
||||
s.clip_history.push(&f, &s.clipboard_text);
|
||||
s.clipboard = Some(f);
|
||||
Ok(super::edit::copy_result(s))
|
||||
let text = f.clipboard_text();
|
||||
let r = super::edit::copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
|
||||
|
||||
@@ -300,7 +300,11 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
|
||||
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
|
||||
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
|
||||
let to = if np == c.page {
|
||||
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
s.page_hint = np;
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
|
||||
@@ -244,10 +244,10 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
rows.push(row_text(s, &a, &b));
|
||||
blocks.push(Block::Para(para));
|
||||
}
|
||||
s.clipboard_text = rows.join("\n");
|
||||
let text = rows.join("\n");
|
||||
let media = s.doc.media_of_blocks(&blocks);
|
||||
s.clipboard = Some(Fragment { blocks, parts, media });
|
||||
Ok(super::edit::copy_result(s))
|
||||
let f = Fragment { blocks, parts, media };
|
||||
super::edit::copy_result(s, &f, &text)
|
||||
}
|
||||
|
||||
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
|
||||
|
||||
@@ -279,6 +279,22 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
|
||||
content_props(&s.doc, &props)
|
||||
}
|
||||
|
||||
/// The formatting of what replaces a control's content: typed text, a list entry, a date or a
|
||||
/// check box's mark. In place of the placeholder, that is the control's own run properties
|
||||
/// (ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style: the
|
||||
/// showing placeholder's own character style is that style, whatever a producer called it (Word
|
||||
/// localizes only the id; another program may localize the name too). In place of a value, it is
|
||||
/// that value's formatting.
|
||||
fn replacement_props(s: &Session, r: &ControlRange) -> CharProps {
|
||||
if !r.control.showing_placeholder {
|
||||
return content_base(s, r);
|
||||
}
|
||||
match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, r) },
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Rules for typing and deleting
|
||||
|
||||
@@ -327,14 +343,8 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
|
||||
if !r.control.showing_placeholder || !r.contains(&b) {
|
||||
return Ok(None);
|
||||
}
|
||||
// Text typed in place of the placeholder takes the control's own run properties (Word, and
|
||||
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
|
||||
// showing placeholder's own character style is that style, whatever a producer called it
|
||||
// (Word localizes only the id; another program may localize the name too).
|
||||
let props = match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, &r) },
|
||||
};
|
||||
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
|
||||
let props = replacement_props(s, &r);
|
||||
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
c.showing_placeholder = false;
|
||||
@@ -666,7 +676,7 @@ fn toggle_check_box(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let now = p::bool(v, "value").unwrap_or(!checked);
|
||||
let (ch, font) = if now { (*checked_char, checked_font) } else { (*unchecked_char, unchecked_font) };
|
||||
let mut props = content_base(s, &r);
|
||||
let mut props = replacement_props(s, &r);
|
||||
if !font.is_empty() {
|
||||
props.font = Some(font.clone());
|
||||
}
|
||||
@@ -696,7 +706,7 @@ fn choose_item(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Err(CmdError::Params("give index, value or text".into()));
|
||||
};
|
||||
let Some(item) = item.cloned() else { return Err(CmdError::Params("no such entry".into())) };
|
||||
let props = content_base(s, &r);
|
||||
let props = replacement_props(s, &r);
|
||||
let end = set_content(s, &r, &item.display, &props)?;
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
if let ControlKind::ComboBox { last_value, .. } | ControlKind::DropDown { last_value, .. } = &mut c.kind {
|
||||
@@ -716,7 +726,7 @@ fn set_date(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let (y, m, d) = p::str(v, "date").and_then(parse_date).ok_or_else(|| CmdError::Params("date: YYYY-MM-DD".into()))?;
|
||||
let text = format_date_value(format, y, m, d);
|
||||
let props = content_base(s, &r);
|
||||
let props = replacement_props(s, &r);
|
||||
let end = set_content(s, &r, &text, &props)?;
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
if let ControlKind::Date { full_date, .. } = &mut c.kind {
|
||||
|
||||
@@ -208,29 +208,28 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
None if a == b => return Ok(json!({"text": ""})),
|
||||
None => s.doc.copy_range(&a, &b),
|
||||
};
|
||||
s.clipboard_text = f.clipboard_text();
|
||||
s.clip_history.push(&f, &s.clipboard_text);
|
||||
s.clipboard = Some(f);
|
||||
Ok(copy_result(s))
|
||||
let text = f.clipboard_text();
|
||||
let r = copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
|
||||
/// #816) and as RTF for the host to put on the system clipboard too, so other programs keep the
|
||||
/// formatting; and for a copy of one equation alone, its MathML (#1297).
|
||||
pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
|
||||
Some(f) => {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
(wordcraft_formats::html::export_fragment(&d), wordcraft_formats::rtf::export(&d))
|
||||
}
|
||||
None => (String::new(), String::new()),
|
||||
};
|
||||
let mut r = json!({"text": s.clipboard_text});
|
||||
for (k, v) in [("html", &s.clipboard_html), ("rtf", &s.clipboard_rtf)] {
|
||||
///
|
||||
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
|
||||
/// is refused, and the clipboard keeps what it held.
|
||||
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
let html = wordcraft_formats::html::export_fragment(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as HTML: {e}")))?;
|
||||
let rtf = wordcraft_formats::rtf::export(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as RTF: {e}")))?;
|
||||
let mut r = json!({"text": text});
|
||||
for (k, v) in [("html", &html), ("rtf", &rtf)] {
|
||||
if !v.is_empty() {
|
||||
r[k] = json!(v);
|
||||
}
|
||||
@@ -239,10 +238,16 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
|
||||
// before anything else when it pastes; a copy with text around the equation doesn't offer
|
||||
// them, so pasting it keeps the text.
|
||||
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
|
||||
if let Some((linear, display)) = f.sole_equation() {
|
||||
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
|
||||
}
|
||||
r
|
||||
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
|
||||
// all at once.
|
||||
s.clipboard_text = text.to_string();
|
||||
s.clipboard = Some(f.clone());
|
||||
s.clipboard_html = html;
|
||||
s.clipboard_rtf = rtf;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
|
||||
|
||||
@@ -703,3 +703,24 @@ fn a_math_name_is_corrected_by_any_character_that_cannot_continue_it() {
|
||||
s.run("equation.type", &json!({"text": r"\alpha+"})).unwrap();
|
||||
assert_eq!(linear(&s), r"\alpha+");
|
||||
}
|
||||
|
||||
/// Paste Formatting keeps an open equation open (matching other formatting commands and
|
||||
/// `cmd::column`), whereas content-pasting commands leave the equation first.
|
||||
#[test]
|
||||
fn paste_formatting_keeps_an_open_equation_open() {
|
||||
let mut s = session();
|
||||
s.run("text.insert", &json!({"text": "source "})).unwrap();
|
||||
s.run("select.text", &json!({"text": "source"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.run("edit.copyFormat", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "x"})).unwrap();
|
||||
let before = s.math.clone();
|
||||
assert!(before.is_some());
|
||||
|
||||
s.run("edit.pasteFormat", &json!({})).unwrap();
|
||||
assert_eq!(s.math, before, "edit.pasteFormat keeps the open equation open");
|
||||
|
||||
s.run("edit.pasteText", &json!({"text": "y"})).unwrap();
|
||||
assert!(s.math.is_none(), "edit.pasteText closes the open equation");
|
||||
}
|
||||
|
||||
@@ -94,9 +94,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.save", "Save", "File", save)
|
||||
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
|
||||
.params(r#"{"path"?: string, "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport)}"#)
|
||||
.params(r#"{"path"?: string (required with `copy`), "password"?: string (encrypt this and later saves with it, as file.encrypt does), "markup"?: bool (Print Markup for a PDF, PNG, HTML, Markdown or text copy: comments shown; default file.printMarkup), "format"?: "wordml2003" (an .xml file as a Word 2003 XML Document) | "flatopc" (as a Word XML Document, the default; saving over a Word 2003 XML file keeps that format), "strict"?: bool (a .pdf or .png only: refuse, writing nothing, if a character can't be drawn or a picture is missing; see file.strictReport), "copy"?: bool (write a copy at `path`, as File › Export does: the document keeps its own file, unsaved changes and save stamps; not with `password`)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save)}"#).pure(),
|
||||
CommandSpec::new("file.saveAs", "Save As", "File", save_as).key(super::mac_or("F12 / Mod+Shift+S", "F12 / Alt+F2")).params(r#"{"path": string, "password"?: string, "markup"?: bool, "format"?: string (as file.save), "strict"?: bool (as file.save), "copy"?: bool (as file.save)}"#).pure(),
|
||||
// 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)
|
||||
@@ -342,6 +342,8 @@ pub(crate) fn new_from_template(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let path = p::req_str(v, "path")?;
|
||||
let (mut doc, _) = read_document(s, path, v)?;
|
||||
doc.settings.attached_template = Some(path.to_string());
|
||||
// A new document: not created when the template was. Saving stamps its creation date.
|
||||
doc.core.created.clear();
|
||||
if p::bool(v, "replaceBlank") == Some(true) && s.used_because().is_none() {
|
||||
s.set_document(doc);
|
||||
} else {
|
||||
@@ -393,6 +395,14 @@ fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Executes `file.save`: writes the document or text to disk, preserving exact file text for
|
||||
/// unedited Markdown files, and updating session path and dirty state.
|
||||
fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// A copy (File › Export, #6131) is written and nothing else: the document keeps its own file,
|
||||
// its unsaved changes and its save stamps, so the next Save still goes to the original.
|
||||
// It never falls back to the document's own file or opens the Save As picker (whose answer is
|
||||
// an ordinary save that adopts the file).
|
||||
let as_copy = p::bool(v, "copy") == Some(true);
|
||||
if as_copy && p::str(v, "path").is_none() {
|
||||
return Err(CmdError::Params("`copy` needs a `path`: the copy has to go somewhere".into()));
|
||||
}
|
||||
let path = match p::str(v, "path").map(std::path::PathBuf::from).or_else(|| s.path.clone()) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
@@ -401,6 +411,9 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
};
|
||||
check_strict_output(p::bool(v, "strict").unwrap_or(false), &path.to_string_lossy())?;
|
||||
if as_copy && v.get("password").is_some_and(|pw| !pw.is_null()) {
|
||||
return Err(CmdError::Params("`password` changes the document's own saves, so it can't come with `copy` (use file.encrypt)".into()));
|
||||
}
|
||||
if let Some(pw) = v.get("password").filter(|pw| !pw.is_null()) {
|
||||
let Some(pw) = pw.as_str().filter(|pw| !pw.is_empty()) else {
|
||||
return Err(CmdError::Params("`password` must be a non-empty string (file.encrypt removes a password)".into()));
|
||||
@@ -443,11 +456,14 @@ fn save(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some(text) => crate::io::save_text_path(&path, text),
|
||||
None => crate::io::save_path_with(&path, copy.as_ref().unwrap_or(&s.doc), password, &opts),
|
||||
};
|
||||
if let Err(e) = written {
|
||||
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
|
||||
return Err(CmdError::Failed(e));
|
||||
}
|
||||
let encrypted = password.is_some() && crate::io::can_encrypt(&path.to_string_lossy());
|
||||
if written.is_err() || as_copy {
|
||||
(s.doc.settings.zoom, s.doc.core.last_modified_by, s.doc.core.created, s.doc.core.modified, s.doc.core.revision) = before_stamp;
|
||||
}
|
||||
written.map_err(CmdError::Failed)?;
|
||||
if as_copy {
|
||||
return Ok(json!({"saved": true, "path": path.to_string_lossy(), "encrypted": encrypted, "copy": true}));
|
||||
}
|
||||
// A save in a format that doesn't keep everything (plain text, Markdown, a page image) is a
|
||||
// copy, except over the document's own file: a note.txt opened and saved is saved (#2376).
|
||||
// A Markdown file saved as another one loses nothing its own save wouldn't: it moves there.
|
||||
|
||||
@@ -209,7 +209,8 @@ fn target(s: &Session) -> Option<(Pos, Pos)> {
|
||||
return Some((a, b));
|
||||
}
|
||||
let p = s.doc.para_at(&a)?;
|
||||
let is_w = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
|
||||
// Word takes a typographic apostrophe (’) like `'` here (#6517).
|
||||
let is_w = |c: char| c.is_alphanumeric() || matches!(c, '\'' | '’' | '_');
|
||||
let before = p.text.get(..a.off)?.chars().next_back();
|
||||
let after = p.text.get(a.off..)?.chars().next();
|
||||
if before.is_some_and(is_w) && after.is_some_and(is_w) {
|
||||
@@ -351,6 +352,16 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
|
||||
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
|
||||
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
|
||||
let chars = resolved(s);
|
||||
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
|
||||
return !chars.first().is_some_and(has);
|
||||
}
|
||||
!chars.iter().all(has)
|
||||
}
|
||||
|
||||
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
|
||||
/// complex-script bold.
|
||||
fn shown_bold(r: &ResolvedChar) -> bool {
|
||||
@@ -366,7 +377,7 @@ fn shown_italic(r: &ResolvedChar) -> bool {
|
||||
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
|
||||
let on = match p::bool(v, "value") {
|
||||
Some(b) => b,
|
||||
None => !resolved(s).iter().all(get),
|
||||
None => turns_on(s, get),
|
||||
};
|
||||
apply(s, &|c| set(c, on))
|
||||
}
|
||||
@@ -376,7 +387,7 @@ fn underline(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let on = match (p::bool(v, "value"), style) {
|
||||
(Some(b), _) => b,
|
||||
(None, Some(_)) => true,
|
||||
(None, None) => !resolved(s).iter().all(|r| r.underline != Underline::None),
|
||||
(None, None) => turns_on(s, |r| r.underline != Underline::None),
|
||||
};
|
||||
let u = if on { style.unwrap_or(Underline::Single) } else { Underline::None };
|
||||
apply(s, &|c| c.underline = Some(u))
|
||||
|
||||
@@ -188,10 +188,14 @@ fn range_index_after_text(s: &Session) -> bool {
|
||||
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let instr = index_instr(v);
|
||||
check_index_reachable(s)?;
|
||||
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
|
||||
// second one beside it (#8034).
|
||||
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
|
||||
// Update Index makes it, so it takes the new settings rather than a second index being added
|
||||
// beside it (#8034).
|
||||
if index_field(s).is_none() && has_index(s, true) {
|
||||
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
|
||||
super::citations::update_generated(s)?;
|
||||
if index_field(s).is_none() {
|
||||
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
|
||||
}
|
||||
}
|
||||
match index_field(s) {
|
||||
Some((i, _)) => {
|
||||
@@ -640,10 +644,10 @@ End.",
|
||||
assert!(!body_has_index(&s));
|
||||
}
|
||||
|
||||
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
|
||||
/// Index says so instead of adding a second one (#8034).
|
||||
/// An index Word wrote as a range field in the main text takes Insert Index's settings and is
|
||||
/// rebuilt, rather than a second index being added at the caret (#8034).
|
||||
#[test]
|
||||
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
|
||||
fn insert_index_gives_a_range_field_index_in_the_main_text_its_settings() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
@@ -654,10 +658,23 @@ End.",
|
||||
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
|
||||
let before = s.doc.body.len();
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
assert_eq!(s.doc.body.len(), before, "no second index was added");
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"columns": 2})).unwrap();
|
||||
let instrs: Vec<String> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX" => {
|
||||
Some(instr.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(instrs.len(), 1, "one index, not a second beside it: {instrs:?}");
|
||||
assert!(FieldCode::parse(&instrs[0]).arg('c').is_some(), "the index took the new columns setting: {instrs:?}");
|
||||
let text: String =
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
|
||||
"
|
||||
|
||||
@@ -21,7 +21,7 @@ pub use items::{
|
||||
};
|
||||
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
|
||||
use links::{bookmark, delete_bookmark, link, link_targets};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span, selection_is_one_line};
|
||||
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
|
||||
use objects::{icon, shape, table, text_box};
|
||||
pub(crate) use objects::{image_ext, picture};
|
||||
|
||||
@@ -205,21 +205,26 @@ pub fn format_date_at_in(fmt: &str, lang: Option<&str>, unix: u64, offset_secs:
|
||||
format_date_parts_in(fmt, lang, y, m as usize, d, hms, days)
|
||||
}
|
||||
|
||||
/// Month and weekday names of a language, as Word writes them in date fields: full names, the
|
||||
/// three-letter forms (`MMM`, `ddd`) being their first three letters, without a full stop.
|
||||
/// Weekdays start on Thursday (1970-01-01).
|
||||
/// Month and weekday names of a language, as Word writes them in date fields: full names and the
|
||||
/// abbreviations used by `MMM` and `ddd`. Weekdays start on Thursday (1970-01-01).
|
||||
struct DateNames {
|
||||
/// Full month names (January through December).
|
||||
months: [&'static str; 12],
|
||||
/// Abbreviated month names for `MMM` (January through December).
|
||||
months_short: [&'static str; 12],
|
||||
/// Weekday names starting on Thursday (1970-01-01).
|
||||
days: [&'static str; 7],
|
||||
/// Abbreviated weekday names for `ddd`, starting on Thursday (1970-01-01).
|
||||
days_short: [&'static str; 7],
|
||||
/// The picture of a `DATE` field without `\@`.
|
||||
default: &'static str,
|
||||
}
|
||||
|
||||
const ENGLISH: DateNames = DateNames {
|
||||
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
|
||||
months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
|
||||
days: ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"],
|
||||
days_short: ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"],
|
||||
default: "M/d/yyyy",
|
||||
};
|
||||
|
||||
@@ -227,14 +232,46 @@ const ENGLISH: DateNames = DateNames {
|
||||
/// `ddd` = `qui`, and `dd/MM/yyyy` for a field without a picture.
|
||||
const PORTUGUESE: DateNames = DateNames {
|
||||
months: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
|
||||
months_short: ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
|
||||
days: ["quinta-feira", "sexta-feira", "sábado", "domingo", "segunda-feira", "terça-feira", "quarta-feira"],
|
||||
days_short: ["qui", "sex", "sáb", "dom", "seg", "ter", "qua"],
|
||||
default: "dd/MM/yyyy",
|
||||
};
|
||||
|
||||
/// Choose month and weekday names according to the primary language subtag.
|
||||
/// German (Word's Windows NLS forms): `MMMM` = `März`, `MMM` = `Mrz`, `ddd` = `Fr` (two
|
||||
/// letters), and `dd.MM.yyyy` for a field without a picture. Covers de-DE, de-CH and bare `de`.
|
||||
const GERMAN: DateNames = DateNames {
|
||||
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||||
months_short: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
|
||||
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
|
||||
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
|
||||
default: "dd.MM.yyyy",
|
||||
};
|
||||
|
||||
/// Austrian Standard German: January is `Jänner`, abbreviated `Jän` (Österreichisches
|
||||
/// Wörterbuch; Windows NLS `de-AT`). Every other month and weekday matches [`GERMAN`].
|
||||
const GERMAN_AUSTRIA: DateNames = DateNames {
|
||||
months: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||||
months_short: ["Jän", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
|
||||
days: ["Donnerstag", "Freitag", "Samstag", "Sonntag", "Montag", "Dienstag", "Mittwoch"],
|
||||
days_short: ["Do", "Fr", "Sa", "So", "Mo", "Di", "Mi"],
|
||||
default: "dd.MM.yyyy",
|
||||
};
|
||||
|
||||
/// Choose month and weekday names from the language tag: the primary subtag picks the language,
|
||||
/// and a region subtag refines it (`de-AT` writes `Jänner`). Tags compare case-insensitively, as
|
||||
/// `w:lang` values do.
|
||||
fn date_names(lang: Option<&str>) -> &'static DateNames {
|
||||
let primary = lang.and_then(|l| l.trim().split(['-', '_']).next()).unwrap_or("");
|
||||
if primary.eq_ignore_ascii_case("pt") { &PORTUGUESE } else { &ENGLISH }
|
||||
let mut subtags = lang.unwrap_or("").trim().split(['-', '_']);
|
||||
let primary = subtags.next().unwrap_or("");
|
||||
if primary.eq_ignore_ascii_case("pt") {
|
||||
&PORTUGUESE
|
||||
} else if primary.eq_ignore_ascii_case("de") {
|
||||
// Austria keeps `Jänner` / `Jän`; Germany and Switzerland keep `Januar` / `Jan`.
|
||||
if subtags.any(|region| region.eq_ignore_ascii_case("AT")) { &GERMAN_AUSTRIA } else { &GERMAN }
|
||||
} else {
|
||||
&ENGLISH
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture Word gives a `DATE` field that has no `\@` switch, in the field's language.
|
||||
@@ -252,9 +289,12 @@ pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u3
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d: u32, (hh, mm, ss): (u32, u32, u32), days_since: i64) -> String {
|
||||
let names = date_names(lang);
|
||||
let month = names.months.get(m.saturating_sub(1)).copied().unwrap_or(names.months[0]);
|
||||
let day = names.days.get(days_since.rem_euclid(7) as usize).copied().unwrap_or(names.days[0]);
|
||||
let three = |s: &str| -> String { s.chars().take(3).collect() };
|
||||
let mi = m.saturating_sub(1);
|
||||
let di = days_since.rem_euclid(7) as usize;
|
||||
let month = names.months.get(mi).copied().unwrap_or(names.months[0]);
|
||||
let month_short = names.months_short.get(mi).copied().unwrap_or(names.months_short[0]);
|
||||
let day = names.days.get(di).copied().unwrap_or(names.days[0]);
|
||||
let day_short = names.days_short.get(di).copied().unwrap_or(names.days_short[0]);
|
||||
let mut out = String::new();
|
||||
let chars: Vec<char> = fmt.chars().collect();
|
||||
let mut i = 0;
|
||||
@@ -296,11 +336,11 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
|
||||
('y' | 'Y', 4..) => out.push_str(&format!("{y:04}")),
|
||||
('y' | 'Y', _) => out.push_str(&format!("{:02}", y % 100)),
|
||||
('M', 4..) => out.push_str(month),
|
||||
('M', 3) => out.push_str(&three(month)),
|
||||
('M', 3) => out.push_str(month_short),
|
||||
('M', 2) => out.push_str(&format!("{m:02}")),
|
||||
('M', 1) => out.push_str(&m.to_string()),
|
||||
('d' | 'D', 4..) => out.push_str(day),
|
||||
('d' | 'D', 3) => out.push_str(&three(day)),
|
||||
('d' | 'D', 3) => out.push_str(day_short),
|
||||
('d' | 'D', 2) => out.push_str(&format!("{d:02}")),
|
||||
('d' | 'D', 1) => out.push_str(&d.to_string()),
|
||||
('H', 2..) => out.push_str(&format!("{hh:02}")),
|
||||
@@ -574,6 +614,43 @@ mod date_time_locale_tests {
|
||||
assert_eq!(format("MMMM", 20), "outubro");
|
||||
}
|
||||
|
||||
/// German month and weekday names, and the default picture, are chosen by the language tag
|
||||
/// (de-DE, de-AT, de-CH), as in Word (#7146).
|
||||
#[test]
|
||||
fn german_date_names_render_for_de() {
|
||||
assert_eq!(format_date_parts_in("dddd, d. MMMM yyyy", Some("de-DE"), 2026, 11, 21, (12, 0, 0), 2), "Samstag, 21. November 2026");
|
||||
assert_eq!(default_date_picture(Some("de-CH")), "dd.MM.yyyy");
|
||||
}
|
||||
|
||||
/// Windows NLS short forms: two-letter weekdays (`Mo`, `Di`…) and `Mrz` for March, with no
|
||||
/// trailing full stop (#7146).
|
||||
#[test]
|
||||
fn german_short_names_match_windows_nls() {
|
||||
let format = |pic| format_date_parts_in(pic, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3);
|
||||
assert_eq!(format("ddd, d. MMM yyyy"), "So, 15. Mrz 2026");
|
||||
assert_eq!(format("dddd"), "Sonntag");
|
||||
assert_eq!(format("MMM"), "Mrz");
|
||||
}
|
||||
|
||||
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland
|
||||
/// and bare `de` keep `Januar` (`Jan`); every other name is shared (#7146).
|
||||
#[test]
|
||||
fn austrian_german_january_is_jaenner() {
|
||||
let january = |lang, pic| format_date_parts_in(pic, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
|
||||
assert_eq!(january("de-AT", "MMMM"), "Jänner");
|
||||
assert_eq!(january("de-AT", "MMM"), "Jän");
|
||||
assert_eq!(january("de_at", "MMMM"), "Jänner", "region subtags compare case-insensitively");
|
||||
for lang in ["de-DE", "de-CH", "de"] {
|
||||
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
|
||||
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
|
||||
}
|
||||
// Only January differs: February and March read the same in Austria and Germany.
|
||||
for month in [2, 3] {
|
||||
let names = |lang| format_date_parts_in("MMMM MMM", Some(lang), 2026, month, 1, (12, 0, 0), 0);
|
||||
assert_eq!(names("de-AT"), names("de-DE"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pt-BR dynamic field keeps its result after DOCX round-trip and refresh.
|
||||
#[test]
|
||||
fn pt_br_date_time_dialog_inserts_dynamic_field() {
|
||||
|
||||
@@ -84,25 +84,45 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// The `text` to retype a selection with before linking it: only when it differs from the selected
|
||||
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
|
||||
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
|
||||
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
|
||||
/// What can't stand in one line of text: breaks, and pictures or fields.
|
||||
const NOT_ONE_LINE: [char; 7] = {
|
||||
use wordcraft_doc::para::{COLUMN_BREAK, LINE_BREAK, OBJ, PAGE_BREAK};
|
||||
/// What can't stand in one line of text: breaks, and pictures or fields.
|
||||
const NOT_ONE_LINE: [char; 7] = [LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ];
|
||||
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
|
||||
if text.contains(NOT_ONE_LINE) {
|
||||
[LINE_BREAK, '\r', '\u{2029}', '\u{b}', PAGE_BREAK, COLUMN_BREAK, OBJ]
|
||||
};
|
||||
|
||||
/// The raw text of the selection when it is one run of one paragraph without breaks, pictures or fields.
|
||||
fn one_line_selection(s: &Session) -> Option<&str> {
|
||||
// A column (block) selection has both ends in one paragraph but holds a piece of each line it
|
||||
// covers: it isn't one line of text (#8581).
|
||||
if s.column_segments().is_some_and(|segs| !segs.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a.story != b.story || a.path != b.path {
|
||||
return None;
|
||||
}
|
||||
let shown = s.doc.para(a.story, &a.path)?.text.get(a.off..b.off)?;
|
||||
if shown.contains(NOT_ONE_LINE) || shown == text {
|
||||
s.doc.para(a.story, &a.path)?.text.get(a.off..b.off).filter(|t| !t.contains(NOT_ONE_LINE))
|
||||
}
|
||||
|
||||
/// Whether the selection is plain text in one line of one paragraph: otherwise (as Word shows
|
||||
/// `<<Selection in Document>>`) Text to display can't show it and linking keeps its content (#8286).
|
||||
pub fn selection_is_one_line(s: &Session) -> bool {
|
||||
one_line_selection(s).is_some()
|
||||
}
|
||||
|
||||
/// The `text` to retype a selection with before linking it: only when it differs from the selected
|
||||
/// text and both fit in one line of one paragraph without pictures or fields, outside any field's
|
||||
/// result. Otherwise (as Word shows `<<Selection in Document>>`) the selection keeps its text.
|
||||
fn retyped_text(s: &Session, v: &Value) -> Option<String> {
|
||||
let text = p::str(v, "text").filter(|t| !t.is_empty() && t.len() <= 4096)?;
|
||||
if text.contains(NOT_ONE_LINE) {
|
||||
return None;
|
||||
}
|
||||
let shown = one_line_selection(s)?;
|
||||
if shown == text {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
// A selection in a field's result (between its markers, which it doesn't hold) is retyped by
|
||||
// the next update of the field, not here.
|
||||
if s.doc.field_ranges(a.story).iter().any(|r| r.start < b && a <= r.end) {
|
||||
|
||||
@@ -103,7 +103,7 @@ fn exact_text(s: &Session) -> Option<String> {
|
||||
return res.clone();
|
||||
}
|
||||
let kept = [s.md_file.latest.as_deref(), s.md_file.saved.as_deref()];
|
||||
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).same_content(&s.doc)).map(str::to_string);
|
||||
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).is_ok_and(|d| d.same_content(&s.doc))).map(str::to_string);
|
||||
*s.md_file.cached_exact.borrow_mut() = Some((s.rev(), res.clone()));
|
||||
res
|
||||
}
|
||||
@@ -216,15 +216,16 @@ fn enter(s: &mut Session) -> Result<(), CmdError> {
|
||||
// The file's own text when it still says what the document holds, so nothing is lost.
|
||||
let (text, loses_content, block_lines) = match exact_text(s) {
|
||||
Some(text) => {
|
||||
let (_, lines) = parse_with_lines(&s.doc, &text);
|
||||
let (_, lines) = parse_with_lines(&s.doc, &text)?;
|
||||
(text, false, lines)
|
||||
}
|
||||
None => {
|
||||
let text = wordcraft_formats::markdown::export(&s.doc);
|
||||
let text = wordcraft_formats::markdown::export(&s.doc)
|
||||
.map_err(|e| CmdError::Failed(format!("the document cannot be written as Markdown: {e}")))?;
|
||||
if text.len() > MAX_SOURCE_BYTES {
|
||||
return Err(CmdError::Failed(too_long()));
|
||||
}
|
||||
let (doc, lines) = parse_with_lines(&s.doc, &text);
|
||||
let (doc, lines) = parse_with_lines(&s.doc, &text)?;
|
||||
let loses_content = !doc.same_content(&s.doc);
|
||||
(text, loses_content, lines)
|
||||
}
|
||||
@@ -289,7 +290,19 @@ pub fn apply(s: &mut Session) {
|
||||
}
|
||||
(src.text.clone(), src.entry_text.clone(), src.entry_doc.clone(), src.has_step, src.entry_lines.clone())
|
||||
};
|
||||
let (doc, lines) = if text == *entry_text { ((*entry_doc).clone(), entry_lines) } else { parse_with_lines(&s.doc, &text) };
|
||||
let (doc, lines) = if text == *entry_text {
|
||||
((*entry_doc).clone(), entry_lines)
|
||||
} else {
|
||||
// The text cannot be read as Markdown: the document stays as it is, rather than
|
||||
// becoming an empty one.
|
||||
match parse_with_lines(&s.doc, &text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
s.status = e.to_string();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
let step = if !has_step {
|
||||
s.checkpoint(LABEL);
|
||||
Some(s.undo_mark())
|
||||
@@ -313,19 +326,20 @@ pub fn apply(s: &mut Session) {
|
||||
|
||||
/// `text` as a document and block lines, with what isn't in Markdown from `current`: its page, settings,
|
||||
/// properties and language, as opening the file gave it.
|
||||
fn parse_with_lines(current: &Document, text: &str) -> (Document, Vec<usize>) {
|
||||
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, ¤t.last_section);
|
||||
fn parse_with_lines(current: &Document, text: &str) -> Result<(Document, Vec<usize>), CmdError> {
|
||||
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, ¤t.last_section)
|
||||
.map_err(|e| CmdError::Failed(format!("the Markdown cannot be read: {e}")))?;
|
||||
doc.ensure_nonempty();
|
||||
doc.settings = current.settings.clone();
|
||||
doc.core = current.core.clone();
|
||||
Arc::make_mut(&mut doc.styles).default_chr.lang = current.styles.default_chr.lang.clone();
|
||||
(doc, lines)
|
||||
Ok((doc, lines))
|
||||
}
|
||||
|
||||
/// `text` as a document, with what isn't in Markdown from `current`: its page, settings,
|
||||
/// properties and language, as opening the file gave it.
|
||||
fn parse(current: &Document, text: &str) -> Document {
|
||||
parse_with_lines(current, text).0
|
||||
fn parse(current: &Document, text: &str) -> Result<Document, CmdError> {
|
||||
parse_with_lines(current, text).map(|(doc, _)| doc)
|
||||
}
|
||||
|
||||
/// The byte offset where `line` starts, or the end of a text with fewer lines.
|
||||
|
||||
@@ -278,4 +278,23 @@ mod tests {
|
||||
assert_eq!(texts(&s), ["First one.", "Second one.", "Third one."]);
|
||||
assert!(kinds(&mut s).is_empty());
|
||||
}
|
||||
|
||||
/// A command that fails between a tracked cut and its paste changed nothing, so the move
|
||||
/// the cut recorded is still there: the paste is a move, as it was before the command.
|
||||
#[test]
|
||||
fn a_failed_command_between_a_tracked_cut_and_its_paste_leaves_the_move() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
|
||||
s.run("file.setAuthor", &json!({"name": "Ana"})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
|
||||
s.run("edit.cut", &json!({})).unwrap();
|
||||
// A command that fails: there is no such character style.
|
||||
assert!(s.run("format.charStyle", &json!({"style": "NoSuchStyle"})).is_err());
|
||||
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
let k = kinds(&mut s);
|
||||
assert!(k.iter().any(|(k, m)| k == "moveTo" && m == "move1"), "{k:?}");
|
||||
assert!(k.iter().any(|(k, m)| k == "moveFrom" && m == "move1"), "{k:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +187,7 @@ fn paste_special(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Ok(r);
|
||||
}
|
||||
"formatted" => s.clipboard.clone().ok_or_else(|| CmdError::Failed("the clipboard is empty".into()))?,
|
||||
"html" => adopt(s, import_html(&src)),
|
||||
"html" => adopt(s, import_html(&src).map_err(|e| CmdError::Failed(format!("bad HTML: {e}")))?),
|
||||
_ => adopt(s, wordcraft_formats::rtf::import(src.as_bytes()).map_err(|e| CmdError::Failed(format!("bad RTF: {e}")))?),
|
||||
};
|
||||
insert(s, frag)?;
|
||||
@@ -204,8 +204,8 @@ const BLOCKQUOTE_INDENT: f32 = 36.0;
|
||||
/// (#1270): it pastes as a Normal paragraph indented by the page's `blockquote` margins, else half
|
||||
/// an inch each side, rather than in the (centred, italic) Quote style. Opening an .html file keeps
|
||||
/// `<blockquote>` as Quote, so HTML round-trips.
|
||||
fn import_html(html: &str) -> Document {
|
||||
let mut doc = wordcraft_formats::html::import(html_fragment(html));
|
||||
fn import_html(html: &str) -> Result<Document, String> {
|
||||
let mut doc = wordcraft_formats::html::import(html_fragment(html))?;
|
||||
let (left, right) = blockquote_margins(html);
|
||||
for b in &mut doc.body {
|
||||
each_para(Arc::make_mut(b), 0, &mut |p| {
|
||||
@@ -217,7 +217,7 @@ fn import_html(html: &str) -> Document {
|
||||
}
|
||||
});
|
||||
}
|
||||
doc
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// The left and right margins (points) the payload's `<style>` sheets give `blockquote` — LibreOffice
|
||||
@@ -294,7 +294,7 @@ fn has_content(d: &Document) -> bool {
|
||||
/// [`MAX_PASTE_BYTES`], or it holds nothing to paste (the caller pastes the text then).
|
||||
pub fn rich_fragment(s: &mut Session, v: &Value) -> Option<Fragment> {
|
||||
let fits = |k: &str| p::str(v, k).filter(|t| !t.trim().is_empty() && t.len() <= MAX_PASTE_BYTES);
|
||||
let doc = fits("html").map(import_html);
|
||||
let doc = fits("html").and_then(|html| import_html(html).ok());
|
||||
let doc = match doc.filter(has_content) {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
@@ -373,21 +373,22 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
p.props = para.clone();
|
||||
for run in &mut p.runs {
|
||||
let src = std::mem::replace(&mut run.props, base.clone());
|
||||
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
|
||||
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
|
||||
// with the complex-script bold and italic.
|
||||
if src.bold == Some(true) || src.bold_cs == Some(true) {
|
||||
let e = emphasis_of(s, &src);
|
||||
// Emphasis the source shows in either script is kept for both, as the Bold and
|
||||
// Italic buttons set it: text pasted into a run marked `w:cs` (Thai from a WPS or
|
||||
// Word file) is drawn with the complex-script bold and italic.
|
||||
if shown(e.bold, e.bold_cs, &e) {
|
||||
run.props.bold = Some(true);
|
||||
run.props.bold_cs = Some(true);
|
||||
}
|
||||
if src.italic == Some(true) || src.italic_cs == Some(true) {
|
||||
if shown(e.italic, e.italic_cs, &e) {
|
||||
run.props.italic = Some(true);
|
||||
run.props.italic_cs = Some(true);
|
||||
}
|
||||
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
|
||||
run.props.underline = src.underline;
|
||||
if e.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
|
||||
run.props.underline = e.underline;
|
||||
}
|
||||
if src.strike == Some(true) {
|
||||
if e.strike == Some(true) {
|
||||
run.props.strike = Some(true);
|
||||
}
|
||||
run.props.link = src.link;
|
||||
@@ -400,6 +401,34 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The formatting a pasted run's emphasis is judged by: its own, over its character style
|
||||
/// chain's. Word keeps the bold, italic, underline and strikethrough a character style gives the
|
||||
/// source, as direct formatting, but not a paragraph style's (measured in Word for Windows), so
|
||||
/// the paragraph style isn't consulted.
|
||||
fn emphasis_of(s: &Session, src: &wordcraft_doc::CharProps) -> wordcraft_doc::CharProps {
|
||||
use wordcraft_doc::styles::StyleKind;
|
||||
let mut e = wordcraft_doc::CharProps::default();
|
||||
if let Some(id) = src.style.as_deref() {
|
||||
for st in s.doc.styles.chain(id) {
|
||||
if st.kind == StyleKind::Character || st.kind == StyleKind::Paragraph {
|
||||
e.overlay(&st.chr);
|
||||
}
|
||||
}
|
||||
}
|
||||
e.overlay(&wordcraft_doc::CharProps { style: None, ..src.clone() });
|
||||
e
|
||||
}
|
||||
|
||||
/// Whether a run with these Latin and complex-script values of a toggle (bold or italic) shows
|
||||
/// it anywhere, as the resolved formatting draws it: a run marked `w:cs` or `w:rtl` draws all
|
||||
/// its text with the complex-script value, which borrows the Latin one unless the run is marked
|
||||
/// `w:cs`; other runs draw their Latin text with the Latin value.
|
||||
fn shown(latin: Option<bool>, complex: Option<bool>, run: &wordcraft_doc::CharProps) -> bool {
|
||||
let complex_shown = complex.or(latin.filter(|_| run.cs != Some(true))) == Some(true);
|
||||
let all_complex = run.cs == Some(true) || run.rtl == Some(true);
|
||||
complex_shown || (!all_complex && latin == Some(true))
|
||||
}
|
||||
|
||||
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
|
||||
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
|
||||
/// anything else is [`insert_as_is`].
|
||||
|
||||
@@ -305,7 +305,16 @@ pub(crate) fn greyed_out(s: &Session, id: &str, facts: impl FnOnce() -> Facts) -
|
||||
}
|
||||
}
|
||||
let comment_ok = id.starts_with("review.") && (id.contains("Comment") || id == "review.reply");
|
||||
let tracked = matches!(id, "review.accept" | "review.reject" | "review.acceptAll" | "review.rejectAll" | "review.trackChanges");
|
||||
let tracked = matches!(
|
||||
id,
|
||||
"review.accept"
|
||||
| "review.reject"
|
||||
| "review.acceptAndNext"
|
||||
| "review.rejectAndNext"
|
||||
| "review.acceptAll"
|
||||
| "review.rejectAll"
|
||||
| "review.trackChanges"
|
||||
);
|
||||
match mode {
|
||||
"readOnly" => (!facts().exceptions).then_some("the document is protected (read only)"),
|
||||
"forms" => (facts().fillable == 0).then_some("the document is protected (read only)"),
|
||||
|
||||
@@ -213,7 +213,15 @@ fn tracked_changes_protection_keeps_revisions() {
|
||||
select(&mut s, "text");
|
||||
s.run("text.insert", &json!({"text": "words"})).unwrap();
|
||||
let before = s.doc.clone();
|
||||
for id in ["review.acceptAll", "review.rejectAll", "review.accept", "review.reject", "review.trackChanges"] {
|
||||
for id in [
|
||||
"review.acceptAll",
|
||||
"review.rejectAll",
|
||||
"review.accept",
|
||||
"review.reject",
|
||||
"review.acceptAndNext",
|
||||
"review.rejectAndNext",
|
||||
"review.trackChanges",
|
||||
] {
|
||||
assert!(s.run(id, &json!({})).is_err(), "{id}");
|
||||
}
|
||||
assert_eq!(s.doc, before);
|
||||
|
||||
@@ -422,7 +422,19 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
"DATE" | "TIME" | "CREATEDATE" | "SAVEDATE" | "PRINTDATE" => {
|
||||
let lang = field_lang(&s.doc, p, k);
|
||||
let pic = date_picture(instr).unwrap_or_else(|| default_picture(&name, lang.as_deref()));
|
||||
updates.push((k, text_result(instr, crate::cmd::insert::format_date_in(&pic, lang.as_deref()))));
|
||||
let created = s.doc.core.created.trim();
|
||||
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
|
||||
// document, never saved, has no creation date yet and saving stamps now. A
|
||||
// file opened without one, or with one that can't be read, keeps the result
|
||||
// it has.
|
||||
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
|
||||
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
|
||||
} else if let Some((unix, offset)) = created_at(created) {
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
updates.push((k, text_result(instr, text)));
|
||||
}
|
||||
"REF" | "PAGEREF" => {
|
||||
let f = FieldCode::parse(instr);
|
||||
@@ -572,6 +584,24 @@ fn field_lang(doc: &wordcraft_doc::Document, p: &wordcraft_doc::Paragraph, k: us
|
||||
doc.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(off)).lang
|
||||
}
|
||||
|
||||
/// A core-properties creation date as seconds since the epoch and the UTC offset to show it at:
|
||||
/// an instant (`2019-05-05T12:00:00Z`, any offset or fraction, or without the seconds,
|
||||
/// `2019-05-05T12:00Z`, as W3CDTF allows) at the local offset, or a calendar date (`2019-05-05`)
|
||||
/// at its own midnight, whatever the time zone. `None` for another form or a date before 1970.
|
||||
fn created_at(stamp: &str) -> Option<(u64, i64)> {
|
||||
let instant = chrono::DateTime::parse_from_rfc3339(stamp).ok().or_else(|| {
|
||||
// `%:z` takes `+01:00` but not `Z`.
|
||||
let utc = stamp.strip_suffix(['Z', 'z']).map(|t| format!("{t}+00:00"));
|
||||
chrono::DateTime::parse_from_str(utc.as_deref().unwrap_or(stamp), "%Y-%m-%dT%H:%M%:z").ok()
|
||||
});
|
||||
if let Some(t) = instant {
|
||||
let unix = u64::try_from(t.timestamp()).ok()?;
|
||||
return Some((unix, crate::cmd::local_offset_secs(unix)));
|
||||
}
|
||||
let day = chrono::NaiveDate::parse_from_str(stamp, "%Y-%m-%d").ok()?;
|
||||
Some((u64::try_from(day.and_hms_opt(0, 0, 0)?.and_utc().timestamp()).ok()?, 0))
|
||||
}
|
||||
|
||||
/// Word's default date or time picture when a field instruction carries no `\@` picture switch.
|
||||
fn default_picture(name: &str, lang: Option<&str>) -> String {
|
||||
if name == "TIME" { "h:mm am/pm".into() } else { crate::cmd::insert::default_date_picture(lang).into() }
|
||||
|
||||
@@ -506,6 +506,56 @@ fn update_fields_all_covers_every_story() {
|
||||
s.run("references.updateFields", &json!({"all": "yes"})).unwrap();
|
||||
}
|
||||
|
||||
/// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11), not today's date.
|
||||
#[test]
|
||||
fn createdate_keeps_the_creation_date_on_update() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.doc.core.created = "2019-05-05T12:00:00Z".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": "CREATEDATE"})).unwrap();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
// 12:00 UTC is 5 May from UTC-12 to UTC+11:59, the next day east of that.
|
||||
let unix = 1_557_057_600;
|
||||
let (_, _, day, _, _) = crate::cmd::local_civil(unix, crate::cmd::local_offset_secs(unix));
|
||||
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")]);
|
||||
assert!(day == 5 || day == 6, "{day}");
|
||||
// W3CDTF may leave out the seconds; that is the same instant.
|
||||
for minutes in ["2019-05-05T12:00Z", "2019-05-05T14:00+02:00", "2019-05-05T07:00-05:00"] {
|
||||
// From another date first, so an unread stamp, which keeps the result, shows.
|
||||
s.doc.core.created = "2001-02-03".into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[1].1, "2/3/2001");
|
||||
s.doc.core.created = minutes.into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), format!("5/{day}/2019")], "{minutes}");
|
||||
}
|
||||
// A date without a time is that calendar day in every time zone.
|
||||
s.doc.core.created = "2019-06-07".into();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-06", "6/7/2019"]);
|
||||
}
|
||||
|
||||
/// A creation date that can't be read leaves the field's result as it was; a document that has
|
||||
/// never been saved is created now (saving stamps that time as its creation date).
|
||||
#[test]
|
||||
fn createdate_without_a_readable_creation_date() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.doc.core.created = "sometime in May".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, "2019-05");
|
||||
// A file opened without a creation date keeps the result too.
|
||||
s.doc.core.created.clear();
|
||||
s.path = Some(std::env::temp_dir().join("opened.docx"));
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, "2019-05");
|
||||
s.path = None;
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_tabs_ignore_nonentries() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
mod changes;
|
||||
mod comments;
|
||||
mod proofing;
|
||||
pub use proofing::thesaurus_word;
|
||||
|
||||
pub(crate) use changes::StyleTarget;
|
||||
pub use changes::{
|
||||
@@ -61,6 +62,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"next"?: bool (then select the next change)}"#),
|
||||
CommandSpec::new("review.reject", "Reject", "Review › Changes", |s, v| resolve_sel_then(s, v, false))
|
||||
.params(r#"{"next"?: bool (then select the next change)}"#),
|
||||
CommandSpec::new("review.acceptAndNext", "Accept and Move to Next", "Review › Changes", |s, _| {
|
||||
resolve_sel_then(s, &json!({"next": true}), true)
|
||||
}),
|
||||
CommandSpec::new("review.rejectAndNext", "Reject and Move to Next", "Review › Changes", |s, _| {
|
||||
resolve_sel_then(s, &json!({"next": true}), false)
|
||||
}),
|
||||
CommandSpec::new("review.nextChange", "Next Change", "Review › Changes", |s, _| nav_change(s, 1)).pure(),
|
||||
CommandSpec::new("review.previousChange", "Previous Change", "Review › Changes", |s, _| nav_change(s, -1)).pure(),
|
||||
CommandSpec::new("review.markup", "Display for Review", "Review › Tracking", |s, v| {
|
||||
|
||||
@@ -53,10 +53,11 @@ fn resolve_para(
|
||||
}
|
||||
// An inserted paragraph mark that is rejected, or a deleted one that is accepted, goes away:
|
||||
// the next paragraph joins this one (the split is undone). A paragraph left empty goes away
|
||||
// whole, so the next one keeps its own style and numbering, as in Word. The mark at the end
|
||||
// of a story or cell can't go, so it just stops being a revision. An empty paragraph whose
|
||||
// mark carries a section break goes whole too: its section joins the following one, as when
|
||||
// the break is deleted (#5667). Joining instead gave the next paragraph its properties.
|
||||
// whole, so the next one keeps its own style and numbering, as in Word. The end mark of a
|
||||
// story or cell has no follower to join here; `resolve_all` removes the whole paragraph
|
||||
// instead when one is left over (see `remove_trailing_para`). An empty paragraph whose mark
|
||||
// carries a section break goes whole too: its section joins the following one, as when the
|
||||
// break is deleted (#5667). Joining instead gave the next paragraph its properties.
|
||||
if (del.is_some() && accept) || (ins.is_some() && !accept) {
|
||||
let sectioned = story == StoryRef::Body
|
||||
&& path.0.len() == 1
|
||||
@@ -76,6 +77,23 @@ fn resolve_para(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the whole paragraph at `path` when a whole-paragraph revision on its mark resolved to
|
||||
/// removal and it is the last paragraph in its container and carries no section break: it goes
|
||||
/// away, as long as the container keeps another paragraph (a story or cell must never end up
|
||||
/// with none). `false`, changing nothing, otherwise.
|
||||
fn remove_trailing_para(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path) -> Result<bool, CmdError> {
|
||||
let Some(p) = s.doc.para(story, path) else { return Ok(false) };
|
||||
if !p.is_empty() || p.section.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(container) = s.doc.container(story, path) else { return Ok(false) };
|
||||
if container.iter().filter(|b| b.as_para().is_some()).count() <= 1 {
|
||||
return Ok(false);
|
||||
}
|
||||
s.doc.remove_block(story, path)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Accept or reject the changes of the table cell `path` is in: the table's, its row's and the
|
||||
/// cell's own. Returns whether there were any.
|
||||
fn resolve_cell(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, accept: bool) -> Result<bool, CmdError> {
|
||||
@@ -245,8 +263,16 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
// A whole-paragraph mark that resolves to removal at the end of its container takes
|
||||
// the paragraph with it (there is no follower for `resolve_para` to join). A paragraph
|
||||
// followed by a table is not the end: removing it could make two tables adjacent.
|
||||
let is_last = s.doc.block(st, &path.with_last(path.last().saturating_add(1))).is_none();
|
||||
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
|
||||
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
|
||||
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing {
|
||||
remove_trailing_para(s, st, &path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Tables, rows, cells, sections and style definitions.
|
||||
|
||||
@@ -128,6 +128,20 @@ pub(super) fn suggestions(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
|
||||
/// The word at the caret that the thesaurus looks up and a chosen synonym replaces: the word unit
|
||||
/// without the spaces after it or the quotes around it, so `‘good’` is `good` and its quotes stay
|
||||
/// when it is replaced; an apostrophe inside a word (`don’t`) is kept (#6517).
|
||||
pub fn thesaurus_word(s: &Session) -> Option<(Pos, Pos)> {
|
||||
let f = &s.sel.focus;
|
||||
let p = s.doc.para_at(f)?;
|
||||
let (a, b) = p.word_at(f.off);
|
||||
let w = p.text.get(a..b)?;
|
||||
let edge = |c: char| c.is_whitespace() || matches!(c, '’' | '‘' | '\'');
|
||||
let start = a + (w.len() - w.trim_start_matches(edge).len());
|
||||
let end = (a + w.trim_end_matches(edge).len()).max(start);
|
||||
Some((Pos { off: start, ..f.clone() }, Pos { off: end, ..f.clone() }))
|
||||
}
|
||||
|
||||
/// A tiny built-in thesaurus of common words (our own list).
|
||||
pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
|
||||
const T: &[(&str, &[&str])] = &[
|
||||
@@ -164,10 +178,8 @@ pub(super) fn thesaurus(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let word = match p::str(v, "word") {
|
||||
Some(w) => w.to_lowercase(),
|
||||
None => {
|
||||
let f = s.sel.focus.clone();
|
||||
let p = s.doc.para_at(&f).ok_or_else(|| CmdError::Failed("no word".into()))?;
|
||||
let (a, b) = p.word_at(f.off);
|
||||
p.text.get(a..b).unwrap_or("").trim().to_lowercase()
|
||||
let (a, b) = thesaurus_word(s).ok_or_else(|| CmdError::Failed("no word".into()))?;
|
||||
s.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).unwrap_or("").to_lowercase()
|
||||
}
|
||||
};
|
||||
let syn = T.iter().find(|(w, _)| *w == word).map(|(_, l)| l.to_vec()).unwrap_or_default();
|
||||
|
||||
@@ -703,6 +703,20 @@ fn accept_and_reject_can_move_to_the_next_change() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_shortcut_commands_resolve_and_select_the_next_change_without_parameters() {
|
||||
for (command, accept) in [("review.acceptAndNext", true), ("review.rejectAndNext", false)] {
|
||||
let mut s = three_changes();
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
s.run(command, &serde_json::Value::Null).unwrap();
|
||||
let remaining = change_spans(&mut s);
|
||||
assert_eq!(remaining.iter().map(|change| change.0.as_str()).collect::<Vec<_>>(), ["delete", "insert"], "{command}");
|
||||
let (_, start, end) = remaining[0];
|
||||
assert_eq!(selected(&s), (start as usize, end as usize), "{command}: the deletion is selected next");
|
||||
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).starts_with("new "), accept, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the caret on no change, Accept and Move to Next selects the next change without
|
||||
/// resolving it, as Accept and Next Change do.
|
||||
#[test]
|
||||
@@ -1248,7 +1262,7 @@ fn rtf_tracked_changes_accept_and_reject_after_opening_and_round_trip() {
|
||||
let rtf: &[u8] = br"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\*\revtbl {Unknown;}{Alice;}{Bob;}}
|
||||
\pard Keep {\revised\revauth1\revdttm-1480361314 added }text{\deleted\revauthdel2\revdttmdel-2016341499 gone} end{\revised\revauth1\revdttm-1480361314\deleted\revauthdel2\revdttmdel-2016341499 both}.\par}";
|
||||
let opened = wordcraft_formats::rtf::import(rtf).unwrap();
|
||||
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).as_bytes()).unwrap();
|
||||
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).unwrap().as_bytes()).unwrap();
|
||||
for doc in [opened, again] {
|
||||
for (cmd, want) in [("review.acceptAll", "Keep added text end."), ("review.rejectAll", "Keep text gone end.")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
|
||||
@@ -443,7 +443,11 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
|
||||
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
|
||||
_ => {
|
||||
if let Some(x) = a {
|
||||
out.push(Arc::new(mark_block(x, &|c| c.del = Some(ctx.del))));
|
||||
out.push(Arc::new(mark_block(x, &|c| {
|
||||
// An existing deletion is another author's: keep their revision
|
||||
// stamp instead of re-attributing the paragraph to this compare.
|
||||
c.del.get_or_insert(ctx.del);
|
||||
})));
|
||||
}
|
||||
if let Some(x) = b {
|
||||
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
|
||||
@@ -1613,8 +1617,16 @@ fn block_text(b: &Block, depth: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a copy of `b` with all text runs and paragraph marks across all nested table cells
|
||||
/// updated by `f` iteratively, without recursion or depth truncation.
|
||||
/// A copy of the block with every run (in tables, every cell's) changed by `f`, and a paragraph's
|
||||
/// mark along with them, so a whole inserted or deleted paragraph carries the revision even when
|
||||
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
|
||||
/// iteratively, without recursion or depth truncation.
|
||||
///
|
||||
/// A whole-paragraph revision on the last paragraph of a story or cell is removed together with
|
||||
/// the paragraph on Accept/Reject All (see `remove_trailing_para` in `review::changes`), except
|
||||
/// where the paragraph carries a section break or is the container's only paragraph. A
|
||||
/// non-terminal section-carrying paragraph is removed whole too: `resolve_para` removes the
|
||||
/// section break first (#5734, issue #5667), so the following paragraph keeps its own properties.
|
||||
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
|
||||
let mut out = b.clone();
|
||||
let mut todo = vec![&mut out];
|
||||
|
||||
@@ -11,6 +11,259 @@ fn compare_marks_changes() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "The dog sat.\nKeep this.\nNew line here.");
|
||||
}
|
||||
|
||||
/// Top-level body blocks that are empty paragraphs.
|
||||
fn empty_paras(s: &Session) -> usize {
|
||||
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_a_whole_paragraph_and_its_mark() {
|
||||
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "NEW");
|
||||
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
|
||||
|
||||
// A whole deleted paragraph carries the deletion on its mark.
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_an_empty_paragraphs_mark() {
|
||||
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
|
||||
|
||||
// An empty deleted paragraph is stamped on its mark too.
|
||||
let mut s = Session::new(Document::from_text("A\n\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_another_authors_deletion_stamp() {
|
||||
// A paragraph the original already carries as a tracked deletion by another author: Compare
|
||||
// must keep that author's revision on its runs and on its paragraph mark, not re-attribute
|
||||
// the block to its own deletion revision.
|
||||
let mut doc = Document::from_text("A\nOLD\nB");
|
||||
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Delete, "Alice", ""));
|
||||
let p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
for r in &mut p.runs {
|
||||
r.props.del = Some(0);
|
||||
}
|
||||
p.mark.del = Some(0);
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.compare", &json!({"text": "A\nB", "author": "Bob"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.runs.iter().all(|r| r.props.del == Some(0)), "the runs' deletion was re-stamped: {:?}", mid.runs);
|
||||
assert_eq!(mid.mark.del, Some(0), "the paragraph mark's deletion was re-stamped");
|
||||
assert_eq!(s.doc.revisions.first().map(|r| (r.kind, r.author.as_str())), Some((RevisionKind::Delete, "Alice")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_terminal_inserted_paragraph_resolves_fully() {
|
||||
// A paragraph inserted at the very end is removed whole when rejected, leaving no empty
|
||||
// paragraph behind.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nC"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a terminal inserted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
// The mirror of `compare_terminal_inserted_paragraph_resolves_fully`: a paragraph deleted
|
||||
// from the very end is removed whole when accepted, leaving no empty paragraph behind.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nC"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
|
||||
// An empty paragraph between two tables is not the container's last block: removing it
|
||||
// would make the tables adjacent, and they would join into one on reopen. Reject All only
|
||||
// clears its mark.
|
||||
use wordcraft_doc::{Block, Paragraph, para_block};
|
||||
let mut doc = Document::from_text("");
|
||||
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, "Alice", ""));
|
||||
let table = || std::sync::Arc::new(Block::Table(wordcraft_doc::table::Table::new(1, 1, 100.0)));
|
||||
let mut between = Paragraph::default();
|
||||
between.mark.ins = Some(0);
|
||||
doc.body = vec![table(), para_block(between), table(), para_block(Paragraph::with_text("end", Default::default()))];
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
let kinds: Vec<bool> = s.doc.body.iter().map(|b| matches!(**b, Block::Table(_))).collect();
|
||||
assert_eq!(kinds, [true, false, true, false]);
|
||||
let kept = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
assert!(kept.is_empty() && kept.mark.ins.is_none(), "{kept:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style() {
|
||||
// Pins the fixed behaviour for rejecting an inserted paragraph that carries a section
|
||||
// break. This was a known limitation recorded on `mark_block` (compare.rs): `resolve`'s
|
||||
// `remove_empty_para` refused paragraphs carrying a section, so once the inserted
|
||||
// paragraph's text was rejected the empty paragraph was joined into the next one, which
|
||||
// took its properties ("Body" came back Normal instead of its original Heading 1). Fixed
|
||||
// on main by #5734 (issue #5667): `resolve_para` now removes the section break first, so
|
||||
// the empty paragraph goes whole and the following paragraph keeps its own properties.
|
||||
// After Reject All the original is restored exactly.
|
||||
let mut original = Document::from_text("Intro\nBody");
|
||||
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
|
||||
let mut s = Session::new(original);
|
||||
|
||||
let mut rev = Document::from_text("Intro\nAppendix\nBody");
|
||||
{
|
||||
let p = rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
p.props.style = Some("Normal".into());
|
||||
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
|
||||
}
|
||||
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-section-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Intro\nBody");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
let body = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(body.plain_text(), "Body");
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
|
||||
// The Accept-side mirror of `compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style`:
|
||||
// compare deletes a paragraph that carries a section break whole (original `A`, `OLD`
|
||||
// with a section break, `B`; revised `A`, `B`). Accept All goes through the same #5734
|
||||
// branch in `resolve_para` as the reject case: the section break is removed first, so
|
||||
// the emptied paragraph goes whole instead of being joined into the next one. After
|
||||
// Accept All the revised text stands exactly and `B` keeps its own properties.
|
||||
let mut original = Document::from_text("A\nOLD\nB");
|
||||
{
|
||||
let p = original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
p.props.style = Some("Normal".into());
|
||||
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
|
||||
}
|
||||
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
|
||||
let mut s = Session::new(original);
|
||||
|
||||
let mut rev = Document::from_text("A\nB");
|
||||
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-section-accept-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted sectioned paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting the deleted sectioned paragraph left it behind");
|
||||
let body = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(body.plain_text(), "B");
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_the_last_paragraphs_mark() {
|
||||
// Inserted last paragraph: rejecting removes it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nNEW");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
|
||||
// Deleted last paragraph: accepting removes it whole.
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nOLD");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_the_only_paragraphs_mark() {
|
||||
let mut s = Session::new(Document::from_text(""));
|
||||
s.doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Insert, s.author.clone(), ""));
|
||||
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 1);
|
||||
assert!(s.doc.body[0].as_para().unwrap().mark.ins.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_options_ignore_case_and_white_space() {
|
||||
let original = "The Cat sat.\nTwo spaces here.";
|
||||
|
||||
@@ -337,6 +337,29 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A document made from a template is created now, not when the template was: it has no
|
||||
/// creation date until it is saved, so CREATEDATE in it shows today.
|
||||
#[test]
|
||||
fn new_from_template_has_no_creation_date_of_its_own_yet() {
|
||||
let d = scratch("created");
|
||||
let path = d.join("Dated.dotx");
|
||||
let mut t = Session::new(wordcraft_doc::Document::new());
|
||||
t.run("document.setText", &json!({"text": "Dated"})).unwrap();
|
||||
t.doc.core.created = "2019-05-05T12:00:00Z".into();
|
||||
crate::io::save_path(&path, &t.doc).unwrap();
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("file.newFromTemplate", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.doc.core.created, "");
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy""#, "result": "2019"})).unwrap();
|
||||
s.run("references.updateFields", &json!({})).unwrap();
|
||||
assert!(s.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(&crate::cmd::insert::format_date("yyyy")));
|
||||
// The template itself keeps its date.
|
||||
let mut again = Session::new(wordcraft_doc::Document::new());
|
||||
again.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(again.doc.core.created, "2019-05-05T12:00:00Z");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// #3433: a template the platform hands the app takes an untouched blank document's place
|
||||
/// (`replaceBlank`), as a file `file.open` opens does; otherwise, and without the flag, the
|
||||
/// new document opens beside the others, as File › New's does. Either way the template on
|
||||
|
||||
@@ -284,14 +284,17 @@ fn import_chunk(c: &wordcraft_docx::AltChunk) -> Option<Document> {
|
||||
|| matches!(ext.as_str(), "mht" | "mhtml")
|
||||
|| mht::is_mht(b)
|
||||
{
|
||||
mht::import(b)
|
||||
mht::import(b).map_err(|e| log::warn!("altChunk {}: the MHT cannot be read: {e}", c.part)).ok()?
|
||||
} else if ct.contains("rtf") || ext == "rtf" || b.starts_with(b"{\\rtf") {
|
||||
rtf::import(b).ok()?
|
||||
rtf::import(b).map_err(|e| log::warn!("altChunk {}: the RTF cannot be read: {e}", c.part)).ok()?
|
||||
} else if ct.contains("html") || matches!(ext.as_str(), "html" | "htm" | "xhtml") {
|
||||
html::import_page(&html::decode_as(b, charset), &|_| None)
|
||||
.map_err(|e| log::warn!("altChunk {}: the HTML cannot be read: {e}", c.part))
|
||||
.ok()?
|
||||
} else if ct == "text/plain" || ext == "txt" {
|
||||
txt::import(b)
|
||||
} else {
|
||||
log::warn!("altChunk {}: its type ({ct}) is not one WordCraft reads", c.part);
|
||||
return None;
|
||||
};
|
||||
// shortcut: pictures fit the chunk's default page, not the section it lands in; fit them there if wide pictures in chunks overflow narrow sections.
|
||||
@@ -496,7 +499,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
|
||||
// Pictures referenced by a relative path load from beside the HTML file.
|
||||
let images = LocalImages::new(path.parent().unwrap_or(std::path::Path::new("")));
|
||||
let html = wordcraft_formats::html::decode(&bytes);
|
||||
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), ®ion_page(region));
|
||||
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), ®ion_page(region))?;
|
||||
fit_pictures(&mut doc);
|
||||
opened(&mut doc);
|
||||
return Ok((doc, false));
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod io;
|
||||
mod io_ext;
|
||||
pub mod keymap;
|
||||
pub(crate) mod locale;
|
||||
pub mod malloc_tuning;
|
||||
pub mod math_gallery;
|
||||
pub mod packs;
|
||||
pub(crate) mod prefs;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! glibc malloc tuning for native binaries (adapted from Storytold's `photocraft` #8743).
|
||||
//!
|
||||
//! With glibc's defaults, transient large buffers (page render targets, autofit tables, decoded
|
||||
//! images) raise glibc's dynamic `mmap` and `trim` thresholds (up to 32 MiB on 64-bit), so later
|
||||
//! heap allocations stay in glibc arenas instead of returning freed pages to the OS. Fixing
|
||||
//! `MALLOC_TRIM_THRESHOLD_` at 128 KiB (`131072`) disables dynamic threshold growth so freed
|
||||
//! pages above 128 KiB are returned cleanly while preserving multi-arena allocation throughput.
|
||||
//!
|
||||
//! Because glibc reads its malloc environment variables once at process start and mutating the
|
||||
//! process environment in Rust requires `unsafe` (forbidden workspace-wide) and happens after glibc
|
||||
//! initialization, [`apply`] re-executes the current executable via `exec` when no malloc tuning
|
||||
//! variable is already set (keeping PID, argv, `argv[0]`, and environment). Setting any `MALLOC_*`
|
||||
//! variable or `glibc.malloc.*` tunable opts out.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// The glibc environment variable [`apply`] sets.
|
||||
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
|
||||
|
||||
/// Fixed trim threshold (128 KiB, glibc's initial default) to disable dynamic threshold escalation.
|
||||
pub const TRIM_THRESHOLD: &str = "131072";
|
||||
|
||||
/// glibc malloc variables that indicate callers or wrappers already configured malloc tuning.
|
||||
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
|
||||
|
||||
/// Whether startup should re-execute with [`TRIM_THRESHOLD_VAR`] set, given an environment reader:
|
||||
/// true only when no malloc variable or `glibc.malloc.*` tunable is present.
|
||||
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
|
||||
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
|
||||
return false;
|
||||
}
|
||||
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
|
||||
}
|
||||
|
||||
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] is true.
|
||||
///
|
||||
/// Must be called early in `main()` before worker threads start or logs/crash hooks initialize.
|
||||
/// Returns immediately if tuning variables are already present or if `exec` fails.
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
pub fn apply() {
|
||||
use std::io::Write;
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
if !needs_restart(|k| std::env::var_os(k)) {
|
||||
return;
|
||||
}
|
||||
let Ok(exe) = std::env::current_exe() else { return };
|
||||
let mut args = std::env::args_os();
|
||||
let mut cmd = std::process::Command::new(exe);
|
||||
if let Some(argv0) = args.next() {
|
||||
cmd.arg0(argv0);
|
||||
}
|
||||
// `exec` replaces the current process in place and only returns on error.
|
||||
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
|
||||
let _ = writeln!(std::io::stderr(), "wordcraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err})");
|
||||
}
|
||||
|
||||
/// No-op on platforms without Linux glibc.
|
||||
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
|
||||
pub fn apply() {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restarts_only_without_malloc_tuning() {
|
||||
assert!(needs_restart(env(&[])));
|
||||
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
|
||||
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "re-executed process stops");
|
||||
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any explicit value opts out");
|
||||
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
|
||||
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
|
||||
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
|
||||
}
|
||||
}
|
||||
@@ -80,8 +80,12 @@ impl Session {
|
||||
};
|
||||
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
|
||||
let [newest, _] = std::mem::take(&mut self.layout);
|
||||
// Only preserve the alternate layout slot for the current document revision (e.g. Print vs
|
||||
// Web/Draft toggling); a superseded revision can never hit `fits()` again and would keep an
|
||||
// obsolete DocLayout live in memory.
|
||||
let prev = newest.filter(|e| e.0 == rev);
|
||||
self.layout =
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), newest];
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
|
||||
l
|
||||
}
|
||||
|
||||
@@ -275,3 +279,31 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
drop(first);
|
||||
|
||||
// Switching view mode at the same revision keeps the prior layout in `layout[1]`.
|
||||
session.view.mode = ViewMode::Draft;
|
||||
let same_rev_other_mode = session.layout();
|
||||
assert!(first_weak.upgrade().is_some(), "same-revision alternate view mode stays cached");
|
||||
|
||||
let draft_weak = Arc::downgrade(&same_rev_other_mode);
|
||||
drop(same_rev_other_mode);
|
||||
|
||||
// Advancing `rev` makes earlier layouts unreachable: building the new layout must drop them.
|
||||
session.run("text.insert", &serde_json::json!({"text": "hello"})).expect("insert");
|
||||
let after_edit = session.layout();
|
||||
assert!(draft_weak.upgrade().is_none(), "superseded revision layout must be dropped");
|
||||
assert!(first_weak.upgrade().is_none(), "older revision layout must not remain live");
|
||||
drop(after_edit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,13 +27,18 @@ struct ElsewhereContext {
|
||||
blocks_before: Option<std::collections::BTreeMap<String, Fragment>>,
|
||||
default_language_before: Option<String>,
|
||||
pending_application_change_before: bool,
|
||||
/// The tracked move the command would have dropped, put back when it fails.
|
||||
move_before: Option<crate::cmd::moves::PendingMove>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn leave_math_for_command(&mut self, id: &str) {
|
||||
self.math_left = false;
|
||||
if self.math.is_some()
|
||||
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
|
||||
&& (id.starts_with("text.")
|
||||
|| id.starts_with("caret.")
|
||||
|| id.starts_with("select.")
|
||||
|| (id.starts_with("edit.paste") && id != "edit.pasteFormat"))
|
||||
&& let Some(m) = self.math.take()
|
||||
{
|
||||
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
|
||||
@@ -213,7 +218,9 @@ impl Session {
|
||||
} else if spec.id.starts_with("caret.") {
|
||||
self.typing_open = false;
|
||||
}
|
||||
// Only the paste right after a tracked cut makes it a move.
|
||||
// Only the paste right after a tracked cut makes it a move. A command that fails
|
||||
// changed nothing, so the move it would have dropped is put back (below).
|
||||
let move_before = self.pending_move.clone();
|
||||
if (spec.mutates || matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo")) && !matches!(id, "edit.cut" | "edit.paste" | "edit.pasteSpecial")
|
||||
{
|
||||
self.pending_move = None;
|
||||
@@ -239,7 +246,7 @@ impl Session {
|
||||
};
|
||||
if self.document_id != home || (result.is_err() && self.order.iter().any(|d| *d >= mark)) {
|
||||
return self.finish_elsewhere(
|
||||
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before },
|
||||
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before },
|
||||
result,
|
||||
);
|
||||
}
|
||||
@@ -304,6 +311,9 @@ impl Session {
|
||||
self.join_anchor = false;
|
||||
}
|
||||
}
|
||||
// The command failed, so the tracked move it would have dropped is still there:
|
||||
// the paste after it is a move, as it was before the command.
|
||||
self.pending_move = move_before;
|
||||
if let Some(dirty) = dirty_before {
|
||||
self.dirty = dirty;
|
||||
}
|
||||
@@ -482,7 +492,8 @@ impl Session {
|
||||
/// as it was (opening a document is no edit to undo there). Failed: the documents the command opened close again and the first document is
|
||||
/// active and as it was.
|
||||
fn finish_elsewhere(&mut self, context: ElsewhereContext, result: Result<Value, CmdError>) -> Result<Value, CmdError> {
|
||||
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before } = context;
|
||||
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before } =
|
||||
context;
|
||||
// Another document is a state change the input method has to see, never an IME edit.
|
||||
self.ime_edit_outcome = ImeEditOutcome::default();
|
||||
match &result {
|
||||
@@ -514,6 +525,9 @@ impl Session {
|
||||
self.undo_evicted = ev;
|
||||
self.column = c;
|
||||
}
|
||||
// The command failed, so the tracked move it would have dropped is still
|
||||
// there: the paste after it is a move, as it was before the command.
|
||||
self.pending_move = move_before;
|
||||
}
|
||||
if let Some(b) = blocks_before {
|
||||
self.building_blocks = b;
|
||||
|
||||
+371
-1
@@ -293,6 +293,15 @@ fn custom_dictionary_words_persist_through_their_file() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confined_sessions_test_is_native_only() {
|
||||
let source = include_str!("tests.rs");
|
||||
assert!(source.contains(
|
||||
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
|
||||
let _guard = crate::custom_dict::DICT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -1043,6 +1052,128 @@ fn bold_toggles_selection_and_caret_word() {
|
||||
assert_eq!(p.props_of_char(9).italic, None);
|
||||
}
|
||||
|
||||
/// A partly formatted selection toggles by its first character, as Word does (#6516).
|
||||
#[test]
|
||||
fn toggles_on_mixed_selection_follow_first_character() {
|
||||
// `Abc abc` with `fmt` set by `cmd`, then `cmd` with `v` on the selection `from` → `to`.
|
||||
let toggled = |cmd: &str, fmt: (usize, usize), from: usize, to: usize, v: serde_json::Value| -> String {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Abc abc"}));
|
||||
let sel = |s: &mut Session, a: usize, b: usize| {
|
||||
run(s, "select.range", json!({"anchor": {"block": 0, "off": a}, "focus": {"block": 0, "off": b}}));
|
||||
};
|
||||
sel(&mut s, fmt.0, fmt.1);
|
||||
run(&mut s, cmd, json!({"value": true}));
|
||||
sel(&mut s, from, to);
|
||||
run(&mut s, cmd, v);
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
(0..7)
|
||||
.map(|i| {
|
||||
let c = p.props_of_char(i);
|
||||
match cmd {
|
||||
"format.italic" => c.italic == Some(true),
|
||||
"format.underline" => c.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None),
|
||||
_ => c.bold == Some(true),
|
||||
}
|
||||
})
|
||||
.map(|on| if on { 'F' } else { '.' })
|
||||
.collect()
|
||||
};
|
||||
let t = || json!({});
|
||||
for cmd in ["format.bold", "format.italic", "format.underline"] {
|
||||
// `FFF....`: a selection starting on formatted text removes the format from all of it.
|
||||
assert_eq!(toggled(cmd, (0, 3), 2, 5, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, t()), ".......", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 1, 7, t()), "F......", "{cmd}");
|
||||
// Made right to left: still the first character in document order.
|
||||
assert_eq!(toggled(cmd, (0, 3), 5, 2, t()), "FF.....", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (0, 3), 7, 0, t()), ".......", "{cmd}");
|
||||
// `....FFF`: a selection starting on plain text applies it to all of it.
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, t()), "FFFFFFF", "{cmd}");
|
||||
// An explicit value still sets.
|
||||
assert_eq!(toggled(cmd, (0, 3), 0, 7, json!({"value": true})), "FFFFFFF", "{cmd}");
|
||||
assert_eq!(toggled(cmd, (4, 7), 0, 7, json!({"value": false})), ".......", "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection that starts in an empty paragraph: Word decides from the first text character, not
|
||||
/// from the empty paragraph's mark (observed in Word for Windows, #6516 review).
|
||||
#[test]
|
||||
fn toggle_on_a_selection_from_an_empty_paragraph_follows_the_first_text() {
|
||||
let toggled = |mark_bold: bool, text_bold: bool| -> Option<bool> {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "abc"}));
|
||||
let first = Pos::body(0, 0);
|
||||
s.doc.para_mut(first.story, &first.path).unwrap().mark.bold = Some(mark_bold);
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({"value": text_bold}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 1, "off": 3}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold
|
||||
};
|
||||
// A bold empty paragraph before plain text: Bold goes on.
|
||||
assert_eq!(toggled(true, false), Some(true));
|
||||
// A plain empty paragraph before bold text: Bold comes off.
|
||||
assert_eq!(toggled(false, true), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
|
||||
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
|
||||
let bold_word = |text: &str, caret: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": text}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap().clone();
|
||||
p.text.char_indices().filter(|&(i, _)| p.props_of_char(i).bold == Some(true)).map(|(_, c)| c).collect::<String>()
|
||||
};
|
||||
assert_eq!(bold_word("don’t stop", 1), "don’t");
|
||||
assert_eq!(bold_word("the dogs’ bone", 5), "dogs’");
|
||||
assert_eq!(bold_word("’tis here", 3), "’tis");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_word_takes_a_typographic_apostrophe() {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "don’t stop"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 1}}));
|
||||
run(&mut s, "select.word", json!({}));
|
||||
let (a, b) = s.sel.ordered();
|
||||
assert_eq!((a.off, b.off), (0, 8), "`don’t ` with its trailing space, as Word selects it (#6517)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thesaurus_at_a_caret_looks_up_a_quoted_word_without_its_quotes() {
|
||||
// The word unit now takes `’`, so `‘good’` gives `good’`; the lookup drops enclosing quotes.
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "a ‘good’ day"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
|
||||
let r = run(&mut s, "review.thesaurus", json!({}));
|
||||
assert_eq!(r["word"], json!("good"));
|
||||
assert!(r["synonyms"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_synonym_replaces_the_word_and_keeps_its_quotes() {
|
||||
// The range a chosen synonym replaces (the context menu's): the word without its quotes or the
|
||||
// space after it, while an apostrophe inside a word stays part of it (#6517).
|
||||
let word = |text: &str, caret: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": text, "raw": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": caret}}));
|
||||
let (a, b) = crate::cmd::review::thesaurus_word(&s).unwrap();
|
||||
s.set_selection(crate::Selection { anchor: a, focus: b });
|
||||
run(&mut s, "text.insert", json!({"text": "fine", "raw": true}));
|
||||
s.doc.plain_text(StoryRef::Body)
|
||||
};
|
||||
assert_eq!(word("a ‘good’ day", 6), "a ‘fine’ day");
|
||||
assert_eq!(word("a 'good' day", 4), "a 'fine' day");
|
||||
assert_eq!(word("a good day", 3), "a fine day");
|
||||
assert_eq!(word("don’t go", 1), "fine go");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn border_toggles_and_saves() {
|
||||
use wordcraft_doc::props::Border;
|
||||
@@ -2054,6 +2185,88 @@ fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
|
||||
assert!(r.bold_cs, "drawn bold as complex script");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_merge_formatting_leaves_plain_what_the_source_draws_plain() {
|
||||
// #4852 review: a run marked `w:cs` is bold and italic only by `w:bCs` and `w:iCs`, so one
|
||||
// with `w:b` and `w:i` alone is drawn plain and pastes plain; one with `w:bCs` pastes bold.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "x"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let pasted = |s: &Session, props: wordcraft_doc::CharProps| {
|
||||
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย");
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| p.runs.iter_mut().for_each(|r| r.props = props.clone()));
|
||||
}
|
||||
crate::cmd::paste::merge_formatting(s, &mut frag);
|
||||
let mut out = Vec::new();
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(None, &r.props))));
|
||||
}
|
||||
out
|
||||
};
|
||||
let cs = wordcraft_doc::CharProps { cs: Some(true), bold: Some(true), italic: Some(true), ..Default::default() };
|
||||
for r in pasted(&s, cs.clone()) {
|
||||
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs, "{r:?}");
|
||||
}
|
||||
for r in pasted(&s, wordcraft_doc::CharProps { bold_cs: Some(true), ..cs }) {
|
||||
assert!(r.bold && r.bold_cs && !r.italic_cs, "{r:?}");
|
||||
}
|
||||
// An unmarked run shows `w:b` in both scripts.
|
||||
for r in pasted(&s, wordcraft_doc::CharProps { bold: Some(true), ..Default::default() }) {
|
||||
assert!(r.bold && r.bold_cs, "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_merge_formatting_keeps_a_character_styles_emphasis_not_a_paragraph_styles() {
|
||||
// #7177 review, measured in Word for Windows: Merge Formatting keeps the bold, italic,
|
||||
// underline and strikethrough a character style gives the source, as direct formatting, but
|
||||
// drops a paragraph style's.
|
||||
use wordcraft_doc::props::Underline;
|
||||
use wordcraft_doc::styles::{Style, StyleKind};
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "x"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let on = wordcraft_doc::CharProps {
|
||||
bold: Some(true),
|
||||
bold_cs: Some(true),
|
||||
italic: Some(true),
|
||||
italic_cs: Some(true),
|
||||
underline: Some(Underline::Single),
|
||||
strike: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let sheet = Arc::make_mut(&mut s.doc.styles);
|
||||
sheet.upsert(Style { id: "ChEmph".into(), name: "ChEmph".into(), kind: StyleKind::Character, chr: on.clone(), ..Default::default() });
|
||||
sheet.upsert(Style { id: "PEmph".into(), name: "PEmph".into(), kind: StyleKind::Paragraph, chr: on, ..Default::default() });
|
||||
let pasted = |s: &Session, para_style: Option<&str>, props: wordcraft_doc::CharProps| {
|
||||
let mut frag = wordcraft_doc::edit::Fragment::from_text("ไทย Thai");
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| {
|
||||
p.props.style = para_style.map(str::to_string);
|
||||
p.runs.iter_mut().for_each(|r| r.props = props.clone());
|
||||
});
|
||||
}
|
||||
crate::cmd::paste::merge_formatting(s, &mut frag);
|
||||
let mut out = Vec::new();
|
||||
for b in &mut frag.blocks {
|
||||
crate::cmd::paste::each_para(b, 0, &mut |p| {
|
||||
out.extend(p.runs.iter().map(|r| s.doc.styles.resolve_char(p.props.style.as_deref(), &r.props)));
|
||||
});
|
||||
}
|
||||
out
|
||||
};
|
||||
for cs in [None, Some(true)] {
|
||||
for r in pasted(&s, None, wordcraft_doc::CharProps { style: Some("ChEmph".into()), cs, ..Default::default() }) {
|
||||
assert!(r.bold && r.bold_cs && r.italic && r.italic_cs && r.strike, "character style, cs {cs:?}: {r:?}");
|
||||
assert_eq!(r.underline, Underline::Single, "character style, cs {cs:?}");
|
||||
}
|
||||
for r in pasted(&s, Some("PEmph"), wordcraft_doc::CharProps { cs, ..Default::default() }) {
|
||||
assert!(!r.bold && !r.bold_cs && !r.italic && !r.italic_cs && !r.strike, "paragraph style, cs {cs:?}: {r:?}");
|
||||
assert_eq!(r.underline, Underline::None, "paragraph style, cs {cs:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
|
||||
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
|
||||
@@ -7301,6 +7514,64 @@ fn saving_a_text_file_over_itself_saves_the_document() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #6131: File › Export to DOCX, ODT or RTF writes a copy (`copy: true`). It made the copy the
|
||||
/// document's file and cleared its unsaved changes, so the next Save went to the copy and the
|
||||
/// original kept its old text. The copy has the edits; the document keeps its file, its changes
|
||||
/// and its save stamps.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn exporting_a_copy_keeps_the_documents_file() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-engine-export-copy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let body = |p: &std::path::Path| crate::io::open_path(p).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
|
||||
for ext in ["docx", "odt", "rtf"] {
|
||||
let original = dir.join(format!("a-{ext}.docx"));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "first"}));
|
||||
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
let stamps = (s.doc.core.revision, s.doc.core.modified.clone());
|
||||
let copy = dir.join(format!("copy.{ext}"));
|
||||
let r = run(&mut s, "file.saveAs", json!({"path": copy.to_string_lossy(), "copy": true}));
|
||||
assert_eq!(r["saved"], true, "{ext}");
|
||||
assert_eq!(body(©), "first edited", "{ext}: the copy has the edits");
|
||||
assert_eq!(s.path.as_deref(), Some(original.as_path()), "{ext}: the document keeps its file");
|
||||
assert!(s.dirty, "{ext}: the document keeps its unsaved changes");
|
||||
assert_eq!((s.doc.core.revision, s.doc.core.modified.clone()), stamps, "{ext}: the document's save stamps are untouched");
|
||||
run(&mut s, "file.save", json!({}));
|
||||
assert_eq!(body(&original), "first edited", "{ext}: Save still writes the original");
|
||||
assert!(!s.dirty);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A copy with no path would open the Save As picker on an untitled document (whose answer is an
|
||||
/// ordinary save that adopts the file) or fall back to the open file's path and overwrite it while
|
||||
/// leaving the document dirty: refused in both cases (#6131 review).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_copy_without_a_path_is_refused() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "first"}));
|
||||
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("copy"), "{e}");
|
||||
assert!(s.ui_requests.is_empty(), "no picker opens");
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-engine-copy-no-path-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("doc.docx");
|
||||
run(&mut s, "file.save", json!({"path": original.to_string_lossy()}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
let e = s.run("file.save", &json!({"copy": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("copy"), "{e}");
|
||||
assert!(s.dirty, "the document keeps its unsaved changes");
|
||||
let on_disk = crate::io::open_path(&original).unwrap().plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(on_disk, "first", "the original file on disk was not overwritten");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A Markdown file saved as another Markdown file is that file from now on: the next save goes
|
||||
/// there and the first file stays as it was. Other formats keep the #2376 rule.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -7407,7 +7678,6 @@ fn scratch_dir(name: &str) -> std::path::PathBuf {
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn tiny_png() -> Vec<u8> {
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 30, 30, 255])).clone()),
|
||||
@@ -9734,6 +10004,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
|
||||
assert_eq!(text(&s), "Q");
|
||||
}
|
||||
|
||||
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
|
||||
#[test]
|
||||
fn change_case_follows_turkic_language_mapping() {
|
||||
// 1. Turkish (tr-TR): all 5 modes
|
||||
// Capitalize Each Word (title)
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Işık");
|
||||
|
||||
// UPPERCASE
|
||||
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
|
||||
assert_eq!(text(&s), "İSTANBUL IŞIK");
|
||||
|
||||
// lowercase
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(text(&s), "istanbul ışık");
|
||||
|
||||
// sentence case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
|
||||
assert_eq!(text(&s), "İstanbul. Işık.");
|
||||
|
||||
// toggle case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
|
||||
assert_eq!(text(&s), "iSTANBUL ıŞIK");
|
||||
|
||||
// 2. Azerbaijani (az-AZ)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 3. Crimean Tatar (crh)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 4. English control (en-US): unchanged Unicode default
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "Istanbul");
|
||||
|
||||
// 5. Mixed-language selection: Turkish run followed by English run
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Istanbul");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_sentence_ignores_decimal_points() {
|
||||
// #3485: Sentence case should not capitalize after decimal points.
|
||||
@@ -9806,6 +10147,9 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
|
||||
#[test]
|
||||
fn markup_pdf_takes_the_track_changes_option_colours() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
|
||||
// A fixed creation date: without one each PDF is stamped with the current time, and the
|
||||
// exports compared below differ when a clock second ticks over between them.
|
||||
s.doc.core.created = "2026-01-01T00:00:00Z".into();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
|
||||
@@ -15341,6 +15685,32 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
for i in 0..80 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
|
||||
}
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 2, "expected a multi-page document, got {pages}");
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let start = s.sel.focus.clone();
|
||||
// Advance page by page until the last page, then one more PageDown must reach the end.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
}
|
||||
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
|
||||
// Step back page by page until page 0, then one more PageUp must reach the start.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
}
|
||||
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -41,6 +41,41 @@ fn assert_fixture_font(s: &mut Session) {
|
||||
assert!(runs > 0, "the font check must inspect laid-out body text");
|
||||
}
|
||||
|
||||
/// A document that just spills onto a second page: the most lines `make` can put on one page,
|
||||
/// then space before the last paragraph until it moves to page 2 ([`spill_last_paragraph`]).
|
||||
/// The fixtures are set in the bundled [`FIXTURE_FONT`], but a fixed line count still depends on
|
||||
/// that font's exact metrics and the page setup, so the tests find the spill point instead.
|
||||
fn just_spilling(make: impl Fn(usize) -> Session) -> Session {
|
||||
let mut lines = 10;
|
||||
while make(lines + 1).layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
assert!(lines < 120, "{lines} lines still fit on one page");
|
||||
}
|
||||
let mut s = make(lines);
|
||||
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page");
|
||||
spill_last_paragraph(&mut s);
|
||||
s
|
||||
}
|
||||
|
||||
/// Adds space before the last paragraph, half a point at a time, until it moves to page 2. The
|
||||
/// document then overflows by less than half a point, which any font reduction it is fitted with
|
||||
/// brings back.
|
||||
fn spill_last_paragraph(s: &mut Session) {
|
||||
let mut before = match s.doc.body.last().map(|b| &**b) {
|
||||
Some(wordcraft_doc::Block::Para(p)) => p.props.space_before.unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
};
|
||||
while s.layout().pages.len() < 2 {
|
||||
before += 0.5;
|
||||
assert!(before <= 200.0, "space before the last paragraph never moved it to page 2");
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = s.doc.body.last_mut().map(std::sync::Arc::make_mut) {
|
||||
p.props.space_before = Some(before);
|
||||
}
|
||||
s.touch();
|
||||
s.relayout();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_on_single_page() {
|
||||
let mut s = create_multiline_doc(5);
|
||||
@@ -144,15 +179,20 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
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);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
let at_11_4 = |lines: usize| {
|
||||
let mut s = create_multiline_doc(lines);
|
||||
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);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.touch();
|
||||
s
|
||||
};
|
||||
let mut s = just_spilling(at_11_4);
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -162,7 +202,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
|
||||
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
|
||||
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, fine-grained steps (0.1..0.4) succeed (11.4 -> 11.0 pt).
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
|
||||
s.doc = doc_backup;
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
|
||||
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
|
||||
@@ -877,7 +917,7 @@ 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(26);
|
||||
let mut s = just_spilling(create_multiline_doc);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -894,12 +934,10 @@ fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
assert_eq!(reopened_doc.fit_state.as_ref().map(|f| f.cum_delta), Some(0.5));
|
||||
assert!(reopened_doc.custom_props.is_empty(), "custom_props must remain empty");
|
||||
|
||||
// Reopen into a new session with additional spill
|
||||
// Reopen into a new session with additional spill: the last paragraph moves to page 2 again
|
||||
let mut s2 = Session::new(reopened_doc);
|
||||
let extra_p = wordcraft_doc::Paragraph::with_text("Extra overflow paragraph.", CharProps::default());
|
||||
s2.doc.body.push(wordcraft_doc::para_block(extra_p));
|
||||
s2.touch();
|
||||
s2.relayout();
|
||||
assert_eq!(s2.layout().pages.len(), 1);
|
||||
spill_last_paragraph(&mut s2);
|
||||
|
||||
// Second fit on reopened document preserves previous 0.5 delta, allowing only remaining 0.5 pt up to 1.0 cap
|
||||
let res2 = s2.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
|
||||
|
||||
@@ -1653,6 +1653,38 @@ fn a_link_keeps_a_selection_it_cannot_retype() {
|
||||
assert_eq!(s.doc.field_ranges(StoryRef::Body).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_selection_in_one_paragraph_is_not_one_line() {
|
||||
// A column (block) selection over the wrapped lines of one paragraph: both its ends are in
|
||||
// that paragraph, but it holds a piece of each line, so Word shows <<Selection in Document>>
|
||||
// for it and the text to display can't retype it (#8581).
|
||||
let mut s = typed("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau");
|
||||
let (first, second) = {
|
||||
let l = s.layout();
|
||||
let len = s.doc.para_at(&Pos::body(0, 0)).unwrap().text.len();
|
||||
let mut top = None;
|
||||
let mut first = None;
|
||||
let mut second = None;
|
||||
for off in 0..=len {
|
||||
let Some(c) = l.caret_on(&Pos::body(0, off), 0) else { continue };
|
||||
if top.is_some_and(|t| t != c.top) && second.is_none() {
|
||||
second = Some(off + 10);
|
||||
break;
|
||||
}
|
||||
if top.is_none() {
|
||||
top = Some(c.top);
|
||||
first = Some(off);
|
||||
}
|
||||
}
|
||||
(first.expect("the paragraph is laid out"), second.expect("the paragraph wraps"))
|
||||
};
|
||||
run(&mut s, "select.column", json!({"anchor": Pos::body(0, first), "focus": Pos::body(0, second)}));
|
||||
let segs = s.column_segments().expect("the block is one paragraph's lines").to_vec();
|
||||
assert_eq!(segs.len(), 2, "the block holds a piece of each of the paragraph's two lines");
|
||||
assert!(segs.iter().all(|(a, b)| a.path == segs[0].0.path && b.path == segs[0].0.path), "both pieces are in one paragraph");
|
||||
assert!(!crate::cmd::insert::selection_is_one_line(&s), "a column selection is not one line of text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_then_selecting_then_typing_are_two_undo_steps() {
|
||||
// #419: a selection that moves the insertion point ends the typing group, like a caret move.
|
||||
@@ -3416,13 +3448,22 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "İNgilizce ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
|
||||
// #3503: two initial capitals and caps-lock with a stray İ in English.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "Wİrd ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "wİRD ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
|
||||
}
|
||||
|
||||
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
|
||||
/// each run's own language; other languages keep the Unicode default.
|
||||
#[test]
|
||||
fn change_case_follows_turkic_case_mapping() {
|
||||
for tag in ["tr-TR", "az-AZ"] {
|
||||
for tag in ["tr-TR", "az-AZ", "crh"] {
|
||||
for (mode, input, want) in [
|
||||
("upper", "istanbul", "İSTANBUL"),
|
||||
("lower", "IŞIK", "ışık"),
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! A value chosen in a content control in place of its placeholder (a list entry, a date, a check
|
||||
//! box's mark) takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 Part 1
|
||||
//! §17.5.2.27), as typed text does (#3116). Packages are hand-written: the controls WordCraft
|
||||
//! inserts carry no run properties.
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_engine::io::{open_bytes, save_bytes};
|
||||
|
||||
const W: &str =
|
||||
r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml""#;
|
||||
const RELS: &str = r#"xmlns="http://schemas.openxmlformats.org/package/2006/relationships""#;
|
||||
const TYPE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
/// Opens a package with `body` and a grey Placeholder Text character style.
|
||||
fn open(body: &str) -> wordcraft_doc::Document {
|
||||
let styles = r#"<w:style w:type="character" w:styleId="PlaceholderText"><w:name w:val="Placeholder Text"/><w:rPr><w:color w:val="808080"/></w:rPr></w:style>"#;
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, value) in [
|
||||
(
|
||||
"_rels/.rels",
|
||||
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/officeDocument" Target="word/document.xml"/></Relationships>"#),
|
||||
),
|
||||
(
|
||||
"word/_rels/document.xml.rels",
|
||||
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/styles" Target="styles.xml"/></Relationships>"#),
|
||||
),
|
||||
("word/document.xml", format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#)),
|
||||
("word/styles.xml", format!(r#"<w:styles {W}>{styles}</w:styles>"#)),
|
||||
] {
|
||||
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
open_bytes("form.docx", &zip.finish().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// A paragraph holding a control of `kind` (its `w:sdtPr` type element) tagged `tag`. Its
|
||||
/// placeholder is grey and boxed; its run properties ask for blue Source Serif 4 at 14 pt.
|
||||
fn control(tag: &str, kind: &str) -> String {
|
||||
let own = r#"<w:rPr><w:rFonts w:ascii="Source Serif 4" w:hAnsi="Source Serif 4"/><w:color w:val="1F4E79"/><w:sz w:val="28"/></w:rPr>"#;
|
||||
let shown =
|
||||
r#"<w:rPr><w:rStyle w:val="PlaceholderText"/><w:color w:val="808080"/><w:bdr w:val="single" w:sz="4" w:space="0" w:color="808080"/></w:rPr>"#;
|
||||
format!(
|
||||
r#"<w:p><w:sdt><w:sdtPr>{own}<w:tag w:val="{tag}"/><w:showingPlcHdr/>{kind}</w:sdtPr><w:sdtContent><w:r>{shown}<w:t>Choose</w:t></w:r></w:sdtContent></w:sdt></w:p>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// The formatting of the control's first character, and the control's own run properties.
|
||||
fn formatting(d: &wordcraft_doc::Document, tag: &str) -> (CharProps, CharProps) {
|
||||
let r = d.control_ranges(StoryRef::Body).into_iter().find(|r| r.control.tag == tag).unwrap();
|
||||
let at = r.content_start();
|
||||
(d.para_at(&at).unwrap().props_of_char(at.off).clone(), r.control.run_props.clone().unwrap())
|
||||
}
|
||||
|
||||
/// What shows of a run's formatting here: colour, font, size and box.
|
||||
fn look(p: &CharProps) -> impl PartialEq + std::fmt::Debug {
|
||||
(p.color, p.font.clone(), p.size, p.border)
|
||||
}
|
||||
|
||||
/// A list entry, a date or a check box's mark chosen in place of the placeholder takes the
|
||||
/// control's run properties, as typed text does; it kept the placeholder's grey and box. A saved
|
||||
/// file keeps the value's formatting.
|
||||
#[test]
|
||||
fn choosing_over_a_placeholder_takes_the_controls_formatting() {
|
||||
let entries = r#"<w:listItem w:displayText="Small" w:value="S"/><w:listItem w:displayText="Large" w:value="L"/>"#;
|
||||
let choices = [
|
||||
("size", format!("<w:dropDownList>{entries}</w:dropDownList>"), "developer.chooseItem", json!({"control": "size", "index": 1})),
|
||||
(
|
||||
"due",
|
||||
r#"<w:date><w:dateFormat w:val="d MMMM yyyy"/></w:date>"#.into(),
|
||||
"developer.setDate",
|
||||
json!({"control": "due", "date": "2026-12-01"}),
|
||||
),
|
||||
("ok", r#"<w14:checkbox><w14:checked w14:val="0"/></w14:checkbox>"#.into(), "developer.toggleCheckBox", json!({"control": "ok"})),
|
||||
];
|
||||
let body: String = choices.iter().map(|(tag, kind, ..)| control(tag, kind)).collect();
|
||||
let mut s = Session::new(open(&body));
|
||||
for (tag, _, command, params) in &choices {
|
||||
let (placeholder, own) = formatting(&s.doc, tag);
|
||||
assert_ne!(look(&placeholder), look(&own), "{tag}: the placeholder is formatted apart from its control");
|
||||
s.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}"));
|
||||
assert_eq!(look(&formatting(&s.doc, tag).0), look(&own), "{tag}: {command} gives the control's run properties");
|
||||
}
|
||||
let saved = open_bytes("form.docx", &save_bytes("form.docx", &s.doc).unwrap()).unwrap();
|
||||
for (tag, ..) in &choices {
|
||||
let (value, own) = formatting(&saved, tag);
|
||||
assert_eq!(look(&value), look(&own), "{tag}: the saved value keeps the control's run properties");
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,105 @@ fn a_date_field_in_a_header_is_refreshed_too() {
|
||||
assert_eq!(found, [today], "the header's field is refreshed as well as the body's");
|
||||
}
|
||||
|
||||
/// A document whose `docDefaults` set `lang`, so a field run that names no language inherits it,
|
||||
/// as a German Word document does.
|
||||
fn open_body_in_lang(lang: &str, body: &str) -> wordcraft_doc::Document {
|
||||
let rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
|
||||
let styles = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:lang w:val="{lang}"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style></w:styles>"#
|
||||
);
|
||||
let doc = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
|
||||
);
|
||||
wordcraft_engine::io::open_bytes(
|
||||
"d.docx",
|
||||
&zip(&[("_rels/.rels", rels), ("word/document.xml", &doc), ("word/_rels/document.xml.rels", doc_rels), ("word/styles.xml", &styles)]),
|
||||
)
|
||||
.expect("opens")
|
||||
}
|
||||
|
||||
/// German documents carry their language in `docDefaults`, not on each field run. A `DATE` field
|
||||
/// without `\@` therefore uses `dd.MM.yyyy`, and `MMMM`/`dddd` name the day in German, on open
|
||||
/// and on an explicit refresh, for `de-DE`, `de-AT` and `de-CH` (#7146).
|
||||
#[test]
|
||||
fn german_date_fields_inherit_the_document_default_language() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy";
|
||||
for lang in ["de-DE", "de-AT", "de-CH"] {
|
||||
let d = open_body_in_lang(
|
||||
lang,
|
||||
&format!(
|
||||
"<w:p>{}</w:p><w:p>{}</w:p>",
|
||||
field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false),
|
||||
field("DATE", "1/1/2020", false)
|
||||
),
|
||||
);
|
||||
let expected = wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some(lang));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got.len(), 2, "{lang}");
|
||||
assert_eq!(got[0].1, expected, "{lang}: weekday and month names come from docDefaults");
|
||||
assert_ne!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, None), "{lang}: not the English names");
|
||||
assert_eq!(
|
||||
got[1].1,
|
||||
wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)),
|
||||
"{lang}: a DATE field without a picture uses the German default"
|
||||
);
|
||||
// Saving and reopening keeps the inherited language, and an explicit refresh does not
|
||||
// fall back to English.
|
||||
let written = wordcraft_docx::write(&d).unwrap();
|
||||
let mut reopened = wordcraft_engine::io::open_bytes("reopened.docx", &written).unwrap();
|
||||
wordcraft_engine::cmd::references::refresh_date_fields(&mut reopened);
|
||||
let got = fields(&reopened);
|
||||
assert_eq!(got[0].1, expected, "{lang}: after round-trip");
|
||||
assert_eq!(got[1].1, wordcraft_engine::cmd::insert::format_date_in("dd.MM.yyyy", Some(lang)), "{lang}: after round-trip");
|
||||
}
|
||||
}
|
||||
|
||||
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
|
||||
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
|
||||
#[test]
|
||||
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
|
||||
const PICTURE: &str = "ddd, d. MMM yyyy";
|
||||
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
|
||||
// The abbreviations at a fixed date, independent of when the test runs.
|
||||
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
|
||||
}
|
||||
|
||||
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
|
||||
/// English result cached in the fixture is replaced with German weekday and month names.
|
||||
#[test]
|
||||
fn a_german_time_field_uses_german_names() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy 'um' HH:mm";
|
||||
let d =
|
||||
open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"TIME \@ "{PICTURE}""#), "Wednesday, 1 January 2020 um 00:00", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].0, format!(r#"TIME \@ "{PICTURE}""#));
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
|
||||
}
|
||||
|
||||
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
|
||||
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
|
||||
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
|
||||
/// of the same formatter at a fixed January instant.
|
||||
#[test]
|
||||
fn austrian_german_documents_use_jaenner() {
|
||||
const PICTURE: &str = "dddd, d. MMMM yyyy";
|
||||
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
|
||||
let got = fields(&d);
|
||||
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
|
||||
|
||||
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
|
||||
assert_eq!(january("de-AT", "MMMM"), "Jänner");
|
||||
assert_eq!(january("de-AT", "MMM"), "Jän");
|
||||
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
|
||||
for lang in ["de-DE", "de-CH", "de"] {
|
||||
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
|
||||
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
|
||||
/// FIB, one compressed text piece, and the Clx that points at it.
|
||||
fn binary_doc_with_stale_date() -> Vec<u8> {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
mod comment_ids;
|
||||
mod content_controls;
|
||||
mod date_fields;
|
||||
mod macro_packages;
|
||||
mod odt_charts;
|
||||
|
||||
@@ -25,7 +25,7 @@ mod lookup;
|
||||
mod names;
|
||||
|
||||
use face::{BUNDLED, FontBytes};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
|
||||
pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled, bundled_inter};
|
||||
#[cfg(test)]
|
||||
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -42,14 +42,52 @@ pub(crate) use names::{last_resort_face, legacy_family};
|
||||
|
||||
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
|
||||
/// Fixed-capacity FIFO cache shared by outline and hinting tables so old zoom/script entries evict
|
||||
/// incrementally instead of wiping the whole table at once.
|
||||
pub(super) struct BoundedCache<K, V> {
|
||||
map: HashMap<K, V>,
|
||||
order: std::collections::VecDeque<K>,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
impl<K: Eq + std::hash::Hash + Clone, V> BoundedCache<K, V> {
|
||||
pub(super) fn new(cap: usize) -> Self {
|
||||
Self { map: HashMap::new(), order: std::collections::VecDeque::new(), cap: cap.max(1) }
|
||||
}
|
||||
|
||||
pub(super) fn get(&self, key: &K) -> Option<&V> {
|
||||
self.map.get(key)
|
||||
}
|
||||
|
||||
pub(super) fn insert(&mut self, key: K, val: V) {
|
||||
if let Some(existing) = self.map.get_mut(&key) {
|
||||
*existing = val;
|
||||
return;
|
||||
}
|
||||
while self.map.len() >= self.cap {
|
||||
let Some(oldest) = self.order.pop_front() else {
|
||||
break;
|
||||
};
|
||||
self.map.remove(&oldest);
|
||||
}
|
||||
self.order.push_back(key.clone());
|
||||
self.map.insert(key, val);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Process-wide font database.
|
||||
pub struct FontDb {
|
||||
faces: RwLock<Vec<Arc<FontFace>>>,
|
||||
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
|
||||
outlines: Mutex<BoundedCache<(u32, u32), Arc<BezPath>>>,
|
||||
/// Screen-hinted outlines per (face, glyph, ppem bits); `None` where the face can't be hinted.
|
||||
hinted: Mutex<HashMap<(u32, u32, u32), Option<Arc<BezPath>>>>,
|
||||
hinted: Mutex<BoundedCache<(u32, u32, u32), Option<Arc<BezPath>>>>,
|
||||
/// Light hinting instances per (face, ppem bits); `None` where the face can't be hinted.
|
||||
hinters: Mutex<HashMap<(u32, u32), Option<Arc<HintingInstance>>>>,
|
||||
hinters: Mutex<BoundedCache<(u32, u32), Option<Arc<HintingInstance>>>>,
|
||||
/// Fallback faces found per (character, excluded face), valid while the face count is the
|
||||
/// one stored (faces are only ever added). Layout asks once per uncovered character, and the
|
||||
/// search sorts every loaded face, so without this text in a script the requested font lacks
|
||||
@@ -63,6 +101,8 @@ pub struct FontDb {
|
||||
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
run_style_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock<Vec<CatalogEntry>>,
|
||||
/// Fonts the user added at run time, and the folder they are stored in (#582).
|
||||
@@ -121,9 +161,9 @@ impl FontDb {
|
||||
}
|
||||
Self {
|
||||
faces: RwLock::new(faces),
|
||||
outlines: Mutex::new(HashMap::new()),
|
||||
hinted: Mutex::new(HashMap::new()),
|
||||
hinters: Mutex::new(HashMap::new()),
|
||||
outlines: Mutex::new(BoundedCache::new(face::OUTLINE_CACHE_MAX)),
|
||||
hinted: Mutex::new(BoundedCache::new(face::HINTED_CACHE_MAX)),
|
||||
hinters: Mutex::new(BoundedCache::new(face::HINTER_CACHE_MAX)),
|
||||
fallbacks: RwLock::new(FallbackCache::default()),
|
||||
run_fallbacks: RwLock::new(RunFallbackCache::default()),
|
||||
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
|
||||
@@ -133,6 +173,8 @@ impl FontDb {
|
||||
diagram_search_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
run_style_hook: Mutex::new(None),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
user: RwLock::new(user::UserFonts::default()),
|
||||
|
||||
@@ -13,6 +13,16 @@ pub fn bundled() -> &'static [&'static [u8]] {
|
||||
BUNDLED
|
||||
}
|
||||
|
||||
/// The bundled Inter Regular and SemiBold, each with its style name: the same bytes as in [`bundled`], so a caller
|
||||
/// adds no second copy to the binary. The interface draws with them behind the suite's Inter, which is cut to Latin,
|
||||
/// Greek and Cyrillic.
|
||||
pub fn bundled_inter() -> [(&'static str, &'static [u8]); 2] {
|
||||
[("Regular", INTER_REGULAR), ("SemiBold", INTER_SEMIBOLD)]
|
||||
}
|
||||
|
||||
static INTER_REGULAR: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
static INTER_SEMIBOLD: &[u8] = include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf");
|
||||
|
||||
pub(super) static BUNDLED: &[&[u8]] = &[
|
||||
include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSans3-Semibold.ttf"),
|
||||
@@ -23,9 +33,9 @@ pub(super) static BUNDLED: &[&[u8]] = &[
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-Semibold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-Bold.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/SourceSerif4-BoldIt.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"),
|
||||
INTER_REGULAR,
|
||||
include_bytes!("../../../../assets/fonts/Inter-Medium.ttf"),
|
||||
include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf"),
|
||||
INTER_SEMIBOLD,
|
||||
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"),
|
||||
];
|
||||
|
||||
@@ -541,9 +551,13 @@ fn is_explicit_serif(name: &str) -> bool {
|
||||
|
||||
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
|
||||
|
||||
pub(super) const OUTLINE_CACHE_MAX: usize = 50_000;
|
||||
/// Unhinted glyph outlines kept per (face, glyph).
|
||||
pub(super) const OUTLINE_CACHE_MAX: usize = 16_384;
|
||||
/// Screen-hinted outlines kept per (face, glyph, ppem bits); narrower than [`OUTLINE_CACHE_MAX`]
|
||||
/// because zoom changes create entries per size.
|
||||
pub(super) const HINTED_CACHE_MAX: usize = 8_192;
|
||||
/// Hinting instances kept (one per face and text size on screen).
|
||||
pub(super) const HINTER_CACHE_MAX: usize = 256;
|
||||
pub(super) const HINTER_CACHE_MAX: usize = 128;
|
||||
/// Sizes hinted, in device pixels per em: below, text is too small to read anyway; above, the
|
||||
/// half-pixel hinting moves is invisible (and each size would cost a cache entry).
|
||||
pub(super) const HINT_PPEM: std::ops::RangeInclusive<f32> = 4.0..=96.0;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::face::{FALLBACK_FAMILY, FontFace};
|
||||
use super::fallback_data::{
|
||||
BALLOT_BOXES, DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block,
|
||||
fallback_order,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
|
||||
use super::fallback_data::{
|
||||
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
|
||||
};
|
||||
use super::{Arc, FontDb};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{HashMap, Ordering};
|
||||
@@ -28,7 +29,11 @@ impl FontDb {
|
||||
_ => "Italic",
|
||||
};
|
||||
let styled = self.face(&base.family, style);
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, &[c]) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
base
|
||||
})
|
||||
}
|
||||
|
||||
/// The fallback search, cached per (character, excluded face) until loaded faces or font
|
||||
@@ -70,6 +75,9 @@ impl FontDb {
|
||||
if let Some(face) = self.circle_fallback(c, exclude) {
|
||||
return (Some(face), self.read_faces().len());
|
||||
}
|
||||
if let Some((face, n)) = self.ballot_box_fallback(c, exclude) {
|
||||
return (Some(face), n);
|
||||
}
|
||||
let (found, n) = self.loaded_fallback(c, exclude);
|
||||
if found.is_some() {
|
||||
return (found, n);
|
||||
@@ -97,6 +105,38 @@ impl FontDb {
|
||||
find()
|
||||
}
|
||||
|
||||
/// A ballot box (☐ ☑ ☒, a check box's symbols) the face lacks: the first of the symbol faces
|
||||
/// ([`crate::word::SYMBOL`], in that order) that has all three, so a check box looks the same
|
||||
/// ticked and unticked (#7863). The UI fallback has ☐, drawn with a drop shadow, and ☑ but no
|
||||
/// ☒, which put a box's two states in different fonts. `None` when no listed face has all
|
||||
/// three: the ordinary fallback then. With the face, the number of loaded faces before the
|
||||
/// search: a face loaded during it (by it, or by another thread for a family it had passed)
|
||||
/// leaves that number behind, so the answer isn't cached for the new face list.
|
||||
fn ballot_box_fallback(&self, c: char, exclude: u32) -> Option<(Arc<FontFace>, usize)> {
|
||||
if !BALLOT_BOXES.contains(&c) {
|
||||
return None;
|
||||
}
|
||||
let n = self.read_faces().len();
|
||||
let all = |f: &Arc<FontFace>| f.id != exclude && BALLOT_BOXES.iter().all(|b| f.covers(*b));
|
||||
for family in crate::word::SYMBOL {
|
||||
if let Some(face) = self.find(family, "Regular").filter(all) {
|
||||
return Some((face, n));
|
||||
}
|
||||
// An installed family is loaded only when its files map all three.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
|
||||
if enabled && !self.is_loaded(family) && BALLOT_BOXES.iter().all(|b| self.family_maps(family, *b)) {
|
||||
self.load_cataloged(family);
|
||||
if let Some(face) = self.find(family, "Regular").filter(all) {
|
||||
return Some((face, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// [`Self::search_fallback`] when no loaded face covers `c`: load a system font that does,
|
||||
/// one search at a time.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -199,8 +239,13 @@ impl FontDb {
|
||||
|
||||
/// The face for a run, and the number of loaded faces the search last chose from.
|
||||
fn search_run(&self, chars: &[char], exclude: u32, bold: bool, italic: bool) -> (Option<Arc<FontFace>>, usize) {
|
||||
// A run of ballot boxes draws in their one face, as each of them alone does (#7863).
|
||||
let ballot = chars.first().filter(|_| chars.iter().all(|c| BALLOT_BOXES.contains(c))).and_then(|c| self.ballot_box_fallback(*c, exclude));
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let (mut base, mut checked) = self.loaded_covering(chars, exclude);
|
||||
let (mut base, mut checked) = match ballot {
|
||||
Some((face, n)) => (Some(face), n),
|
||||
None => self.loaded_covering(chars, exclude),
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if base.is_none() {
|
||||
// A character no loaded face covers: load a system font for it, then retry (the run's
|
||||
@@ -235,12 +280,16 @@ impl FontDb {
|
||||
(true, false) => "Bold",
|
||||
_ => "Italic",
|
||||
};
|
||||
let before_style = self.read_faces().len();
|
||||
// The count stays the one `base` was chosen from. `base` is loaded, so the style lookup
|
||||
// only picks among the family's loaded faces and loads nothing: a later count could only
|
||||
// take in a face another thread loaded meanwhile, and cache this answer for faces it never
|
||||
// saw (#7863).
|
||||
let styled = self.face(&base.family, style);
|
||||
if before_style == checked {
|
||||
checked = self.read_faces().len();
|
||||
#[cfg(test)]
|
||||
if let Some(hook) = self.run_style_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
|
||||
hook(self);
|
||||
}
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, chars) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
base
|
||||
@@ -557,3 +606,11 @@ impl FontDb {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Can `styled`, a bold or italic face of `base`'s family, draw `chars` in its place? It must map
|
||||
/// them all, and all three ballot boxes when they are ballot boxes and `base` has all three, so a
|
||||
/// check box's states stay in one face in bold or italic text too (#7863).
|
||||
fn styled_covers(styled: &FontFace, base: &FontFace, chars: &[char]) -> bool {
|
||||
let boxes = chars.iter().all(|c| BALLOT_BOXES.contains(c)) && BALLOT_BOXES.iter().all(|b| base.covers(*b));
|
||||
chars.iter().chain(BALLOT_BOXES.iter().filter(|_| boxes)).all(|c| styled.covers(*c))
|
||||
}
|
||||
|
||||
@@ -242,6 +242,9 @@ pub const RTL_FALLBACKS: &[&str] = &[
|
||||
pub const RTL_FALLBACKS: &[&str] =
|
||||
&["Noto Naskh Arabic", "Noto Sans Arabic", "Noto Sans Hebrew", "Vazirmatn", "Segoe UI", "Arial", "Tahoma", "DejaVu Sans"];
|
||||
|
||||
/// The ballot boxes ☐ ☑ ☒: a check box's unchecked symbol and its two usual checked ones.
|
||||
pub(super) const BALLOT_BOXES: [char; 3] = ['\u{2610}', '\u{2611}', '\u{2612}'];
|
||||
|
||||
/// Families tried (when installed) for characters the loaded fonts lack: CJK, symbols, emoji.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) const SYSTEM_FALLBACKS: &[&str] = &[
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM, HINTER_CACHE_MAX, OUTLINE_CACHE_MAX};
|
||||
use super::face::{FALLBACK_FAMILY, FontBytes, FontFace, HINT_PPEM};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::fallback_data::read_fallback_file;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -220,11 +220,7 @@ impl FontDb {
|
||||
return p.clone();
|
||||
}
|
||||
let p = Arc::new(face.glyph_outline(gid));
|
||||
let mut cache = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.len() >= OUTLINE_CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(key, p.clone());
|
||||
self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
|
||||
p
|
||||
}
|
||||
|
||||
@@ -247,21 +243,13 @@ impl FontDb {
|
||||
None => {
|
||||
// Built outside the lock: running a font's hinting programs takes a while.
|
||||
let h = face.screen_hinter(ppem).map(Arc::new);
|
||||
let mut cache = self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.len() >= HINTER_CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(hkey, h.clone());
|
||||
self.hinters.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(hkey, h.clone());
|
||||
h
|
||||
}
|
||||
}
|
||||
};
|
||||
let p = hinter.and_then(|h| face.hinted_glyph_outline(gid, &h)).map(Arc::new);
|
||||
let mut cache = self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.len() >= OUTLINE_CACHE_MAX {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(key, p.clone());
|
||||
self.hinted.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +154,18 @@ fn screen_hinting_refuses_hostile_sizes() {
|
||||
assert!(db.hinted_outline(&face, u32::MAX, 20.0).is_none_or(|o| o.elements().is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_outline_cache_evicts_oldest_incrementally() {
|
||||
let mut c = BoundedCache::new(2);
|
||||
c.insert(1u32, "a");
|
||||
c.insert(2u32, "b");
|
||||
c.insert(3u32, "c");
|
||||
assert_eq!(c.len(), 2);
|
||||
assert!(c.get(&1).is_none(), "oldest entry evicted");
|
||||
assert_eq!(c.get(&2), Some(&"b"), "newer entry retained");
|
||||
assert_eq!(c.get(&3), Some(&"c"));
|
||||
}
|
||||
|
||||
/// The issue's run (#1549): Thai letters and digits, Latin letters, digits and the baht sign.
|
||||
const THAI_RUN: &str = "[D] น้ำ ค่ำ ปั้น ฝั่ง ปู่ ๑๒๓๔๕๖๗๘๙๐ ฿1,250.50";
|
||||
|
||||
|
||||
@@ -866,6 +866,130 @@ fn circle_checks_face_coverage() {
|
||||
assert_eq!(db.fallback_for('●', primary.id()).unwrap().family, FALLBACK_FAMILY);
|
||||
}
|
||||
|
||||
/// A bundled Source Sans 3 Regular named `family` that maps ☒ (U+2612) too: its ☐–☑ cmap group
|
||||
/// runs on one character further (the next group starts at U+2615, so the groups stay sorted).
|
||||
fn with_every_ballot_box(family: &str) -> Vec<u8> {
|
||||
let mut data = named_face("SourceSans3-Regular.ttf", family);
|
||||
let (from, to) = ([0x2610_u32, 0x2611].map(u32::to_be_bytes).concat(), [0x2610_u32, 0x2612].map(u32::to_be_bytes).concat());
|
||||
let mut patched = 0;
|
||||
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
|
||||
data[at..at + to.len()].copy_from_slice(&to);
|
||||
patched += 1;
|
||||
}
|
||||
assert!(patched > 0);
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_draws_every_state_in_one_face() {
|
||||
// #7863: with the check box's font missing, ☐ and ☑ came from the UI fallback, which has no
|
||||
// ☒, and ☒ from another face, so ticking a box changed how it looked.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
assert!(!primary.covers('☐'), "the requested face lacks the boxes");
|
||||
// A listed symbol face with ☐ and ☑ only, then a later one with all three.
|
||||
db.add_document_fonts(vec![
|
||||
(named_face("SourceSerif4-Regular.ttf", "Apple Symbols"), "Apple Symbols".to_string()),
|
||||
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
]);
|
||||
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").id()).collect();
|
||||
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
|
||||
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), false, false).expect("a face has them");
|
||||
assert_eq!(run.id(), faces[0], "a run of them takes the same face");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_check_box_draws_every_state_in_one_face() {
|
||||
// The listed family's Regular face has all three boxes and its Bold face only ☐ and ☑: bold ☐
|
||||
// and ☑ took the Bold face, and ☒ the Regular one.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.add_document_fonts(vec![
|
||||
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
(named_face("SourceSans3-Bold.ttf", "DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
]);
|
||||
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").id()).collect();
|
||||
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
|
||||
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), true, false).expect("a face has them");
|
||||
assert_eq!(run.id(), faces[0], "a bold run of them takes the same face");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ballot_boxes_load_an_installed_symbol_face() {
|
||||
let dir = font_dir("ballot-boxes");
|
||||
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("DejaVu Sans")).unwrap();
|
||||
// An earlier listed family with only two of the boxes: never loaded for them.
|
||||
std::fs::write(dir.join("TwoBoxes-Regular.ttf"), named_face("SourceSerif4-Regular.ttf", "Apple Symbols")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.set_system_fallback(false);
|
||||
assert!(db.fallback_for('☐', primary.id()).is_some());
|
||||
assert!(!db.is_loaded("DejaVu Sans"), "nothing is loaded with the system fallback off");
|
||||
db.set_system_fallback(true);
|
||||
let found = db.fallback_for('☐', primary.id()).unwrap();
|
||||
assert_eq!(found.family, "DejaVu Sans", "the installed face with all three");
|
||||
assert_eq!(db.fallback_for('☒', primary.id()).unwrap().id(), found.id());
|
||||
assert!(!db.is_loaded("Apple Symbols"), "a listed family without all three is not loaded");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_keeps_one_face_when_a_symbol_face_loads_during_its_search() {
|
||||
// A search for ☐ passed Apple Symbols, not loaded yet, and was loading the installed Segoe UI
|
||||
// Symbol when another thread loaded Apple Symbols. Its answer was remembered for the face count
|
||||
// after both loads, so ☐ kept Segoe UI Symbol while ☑ and ☒ took Apple Symbols, the first
|
||||
// listed face with all three.
|
||||
let dir = font_dir("ballot-box-race");
|
||||
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("Segoe UI Symbol")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
let reads = || db.coverage.lock().unwrap().reads;
|
||||
let unread = reads();
|
||||
let loading = db.loading.lock().unwrap();
|
||||
std::thread::scope(|s| {
|
||||
let search = s.spawn(|| db.fallback_for('☐', primary.id()));
|
||||
// Past Apple Symbols, the search reads the installed file's character map, then waits for
|
||||
// `loading` to load the file. (A search that finishes without reading it ends the wait too.)
|
||||
while reads() == unread && !search.is_finished() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Another thread loads Apple Symbols meanwhile, as a font load adds faces (`loading` is
|
||||
// held here).
|
||||
db.add_fonts(vec![(with_every_ballot_box("Apple Symbols"), None)]);
|
||||
drop(loading);
|
||||
assert!(search.join().unwrap().is_some());
|
||||
});
|
||||
let faces: Vec<String> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").family.clone()).collect();
|
||||
assert_eq!(faces, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_run_of_check_boxes_keeps_one_face_when_a_symbol_face_loads_during_its_style_lookup() {
|
||||
// A bold run of boxes chose DejaVu Sans, the first listed face loaded with all three, and
|
||||
// looked up its bold face while another thread loaded Apple Symbols, listed earlier. The run's
|
||||
// answer was remembered for the face count after that load, so the run kept DejaVu Sans while
|
||||
// each box alone took Apple Symbols.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.add_document_fonts(vec![(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string())]);
|
||||
let apple = with_every_ballot_box("Apple Symbols");
|
||||
*db.run_style_hook.lock().unwrap() = Some(Box::new(move |db| {
|
||||
// A font load adds faces and leaves the generation as it is.
|
||||
db.add_fonts(vec![(apple, None)]);
|
||||
}));
|
||||
let run = ['☐', '☑', '☒'];
|
||||
assert!(db.fallback_for_run(&run, primary.id(), true, false).is_some());
|
||||
assert!(db.run_style_hook.lock().unwrap().is_none(), "Apple Symbols loaded during the run's style lookup");
|
||||
let boxes: Vec<String> = run.iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").family.clone()).collect();
|
||||
assert_eq!(boxes, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
|
||||
let again = db.fallback_for_run(&run, primary.id(), true, false).expect("a face has them");
|
||||
assert_eq!(again.family, "Apple Symbols", "the run takes the face each box takes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_postscript_names() {
|
||||
let dir = font_dir("postscript");
|
||||
|
||||
@@ -17,7 +17,7 @@ pub mod word;
|
||||
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FONT_FILE_EXTS, FaceRef, FontDb, FontFace, FontFormat, Installed, LocalName, MAX_FONT_FILE_BYTES, UserFont, UserFontError,
|
||||
base_style, bundled, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
|
||||
base_style, bundled, bundled_inter, decode_font_file, is_font_file_name, name_language_matches, sniff, system_font_dirs,
|
||||
};
|
||||
pub use harfrust::Feature;
|
||||
use harfrust::{Direction, ShapeOptions, ShapePlan, ShapePlanKey, Shaper, Tag, UnicodeBuffer};
|
||||
|
||||
@@ -40,6 +40,11 @@ pub fn has_named_substitutes(family: &str) -> bool {
|
||||
|
||||
const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"];
|
||||
|
||||
/// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
|
||||
/// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
|
||||
/// A check box's ballot boxes take their face from this list too (`FontDb::fallback_for`, #7863).
|
||||
pub(crate) const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
|
||||
|
||||
/// Serif faces known by name with no open clone of their own (lowercase): they take the generic
|
||||
/// serif list, but as fonts we know, not by a guess from the name ([`has_own_substitutes`]).
|
||||
const KNOWN_SERIFS: &[&str] = &[
|
||||
@@ -75,9 +80,6 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
|
||||
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
|
||||
// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
|
||||
// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
|
||||
const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
|
||||
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
|
||||
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
|
||||
// headings and screens. Open fonts with full Persian coverage first.
|
||||
|
||||
+14
-24
@@ -4,38 +4,28 @@ use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_html::doc::{ImageLoader, PAGE_FONT, css_len_pt, decode, decode_as, decode_entity, esc, export_flow, parse, parse_with, unescape};
|
||||
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
use crate::{from_shared, shared_section, to_shared};
|
||||
|
||||
pub fn import(html: &str) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import(html))
|
||||
}
|
||||
|
||||
pub fn import(html: &str) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import(html)).unwrap_or_default()
|
||||
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_page(html, images))
|
||||
}
|
||||
|
||||
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_page(html, images)).unwrap_or_default()
|
||||
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_with(html, images))
|
||||
}
|
||||
|
||||
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_with(html, images)).unwrap_or_default()
|
||||
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_on(html, images, &shared_section(page)?))
|
||||
}
|
||||
|
||||
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_on(html, images, &shared_section(page))).unwrap_or_default()
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_html::doc::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_html::doc::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn export_fragment(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_html::doc::export_fragment(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
pub fn export_fragment(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_html::doc::export_fragment(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
@@ -4,23 +4,22 @@ use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_latex::{escape_text, latex_to_linear, linear_to_latex};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_latex::import(bytes)).unwrap_or_default()
|
||||
use crate::{from_shared, to_shared};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
from_shared(craft_latex::import(bytes))
|
||||
}
|
||||
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
let mut d = import(bytes);
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let mut d = import(bytes)?;
|
||||
d.last_section = page.clone();
|
||||
d
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> craft_flow::Flow {
|
||||
craft_latex::parse(text)
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_latex::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_latex::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
+39
-15
@@ -28,6 +28,27 @@ use wordcraft_doc::Document;
|
||||
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
|
||||
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
|
||||
|
||||
/// The document as the shared model the format crates read and write.
|
||||
///
|
||||
/// A conversion that fails is an error, never an empty document or an empty file: the caller
|
||||
/// says so instead of writing a file with nothing in it.
|
||||
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
|
||||
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The shared model as the app's document model. A conversion that fails is an error, never
|
||||
/// an empty document.
|
||||
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The page a file that gives no page size starts on, as the shared model.
|
||||
pub(crate) fn shared_section(page: &wordcraft_doc::SectionProps) -> Result<craft_wordmodel::SectionProps, String> {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
Ok(to_shared(&d)?.last_section)
|
||||
}
|
||||
|
||||
/// Extensions this crate handles.
|
||||
pub const EXTENSIONS: &[&str] =
|
||||
&["txt", "text", "md", "markdown", "html", "htm", "xhtml", "mht", "mhtml", "rtf", "odt", "ott", "fodt", "tex", "latex", "ltx"];
|
||||
@@ -35,15 +56,15 @@ pub const EXTENSIONS: &[&str] =
|
||||
/// Import `bytes` in the format named by `ext` (no dot, any case). `None` = not our format.
|
||||
pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let r = match ext.as_str() {
|
||||
let r: Result<Document, String> = match ext.as_str() {
|
||||
"txt" | "text" => Ok(txt::import(bytes)),
|
||||
"md" | "markdown" => Ok(markdown::import(&txt::decode(bytes))),
|
||||
"html" | "htm" | "xhtml" => Ok(html::import_page(&html::decode(bytes), &|_| None)),
|
||||
"mht" | "mhtml" => Ok(mht::import(bytes)),
|
||||
"md" | "markdown" => markdown::import(&txt::decode(bytes)),
|
||||
"html" | "htm" | "xhtml" => html::import_page(&html::decode(bytes), &|_| None),
|
||||
"mht" | "mhtml" => mht::import(bytes),
|
||||
"rtf" => rtf::import(bytes),
|
||||
"odt" | "ott" => odt::import(bytes),
|
||||
"fodt" => odt::import_flat(bytes),
|
||||
"tex" | "latex" | "ltx" => Ok(latex::import(bytes)),
|
||||
"tex" | "latex" | "ltx" => latex::import(bytes),
|
||||
_ => return None,
|
||||
};
|
||||
Some(r.map(|mut d| {
|
||||
@@ -57,33 +78,36 @@ pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
|
||||
/// formats keep the page their file gives.
|
||||
pub fn import_on(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Option<Result<Document, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let mut doc = match ext.as_str() {
|
||||
let mut doc: Result<Document, String> = match ext.as_str() {
|
||||
"odt" | "ott" => return Some(odt::import_on(bytes, page)),
|
||||
"fodt" => return Some(odt::import_flat_on(bytes, page)),
|
||||
"txt" | "text" => txt::import_on(bytes, page),
|
||||
"txt" | "text" => Ok(txt::import_on(bytes, page)),
|
||||
"md" | "markdown" => markdown::import_on(&txt::decode(bytes), page),
|
||||
"html" | "htm" | "xhtml" => html::import_on(&html::decode(bytes), &|_| None, page),
|
||||
"mht" | "mhtml" => mht::import_on(bytes, page),
|
||||
_ => return import(&ext, bytes),
|
||||
};
|
||||
doc.ensure_nonempty();
|
||||
Some(Ok(doc))
|
||||
if let Ok(d) = doc.as_mut() {
|
||||
d.ensure_nonempty();
|
||||
}
|
||||
Some(doc)
|
||||
}
|
||||
|
||||
/// Export `doc` in the format named by `ext`. `None` = not our format.
|
||||
pub fn export(ext: &str, doc: &Document) -> Option<Result<Vec<u8>, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
let out: Result<Vec<u8>, String> = match ext.as_str() {
|
||||
"txt" | "text" => Ok(txt::export(doc)),
|
||||
"md" | "markdown" => Ok(markdown::export(doc).into_bytes()),
|
||||
"html" | "htm" | "xhtml" => Ok(html::export(doc).into_bytes()),
|
||||
"rtf" => Ok(rtf::export(doc).into_bytes()),
|
||||
"md" | "markdown" => markdown::export(doc).map(String::into_bytes),
|
||||
"html" | "htm" | "xhtml" => html::export(doc).map(String::into_bytes),
|
||||
"rtf" => rtf::export(doc).map(String::into_bytes),
|
||||
"odt" => odt::export(doc),
|
||||
"ott" => odt::export_template(doc),
|
||||
"fodt" => odt::export_flat(doc),
|
||||
"tex" | "latex" | "ltx" => Ok(latex::export(doc).into_bytes()),
|
||||
"tex" | "latex" | "ltx" => latex::export(doc).map(String::into_bytes),
|
||||
_ => return None,
|
||||
})
|
||||
};
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// How [`export_with`] writes a copy.
|
||||
|
||||
@@ -4,23 +4,19 @@ use wordcraft_doc::{Block, Document, SectionProps};
|
||||
|
||||
pub use craft_markdown::{Refs, escape, parse, parse_inlines};
|
||||
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
use crate::{from_shared, shared_section, to_shared};
|
||||
|
||||
pub fn import(text: &str) -> Result<Document, String> {
|
||||
from_shared(craft_markdown::import(text))
|
||||
}
|
||||
|
||||
pub fn import(text: &str) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_markdown::import(text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_on(text: &str, page: &SectionProps) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_markdown::import_on(text, &shared_section(page))).unwrap_or_default()
|
||||
pub fn import_on(text: &str, page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_markdown::import_on(text, &shared_section(page)?))
|
||||
}
|
||||
|
||||
/// [`import_on`] returning the document and the 0-based starting line of each top-level block.
|
||||
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<usize>) {
|
||||
let doc = import_on(text, page);
|
||||
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document, Vec<usize>), String> {
|
||||
let doc = import_on(text, page)?;
|
||||
let src_lines: Vec<&str> = text.strip_prefix('\u{FEFF}').unwrap_or(text).lines().collect();
|
||||
let mut out = Vec::with_capacity(doc.body.len());
|
||||
let mut cursor = 0usize;
|
||||
@@ -57,12 +53,9 @@ pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<u
|
||||
}
|
||||
out.push(found.min(src_lines.len()));
|
||||
}
|
||||
(doc, out)
|
||||
Ok((doc, out))
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_markdown::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_markdown::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn is_mht(bytes: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
/// Import an MHT file.
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
import_on(bytes, &SectionProps::default())
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ fn part_bytes(part: &Part) -> &[u8] {
|
||||
}
|
||||
|
||||
/// [`import`] onto `page`.
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let msg = craft_mime::parse(bytes, &craft_mime::Limits::DEFAULT);
|
||||
let mut leaves = Vec::new();
|
||||
collect_leaves(&msg.root, &mut leaves);
|
||||
@@ -46,7 +46,7 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
.or_else(|| leaves.iter().copied().find(|p| matches!(p.declared_media_type(), Some("text/html" | "application/xhtml+xml"))));
|
||||
let Some(root) = root else {
|
||||
let text = leaves.iter().copied().find(|p| p.declared_media_type().unwrap_or("text/plain") == "text/plain").map(part_bytes).unwrap_or(&[]);
|
||||
return crate::txt::import_on(text, page);
|
||||
return Ok(crate::txt::import_on(text, page));
|
||||
};
|
||||
let html = crate::html::decode_as(part_bytes(root), root.content_type.get("charset"));
|
||||
let base = root.content_location().unwrap_or("");
|
||||
|
||||
@@ -1,33 +1,83 @@
|
||||
//! OpenDocument Text (`.odt`, `.ott`, `.fodt`) import and export via `craft-odf`.
|
||||
|
||||
use wordcraft_doc::{Document, SectionProps};
|
||||
use std::sync::Arc;
|
||||
|
||||
use wordcraft_doc::{Block, Document, SectionProps};
|
||||
|
||||
pub use craft_odf::text::{CryptError, TEMPLATE_MIME, TEXT_MIME, decrypt, encrypt, is_encrypted};
|
||||
|
||||
/// Text room, points, that header and footer bands leave on a page (as Page Setup's margins must).
|
||||
const MIN_TEXT_ROOM: f32 = 36.0;
|
||||
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A shared document opened as a WordCraft one, its pages keeping the text room the header and
|
||||
/// footer bands leave ([`keep_text_room`]).
|
||||
fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
|
||||
let mut doc = wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())?;
|
||||
keep_text_room(&mut doc);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// A page's header and footer bands grow its margins, and a band as tall as the page (to fit a
|
||||
/// full-page picture, #5806) takes all the text's room: every page then draws one line below the
|
||||
/// paper and the rest of the body is missing from the render and PDF. The bands grow the margins
|
||||
/// only while the text keeps half an inch (Page Setup's rule for margins): the larger margin, the
|
||||
/// larger band with it, gives up the excess first, so the smaller band is kept whole. The band's
|
||||
/// own height is untouched: the header still draws as tall as its content.
|
||||
///
|
||||
/// `craft-odf` caps a band at the page's longer side rather than at the room left for text; this
|
||||
/// is the guard that keeps the text on the page until the shared reader makes the same one.
|
||||
fn keep_text_room(doc: &mut Document) {
|
||||
for b in &mut doc.body {
|
||||
if let Block::Para(p) = &mut *Arc::make_mut(b)
|
||||
&& let Some(sec) = p.section.as_mut()
|
||||
{
|
||||
keep_section_room(sec);
|
||||
}
|
||||
}
|
||||
keep_section_room(&mut doc.last_section);
|
||||
}
|
||||
|
||||
fn keep_section_room(sec: &mut SectionProps) {
|
||||
if !(sec.page_h.is_finite() && sec.margin_top.is_finite() && sec.margin_bottom.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let mut excess = sec.margin_top + sec.margin_bottom - (sec.page_h - MIN_TEXT_ROOM);
|
||||
if excess <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let (first, second) = if sec.margin_top >= sec.margin_bottom {
|
||||
(&mut sec.margin_top, &mut sec.margin_bottom)
|
||||
} else {
|
||||
(&mut sec.margin_bottom, &mut sec.margin_top)
|
||||
};
|
||||
let cut = excess.min(first.max(0.0));
|
||||
*first -= cut;
|
||||
excess -= cut;
|
||||
if excess > 0.0 {
|
||||
*second = (*second - excess).max(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
let shared = craft_odf::text::import(bytes)?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
from_shared(craft_odf::text::import(bytes)?)
|
||||
}
|
||||
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let shared = craft_odf::text::import_on(bytes, &shared_section(page))?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
from_shared(craft_odf::text::import_on(bytes, &shared_section(page))?)
|
||||
}
|
||||
|
||||
pub fn import_flat(bytes: &[u8]) -> Result<Document, String> {
|
||||
let shared = craft_odf::text::import_flat(bytes)?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
from_shared(craft_odf::text::import_flat(bytes)?)
|
||||
}
|
||||
|
||||
pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let shared = craft_odf::text::import_flat_on(bytes, &shared_section(page))?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
from_shared(craft_odf::text::import_flat_on(bytes, &shared_section(page))?)
|
||||
}
|
||||
|
||||
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
use wordcraft_doc::Document;
|
||||
|
||||
use crate::{from_shared, to_shared};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
let shared = craft_rtf::doc::import(bytes)?;
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
from_shared(shared)
|
||||
}
|
||||
|
||||
pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
|
||||
@@ -12,9 +14,6 @@ pub fn parse(bytes: &[u8]) -> Result<crate::model::Flow, String> {
|
||||
Ok(craft_flow::from_doc(&shared))
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
let Ok(shared) = wordcraft_docx::to_shared_model(doc) else {
|
||||
return String::new();
|
||||
};
|
||||
craft_rtf::doc::export(&shared)
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_rtf::doc::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
+337
-9
@@ -95,15 +95,7 @@ pub fn read_rows(bytes: &[u8], pick: Pick<'_>) -> Result<(Vec<String>, Vec<Vec<S
|
||||
let names: Vec<String> = book.sheets.iter().map(|s| s.name.clone()).collect();
|
||||
let i = resolve(&names, pick)?;
|
||||
let sheet = &book.sheets[i];
|
||||
let rows = cells_to_rows(&sheet.cells, |c| {
|
||||
if !c.text.is_empty() {
|
||||
clamp_cell(c.text.clone())
|
||||
} else if let Some(v) = c.value() {
|
||||
format_value(&v)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
});
|
||||
let rows = cells_to_rows(&sheet.cells, ods_value);
|
||||
return Ok((names, rows));
|
||||
}
|
||||
Err("not an Excel or OpenDocument spreadsheet".into())
|
||||
@@ -178,6 +170,187 @@ fn format_value(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// An OpenDocument cell's display string, from `office:value-type`: floats from `office:value`,
|
||||
/// dates and times from `office:date-value` / `office:time-value` in ISO 8601 form (`yyyy-mm-dd`,
|
||||
/// `yyyy-mm-dd hh:mm[:ss]`, `hh:mm[:ss]`), booleans as `TRUE`/`FALSE`, and strings, percentages
|
||||
/// and currencies as the cell's text (their value when the text is blank). A value that does not
|
||||
/// parse falls back to the text. A covered cell under a merged cell is blank.
|
||||
///
|
||||
/// A float merges its value, not the text its number format shows: a ZIP code `01234` shown
|
||||
/// through the format `00000` merges as `1234`, and `1,234` shown with a thousands separator
|
||||
/// merges as `1234`.
|
||||
fn ods_value(c: &craft_ods::Cell) -> String {
|
||||
use craft_ods::ValueType as T;
|
||||
if c.covered {
|
||||
return String::new();
|
||||
}
|
||||
let typed = match (c.value_type, c.raw.as_deref().map(str::trim)) {
|
||||
(Some(T::Float | T::Boolean), Some(_)) => c.value().map(|v| format_value(&v)),
|
||||
(Some(T::Date), Some(v)) => iso_datetime(v),
|
||||
(Some(T::Time), Some(v)) => iso_time(v),
|
||||
(Some(T::Percentage | T::Currency | T::String), Some(_)) if c.text.is_empty() => c.value().map(|v| format_value(&v)),
|
||||
_ => None,
|
||||
};
|
||||
typed.map(clamp_cell).unwrap_or_else(|| clamp_cell(c.text.clone()))
|
||||
}
|
||||
|
||||
/// An ISO 8601 date or date-time (`2024-03-05`, `2024-03-05T13:45:00.000`) as `yyyy-mm-dd`,
|
||||
/// with ` hh:mm[:ss]` when the time isn't midnight. `None` unless the whole value is a valid
|
||||
/// calendar date and clock time.
|
||||
fn iso_datetime(v: &str) -> Option<String> {
|
||||
use chrono::Datelike;
|
||||
let v = v.trim();
|
||||
let (date, time) = match v.split_once('T') {
|
||||
Some((date, time)) => (date, Some(time)),
|
||||
None => (v, None),
|
||||
};
|
||||
// A date alone may carry a zone (`Z` or `±hh:mm`), which is left out.
|
||||
let date = match (time, date.strip_suffix('Z')) {
|
||||
(None, Some(d)) => d,
|
||||
(None, None) if date.len() > 6 && date.get(date.len() - 6..).is_some_and(|z| z.starts_with(['+', '-']) && z.get(3..4) == Some(":")) => {
|
||||
zone_offset(date.get(date.len() - 5..)?)?;
|
||||
date.get(..date.len() - 6)?
|
||||
}
|
||||
_ => date,
|
||||
};
|
||||
let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
|
||||
let mut out = format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day());
|
||||
if let Some(time) = time {
|
||||
let (clock, fraction) = clock_time(time)?;
|
||||
if clock != chrono::NaiveTime::MIN || !fraction.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&hh_mm((clock, fraction)));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A clock time `hh:mm[:ss[.s…]]` with an optional `Z` or `±hh:mm` zone (one, not both), which is
|
||||
/// left out. The seconds' fraction comes back as its digits as written, trailing zeros dropped,
|
||||
/// so a fraction finer than a nanosecond is kept.
|
||||
fn clock_time(t: &str) -> Option<(chrono::NaiveTime, String)> {
|
||||
let t = match (t.strip_suffix('Z'), t.rfind(['+', '-'])) {
|
||||
(Some(t), _) => t,
|
||||
(None, Some(i)) => {
|
||||
zone_offset(t.get(i + 1..)?)?;
|
||||
t.get(..i)?
|
||||
}
|
||||
(None, None) => t,
|
||||
};
|
||||
let (clock, fraction) = match t.split_once('.') {
|
||||
// A fraction needs whole seconds before it.
|
||||
Some((t, frac)) => {
|
||||
if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
(chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").ok()?, frac.trim_end_matches('0'))
|
||||
}
|
||||
None => (chrono::NaiveTime::parse_from_str(t, "%H:%M:%S").or_else(|_| chrono::NaiveTime::parse_from_str(t, "%H:%M")).ok()?, ""),
|
||||
};
|
||||
// A leap second (`23:59:60`) is not a time a cell holds.
|
||||
(chrono::Timelike::nanosecond(&clock) < 1_000_000_000).then(|| (clock, fraction.to_string()))
|
||||
}
|
||||
|
||||
/// A zone offset's `hh:mm`, two digits each and at most `14:00` as XML Schema allows.
|
||||
fn zone_offset(z: &str) -> Option<()> {
|
||||
use chrono::Timelike;
|
||||
let two_digit = z.len() == 5 && z.bytes().enumerate().all(|(i, b)| if i == 2 { b == b':' } else { b.is_ascii_digit() });
|
||||
if !two_digit {
|
||||
return None;
|
||||
}
|
||||
let z = chrono::NaiveTime::parse_from_str(z, "%H:%M").ok()?;
|
||||
(z.hour() < 14 || (z.hour() == 14 && z.minute() == 0)).then_some(())
|
||||
}
|
||||
|
||||
/// `hh:mm`, with `:ss` when the seconds aren't zero and their fraction when it isn't.
|
||||
fn hh_mm((t, fraction): (chrono::NaiveTime, String)) -> String {
|
||||
use chrono::Timelike;
|
||||
let (h, m, s) = (t.hour(), t.minute(), t.second());
|
||||
if !fraction.is_empty() {
|
||||
format!("{h:02}:{m:02}:{s:02}.{fraction}")
|
||||
} else if s == 0 {
|
||||
format!("{h:02}:{m:02}")
|
||||
} else {
|
||||
format!("{h:02}:{m:02}:{s:02}")
|
||||
}
|
||||
}
|
||||
|
||||
/// An ISO 8601 duration (`PT13H45M00S`, `P1DT2H`, `-PT1H`) or clock time (`13:45[:00]`) as
|
||||
/// `hh:mm[:ss]`, a duration's days counted as hours and a negative one with a leading `-`.
|
||||
/// `None` for anything else, years and months included.
|
||||
fn iso_time(v: &str) -> Option<String> {
|
||||
let t = v.trim();
|
||||
let (negative, t) = match t.strip_prefix('-') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, t),
|
||||
};
|
||||
let Some(t) = t.strip_prefix('P') else {
|
||||
return if negative { None } else { clock_time(t).map(hh_mm) };
|
||||
};
|
||||
let (days, t, has_t) = match t.split_once('T') {
|
||||
Some((days, time)) => (days, time, true),
|
||||
None => (t, "", false),
|
||||
};
|
||||
// A `T` needs a time after it.
|
||||
if has_t && t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut any = !days.is_empty();
|
||||
let days: u64 = if days.is_empty() { 0 } else { days.strip_suffix('D')?.parse().ok()? };
|
||||
let (mut h, mut m, mut s) = (0u64, 0u64, 0u64);
|
||||
// The seconds' fraction digits, kept as written.
|
||||
let mut fraction = String::new();
|
||||
let mut num = String::new();
|
||||
// Units come in the order H, M, S, each at most once.
|
||||
let mut next_unit = 0;
|
||||
for c in t.chars() {
|
||||
let unit = match c {
|
||||
'H' => 1,
|
||||
'M' => 2,
|
||||
'S' => 3,
|
||||
'0'..='9' | '.' if num.len() < 20 => {
|
||||
num.push(c);
|
||||
continue;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if unit <= next_unit {
|
||||
return None;
|
||||
}
|
||||
next_unit = unit;
|
||||
let n = std::mem::take(&mut num);
|
||||
match unit {
|
||||
1 => h = n.parse().ok()?,
|
||||
2 => m = n.parse().ok()?,
|
||||
_ => {
|
||||
let (whole, frac) = n.split_once('.').unwrap_or((&n, ""));
|
||||
if whole.is_empty() || (n.contains('.') && frac.is_empty()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
s = whole.parse().ok()?;
|
||||
fraction = frac.trim_end_matches('0').to_string();
|
||||
}
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
if !any || !num.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// A duration too long to count in hours is not a time.
|
||||
m = m.checked_add(s / 60)?;
|
||||
s %= 60;
|
||||
h = h.checked_add(m / 60)?.checked_add(days.checked_mul(24)?)?;
|
||||
m %= 60;
|
||||
let sign = if negative && ((h, m, s) != (0, 0, 0) || !fraction.is_empty()) { "-" } else { "" };
|
||||
Some(if !fraction.is_empty() {
|
||||
format!("{sign}{h:02}:{m:02}:{s:02}.{fraction}")
|
||||
} else if s == 0 {
|
||||
format!("{sign}{h:02}:{m:02}")
|
||||
} else {
|
||||
format!("{sign}{h:02}:{m:02}:{s:02}")
|
||||
})
|
||||
}
|
||||
|
||||
fn cells_to_rows<C>(cells: &BTreeMap<CellRef, C>, fmt: impl Fn(&C) -> String) -> Vec<Vec<String>> {
|
||||
let mut grid: BTreeMap<(u32, u32), String> = BTreeMap::new();
|
||||
for (r, c) in cells {
|
||||
@@ -208,3 +381,158 @@ fn grid_to_rows(grid: &BTreeMap<(u32, u32), String>) -> Vec<Vec<String>> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An `.ods` package whose body is `tables` (`table:table` elements).
|
||||
fn spreadsheet(tables: &str) -> Result<Vec<u8>, craft_odf::Error> {
|
||||
let content = format!(
|
||||
r#"<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>"#
|
||||
);
|
||||
let mut w = craft_odf::PackageWriter::new(craft_odf::mime::SPREADSHEET);
|
||||
w.file("content.xml", "text/xml", content.as_bytes());
|
||||
w.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_cells_read_their_typed_values() {
|
||||
let book = spreadsheet(
|
||||
r#"<table:table table:name="Guests">
|
||||
<table:table-row><table:table-cell office:value-type="string"><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"><text:p>When</text:p></table:table-cell><table:table-cell office:value-type="string" table:number-columns-repeated="2"><text:p>Tag</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row table:number-rows-repeated="2"><table:table-cell office:value-type="string" table:number-columns-spanned="2"><text:p>Ada<text:s text:c="2"/>L</text:p><text:p>x</text:p><office:annotation><text:p>note</text:p></office:annotation></table:table-cell><table:covered-table-cell office:value-type="string"><text:p>hidden</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="3.50"><text:p>3,5</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T00:00:00"><text:p>05/03/24</text:p></table:table-cell><table:table-cell office:value-type="boolean" office:boolean-value="false"><text:p>NO</text:p></table:table-cell><table:table-cell office:value-type="time" office:time-value="PT13H45M00S"><text:p>01:45 PM</text:p></table:table-cell></table:table-row>
|
||||
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:30"><text:p>Tue</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="not a date"><text:p>someday</text:p></table:table-cell><table:table-cell office:value-type="percentage" office:value="0.25"><text:p>25%</text:p></table:table-cell><table:table-cell office:value-type="currency" office:value="9"/></table:table-row>
|
||||
</table:table>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Guests")).unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[0], ["Name", "", "", "When", "Tag", "Tag"]);
|
||||
assert_eq!(rows[1], ["Ada L\nx", "", "3.5", "2024-03-05", "FALSE", "13:45"]);
|
||||
assert_eq!(rows[1], rows[2]);
|
||||
assert_eq!(rows[3], ["2024-03-05 13:45:30", "someday", "25%", "9"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ods_date_with_two_zones_reads_its_text() {
|
||||
let book = spreadsheet(
|
||||
r#"<table:table table:name="Dates">
|
||||
<table:table-row><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00Z"><text:p>offset then Z</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00Z+02:00"><text:p>Z then offset</text:p></table:table-cell><table:table-cell office:value-type="date" office:date-value="2024-03-05T13:45:00+02:00"><text:p>one zone</text:p></table:table-cell></table:table-row>
|
||||
</table:table>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Dates")).unwrap();
|
||||
assert_eq!(rows, [["offset then Z", "Z then offset", "2024-03-05 13:45"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_dates_and_durations() {
|
||||
assert_eq!(iso_time("PT1H59M59.6S").as_deref(), Some("01:59:59.6"));
|
||||
assert_eq!(iso_time("PT0.25S").as_deref(), Some("00:00:00.25"));
|
||||
assert_eq!(iso_time("PT59M60.50S").as_deref(), Some("01:00:00.5"));
|
||||
assert_eq!(iso_time("PT0H0M59S").as_deref(), Some("00:00:59"));
|
||||
assert_eq!(iso_time("PT1H2M3S").as_deref(), Some("01:02:03"));
|
||||
assert_eq!(iso_time("PT1.S"), None);
|
||||
assert_eq!(iso_time("P1000000000000000000D"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_time_keeps_its_seconds_fraction_as_written() {
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.0000000001").as_deref(), Some("2024-03-05 00:00:00.0000000001"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30.1234567891Z").as_deref(), Some("2024-03-05 13:45:30.1234567891"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30.500+02:00").as_deref(), Some("2024-03-05 13:45:30.5"));
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_time("13:45:00.1234567891").as_deref(), Some("13:45:00.1234567891"));
|
||||
assert_eq!(iso_time("PT13H45M0.1234567891S").as_deref(), Some("13:45:00.1234567891"));
|
||||
assert_eq!(iso_time("13:45:00."), None);
|
||||
assert_eq!(iso_time("13:45:00.5x"), None);
|
||||
assert_eq!(iso_time("13:45.5"), None);
|
||||
assert_eq!(iso_time("23:59:60.5"), None);
|
||||
assert_eq!(iso_time("13: 45.5"), None);
|
||||
assert_eq!(iso_time("1:45:30.5").as_deref(), Some("01:45:30.5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_ods_value_keeps_to_the_cell_limit() {
|
||||
let long = format!("2024-03-05T13:45:30.{}", "1".repeat(MAX_CELL_CHARS));
|
||||
let book = spreadsheet(&format!(
|
||||
r#"<table:table table:name="Long"><table:table-row><table:table-cell office:value-type="date" office:date-value="{long}"><text:p>x</text:p></table:table-cell></table:table-row></table:table>"#
|
||||
))
|
||||
.unwrap();
|
||||
let (_, rows) = read_rows(&book, Pick::Name("Long")).unwrap();
|
||||
assert_eq!(rows[0][0].chars().count(), MAX_CELL_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_date_alone_drops_its_zone() {
|
||||
assert_eq!(iso_datetime("2024-03-05Z").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+02:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05-05:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+02:99"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_is_at_most_fourteen_hours() {
|
||||
assert_eq!(iso_datetime("2024-03-05+14:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05-14:00").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05+14:01"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05-15:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:00").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+14:01"), None);
|
||||
assert_eq!(iso_time("13:45:00-15:00"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_is_z_or_an_offset_not_both() {
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+02:00Z"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00Z+02:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05+02:00Z"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05Z+02:00"), None);
|
||||
assert_eq!(iso_time("13:45:00+02:00Z"), None);
|
||||
assert_eq!(iso_time("13:45:00Z+02:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00Z").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00-05:00").as_deref(), Some("2024-03-05 13:45"));
|
||||
assert_eq!(iso_time("13:45:00+02:00").as_deref(), Some("13:45"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zone_offset_has_two_digit_hours_and_minutes() {
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+2:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:00+ 2:00"), None);
|
||||
assert_eq!(iso_time("13:45:00-5:00"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leap_second_is_not_a_time() {
|
||||
assert_eq!(iso_datetime("2024-03-05T23:59:60Z"), None);
|
||||
assert_eq!(iso_time("23:59:60"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duration_with_t_needs_a_time() {
|
||||
assert_eq!(iso_time("P1DT"), None);
|
||||
assert_eq!(iso_time("P0DT"), None);
|
||||
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
|
||||
assert_eq!(iso_time("PT.S"), None);
|
||||
assert_eq!(iso_time("13:45:00Z").as_deref(), Some("13:45"));
|
||||
assert_eq!(iso_time("-PT1H").as_deref(), Some("-01:00"));
|
||||
assert_eq!(iso_time("P2DT1H30M").as_deref(), Some("49:30"));
|
||||
assert_eq!(iso_time("P1D").as_deref(), Some("24:00"));
|
||||
assert_eq!(iso_time("P1Y2M"), None);
|
||||
assert_eq!(iso_time("PT"), None);
|
||||
assert_eq!(iso_time("PT5"), None);
|
||||
assert_eq!(iso_time("PT1H2H"), None);
|
||||
assert_eq!(iso_time("PT1S2H"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.500").as_deref(), Some("2024-03-05 00:00:00.5"));
|
||||
assert_eq!(iso_time("00:00:00.250").as_deref(), Some("00:00:00.25"));
|
||||
assert_eq!(iso_time("25:00"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T00:00:00.000").as_deref(), Some("2024-03-05"));
|
||||
assert_eq!(iso_datetime("2024-03-05T13:45:30+02:00").as_deref(), Some("2024-03-05 13:45:30"));
|
||||
assert_eq!(iso_datetime("2024-13-05"), None);
|
||||
assert_eq!(iso_datetime("2023-02-29"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05junk"), None);
|
||||
assert_eq!(iso_datetime("2024-03-05T13:99"), None);
|
||||
}
|
||||
}
|
||||
|
||||
+65
-14
@@ -330,6 +330,14 @@ fn rtf_round_trip() {
|
||||
assert_eq!(back.core.creator, "Ada Writer");
|
||||
}
|
||||
|
||||
/// A file the format cannot read is an error, not a blank document: the reader says what it
|
||||
/// could not read, so the caller can say so too.
|
||||
#[test]
|
||||
fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
|
||||
let e = import("rtf", b"not an RTF document").unwrap().unwrap_err();
|
||||
assert!(e.contains("RTF"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odt_round_trip() {
|
||||
check_round_trip("odt", true);
|
||||
@@ -342,6 +350,47 @@ fn odt_round_trip() {
|
||||
assert_eq!(back.core.creator, "Ada Writer");
|
||||
}
|
||||
|
||||
/// A flat ODT on A4 with a header and a footer, their bands' minimum heights (`fo:min-height`)
|
||||
/// stated, and two body paragraphs.
|
||||
fn flat_odt_with_bands(header: &str, footer: &str) -> Vec<u8> {
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text">
|
||||
<office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21cm" fo:page-height="29.7cm" fo:margin-top="2cm" fo:margin-bottom="1.5cm" fo:margin-left="2cm" fo:margin-right="2cm"/><style:header-style><style:header-footer-properties fo:min-height="{header}" fo:margin-bottom="0.25cm"/></style:header-style><style:footer-style><style:header-footer-properties fo:min-height="{footer}" fo:margin-top="0.5cm"/></style:footer-style></style:page-layout></office:automatic-styles>
|
||||
<office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"><style:header><text:p>H</text:p></style:header><style:footer><text:p>F</text:p></style:footer></style:master-page></office:master-styles>
|
||||
<office:body><office:text><text:p>a</text:p><text:p>b</text:p></office:text></office:body>
|
||||
</office:document>"#
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_band_as_tall_as_the_page_leaves_the_text_room() {
|
||||
// #5806: a header's min-height raised to the page height (to fit a full-page picture) made the
|
||||
// text's top margin the page's bottom edge, so each page drew one line off the paper and the
|
||||
// rest of the text was lost. The bands grow the margins only while the text keeps half an
|
||||
// inch, as Page Setup's margins must.
|
||||
let cm = |v: f32| v * 72.0 / 2.54;
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 0.05;
|
||||
let room = |header: &str, footer: &str| {
|
||||
let doc = import("fodt", &flat_odt_with_bands(header, footer)).unwrap().unwrap();
|
||||
let s = doc.last_section.clone();
|
||||
(s.page_h - s.margin_top - s.margin_bottom, s)
|
||||
};
|
||||
let (left, s) = room("29.7cm", "1cm");
|
||||
assert!(left >= 36.0 - 0.05, "text room {left}: {s:?}");
|
||||
// The header still starts at the page margin; the text right after as much band as fits.
|
||||
assert!(near(s.header, cm(2.0)) && near(s.margin_top, s.page_h - cm(3.0) - 36.0), "{s:?}");
|
||||
// A footer as tall as the page leaves it too, and so do both at once.
|
||||
let (left, s) = room("0.5cm", "29.7cm");
|
||||
assert!(left >= 36.0 - 0.05 && near(s.margin_top, cm(2.75)), "text room {left}: {s:?}");
|
||||
let (left, s) = room("29.7cm", "29.7cm");
|
||||
assert!(left >= 36.0 - 0.05, "text room {left}: {s:?}");
|
||||
// Bands that fit are as stated.
|
||||
let (_, s) = room("0.5cm", "1cm");
|
||||
assert!(near(s.margin_top, cm(2.75)) && near(s.margin_bottom, cm(3.0)), "{s:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latex_round_trip() {
|
||||
check_round_trip("tex", true);
|
||||
@@ -558,7 +607,7 @@ fn latex_export_carries_no_commands_from_the_document() {
|
||||
assert_eq!(crate::latex::linear_to_latex("\\alpha+\\sin x+\\mathbb R"), "\\alpha+\\sin x+\\mathbb R");
|
||||
assert_eq!(crate::latex::linear_to_latex("x^2^3"), "x^2^3");
|
||||
// The same through a whole file, and for a bookmark name.
|
||||
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes());
|
||||
let d = crate::latex::import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes()).unwrap();
|
||||
let out = String::from_utf8(export("tex", &d).unwrap().unwrap()).unwrap();
|
||||
assert!(!out.contains("\\input") && !out.contains("^^"), "{out}");
|
||||
}
|
||||
@@ -571,11 +620,11 @@ fn latex_export_carries_no_commands_from_the_document() {
|
||||
fn latex_labels_in_a_row_are_read_in_linear_time() {
|
||||
let started = std::time::Instant::now();
|
||||
for src in ["\\label{a} ".repeat(100_000) + "x", "\\label{a}".repeat(100_000) + "x", "\\hypertarget{a}{} ".repeat(100_000)] {
|
||||
let d = crate::latex::import(src.as_bytes());
|
||||
let d = crate::latex::import(src.as_bytes()).unwrap();
|
||||
assert!(d.body.len() <= 2);
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
|
||||
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes());
|
||||
let d = crate::latex::import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()).unwrap();
|
||||
let p = d.para_at(&wordcraft_doc::Pos::body(0, 0)).unwrap();
|
||||
let names: Vec<&str> = p
|
||||
.objects
|
||||
@@ -692,7 +741,8 @@ fn html_img_sources_go_through_the_loader() {
|
||||
let d = crate::html::import_with(html, &|src| {
|
||||
seen.borrow_mut().push(src.to_string());
|
||||
(src == "logo.png").then(|| std::sync::Arc::new(pic.clone()))
|
||||
});
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(*seen.borrow(), ["logo.png", "gone.png"]);
|
||||
assert_eq!(d.media.len(), 1);
|
||||
let text = d.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
@@ -1080,7 +1130,7 @@ fn hidden_drawings_are_left_out_of_exports() {
|
||||
d.insert_object(&wordcraft_doc::Pos::body(0, 0), image, &Default::default()).unwrap();
|
||||
}
|
||||
// Two pictures, one hidden: one comes out.
|
||||
assert_eq!(crate::html::export(&d).matches("<img").count(), 1);
|
||||
assert_eq!(crate::html::export(&d).unwrap().matches("<img").count(), 1);
|
||||
}
|
||||
|
||||
/// Every text span of the flow, with its formatting.
|
||||
@@ -1168,16 +1218,17 @@ fn dropped_names_and_links_are_logged_once_per_document() {
|
||||
let count = |w: &[String], what: &str| w.iter().filter(|l| l.contains(what)).count();
|
||||
for _ in 0..2 {
|
||||
// Each import is its own document: the second is reported too.
|
||||
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html));
|
||||
let (doc, warned) = crate::test_log::warnings(|| crate::html::import(&html).unwrap());
|
||||
assert!(doc.body.len() == 1, "the text is kept");
|
||||
assert_eq!(count(&warned, "font names longer"), 1, "{warned:?}");
|
||||
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
|
||||
}
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>"));
|
||||
let (_, warned) =
|
||||
crate::test_log::warnings(|| crate::html::import("<p><a href=\"https://e.com\" style=\"font-family:Georgia\">fine</a></p>").unwrap());
|
||||
assert!(warned.is_empty(), "nothing left out, nothing said: {warned:?}");
|
||||
|
||||
let md = format!("[a](https://e.com/{long}) [b](https://e.com/{long})");
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md));
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::markdown::import(&md).unwrap());
|
||||
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
|
||||
|
||||
let rtf =
|
||||
@@ -1187,14 +1238,14 @@ fn dropped_names_and_links_are_logged_once_per_document() {
|
||||
assert_eq!(count(&warned, "style names longer"), 1, "{warned:?}");
|
||||
|
||||
let tex = format!("\\href{{https://e.com/{long}}}{{a}} \\url{{https://e.com/{long}}}");
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()));
|
||||
let (_, warned) = crate::test_log::warnings(|| crate::latex::import(tex.as_bytes()).unwrap());
|
||||
assert_eq!(count(&warned, "links longer"), 1, "{warned:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_title_outside_head_is_metadata_not_body() {
|
||||
for html in ["<title>T</title><p>b</p>", "<html><title>T</title><body>b</body></html>"] {
|
||||
let d = crate::html::import(html);
|
||||
let d = crate::html::import(html).unwrap();
|
||||
assert_eq!(para_texts(&d), vec!["b".to_string()], "{html}");
|
||||
assert_eq!(d.core.title, "T", "{html}");
|
||||
}
|
||||
@@ -1220,7 +1271,7 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
|
||||
r#"<div style="background-color:#1e1e1e"><div>a</div><div> </div><div>b</div></div>"#,
|
||||
);
|
||||
let doc = crate::html::import(html);
|
||||
let doc = crate::html::import(html).unwrap();
|
||||
assert_eq!(doc.body.len(), 7);
|
||||
|
||||
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
|
||||
@@ -1245,8 +1296,8 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
|
||||
}
|
||||
|
||||
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
|
||||
let back = crate::html::import(&exported);
|
||||
for exported in [crate::html::export(&doc).unwrap(), crate::html::export_fragment(&doc).unwrap()] {
|
||||
let back = crate::html::import(&exported).unwrap();
|
||||
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
|
||||
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
|
||||
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
|
||||
@@ -1265,7 +1316,7 @@ fn odt_list_item_later_paragraphs_stay_in_the_item() {
|
||||
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
|
||||
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
|
||||
let html = crate::html::export(&doc);
|
||||
let html = crate::html::export(&doc).unwrap();
|
||||
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
|
||||
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
|
||||
assert!(one < still && still < two, "{html}");
|
||||
|
||||
@@ -152,7 +152,7 @@ pub(crate) fn add(ctx: &mut Ctx, lay: &mut DocLayout) {
|
||||
author_name(&cm.author),
|
||||
CharProps { bold: Some(true), size: Some(9.0), color: Some(TextColor::Rgb(color)), ..Default::default() },
|
||||
);
|
||||
let pl = ctx.para_labelled(&head, inner, None, &[], None);
|
||||
let pl = ctx.para_labelled(&head, inner, None, &[], 0.0, None);
|
||||
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
|
||||
push_para(&mut items, (story, &[HEADER_PATH]), &pl, (0, pl.lines.len()), (x, y + lead), inner, Edges::own(&pl, 0, pl.lines.len()));
|
||||
y += pl.height + 2.0;
|
||||
|
||||
+22
-11
@@ -261,6 +261,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// Word has no frames in a text box: a framed paragraph there (its style's frame, usually)
|
||||
// runs with the box's text (#2357).
|
||||
let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox));
|
||||
// Nor in a table cell for a frame placed on the page: Word keeps its text in the cell.
|
||||
let cell_frame = |fr: &wordcraft_doc::props::TextFrame| !in_cell || fr.v_anchor == "text";
|
||||
// The bottom of the last paragraph's lines.
|
||||
let mut prev_end = 0.0f32;
|
||||
// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
|
||||
@@ -274,17 +276,17 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
Block::Para(p) => {
|
||||
// A paragraph after one whose mark is hidden goes on from that one's last line
|
||||
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table, cell_frame);
|
||||
let p = taken.as_ref().map_or(p, |t| &t.para);
|
||||
let label = ctx.next_label(p);
|
||||
let listed = label.is_some();
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], 0.0, label.clone());
|
||||
// A text frame (a footer's page number in a frame, say) is placed apart, like a
|
||||
// floating object, and the text after it wraps around it; it takes no room in
|
||||
// the flow.
|
||||
if let Some(fr) = pl.rp.frame.clone().filter(|_| frames) {
|
||||
if let Some(fr) = pl.rp.frame.clone().filter(|fr| frames && cell_frame(fr)) {
|
||||
let fw = fr.w.unwrap_or_else(|| natural_width(&pl)).clamp(1.0, 1584.0);
|
||||
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], label) } else { pl };
|
||||
let pf = if (fw - width).abs() > 0.01 { ctx.para_labelled(p, fw, table, &[], 0.0, label) } else { pl };
|
||||
let h = match fr.h {
|
||||
Some(h) if fr.h_exact => h,
|
||||
Some(h) => h.max(pf.height),
|
||||
@@ -316,7 +318,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// body path. Keep text and wrap exclusions relative to the text's actual top.
|
||||
// A paragraph going on from a shared line has its origin at that line's top.
|
||||
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
|
||||
y += if i == 0 { before } else { before.max(0.0) };
|
||||
let applied = if i == 0 { before } else { before.max(0.0) };
|
||||
y += applied;
|
||||
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
|
||||
// Floating objects anchored here: place them, then wrap the text around them.
|
||||
// One left out of the layout (hidden, or deleted in the final text) takes no room.
|
||||
@@ -362,7 +365,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
if !rel.is_empty() {
|
||||
pl = ctx.para_labelled(p, width, table, &rel, label);
|
||||
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
|
||||
}
|
||||
TakenUp::clear(taken.as_ref(), &mut excl);
|
||||
// Bordered paragraphs: room for their borders, those of a group joined in one box.
|
||||
@@ -475,7 +478,7 @@ fn natural_width(pl: &ParaLayout) -> f32 {
|
||||
}
|
||||
|
||||
/// A text frame's placement as a floating object's (`w:framePr` → anchors, alignment, wrap).
|
||||
fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
|
||||
pub(crate) fn frame_float(fr: &wordcraft_doc::props::TextFrame) -> Float {
|
||||
let anchor = |a: &str, text: Anchor| match a {
|
||||
"page" => Anchor::Page,
|
||||
"margin" => Anchor::Margin,
|
||||
@@ -775,13 +778,14 @@ impl Joint {
|
||||
(i, p): (usize, &Paragraph),
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
|
||||
) -> (bool, bool, Option<TakenUp>) {
|
||||
let chr = table.map(|t| &t.chr);
|
||||
let mark_hidden = ctx.mark_hidden(p, chr);
|
||||
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
|
||||
let came = joint.take().filter(|j| j.next == i);
|
||||
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table, cell_frame));
|
||||
(mark_hidden, shows_nothing, taken)
|
||||
}
|
||||
|
||||
@@ -797,7 +801,7 @@ impl Joint {
|
||||
/// taller than the text going on from it), with the room for its bottom border (Word).
|
||||
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<¶::CellText>) -> (f32, Vec<WrapArea>) {
|
||||
let eq = ctx.eq_count;
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
|
||||
@@ -825,9 +829,16 @@ impl Joint {
|
||||
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
|
||||
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
|
||||
/// without its space before, as [`Joint::fit`] lays it out.
|
||||
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<¶::CellText>) -> Option<TakenUp> {
|
||||
fn take_up(
|
||||
self,
|
||||
ctx: &mut Ctx,
|
||||
p: &Paragraph,
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
cell_frame: impl Fn(&wordcraft_doc::props::TextFrame) -> bool,
|
||||
) -> Option<TakenUp> {
|
||||
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
|
||||
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
|
||||
if own.page_break_before || own.bidi || own.frame.as_ref().is_some_and(|fr| frames && cell_frame(fr)) {
|
||||
return None;
|
||||
}
|
||||
let mut para = p.clone();
|
||||
|
||||
@@ -16,6 +16,9 @@ pub(crate) struct Key {
|
||||
pub(crate) table: u64,
|
||||
pub(crate) notes: u64,
|
||||
pub(crate) excl: u64,
|
||||
/// The space before the paragraph layout applied above it, which a Top-and-Bottom object in
|
||||
/// it is laid out again below ([`para::ParaEnv::space_before`]).
|
||||
pub(crate) space_before: u32,
|
||||
pub(crate) eq: u32,
|
||||
pub(crate) read_spacing: Option<u32>,
|
||||
pub(crate) grid: (u32, u32, u32, bool),
|
||||
@@ -32,6 +35,14 @@ pub(crate) struct Key {
|
||||
pub(crate) joined: Option<(u32, bool)>,
|
||||
}
|
||||
|
||||
pub(crate) struct StylesEnv {
|
||||
styles: std::sync::Weak<wordcraft_doc::styles::StyleSheet>,
|
||||
numbering: std::sync::Weak<wordcraft_doc::numbering::Numbering>,
|
||||
default_tab: u32,
|
||||
footnote_format: wordcraft_doc::section::NumFormat,
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
/// Memoised paragraph layouts.
|
||||
#[derive(Default)]
|
||||
pub struct LayoutCache {
|
||||
@@ -44,6 +55,7 @@ pub struct LayoutCache {
|
||||
/// kept, so no other picture's bytes can come to have its address ([`Outlines`]).
|
||||
pub(crate) outlines: Outlines,
|
||||
pub(crate) env: u64,
|
||||
pub(crate) styles_env: Option<StylesEnv>,
|
||||
pub(crate) used: HashSet<Key>,
|
||||
/// The STYLEREF style index of the last pass and what it was built from: the body blocks
|
||||
/// (shared, so an edited block is a different pointer) and `env` (styles and numbering). Kept
|
||||
@@ -67,6 +79,7 @@ impl LayoutCache {
|
||||
self.paras.clear();
|
||||
self.measures.clear();
|
||||
self.outlines.clear();
|
||||
self.styles_env = None;
|
||||
self.styleref = None;
|
||||
}
|
||||
|
||||
@@ -91,12 +104,56 @@ pub(crate) fn hash_of<T: Hash>(t: &T) -> u64 {
|
||||
h.finish()
|
||||
}
|
||||
|
||||
pub(crate) fn env_hash(doc: &Document, opts: &LayoutOptions) -> u64 {
|
||||
let s = serde_json::to_string(&(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format)).unwrap_or_default();
|
||||
struct HashWriter<'a>(&'a mut std::collections::hash_map::DefaultHasher);
|
||||
|
||||
impl std::io::Write for HashWriter<'_> {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.write(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fingerprint of stylesheet, numbering, default tab, and footnote format, memoised on
|
||||
/// [`LayoutCache::styles_env`] via `Weak` pointers so unchanged passes skip JSON serialisation.
|
||||
/// Holding live `Weak` references keeps the underlying `ArcInner` allocations reserved, ensuring a
|
||||
/// fresh `Arc` allocation cannot reuse a still-cached address.
|
||||
fn styles_env_hash(doc: &Document, cache: &mut LayoutCache) -> u64 {
|
||||
let tab = doc.settings.default_tab.to_bits();
|
||||
if let Some(cached) = &cache.styles_env
|
||||
&& cached.styles.as_ptr() == Arc::as_ptr(&doc.styles)
|
||||
&& cached.styles.strong_count() > 0
|
||||
&& cached.numbering.as_ptr() == Arc::as_ptr(&doc.numbering)
|
||||
&& cached.numbering.strong_count() > 0
|
||||
&& cached.default_tab == tab
|
||||
&& cached.footnote_format == doc.settings.footnote_format
|
||||
{
|
||||
return cached.hash;
|
||||
}
|
||||
let mut sh = std::collections::hash_map::DefaultHasher::new();
|
||||
let _ = serde_json::to_writer(HashWriter(&mut sh), &(&doc.styles, &doc.numbering, doc.settings.default_tab, &doc.settings.footnote_format));
|
||||
let hash = sh.finish();
|
||||
cache.styles_env = Some(StylesEnv {
|
||||
styles: Arc::downgrade(&doc.styles),
|
||||
numbering: Arc::downgrade(&doc.numbering),
|
||||
default_tab: tab,
|
||||
footnote_format: doc.settings.footnote_format,
|
||||
hash,
|
||||
});
|
||||
hash
|
||||
}
|
||||
|
||||
pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> u64 {
|
||||
let styles = styles_env_hash(doc, cache);
|
||||
// Outline view lays paragraphs out changed (no indents; plain without text formatting).
|
||||
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
s.hash(&mut h);
|
||||
styles.hash(&mut h);
|
||||
// The compatibility mode changes paragraph layout too (widow control in table cells).
|
||||
doc.settings.compat_mode.hash(&mut h);
|
||||
opts.show_hidden.hash(&mut h);
|
||||
opts.hide_deleted.hash(&mut h);
|
||||
opts.hide_marked.hash(&mut h);
|
||||
|
||||
@@ -113,12 +113,21 @@ struct ParaEnvInput<'a> {
|
||||
label: Option<(String, Level)>,
|
||||
table: Option<&'a para::CellText>,
|
||||
exclusions: &'a [para::Exclusion],
|
||||
space_before: f32,
|
||||
eq_number: u32,
|
||||
typing_word: Option<(usize, usize)>,
|
||||
fitted: &'a [(usize, f32)],
|
||||
joined: bool,
|
||||
}
|
||||
|
||||
/// The flow's wrap context for a paragraph's layout, as its cache key needs it: the areas text
|
||||
/// flows around (relative to its first line) and the space before it the flow laid out, which
|
||||
/// reaches up to them (see [`para::ParaEnv::space_before`]).
|
||||
struct WrapAreas<'a> {
|
||||
exclusions: &'a [para::Exclusion],
|
||||
space_before: f32,
|
||||
}
|
||||
|
||||
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
|
||||
/// table cells' floats placed on the page rather than in their cell ([`Float::outside_cell`],
|
||||
/// Word's picture watermark in a header that starts with a table), drawn behind the header's
|
||||
@@ -252,6 +261,7 @@ impl Ctx<'_> {
|
||||
typing_word: None,
|
||||
numeral: self.opts.numeral,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
read_line_spacing: None,
|
||||
grid: para::Grid::default(),
|
||||
@@ -299,16 +309,18 @@ impl Ctx<'_> {
|
||||
|
||||
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
|
||||
/// floating objects, or after it moved) doesn't advance the list counters twice.
|
||||
/// `space_before` is the space before `p` that the flow laid out above it ([`para::ParaEnv`]).
|
||||
pub(crate) fn para_labelled(
|
||||
&mut self,
|
||||
p: &Paragraph,
|
||||
width: f32,
|
||||
table: Option<¶::CellText>,
|
||||
exclusions: &[para::Exclusion],
|
||||
space_before: f32,
|
||||
label: Option<(String, Level)>,
|
||||
) -> Arc<ParaLayout> {
|
||||
let fitted = self.fitted_boxes(p);
|
||||
let (key, eq_number) = self.para_key(p, width, table, exclusions, label.as_ref(), &fitted);
|
||||
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions, space_before }, label.as_ref(), &fitted);
|
||||
self.cache.used.insert(key.clone());
|
||||
if let Some(pl) = self.cache.paras.get(&key) {
|
||||
self.cache.hits += 1;
|
||||
@@ -323,6 +335,7 @@ impl Ctx<'_> {
|
||||
label,
|
||||
table,
|
||||
exclusions,
|
||||
space_before,
|
||||
eq_number,
|
||||
typing_word: typing,
|
||||
fitted: &fitted,
|
||||
@@ -347,7 +360,7 @@ impl Ctx<'_> {
|
||||
return None;
|
||||
}
|
||||
let kept = (self.eq_count, self.uses_totals);
|
||||
let (key, eq_number) = self.para_key(p, width, None, &[], label.as_ref(), &[]);
|
||||
let (key, eq_number) = self.para_key(p, width, None, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &[]);
|
||||
(self.eq_count, self.uses_totals) = kept;
|
||||
if key.typing.is_some() {
|
||||
return None;
|
||||
@@ -365,6 +378,7 @@ impl Ctx<'_> {
|
||||
label,
|
||||
table: None,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number,
|
||||
typing_word: None,
|
||||
fitted: &[],
|
||||
@@ -387,7 +401,7 @@ impl Ctx<'_> {
|
||||
measure: impl FnOnce(&ParaLayout) -> (f32, f32),
|
||||
) -> (f32, f32) {
|
||||
let fitted = self.fitted_boxes(p);
|
||||
let (key, eq_number) = self.para_key(p, width, table, &[], label.as_ref(), &fitted);
|
||||
let (key, eq_number) = self.para_key(p, width, table, WrapAreas { exclusions: &[], space_before: 0.0 }, label.as_ref(), &fitted);
|
||||
self.cache.used.insert(key.clone());
|
||||
if let Some(m) = self.cache.measures.get(&key) {
|
||||
self.cache.hits += 1;
|
||||
@@ -402,6 +416,7 @@ impl Ctx<'_> {
|
||||
label,
|
||||
table,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number,
|
||||
typing_word: typing,
|
||||
fitted: &fitted,
|
||||
@@ -455,10 +470,11 @@ impl Ctx<'_> {
|
||||
p: &Paragraph,
|
||||
width: f32,
|
||||
table: Option<¶::CellText>,
|
||||
exclusions: &[para::Exclusion],
|
||||
wrap: WrapAreas<'_>,
|
||||
label: Option<&(String, Level)>,
|
||||
fitted: &[(usize, f32)],
|
||||
) -> (Key, u32) {
|
||||
let WrapAreas { exclusions, space_before } = wrap;
|
||||
let page = if has_page_fields(p) { Some(self.fields.page_key()) } else { None };
|
||||
if self.track_totals && !self.uses_totals && has_total_fields(p) {
|
||||
self.uses_totals = true;
|
||||
@@ -483,6 +499,7 @@ impl Ctx<'_> {
|
||||
table: table.map(|t| self.table_key(t)).unwrap_or(0),
|
||||
notes: if p.objects.iter().any(|o| matches!(o, InlineObject::NoteRef { .. })) { self.notes_hash } else { 0 },
|
||||
excl: if exclusions.is_empty() { 0 } else { hash_of(&format!("{exclusions:?}")) },
|
||||
space_before: space_before.to_bits(),
|
||||
eq: if eq_here > 0 { eq_number } else { 0 },
|
||||
read_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing.map(f32::to_bits) } else { None },
|
||||
grid: self.grid.key(),
|
||||
@@ -512,7 +529,7 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
|
||||
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
|
||||
let ParaEnvInput { width, label, table, exclusions, space_before, eq_number, typing_word, fitted, joined } = input;
|
||||
para::ParaEnv {
|
||||
doc: self.doc,
|
||||
width,
|
||||
@@ -526,6 +543,7 @@ impl Ctx<'_> {
|
||||
typing_word,
|
||||
numeral: self.opts.numeral,
|
||||
exclusions,
|
||||
space_before,
|
||||
eq_number,
|
||||
read_line_spacing: if self.opts.view == ViewMode::Read { self.opts.read_line_spacing } else { None },
|
||||
grid: self.grid,
|
||||
|
||||
@@ -232,7 +232,10 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::E
|
||||
side: *side,
|
||||
table: *table,
|
||||
})
|
||||
.filter(|e| e.bottom > 0.0)
|
||||
// Top-and-Bottom areas above the first line can still take room: they sit in the
|
||||
// paragraph's space before, which Word lays out again below them (#7143). Side-wrapping
|
||||
// areas there are above the text and take no room, as before.
|
||||
.filter(|e| e.bottom > 0.0 || e.top_bottom)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -526,7 +529,7 @@ fn anchor_floats_but(
|
||||
}
|
||||
}
|
||||
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, label.clone());
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
|
||||
(rects, pl, rel)
|
||||
}
|
||||
|
||||
|
||||
+81
-20
@@ -1,9 +1,9 @@
|
||||
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
|
||||
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, frame_float, joined, layout_box, push_para};
|
||||
use super::cache::has_page_number_fields;
|
||||
use super::ctx::{Ctx, Joining};
|
||||
use super::floats::{
|
||||
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
|
||||
place_objects,
|
||||
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, float_rect, late_floats,
|
||||
place_late, place_objects, wrap_area,
|
||||
};
|
||||
use super::notes::{DECOR_STORY, NoteBox, para_notes};
|
||||
use super::page::{PageBuilder, PageFrame, item_bottom};
|
||||
@@ -19,6 +19,9 @@ use crate::WRAP_RELAYS;
|
||||
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
|
||||
/// as Word shows them, on one line (#3986): see [`Joint`].
|
||||
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
if place_page_text_frame(ctx, pb, p, block) {
|
||||
return;
|
||||
}
|
||||
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
|
||||
let mark_hidden = ctx.mark_hidden(p, None);
|
||||
// Nothing of it is shown: the place passes on to the paragraph after it.
|
||||
@@ -96,6 +99,39 @@ fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
|
||||
}
|
||||
}
|
||||
|
||||
fn place_page_text_frame(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize) -> bool {
|
||||
if pb.web {
|
||||
return false;
|
||||
}
|
||||
let Some(fr) = ctx.doc.styles.resolve_para_in(&p.props, None).frame else { return false };
|
||||
if fr.h_anchor != "page" || fr.v_anchor != "page" {
|
||||
return false;
|
||||
}
|
||||
let width = fr.w.unwrap_or_else(|| pb.col_w()).clamp(1.0, 1584.0);
|
||||
let label = ctx.next_label(p);
|
||||
let pl = ctx.para_labelled(p, width, None, &[], 0.0, label);
|
||||
let notes = para_notes(ctx.doc, p, &pl);
|
||||
let mut new_notes = Vec::new();
|
||||
for line in &pl.lines {
|
||||
new_notes.extend(notes_on_line(ctx, pb, line, ¬es, &new_notes));
|
||||
}
|
||||
add_notes(pb, new_notes, ¬es, pl.lines.last().map_or(0, |line| line.c1));
|
||||
let height = fr.h.map_or(pl.height, |h| if fr.h_exact { h } else { h.max(pl.height) });
|
||||
let float = frame_float(&fr);
|
||||
let page = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
|
||||
let rect = float_rect(Some(page), (pb.col_x(), pb.col_w()), pb.y, width, height, &float);
|
||||
let path = [block as u32];
|
||||
if let Some(page) = pb.page() {
|
||||
push_para(&mut page.items, (StoryRef::Body, &path), &pl, (0, pl.lines.len()), (rect.x, rect.y), width, Edges::own(&pl, 0, pl.lines.len()));
|
||||
}
|
||||
// The body text after the frame wraps around it as its wrap mode says.
|
||||
if let Some(area) = wrap_area(rect, &float, None) {
|
||||
pb.framed.push(area.0);
|
||||
pb.excl.push(area);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A closing mark before a continuous section takes no room after content. An otherwise empty
|
||||
/// section starting a new page retains its paragraph line.
|
||||
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
@@ -236,6 +272,10 @@ struct Flow<'a> {
|
||||
label: Option<(String, Level)>,
|
||||
/// Where it was expected to start; floats anchored here are placed again if it starts elsewhere.
|
||||
guess: f32,
|
||||
/// The space before it that its layout (`pl`) was broken with: the declared space before
|
||||
/// until the flow settles what it really lays out, then that, so a later relay keeps a
|
||||
/// Top-and-Bottom object in it pushing the first line to the same place.
|
||||
space_applied: f32,
|
||||
excl_mark: usize,
|
||||
/// Where its automatic equation numbers start: each layout of it again counts from here.
|
||||
eq_start: u32,
|
||||
@@ -269,6 +309,21 @@ struct Flow<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Flow<'a> {
|
||||
/// [`PageBuilder::fresh`] for this paragraph's text, which its negative indents take past the
|
||||
/// column's edges: the first line's indent while it is still to place, the other lines'
|
||||
/// indent while lines after the first are, on the physical sides the paragraph's direction
|
||||
/// puts them.
|
||||
fn fresh(&self, pb: &PageBuilder) -> bool {
|
||||
let rp = &self.pl.rp;
|
||||
let first = rp.indent_left + rp.indent_first;
|
||||
let leading = match (self.l0 == 0, self.pl.lines.len() > 1) {
|
||||
(true, true) => rp.indent_left.min(first),
|
||||
(true, false) => first,
|
||||
(false, _) => rp.indent_left,
|
||||
};
|
||||
let (leading, trailing) = ((-leading).max(0.0), (-rp.indent_right).max(0.0));
|
||||
pb.fresh(if rp.bidi { (trailing, leading) } else { (leading, trailing) })
|
||||
}
|
||||
fn new(ctx: &mut Ctx, pb: &mut PageBuilder, p: &'a Paragraph, (block, body_top): (usize, f32)) -> Self {
|
||||
let width = pb.col_w();
|
||||
// Floating objects anchored here join the page's wrap areas before the text is laid out; if
|
||||
@@ -288,6 +343,7 @@ impl<'a> Flow<'a> {
|
||||
width,
|
||||
label,
|
||||
guess,
|
||||
space_applied: space_before,
|
||||
excl_mark,
|
||||
eq_start,
|
||||
float_rects,
|
||||
@@ -324,13 +380,14 @@ impl<'a> Flow<'a> {
|
||||
});
|
||||
(self.float_rects, self.pl, self.rel) = (rects, pl, rel);
|
||||
self.late = LateFloats::new(&late);
|
||||
self.space_applied = before;
|
||||
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
|
||||
}
|
||||
|
||||
/// Lay the paragraph out again around the wrap areas `rel`, with its fields on their pages.
|
||||
fn relay(&mut self, ctx: &mut Ctx, rel: &[para::Exclusion]) -> Arc<ParaLayout> {
|
||||
let (p, width, eq_start, label) = (self.p, self.laid_width, self.eq_start, &self.label);
|
||||
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, label.clone())))
|
||||
let (p, width, eq_start, label, space_before) = (self.p, self.laid_width, self.eq_start, &self.label, self.space_applied);
|
||||
with_page_map(ctx, &mut self.page_map, |ctx| again(ctx, eq_start, |ctx| ctx.para_labelled(p, width, None, rel, space_before, label.clone())))
|
||||
}
|
||||
|
||||
/// The space before the paragraph, after the one between it and the previous paragraph is
|
||||
@@ -367,7 +424,7 @@ impl<'a> Flow<'a> {
|
||||
// space before (Word's PDFs: 0 pt and 12 pt before put the text after it at the same place).
|
||||
// Only that shape is observed: later pages and columns keep theirs.
|
||||
if self.block == 1
|
||||
&& pb.fresh()
|
||||
&& self.fresh(pb)
|
||||
&& !pb.web
|
||||
&& pb.pages.last().is_some_and(|pg| pg.float_tables.contains(&Path::top(0)))
|
||||
&& only_markers(self.p, 0..self.p.text.len())
|
||||
@@ -444,7 +501,7 @@ impl<'a> Flow<'a> {
|
||||
// (Against the whole column: balanced columns grow to hold it.)
|
||||
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
|
||||
// keeps the lines and the next paragraph together at the top of a column too (#6821).
|
||||
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
if pb.y + need > pb.bottom + 0.01 && (!self.fresh(pb) || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
pb.advance(self.block, self.body_top);
|
||||
unjoin(ctx, self.p);
|
||||
pb.y += rp.space_before.min(0.0);
|
||||
@@ -458,7 +515,7 @@ impl<'a> Flow<'a> {
|
||||
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
|
||||
/// ends up (#6821).
|
||||
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
|
||||
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
|
||||
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && self.fresh(pb) && Self::strict_widow_control(ctx, pb) {
|
||||
let (col, pages) = (pb.col, pb.pages.len());
|
||||
let before = self.keep_together(ctx, pb, rooms, 0.0);
|
||||
if (pb.col, pb.pages.len()) == (col, pages) {
|
||||
@@ -550,7 +607,7 @@ impl<'a> Flow<'a> {
|
||||
if over && fit.l1 > l0 && !split {
|
||||
break;
|
||||
}
|
||||
if over && fit.l1 == l0 && !pb.fresh() && !split && !self.stays_at_bottom(pb, l) {
|
||||
if over && fit.l1 == l0 && !self.fresh(pb) && !split && !self.stays_at_bottom(pb, l) {
|
||||
break;
|
||||
}
|
||||
fit.notes.extend(line_notes);
|
||||
@@ -608,11 +665,11 @@ impl<'a> Flow<'a> {
|
||||
// one (#6821).
|
||||
let strict = Self::strict_widow_control(ctx, pb);
|
||||
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
|
||||
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
|
||||
if l1 - l0 == 1 && l0 == 0 && (!self.fresh(pb) || strict) {
|
||||
l1 = l0; // orphan: move the first line to the next page
|
||||
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
|
||||
l1 -= 1; // widow: take one more line along
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!self.fresh(pb) || strict) {
|
||||
// Neither split of a three-line paragraph is allowed (two and a widow, or an
|
||||
// orphan and two): it moves whole, as in Word.
|
||||
l1 = l0;
|
||||
@@ -776,6 +833,7 @@ impl<'a> Flow<'a> {
|
||||
(self.float_rects, self.pl, self.rel) = (rects, relaid, relaid_rel);
|
||||
(self.laid_page, self.laid_width) = (pb.number, pb.col_w());
|
||||
self.anchor_y = y0;
|
||||
self.space_applied = 0.0;
|
||||
self.l0 = k;
|
||||
}
|
||||
}
|
||||
@@ -890,10 +948,10 @@ fn notes_limit(pb: &PageBuilder, new_notes: &[NoteBox], line_notes: &[NoteBox])
|
||||
/// the text (see `baseline_offset`), and Word lets that leading of a page's last line run into the
|
||||
/// bottom margin: only the text has to fit (observed: a double-spaced 12pt line stays on the page
|
||||
/// while its text ends above the margin, about half a line lower than when the whole line must
|
||||
/// fit). Only the bottom margin takes that leading: a footer taller than the margin, or
|
||||
/// footnotes (`free` is false), keep the whole line clear of them.
|
||||
/// fit). Only the bottom margin takes that leading, or the top of a footer that reaches above it
|
||||
/// (see [`PageBuilder::at_margin`]): footnotes (`free` is false) keep the whole line clear of them.
|
||||
fn fit_height(pb: &PageBuilder, l: ¶::Line, rp: &wordcraft_doc::resolve::ResolvedPara, free: bool) -> f32 {
|
||||
let at_margin = pb.bottom >= pb.sect.page_h - pb.sect.margin_bottom - 0.01;
|
||||
let at_margin = pb.at_margin();
|
||||
match rp.line_spacing {
|
||||
// The text (or a taller picture) ends `leading` above the line's bottom.
|
||||
wordcraft_doc::props::LineSpacing::Multiple(m) if m > 1.0 && at_margin && free => (l.height - l.leading).clamp(0.0, l.height),
|
||||
@@ -989,8 +1047,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
let mut f = Flow::new(ctx, pb, p, (block, body_top));
|
||||
let spot = |pb: &PageBuilder| (pb.pages.len(), pb.col);
|
||||
let placed_at = spot(pb);
|
||||
// A continuous section's top mid-page is not a page top, so the break still applies.
|
||||
let broke_before = f.pl.rp.page_break_before && !pb.fresh() && !pb.web;
|
||||
// A continuous section's top mid-page is not a page top, so the break still applies. A
|
||||
// page-anchored frame is not content above the paragraph, so it does not make the break
|
||||
// apply either: the frame's wrap area moves the text below or beside it (#8577).
|
||||
let broke_before = f.pl.rp.page_break_before && !pb.at_page_top() && !pb.web;
|
||||
if broke_before {
|
||||
pb.new_page(block, body_top);
|
||||
}
|
||||
@@ -1023,7 +1083,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
fit.l1 = end;
|
||||
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
|
||||
// the lines on without emitting anything and must release their late floats as well.
|
||||
let overflow = end == f.l0 && pb.fresh() && !widowed;
|
||||
let overflow = end == f.l0 && f.fresh(pb) && !widowed;
|
||||
if f.settle_late(pb, end, overflow) {
|
||||
continue;
|
||||
}
|
||||
@@ -1085,7 +1145,7 @@ pub(crate) fn place_outline_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragr
|
||||
let width = (pb.col_w() - indent - outline::SYMBOL_W).max(72.0);
|
||||
let q = outline::outline_para(ctx.doc, p, o.view.plain);
|
||||
ctx.fields.page = pb.number;
|
||||
let pl = ctx.para_labelled(&q, width, None, &[], label);
|
||||
let pl = ctx.para_labelled(&q, width, None, &[], 0.0, label);
|
||||
pb.y += pl.rp.space_before.max(0.0);
|
||||
let n = pl.lines.len();
|
||||
let l1 = if o.view.first_line_only && level >= outline::BODY { n.min(1) } else { n };
|
||||
@@ -1197,6 +1257,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
typing_word: None,
|
||||
numeral: ctx.opts.numeral,
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: ctx.eq_count,
|
||||
read_line_spacing: if ctx.opts.view == ViewMode::Read { ctx.opts.read_line_spacing } else { None },
|
||||
grid: ctx.grid,
|
||||
@@ -1311,7 +1372,7 @@ mod tests {
|
||||
// Continue after the first line. The balance attempt can fit only one of the two lines left.
|
||||
flow.l0 = 1;
|
||||
pb.advance(0, top);
|
||||
assert!(pb.fresh());
|
||||
assert!(flow.fresh(pb));
|
||||
assert!((pb.bottom - pb.top - height).abs() < 0.01);
|
||||
flow.place_due_late(ctx, pb);
|
||||
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
|
||||
@@ -1320,7 +1381,7 @@ mod tests {
|
||||
assert_eq!(fit.l1, 2);
|
||||
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
|
||||
assert_eq!((end, widowed), (1, true));
|
||||
let overflow = end == flow.l0 && pb.fresh() && !widowed;
|
||||
let overflow = end == flow.l0 && flow.fresh(pb) && !widowed;
|
||||
assert!(!flow.settle_late(pb, end, overflow));
|
||||
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
|
||||
});
|
||||
|
||||
@@ -36,6 +36,27 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `page` (after `prev`) is its section's first page, the one a different first page's
|
||||
/// header and footer go on: the page where the section begins. A page's section is the one at its
|
||||
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
|
||||
/// Word shows the earlier section's header there and the section's default one from the next page
|
||||
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
|
||||
/// [`Document::sections`] gives them (each with its last block).
|
||||
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
|
||||
if prev.is_some_and(|p| p.section == page.section) {
|
||||
return false;
|
||||
}
|
||||
let start = page.section.checked_sub(1).and_then(|k| sections.get(k)).map_or(0, |(end, _)| end.saturating_add(1));
|
||||
// A first paragraph (or table) that begins part-way down `prev` and runs over still began
|
||||
// the section there.
|
||||
let began_before = prev.is_some_and(|p| {
|
||||
p.items
|
||||
.iter()
|
||||
.any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0.first().is_some_and(|&b| b as usize >= start)))
|
||||
});
|
||||
start >= page.first_block && !began_before
|
||||
}
|
||||
|
||||
/// The document's sections with their headers and footers (Word's "link to previous"), each
|
||||
/// section's resolved once for the whole layout in document order rather than by looking back
|
||||
/// over the sections before it whenever one is needed.
|
||||
@@ -174,12 +195,12 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(page) = pb.pages.last() else { return Vec::new() };
|
||||
let first = pb.pages.iter().rev().nth(1).is_none_or(|prev| prev.section != page.section);
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let first = begins_section(&hf.sections, pb.pages.iter().rev().nth(1), page);
|
||||
let key = (page.section, page.number, first);
|
||||
if let Some(areas) = ctx.header_tables.get(&key) {
|
||||
return areas.clone();
|
||||
}
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let Some((_, sect)) = hf.sections.get(page.section) else { return Vec::new() };
|
||||
if sect.text_direction.is_turned() {
|
||||
return Vec::new();
|
||||
@@ -405,13 +426,9 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
|
||||
let hf = Arc::clone(&ctx.hf);
|
||||
let even_odd = ctx.doc.settings.even_odd_headers;
|
||||
let styles = styleref::headers_use_styleref(ctx.doc).then(|| ctx.cache.style_index(ctx.doc));
|
||||
let mut first_of_section: HashSet<usize> = HashSet::new();
|
||||
let mut seen = HashSet::new();
|
||||
for (i, p) in pages.iter().enumerate() {
|
||||
if seen.insert(p.section) {
|
||||
first_of_section.insert(i);
|
||||
}
|
||||
}
|
||||
let first_of_section: HashSet<usize> = (0..pages.len())
|
||||
.filter(|&i| pages.get(i).is_some_and(|p| begins_section(sections, i.checked_sub(1).and_then(|k| pages.get(k)), p)))
|
||||
.collect();
|
||||
for (i, page) in pages.iter_mut().enumerate() {
|
||||
let Some((_, sect)) = sections.get(page.section) else { continue };
|
||||
// Inherit header/footer references from earlier sections (Word's "link to previous").
|
||||
|
||||
@@ -210,10 +210,31 @@ impl NoteBox {
|
||||
cuts
|
||||
}
|
||||
|
||||
/// The least of the note that must stay with its reference: its first line (all of it if it
|
||||
/// can't be split).
|
||||
/// Whether widow/orphan control in the note's paragraphs forbids splitting at `cut`: a
|
||||
/// paragraph's first line alone above it (an orphan) or its last line alone below it (a
|
||||
/// widow), as in Word for Mac 16.114.4.
|
||||
pub(crate) fn breaks_widow_control(&self, cut: f32) -> bool {
|
||||
self.items.iter().filter(|it| self.splittable(it)).any(|it| {
|
||||
let Placed::Lines { para, l0, l1, y, .. } = it else { return false };
|
||||
let Some(first) = para.lines.get(*l0) else { return false };
|
||||
let ends_at = |k: usize| para.lines.get(k).is_some_and(|l| (y + l.top - first.top + l.height - cut).abs() < 0.01);
|
||||
let n = para.lines.len();
|
||||
para.rp.widow_control && n >= 2 && ((*l0 == 0 && *l1 >= 2 && ends_at(0)) || (*l1 == n && ends_at(n - 2)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the note may be split with its paragraphs' widow/orphan control kept, ascending.
|
||||
pub(crate) fn kept_cuts(&self) -> Vec<f32> {
|
||||
let mut cuts = self.cuts();
|
||||
cuts.retain(|&c| !self.breaks_widow_control(c));
|
||||
cuts
|
||||
}
|
||||
|
||||
/// The least of the note that must stay with its reference: its first line, or more under
|
||||
/// widow/orphan control (all of it if it can't be split).
|
||||
pub(crate) fn first_piece(&self) -> f32 {
|
||||
self.cuts().first().copied().unwrap_or(self.h).min(self.h)
|
||||
// Widow/orphan control may keep more lines together (two, or a short paragraph whole).
|
||||
self.kept_cuts().first().copied().unwrap_or(self.h).min(self.h)
|
||||
}
|
||||
|
||||
/// Split the note at line bottom `cut`: the part above (`cut` tall) and the rest, moved up to
|
||||
|
||||
@@ -89,10 +89,16 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// Top of the footer of the pages being started: a footer reaching above the bottom margin
|
||||
/// pushes the body up (`f32::MAX`: no footer).
|
||||
pub(crate) foot_top: f32,
|
||||
/// How low the last line's leading may reach on the current page: the bottom margin, or the
|
||||
/// top of a footer reaching above it (set as the page starts, from that page's footer).
|
||||
pub(crate) leading_floor: f32,
|
||||
/// The wrap areas pages start with ([`EarlyFloats`]) ...
|
||||
pub(crate) early: &'a EarlyFloats,
|
||||
/// ... and how many of the current page's `excl` they are (its first ones).
|
||||
pub(crate) seeded: usize,
|
||||
/// The wrap areas of the page-anchored body text frames on the current page. Text at the top
|
||||
/// of a column that one of them reaches into gains room by moving on.
|
||||
pub(crate) framed: Vec<Rect>,
|
||||
/// No layout pass follows for floats found above their anchors: each is kept clear of the
|
||||
/// text laid out before it ([`settle_early`]).
|
||||
pub(crate) settle: bool,
|
||||
@@ -160,7 +166,7 @@ impl PageBuilder<'_> {
|
||||
// The note area starts below the text (a page of continued notes alone: at its top).
|
||||
let area = self.bottom.max(self.body_floor());
|
||||
let fits = total <= self.orig_bottom - area + 0.01;
|
||||
let top = match (fits, self.beneath) {
|
||||
let mut top = match (fits, self.beneath) {
|
||||
(false, _) => area,
|
||||
// Below the page's last line of text.
|
||||
(true, true) => self.body_floor().min(self.orig_bottom - total),
|
||||
@@ -173,12 +179,15 @@ impl PageBuilder<'_> {
|
||||
let mut placed = Vec::new();
|
||||
// Where the continuation notice goes, below a note that continues on the next page.
|
||||
let mut notice_y = None;
|
||||
// The bottom of what is placed (with the notice).
|
||||
let mut end = y;
|
||||
let mut rest = notes.into_iter();
|
||||
while let Some(n) = rest.next() {
|
||||
let room = self.orig_bottom - y;
|
||||
if fits || n.h <= room + 0.01 {
|
||||
let ny = y;
|
||||
y += n.h;
|
||||
end = y;
|
||||
placed.push((n, ny));
|
||||
continue;
|
||||
}
|
||||
@@ -186,21 +195,38 @@ impl PageBuilder<'_> {
|
||||
// always leaves something here (its first line, or all of it if it can't be split),
|
||||
// so continuing ends.
|
||||
let first = placed.is_empty();
|
||||
let cuts = n.cuts();
|
||||
// Widow/orphan control in the note keeps two of a paragraph's lines on either side;
|
||||
// the page's first note gives that up before it gives up the page's room.
|
||||
let room = room - self.seps.notice_h();
|
||||
match cuts.iter().rev().find(|&&c| c <= room + 0.01).or(cuts.first().filter(|_| first)).copied() {
|
||||
let fit = |cuts: Vec<f32>| cuts.into_iter().rev().find(|&c| c <= room + 0.01);
|
||||
let cut = fit(n.kept_cuts()).or_else(|| if first { fit(n.cuts()).or(n.cuts().first().copied()) } else { None });
|
||||
match cut {
|
||||
Some(c) => {
|
||||
let (head, tail) = n.split(c);
|
||||
notice_y = Some(y + head.h);
|
||||
end = y + head.h + self.seps.notice_h();
|
||||
placed.push((head, y));
|
||||
self.carry.push(tail);
|
||||
}
|
||||
None if first => placed.push((n, y)),
|
||||
None if first => {
|
||||
end = y + n.h;
|
||||
placed.push((n, y));
|
||||
}
|
||||
None => self.carry.push(n),
|
||||
}
|
||||
self.carry.extend(rest.by_ref());
|
||||
break;
|
||||
}
|
||||
// Notes that continue on the next page still end on the bottom margin, the room left
|
||||
// going above the separator (Word for Mac 16.114.4), unless they go beneath the text.
|
||||
if !fits && !self.beneath {
|
||||
let shift = (self.orig_bottom - end).max(0.0);
|
||||
top += shift;
|
||||
notice_y = notice_y.map(|ny| ny + shift);
|
||||
for (_, ny) in &mut placed {
|
||||
*ny += shift;
|
||||
}
|
||||
}
|
||||
if let Some(pg) = self.pages.last_mut() {
|
||||
match if cont { &self.seps.cont } else { &self.seps.sep } {
|
||||
Some((items, _)) => pg.items.extend(items.iter().cloned().map(|mut it| {
|
||||
@@ -351,6 +377,7 @@ impl PageBuilder<'_> {
|
||||
let early = self.early;
|
||||
self.excl.extend(early.get(&self.pages.len()).into_iter().flatten().map(|(_, _, a)| a.clone()));
|
||||
self.seeded = self.excl.len();
|
||||
self.framed.clear();
|
||||
self.float_tables.clear();
|
||||
if self.sect.line_numbers.as_ref().is_some_and(|l| l.restart == wordcraft_doc::section::LineNumberRestart::Page) {
|
||||
self.line_no = 0;
|
||||
@@ -359,6 +386,7 @@ impl PageBuilder<'_> {
|
||||
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
|
||||
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
|
||||
let bottom = self.body_bottom(body_top);
|
||||
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
|
||||
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
|
||||
let mut decor = Vec::new();
|
||||
if !self.web {
|
||||
@@ -437,6 +465,13 @@ impl PageBuilder<'_> {
|
||||
self.bottom = self.bottom.min(self.top + h);
|
||||
}
|
||||
}
|
||||
/// Whether the body ends at the bottom margin, or at the top of a footer that reaches above
|
||||
/// it: the page's last multiple-spaced line may leave its leading there (see `fit_height`).
|
||||
/// Word lets it run past the footer's top as into the margin, whatever the footer holds (a
|
||||
/// page number, several lines of text, an empty paragraph): only the text has to end above it.
|
||||
pub(crate) fn at_margin(&self) -> bool {
|
||||
self.bottom >= self.leading_floor - 0.01
|
||||
}
|
||||
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
|
||||
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
|
||||
fn body_bottom(&self, body_top: f32) -> f32 {
|
||||
@@ -476,9 +511,22 @@ impl PageBuilder<'_> {
|
||||
/// At the top with nothing above on this page, so moving on gains no room. A continuous
|
||||
/// section starting mid-page is at its top but not fresh: what doesn't fit there goes to the
|
||||
/// next page (#3907).
|
||||
pub(crate) fn fresh(&self) -> bool {
|
||||
/// `reach` is how far the text reaches past the column's left and right edges (a paragraph's
|
||||
/// negative indents).
|
||||
pub(crate) fn fresh(&self, reach: (f32, f32)) -> bool {
|
||||
self.at_page_top() && !self.framed_here(reach)
|
||||
}
|
||||
/// At the top of the page's text with nothing placed above it. A page-anchored frame is not
|
||||
/// content above it: a paragraph with a page break before needs no new page for one.
|
||||
pub(crate) fn at_page_top(&self) -> bool {
|
||||
self.at_top() && self.top <= self.page_top + 0.01
|
||||
}
|
||||
/// A page-anchored body text frame's wrap area reaches into the current column's text,
|
||||
/// widened by `reach` on the left and right.
|
||||
fn framed_here(&self, (left, right): (f32, f32)) -> bool {
|
||||
let (x0, x1) = (self.col_x() - left, self.col_x() + self.col_w() + right);
|
||||
self.framed.iter().any(|r| r.x < x1 && r.right() > x0 && r.y < self.bottom && r.bottom() > self.y)
|
||||
}
|
||||
/// Move to the next column or page.
|
||||
pub(crate) fn advance(&mut self, block: usize, body_top: f32) {
|
||||
if self.col + 1 < self.cols.len() {
|
||||
|
||||
@@ -367,6 +367,7 @@ mod label_spacing_tests {
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
numeral: crate::NumeralMode::default(),
|
||||
read_line_spacing: None,
|
||||
@@ -513,6 +514,7 @@ mod tests {
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
space_before: 0.0,
|
||||
eq_number: 0,
|
||||
numeral: Default::default(),
|
||||
read_line_spacing: None,
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::chars::{
|
||||
};
|
||||
use super::grid::east_asian;
|
||||
use super::model::{ClKind, Cluster, Enclosed, Glyph, ParaEnv, RubyLayout, StyleRun, SymbolRun};
|
||||
use super::{Arc, Document, FaceRef, NumeralMode, ResolvedChar, RubyAlign, SOFT_HYPHEN};
|
||||
use super::{Arc, Document, FaceRef, NumeralMode, OBJ, ResolvedChar, RubyAlign, SOFT_HYPHEN};
|
||||
use wordcraft_fonts::ShapeContext;
|
||||
|
||||
pub(super) struct Builder<'a> {
|
||||
@@ -52,6 +52,25 @@ struct SegmentInput<'a> {
|
||||
context: &'a [bool],
|
||||
}
|
||||
|
||||
/// Whether `face` draws `cluster`, a character and its combining marks, with no missing glyph.
|
||||
/// The shaper composes a pair the face has a precomposed glyph for (`=` and U+0338 as `≠`), so a
|
||||
/// face without the mark itself can still draw the pair.
|
||||
fn draws_all(face: FaceRef, cluster: &str) -> bool {
|
||||
let glyphs = wordcraft_fonts::shape_in(&face, cluster, &[], |c| c, ShapeContext::default());
|
||||
!glyphs.is_empty() && glyphs.iter().all(|g| g.gid != 0)
|
||||
}
|
||||
|
||||
/// A face other than `current` that draws all of `cluster` (CSS Fonts 4 §5.3, cluster matching):
|
||||
/// the run's Thai face or its own font when one does, else the first face in fallback order with
|
||||
/// every character of it that draws something.
|
||||
fn cluster_face(cluster: &str, current: FaceRef, run_face: Option<FaceRef>, primary: FaceRef, bold: bool, italic: bool) -> Option<FaceRef> {
|
||||
if let Some(f) = run_face.into_iter().chain([primary]).filter(|f| f.id() != current.id()).find(|f| draws_all(*f, cluster)) {
|
||||
return Some(f);
|
||||
}
|
||||
let chars: Vec<char> = cluster.chars().filter(|c| draws_something(*c)).collect();
|
||||
wordcraft_fonts::FontDb::global().fallback_for_run(&chars, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
|
||||
}
|
||||
|
||||
impl<'a> Builder<'a> {
|
||||
/// Displayed form of `c` at run-relative byte `at` (Word › Numeral): one char in, one
|
||||
/// char out. `rtl` is the shaping direction; in Context mode `context` (from
|
||||
@@ -68,6 +87,10 @@ impl<'a> Builder<'a> {
|
||||
let mut seg_start = 0;
|
||||
let mut cur: Option<SegKey> = None;
|
||||
let mut segs = Vec::new();
|
||||
// The character the marks after it belong to: where it starts, and as drawn.
|
||||
let mut base: Option<(usize, char)> = None;
|
||||
// The character whose cluster was matched, and whether its marks stay with it.
|
||||
let mut matched: Option<(usize, bool)> = None;
|
||||
for (i, c) in text.char_indices() {
|
||||
let rtl = use_levels && levels.get(lbase + i).is_some_and(|l| l % 2 == 1);
|
||||
let c = show(c);
|
||||
@@ -78,19 +101,67 @@ impl<'a> Builder<'a> {
|
||||
_ => rc_cs.is_some() && rc.uses_complex(dc),
|
||||
};
|
||||
let primary = if complex { primary_cs.unwrap_or(primary) } else { primary };
|
||||
let face = match cur {
|
||||
Some(k) if mark => k.face,
|
||||
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
|
||||
// A mark stays in the face of the character it belongs to (Arabic harakat with their
|
||||
// letter, so the letters join) while that face draws it. When it doesn't, the
|
||||
// character and its marks go together to a face that draws them all (CSS Fonts 4
|
||||
// §5.3, cluster matching). With no such face, a mark in left-to-right text that isn't
|
||||
// complex script is matched on its own like any other character; in right-to-left or
|
||||
// complex-script text it stays with its letter (#7865). A cluster is matched once, at
|
||||
// its first mark the face lacks: matching it again at every later mark would make a
|
||||
// long run of marks quadratic.
|
||||
let mut with_base = false;
|
||||
let mut moved = None;
|
||||
if let Some(k) = cur.filter(|_| mark) {
|
||||
let current = k.face.unwrap_or(primary);
|
||||
with_base = !draws_something(c) || current.covers(dc);
|
||||
if !with_base {
|
||||
match (base.filter(|(at, _)| *at >= seg_start), matched) {
|
||||
(Some((at, _)), Some((done, stays))) if done == at => with_base = stays,
|
||||
(Some((at, b)), _) => {
|
||||
let marks = text.get(at..).unwrap_or("").chars().skip(1).map(show).take_while(|m| is_mark(*m));
|
||||
let all: String = std::iter::once(b).chain(marks).inspect(|_| crate::work::steps(1)).collect();
|
||||
if draws_all(current, &all) {
|
||||
with_base = true;
|
||||
} else if let Some(f) = cluster_face(&all, current, run_face, primary, bold, italic) {
|
||||
// The character goes to that face with its marks.
|
||||
if at > seg_start {
|
||||
segs.push((seg_start, at, k));
|
||||
seg_start = at;
|
||||
}
|
||||
let face = (f.id() != primary.id()).then_some(f);
|
||||
cur = Some(SegKey { face, ..k });
|
||||
moved = Some(face);
|
||||
} else {
|
||||
with_base = k.complex || k.rtl;
|
||||
}
|
||||
matched = Some((at, with_base || moved.is_some()));
|
||||
}
|
||||
(None, _) => with_base = k.complex || k.rtl,
|
||||
}
|
||||
}
|
||||
}
|
||||
if !mark {
|
||||
base = (!c.is_control() && c != OBJ).then_some((i, dc));
|
||||
}
|
||||
let face = match (moved, cur) {
|
||||
(Some(face), _) => face,
|
||||
(None, Some(k)) if with_base => k.face,
|
||||
_ if !complex && east_asian(c) && primary_ea.is_some_and(|f| f.covers(c)) => primary_ea,
|
||||
_ if !c.is_control() && c != SOFT_HYPHEN && run_face.is_some_and(|f| f.covers(dc)) => run_face,
|
||||
_ if primary.covers(dc) || c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN => None,
|
||||
Some(SegKey { face: Some(face), .. }) if face.covers(dc) => Some(face),
|
||||
(None, Some(SegKey { face: Some(face), .. })) if face.covers(dc) => Some(face),
|
||||
_ if !complex && ea_face.is_some() && crate::kinsoku::is_east_asian(c) => ea_face,
|
||||
_ => {
|
||||
let (bold, italic) = if complex { (rc.bold_cs, rc.italic_cs) } else { (rc.bold, rc.italic) };
|
||||
wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f))
|
||||
}
|
||||
_ => wordcraft_fonts::FontDb::global().fallback_styled(dc, primary.id(), bold, italic).map(|f| FaceRef::of(&f)),
|
||||
};
|
||||
let key = SegKey { face, small: rc.small_caps && !rc.caps && c.is_lowercase(), complex, rtl };
|
||||
// A mark is set like the character it belongs to, as for `complex`: in small capitals at
|
||||
// that character's size, so the two stay in one shaping run and its cluster is matched
|
||||
// whole.
|
||||
let small = match cur {
|
||||
Some(k) if mark => k.small,
|
||||
_ => rc.small_caps && !rc.caps && c.is_lowercase(),
|
||||
};
|
||||
let key = SegKey { face, small, complex, rtl };
|
||||
match cur {
|
||||
Some(previous) if previous.same(&key) => {}
|
||||
Some(previous) => {
|
||||
@@ -139,6 +210,15 @@ impl<'a> Builder<'a> {
|
||||
// the height Word gives it.
|
||||
let (a, d) = match wordcraft_fonts::word::symbol_line(&rc.font, &r) {
|
||||
Some((a, d)) => (a * face.upem, d * face.upem),
|
||||
// A character Times New Roman or its metric twin lacks: the twin lacks more than
|
||||
// Times New Roman ("‒", "₽" in Liberation Serif), so the line is as tall as the run's
|
||||
// font, as with Times New Roman in Word, not as the taller fallback. East Asian text
|
||||
// keeps its face's height.
|
||||
None if face_override.is_some() && is_times_twin(&r.face.family) && !face.is_east_asian() => {
|
||||
let (a, d) = wordcraft_fonts::word::line_metrics(&r.face);
|
||||
let k = face.upem / r.face.upem.max(1.0);
|
||||
(a * k, d * k)
|
||||
}
|
||||
None => wordcraft_fonts::word::line_metrics(&face),
|
||||
};
|
||||
let k = size as f64 / face.upem.max(1.0);
|
||||
@@ -422,12 +502,15 @@ impl<'a> Builder<'a> {
|
||||
let ge = bounds.get(bi + 1).copied().unwrap_or(shape_text.len());
|
||||
let g0 = self.glyphs.len() as u32;
|
||||
let mut adv = 0.0f32;
|
||||
// What kerning added to the last glyph's advance: its pair with the next glyph.
|
||||
let mut kern = 0.0f32;
|
||||
while let Some(g) = shaped.get(gi) {
|
||||
if g.cluster >= ge {
|
||||
break;
|
||||
}
|
||||
self.glyphs.push(Glyph { gid: g.gid, dx: adv + g.x_offset as f32 * k * hscale, dy: g.y_offset as f32 * k });
|
||||
adv += g.x_advance as f32 * k * hscale;
|
||||
kern = if rc.kerned() && !key.rtl { pair_with_next(g, st.face.advance(g.gid)) * k * hscale } else { 0.0 };
|
||||
gi += 1;
|
||||
}
|
||||
let g1 = self.glyphs.len() as u32;
|
||||
@@ -455,6 +538,7 @@ impl<'a> Builder<'a> {
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: s == "." || s == ",",
|
||||
kern: if kind == ClKind::Text && g1 == g0 + 1 { kern } else { 0.0 },
|
||||
});
|
||||
}
|
||||
if matches!(dir, Dir::Para) {
|
||||
@@ -527,6 +611,7 @@ impl<'a> Builder<'a> {
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
});
|
||||
return;
|
||||
};
|
||||
@@ -560,7 +645,20 @@ impl<'a> Builder<'a> {
|
||||
let style = first.style;
|
||||
let g1 = added.last().map(|c| c.g1).unwrap_or(g0);
|
||||
self.shown.push((self.clusters.len(), text.to_string(), ranges));
|
||||
self.clusters.push(Cluster { start, end, adv: x, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
|
||||
self.clusters.push(Cluster {
|
||||
start,
|
||||
end,
|
||||
adv: x,
|
||||
kind: ClKind::Text,
|
||||
style,
|
||||
g0,
|
||||
g1,
|
||||
break_after: false,
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
});
|
||||
}
|
||||
|
||||
/// Shape `texts` on top of one another as one cluster for `start..end`: each aligned within
|
||||
@@ -610,11 +708,38 @@ impl<'a> Builder<'a> {
|
||||
if !text.is_empty() {
|
||||
self.shown.push((k, text, ranges));
|
||||
}
|
||||
self.clusters.push(Cluster { start, end, adv, kind: ClKind::Text, style, g0, g1, break_after: false, obj_h: 0.0, obj_d: 0.0, dot: false });
|
||||
self.clusters.push(Cluster {
|
||||
start,
|
||||
end,
|
||||
adv,
|
||||
kind: ClKind::Text,
|
||||
style,
|
||||
g0,
|
||||
g1,
|
||||
break_after: false,
|
||||
obj_h: 0.0,
|
||||
obj_d: 0.0,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
});
|
||||
Some(k)
|
||||
}
|
||||
}
|
||||
|
||||
/// What kerning added to a glyph's advance (in font units) for its pair with the next glyph. An
|
||||
/// old-style `kern` table's pair is split between its two glyphs, the second's half in its advance
|
||||
/// and its offset alike: that half is the pair with the glyph before, which stays on the line.
|
||||
fn pair_with_next(g: &wordcraft_fonts::ShapedGlyph, plain_advance: f64) -> f32 {
|
||||
let added = g.x_advance as f32 - plain_advance as f32;
|
||||
let before = if added != 0.0 { g.x_offset as f32 } else { 0.0 };
|
||||
added - before
|
||||
}
|
||||
|
||||
/// Times New Roman or one of its metric twins.
|
||||
fn is_times_twin(family: &str) -> bool {
|
||||
["Times New Roman", "Liberation Serif", "Tinos"].iter().any(|f| family.eq_ignore_ascii_case(f))
|
||||
}
|
||||
|
||||
/// Lay out an `EQ \o` field (ECMA-376 Part 1 §17.16.5.20): its arguments drawn on top of one
|
||||
/// another, as one cluster. An enclosure symbol among them (○ □ △ ◇, see
|
||||
/// [`wordcraft_doc::eq::EncloseShape`]) is drawn as a shape around the text rather than as a
|
||||
|
||||
@@ -55,7 +55,8 @@ pub(super) fn caps_expands(c: char) -> bool {
|
||||
}
|
||||
|
||||
/// Combining marks and joiners (bidi classes NSM, BN: harakat, ZWNJ, ZWJ) belong to the
|
||||
/// character before them: same font, same shaping run, so Arabic joining isn't broken.
|
||||
/// character before them: same font, same shaping run, so Arabic joining isn't broken. A mark
|
||||
/// that font can't draw takes its character to a face that draws both (`segment_keys`, #7865).
|
||||
pub(super) fn is_mark(c: char) -> bool {
|
||||
use unicode_bidi::BidiClass::{BN, NSM};
|
||||
// No ASCII character is a mark (its BN characters are controls).
|
||||
|
||||
@@ -14,6 +14,9 @@ const MIN_LINE_WIDTH: f32 = 1.0;
|
||||
struct Breaker<'e> {
|
||||
level: Option<&'e Level>,
|
||||
rp: wordcraft_doc::resolve::ResolvedPara,
|
||||
/// The space before the paragraph that the flow laid out above it, which a Top-and-Bottom
|
||||
/// object in it is laid out again below (see [`ParaEnv::space_before`]).
|
||||
space_before: f32,
|
||||
mark_style: u32,
|
||||
exclusions: &'e [Exclusion],
|
||||
n: usize,
|
||||
@@ -220,6 +223,7 @@ impl<'e> Breaker<'e> {
|
||||
// Exact spacing fixes the table-contact boundary even when the mark has other metrics.
|
||||
// Keep the existing estimate for shapes and for non-exact spacing.
|
||||
table_h: if let LineSpacing::Exactly(h) = rp.line_spacing { h } else { est_h },
|
||||
space_before: env.space_before,
|
||||
rp,
|
||||
first_x0: None,
|
||||
hcache: Vec::new(),
|
||||
@@ -262,6 +266,26 @@ impl<'e> Breaker<'e> {
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
let lo = self.row_left(pl);
|
||||
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
|
||||
// its first line) is a block the first line must start below, with that space before
|
||||
// laid out again under it (#7143). Exclusions are relative to the first line, so look
|
||||
// `space_before` above it too: the space the flow actually laid out, so an object
|
||||
// above a gap that collapsing, contextual spacing or a page top removed takes no
|
||||
// room, while the part of a merged gap that was laid out still does.
|
||||
if self.first && self.space_before > 0.0 {
|
||||
let before = self.space_before;
|
||||
let row = (self.top - before, self.est_h + before, self.table_h);
|
||||
if let Some(below) = self
|
||||
.exclusions
|
||||
.iter()
|
||||
.filter(|e| e.top_bottom)
|
||||
.filter(|e| e.intersects_row(row.0, row.1, row.2, lo, self.base_right))
|
||||
.map(|e| e.bottom)
|
||||
.reduce(f32::max)
|
||||
{
|
||||
self.top = self.top.max(below + before);
|
||||
}
|
||||
}
|
||||
let row = (self.top, self.est_h, self.table_h);
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
|
||||
Ok((Some((a, b)), rest)) => {
|
||||
@@ -442,7 +466,7 @@ impl<'e> Breaker<'e> {
|
||||
/// tallest picture on it (which sits on the baseline).
|
||||
fn extents(&self, pl: &ParaLayout, (c0, c1): (usize, usize)) -> Extents {
|
||||
let rp = &self.rp;
|
||||
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false };
|
||||
let mut ex = Extents { asc: 0.0, desc: 0.0, obj_asc: 0.0, obj_desc: 0.0, text: false, single: 0.0 };
|
||||
let mut any = false;
|
||||
let dropped = pl.drop_cap.map_or(0, |d| d.0);
|
||||
for (k, c) in pl.clusters.get(c0..c1).into_iter().flatten().enumerate() {
|
||||
@@ -486,6 +510,7 @@ impl<'e> Breaker<'e> {
|
||||
};
|
||||
ex.asc = ex.asc.max(a);
|
||||
ex.desc = ex.desc.max(d);
|
||||
ex.single = ex.single.max(a + d);
|
||||
any = true;
|
||||
// Text needs its descent below the line; so do inline math (an object with its own
|
||||
// descent) and a check box. A line break ending the line is no text.
|
||||
@@ -503,7 +528,7 @@ impl<'e> Breaker<'e> {
|
||||
/// The line's height, baseline and text extent.
|
||||
fn measure(&self, pl: &ParaLayout, range: (usize, usize)) -> Measure {
|
||||
let rp = &self.rp;
|
||||
let Extents { mut asc, mut desc, obj_asc, obj_desc, text } = self.extents(pl, range);
|
||||
let Extents { mut asc, mut desc, obj_asc, obj_desc, text, single } = self.extents(pl, range);
|
||||
let mut text_natural = asc + desc;
|
||||
let font_desc = desc;
|
||||
desc = desc.max(obj_desc);
|
||||
@@ -516,8 +541,8 @@ impl<'e> Breaker<'e> {
|
||||
// Word, measured with Arial at 10 and 20 pt, single, 1.15 and 1.5 spacing: a 30 pt picture
|
||||
// alone takes 30, 30 + 0.15 and 30 + 0.5 times the font's height, lowered 10 or 30 pt or
|
||||
// not; raised 10 pt, 10 more; a 6 pt one, the font's height; beside text and lowered
|
||||
// 10 pt, 30. Not on a line lowered further than the picture's height, which layout limits
|
||||
// to that height where Word's line keeps growing.
|
||||
// 10 pt, 30; lowered 30 pt, a 6 pt one makes a 30 pt line (`drawing` leaves the lowering
|
||||
// whole; exact spacing keeps it to the picture's height, see `extents`).
|
||||
let spacing = if let LineSpacing::Multiple(m) = rp.line_spacing { Some(m) } else { None };
|
||||
let pictures_alone = !text && obj_asc + obj_desc > 0.0 && spacing.is_some();
|
||||
let below = if pictures_alone { obj_desc } else { desc };
|
||||
@@ -554,6 +579,10 @@ impl<'e> Breaker<'e> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Multiple spacing adds (m - 1) x the tallest of the line's runs, not of the line: a line
|
||||
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
|
||||
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
|
||||
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
|
||||
// Keep the picture floor independent of list-label metrics.
|
||||
let natural = asc + desc;
|
||||
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
|
||||
@@ -562,7 +591,9 @@ impl<'e> Breaker<'e> {
|
||||
let (height, centred) = match (rp.line_spacing, grid) {
|
||||
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
|
||||
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
|
||||
(LineSpacing::Multiple(m), None) => ((text_natural * m + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false),
|
||||
(LineSpacing::Multiple(m), None) => {
|
||||
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
|
||||
}
|
||||
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
|
||||
(LineSpacing::Exactly(v), _) => (v, false),
|
||||
};
|
||||
@@ -745,6 +776,8 @@ struct Extents {
|
||||
obj_desc: f32,
|
||||
/// Whether the line holds text besides its pictures (spaces and tabs don't count).
|
||||
text: bool,
|
||||
/// The tallest of its runs' own heights (ascent plus descent): the multiple's leading.
|
||||
single: f32,
|
||||
}
|
||||
|
||||
/// A line's height and baseline, and the extent of its text.
|
||||
@@ -876,6 +909,14 @@ impl Scan {
|
||||
bk.wrapped_tab = Some(j);
|
||||
return true;
|
||||
}
|
||||
if bk.wrapped_tab == Some(j) && self.narrowed && stop.pos > bk.base_right + 0.01 && bk.skipped < 50 {
|
||||
// A left tab past the right indent that wrapped into a span narrowed by a
|
||||
// floating object (the far side of it, say): like Word, it goes on to the
|
||||
// first line clear of the object (#6577). A stop inside the right indent
|
||||
// keeps the zero-width path below.
|
||||
self.skip = true;
|
||||
return true;
|
||||
}
|
||||
if bk.wrapped_tab == Some(j) {
|
||||
// Still past the right indent on the line it wrapped to: it takes no
|
||||
// room, and its text starts at the indent rather than on a line of its own.
|
||||
@@ -909,19 +950,33 @@ impl Scan {
|
||||
}
|
||||
self.x += w;
|
||||
}
|
||||
_ => self.pending_tab = Some((j, stop, self.x)),
|
||||
_ => {
|
||||
// A right tab's room grows from nothing with its text (a tab moved on from the
|
||||
// line before may still hold the width it had there).
|
||||
if stop.align == TabAlign::Right
|
||||
&& let Some(c) = pl.clusters.get_mut(j)
|
||||
{
|
||||
c.adv = 0.0;
|
||||
}
|
||||
self.pending_tab = Some((j, stop, self.x));
|
||||
}
|
||||
}
|
||||
if stop.leader != TabLeader::None {
|
||||
self.leaders.push((j, stop.leader));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether text after a right/centre tab grows leftwards into the tab's space first.
|
||||
/// Whether text after a right/centre tab grows leftwards into the tab's space first. Up to a
|
||||
/// right stop it fits even past the right indent (Word: a TOC entry whose text ends
|
||||
/// less than a digit short of the indent keeps its page number on its line when the stop is
|
||||
/// at the margin); unshifted, the text after the tab ends at `x - room`.
|
||||
fn absorbs(&self, pl: &ParaLayout, advance: f32) -> bool {
|
||||
self.pending_tab.is_some_and(|(tj, stop, _)| {
|
||||
let room = pl.clusters.get(tj).map(|t| t.adv).unwrap_or(0.0);
|
||||
match stop.align {
|
||||
TabAlign::Right | TabAlign::Decimal => room >= advance,
|
||||
// Not where a floating object narrows the line: the text would run into it.
|
||||
TabAlign::Right => room >= advance || (!self.narrowed && self.x - room + advance <= stop.pos + 0.01),
|
||||
TabAlign::Decimal => room >= advance,
|
||||
TabAlign::Center => room >= advance / 2.0 && self.x + advance / 2.0 <= self.right_edge + 0.01,
|
||||
_ => false,
|
||||
}
|
||||
@@ -947,7 +1002,7 @@ impl Scan {
|
||||
0.0
|
||||
};
|
||||
let fits = absorbs
|
||||
|| self.x + advance - pl.auto_space_after(j) <= self.right_edge + shrink + 0.01
|
||||
|| self.x + advance - pl.auto_space_after(j) - line_end_kern(pl, j) <= self.right_edge + shrink + 0.01
|
||||
|| c.kind == ClKind::Space
|
||||
|| c.kind == ClKind::Marker;
|
||||
if !fits && pl.is_edit_boundary(c.start) && (c0..j).any(|k| pl.clusters.get(k).is_some_and(takes_room)) {
|
||||
@@ -997,7 +1052,9 @@ impl Scan {
|
||||
/// Text after a decimal/centre/right tab shifts as it grows.
|
||||
fn shift_pending_tab(&mut self, pl: &mut ParaLayout) {
|
||||
let Some((tj, stop, tx)) = self.pending_tab else { return };
|
||||
let seg_w = self.x - tx;
|
||||
// For a right tab `x` includes the room the tab has so far (it starts from none).
|
||||
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
|
||||
let seg_w = self.x - tx - if stop.align == TabAlign::Right { old } else { 0.0 };
|
||||
let shift = match stop.align {
|
||||
TabAlign::Right => stop.pos - tx - seg_w,
|
||||
TabAlign::Center => stop.pos - tx - seg_w / 2.0,
|
||||
@@ -1006,7 +1063,6 @@ impl Scan {
|
||||
_ => 0.0,
|
||||
};
|
||||
let shift = shift.max(0.0);
|
||||
let old = pl.clusters.get(tj).map(|c| c.adv).unwrap_or(0.0);
|
||||
if (shift - old).abs() > 0.001 {
|
||||
let delta = shift - old;
|
||||
if let Some(c) = pl.clusters.get_mut(tj) {
|
||||
@@ -1114,6 +1170,17 @@ impl Scan {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kerning cluster `j` loses when the line ends after it inside a word: Word measures a line's
|
||||
/// last letter without its pair with the letter that goes on to the next line (a cell's width
|
||||
/// swept a twip at a time in Word: the letters before a broken kerning pair fit only where they
|
||||
/// fit on their own, without the pair).
|
||||
fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
|
||||
match (pl.clusters.get(j), pl.clusters.get(j + 1)) {
|
||||
(Some(c), Some(next)) if next.kind == ClKind::Text => c.kern,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
|
||||
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
|
||||
const MIN_SPAN: f32 = 20.0;
|
||||
|
||||
@@ -147,6 +147,9 @@ pub struct Cluster {
|
||||
pub obj_d: f32,
|
||||
/// The cluster is a decimal separator (decimal tabs align on it).
|
||||
pub dot: bool,
|
||||
/// The kerning between this cluster and the next (part of `adv`, usually negative): a line
|
||||
/// that ends between them lays the cluster out without it.
|
||||
pub kern: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -391,8 +394,14 @@ pub struct ParaEnv<'a> {
|
||||
/// How digits look on screen (an unresolved `System` shows Western digits).
|
||||
pub numeral: NumeralMode,
|
||||
/// Areas text must flow around (floating objects), relative to the paragraph: x from the
|
||||
/// column's left edge, y from the top of the first line.
|
||||
/// column's left edge, y from the top of the first line (its top with the space before
|
||||
/// applied, which is where [`ParaEnv::space_before`] reaches up to).
|
||||
pub exclusions: &'a [Exclusion],
|
||||
/// The space before the paragraph that the flow above it actually laid out: its declared
|
||||
/// space before less what collapsing against the previous paragraph's space after, contextual
|
||||
/// spacing or a page top took away (and the negative space applied at a page top). A
|
||||
/// Top-and-Bottom object reaching into it is laid out again below it (#7143).
|
||||
pub space_before: f32,
|
||||
/// Automatic equation numbers used before this paragraph.
|
||||
pub eq_number: u32,
|
||||
pub read_line_spacing: Option<f32>,
|
||||
|
||||
@@ -62,6 +62,7 @@ impl Slot {
|
||||
obj_h,
|
||||
obj_d,
|
||||
dot: false,
|
||||
kern: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,6 +102,11 @@ fn is_special(c: char) -> bool {
|
||||
fn paragraph_props(p: &Paragraph, env: &ParaEnv) -> ResolvedPara {
|
||||
let doc = env.doc;
|
||||
let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para));
|
||||
// Before Word 2013 layout (compatibility mode 15) a row split across pages divides its cells'
|
||||
// text at any line: widow/orphan control doesn't apply in a table (measured in modes 12, 14).
|
||||
if env.table.is_some() && doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT {
|
||||
rp.widow_control = false;
|
||||
}
|
||||
if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) {
|
||||
rp.line_spacing = wordcraft_doc::props::LineSpacing::Multiple(spacing);
|
||||
}
|
||||
@@ -392,6 +398,11 @@ impl<'a> Shaped<'a> {
|
||||
},
|
||||
_ => w,
|
||||
};
|
||||
// Word keeps the height in whole twips and drops the rest of the EMUs: 2007874 EMU
|
||||
// (3161.99tw) is drawn 158.05pt high, and only that has to fit above the bottom margin
|
||||
// (Word for Mac and Windows). Back to whole EMUs first: f32 points keep them to the EMU
|
||||
// for pictures up to a page high.
|
||||
let h = (((h as f64 * 12_700.0).round() / 635.0).floor() / 20.0) as f32;
|
||||
let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0));
|
||||
let s = if env.fit_objects && w > maxw { maxw / w } else { 1.0 };
|
||||
// The line makes room for effects (shadows) around the picture too, and
|
||||
@@ -541,7 +552,12 @@ fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
|
||||
let break_only =
|
||||
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
|
||||
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
|
||||
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
|
||||
let mut rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
|
||||
// Word never kerns a list number, whatever the kerning of the paragraph mark or the level
|
||||
// (measured in Word for Mac: "11)" in Times New Roman with kerning on is 16 pt wide, not
|
||||
// the 15.55 pt of the kerned "11", so it passes a 312-twip hanging indent and the text goes on
|
||||
// to the next tab stop).
|
||||
Arc::make_mut(&mut rc).kern = 0.0;
|
||||
// A bullet no installed font can draw would come from whatever icon font has its
|
||||
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
|
||||
// default bullet instead.
|
||||
@@ -677,9 +693,13 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
|
||||
if rp.snap_to_grid {
|
||||
snap_chars(&mut sh.b, &p.text, &env.grid);
|
||||
}
|
||||
// Text on a character grid keeps to its cells.
|
||||
let auto_space =
|
||||
if rp.snap_to_grid && env.grid.chars.is_some() { Vec::new() } else { auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn) };
|
||||
// Text snapping to every cell of a character grid (`snapToChars`) keeps to its cells. On a
|
||||
// `linesAndChars` grid Word keeps the automatic space, as on a line grid (#6584).
|
||||
let auto_space = if rp.snap_to_grid && env.grid.snap_all && env.grid.chars.is_some() {
|
||||
Vec::new()
|
||||
} else {
|
||||
auto_space(&mut sh.b, &p.text, rp.auto_space_de, rp.auto_space_dn)
|
||||
};
|
||||
let mut skip = sh.left.clone();
|
||||
skip.extend(sh.bare.iter().cloned());
|
||||
let bt = BreakText::new(&p.text, skip);
|
||||
@@ -854,6 +874,15 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
|
||||
if !before_slash.is_empty() {
|
||||
found.extend(before_slash);
|
||||
}
|
||||
// Word breaks after a space whatever follows it, where UAX #14 keeps a space with a closing
|
||||
// bracket or punctuation after it (LB13: "x :=", "false );", "JDK} ,") and an opening bracket
|
||||
// with the space after it (LB14: "( word"). Measured in Word for Mac and Windows: the next line
|
||||
// starts with ":=", ";", ",", ".", ")", "]", "}", "!", "?", "%", or with "word" after "( ". Not
|
||||
// before another space or a no-break space: the spaces stay together; nor before a word joiner
|
||||
// or a zero-width space, which UAX #14 never lets start a line (LB11, LB7).
|
||||
found.extend(text.match_indices(' ').map(|(i, _)| i + 1).filter(|&i| {
|
||||
text.get(i..).and_then(|t| t.chars().next()).is_some_and(|c| !c.is_whitespace() && !matches!(c, '\u{2060}' | '\u{FEFF}' | '\u{200B}'))
|
||||
}));
|
||||
|
||||
// Word breaks after a hyphen even when a digit follows ("2016-" / "2022"), where UAX #14
|
||||
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
|
||||
|
||||
@@ -54,7 +54,7 @@ struct Sec<'p> {
|
||||
|
||||
/// Forget cached layouts made for another environment, and what the last pass used.
|
||||
fn reset_cache(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) {
|
||||
let env = env_hash(doc, opts);
|
||||
let env = env_hash(doc, cache, opts);
|
||||
if env != cache.env {
|
||||
cache.paras.clear();
|
||||
cache.measures.clear();
|
||||
@@ -234,8 +234,10 @@ fn new_page_builder<'p>(
|
||||
sect_beneath: false,
|
||||
beneath: false,
|
||||
foot_top: f32::MAX,
|
||||
leading_floor: 0.0,
|
||||
early,
|
||||
seeded: 0,
|
||||
framed: Vec::new(),
|
||||
settle,
|
||||
column_lines: None,
|
||||
}
|
||||
@@ -445,9 +447,10 @@ fn section_endnotes(ctx: &mut Ctx, pb: &mut PageBuilder, endnotes: &mut VecDeque
|
||||
/// the turned pages of vertical sections.
|
||||
fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionProps)], web: bool) -> Vec<Page> {
|
||||
let mut pb = pb;
|
||||
pb.close_column_lines();
|
||||
pb.apply_valign();
|
||||
pb.flush_notes();
|
||||
// Each page is aligned once, before its notes go on it: `finish_page` leaves the page
|
||||
// top-aligned after, so a page of continued notes isn't moved down again past the bottom
|
||||
// margin when the next one starts.
|
||||
pb.finish_page();
|
||||
let last_block = doc.body.len().saturating_sub(1);
|
||||
for _ in 0..MAX_NOTE_PAGES {
|
||||
if pb.carry.is_empty() {
|
||||
@@ -455,7 +458,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
|
||||
}
|
||||
let top = pb.top;
|
||||
pb.new_page(last_block, top);
|
||||
pb.flush_notes();
|
||||
pb.finish_page();
|
||||
}
|
||||
pb.carry.clear();
|
||||
pb.raise_front();
|
||||
@@ -521,12 +524,18 @@ fn fill_headers_footers(
|
||||
None
|
||||
}
|
||||
|
||||
/// Evict paragraph layouts that weren't used this pass if the cache grew large.
|
||||
/// Evict paragraph layouts that weren't used this pass if the cache accumulated too many stale entries.
|
||||
fn evict_unused(cache: &mut LayoutCache) {
|
||||
if cache.paras.len() + cache.measures.len() > 4 * cache.used.len().max(1024) {
|
||||
if cache.paras.len() + cache.measures.len() > cache.used.len() + cache.used.len().clamp(512, 1024) {
|
||||
let used = std::mem::take(&mut cache.used);
|
||||
cache.paras.retain(|k, _| used.contains(k));
|
||||
cache.measures.retain(|k, _| used.contains(k));
|
||||
if cache.paras.capacity() > cache.paras.len().max(512) * 4 {
|
||||
cache.paras.shrink_to(cache.paras.len() * 2);
|
||||
}
|
||||
if cache.measures.capacity() > cache.measures.len().max(256) * 4 {
|
||||
cache.measures.shrink_to(cache.measures.len() * 2);
|
||||
}
|
||||
cache.used = used;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user