mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 20:27:02 -06:00
Compare commits
1006
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47ad5dd540 | ||
|
|
6f3b1b7d17 | ||
|
|
f98a4d004c | ||
|
|
f1d3b6dccd | ||
|
|
6b0f28c744 | ||
|
|
fd179f880e | ||
|
|
a822ef33ea | ||
|
|
9348c590c0 | ||
|
|
c8186db02c | ||
|
|
c59b417f94 | ||
|
|
29460b5583 | ||
|
|
311fad12b8 | ||
|
|
cb0647a685 | ||
|
|
044bbce813 | ||
|
|
dfa1223a01 | ||
|
|
28f0c40503 | ||
|
|
63cc890f30 | ||
|
|
e194d86db6 | ||
|
|
c658b7a3ba | ||
|
|
d89f035219 | ||
|
|
860d728dfd | ||
|
|
0282a6124f | ||
|
|
3bb8a438b0 | ||
|
|
f333552fe5 | ||
|
|
9a36468569 | ||
|
|
ba1b2d5951 | ||
|
|
38f277cb10 | ||
|
|
63dbe61cda | ||
|
|
722ee1b60d | ||
|
|
53e426820a | ||
|
|
e77669a552 | ||
|
|
55ee6bfcb8 | ||
|
|
b6adce3262 | ||
|
|
68c94e9a2b | ||
|
|
ae713e05a8 | ||
|
|
b8ba467e54 | ||
|
|
71a3072fec | ||
|
|
25af5ed462 | ||
|
|
8a24807722 | ||
|
|
a269d3e13d | ||
|
|
b5d21f1ba9 | ||
|
|
8bda45fefa | ||
|
|
ba31d08b3f | ||
|
|
b6ced6363b | ||
|
|
3c22bd688c | ||
|
|
7460b7f916 | ||
|
|
bcaba5a37c | ||
|
|
e927cd7e8e | ||
|
|
cc1f3231a7 | ||
|
|
f5930f52ca | ||
|
|
777aae19e5 | ||
|
|
d81b0b503e | ||
|
|
538597a7ea | ||
|
|
58a3e6cf5b | ||
|
|
53c9e64e98 | ||
|
|
3ee43d57d2 | ||
|
|
6c3c3d181e | ||
|
|
5b4302828e | ||
|
|
08e21b1abc | ||
|
|
a188a76506 | ||
|
|
e219a5a9c3 | ||
|
|
7810b05973 | ||
|
|
89f0d39e7f | ||
|
|
946a626f5c | ||
|
|
9769b941c4 | ||
|
|
769a799620 | ||
|
|
0de7b3a5aa | ||
|
|
9f813636cf | ||
|
|
7e70097130 | ||
|
|
4cb1d22b0e | ||
|
|
d9b3a8eb9c | ||
|
|
9bb2d72898 | ||
|
|
3c73997925 | ||
|
|
d7748aa732 | ||
|
|
f5a9d415b8 | ||
|
|
a5b4b22ebf | ||
|
|
4f7d01edac | ||
|
|
5aa1a78082 | ||
|
|
9986d9b4cd | ||
|
|
dd017d865d | ||
|
|
393103ffdd | ||
|
|
c7661b2b0e | ||
|
|
20dd292da4 | ||
|
|
988cfaa5f1 | ||
|
|
0bd4878a34 | ||
|
|
737a19bbb0 | ||
|
|
c5f0865fa7 | ||
|
|
319838ab02 | ||
|
|
21b1ceb1c1 | ||
|
|
845df1cd48 | ||
|
|
0c9e6054d9 | ||
|
|
8f6a40d3f4 | ||
|
|
9ce63943af | ||
|
|
74ffe933cf | ||
|
|
306040b646 | ||
|
|
65960089a8 | ||
|
|
ec4922027f | ||
|
|
cb919da767 | ||
|
|
aadcc80cab | ||
|
|
6bf2ef18bb | ||
|
|
3b929eac31 | ||
|
|
a895098132 | ||
|
|
82887db8bb | ||
|
|
ac99969305 | ||
|
|
76b74dec50 | ||
|
|
2daca588a4 | ||
|
|
ae4f2dbf48 | ||
|
|
591a5ace12 | ||
|
|
f6d1207be2 | ||
|
|
77aab09d31 | ||
|
|
ee9a8153d3 | ||
|
|
5ad1be0472 | ||
|
|
ae876e0cdc | ||
|
|
f0b95f73fb | ||
|
|
4c8296a5b1 | ||
|
|
9b1ef01485 | ||
|
|
a46514f5df | ||
|
|
6af5d8c650 | ||
|
|
1e91f5cc1e | ||
|
|
bd9529b083 | ||
|
|
a7396929c7 | ||
|
|
42df428b01 | ||
|
|
fbb26d0b85 | ||
|
|
84a8675092 | ||
|
|
bfa3d12bfa | ||
|
|
e92a4d45f8 | ||
|
|
f4431d6b63 | ||
|
|
5203e2e7dc | ||
|
|
bdae1b73ae | ||
|
|
bdb955d2c6 | ||
|
|
d78467b616 | ||
|
|
069a69a5eb | ||
|
|
50f4b803a6 | ||
|
|
b81f67dfab | ||
|
|
ddcaffe387 | ||
|
|
11f830907d | ||
|
|
3512da9553 | ||
|
|
9a349bf372 | ||
|
|
16b7706a4d | ||
|
|
ffdc0c2332 | ||
|
|
d813e02661 | ||
|
|
b2c183fc8b | ||
|
|
f900ac06c2 | ||
|
|
4bc5b97c31 | ||
|
|
3f70941206 | ||
|
|
f1583c3417 | ||
|
|
f4f182b900 | ||
|
|
f966ceaa25 | ||
|
|
9b9dc5b103 | ||
|
|
2c70194a5b | ||
|
|
57bdc13e28 | ||
|
|
f302f189a6 | ||
|
|
a12799387d | ||
|
|
c3696df3d9 | ||
|
|
b6022a338c | ||
|
|
1e4c3d52de | ||
|
|
3c1ea66dd9 | ||
|
|
55992a696b | ||
|
|
eaec70d125 | ||
|
|
b4db8a407c | ||
|
|
4094828264 | ||
|
|
6f7afc6a5d | ||
|
|
c634f6c83e | ||
|
|
6cc86be260 | ||
|
|
f5d1d992a2 | ||
|
|
f550268bab | ||
|
|
b3c7338b3c | ||
|
|
a1e458a1c0 | ||
|
|
31b7bd6a63 | ||
|
|
63e43ae563 | ||
|
|
c479c88bbc | ||
|
|
af3179b7e8 | ||
|
|
31001fc6df | ||
|
|
259c86f8f8 | ||
|
|
0d5052d76d | ||
|
|
c2d4f64766 | ||
|
|
2804833dae | ||
|
|
00eaa42e0d | ||
|
|
308d4b6b05 | ||
|
|
b6eafa3d09 | ||
|
|
6f4652f976 | ||
|
|
f70664a13c | ||
|
|
ba4d06c12d | ||
|
|
e319029fdf | ||
|
|
4431cc1fea | ||
|
|
010b065dad | ||
|
|
c8629cfe9c | ||
|
|
0dcf26fcd1 | ||
|
|
2b6160b528 | ||
|
|
167bde7ed4 | ||
|
|
1a79ad29d8 | ||
|
|
45a00707c7 | ||
|
|
f81608db32 | ||
|
|
add2a11697 | ||
|
|
a917d2a4de | ||
|
|
739454c0f3 | ||
|
|
887e2c7af0 | ||
|
|
a82e4003c9 | ||
|
|
35dafa9376 | ||
|
|
85a7c754b3 | ||
|
|
dffc8f903c | ||
|
|
26ef54f4df | ||
|
|
81d0cf4a01 | ||
|
|
82c9dc4a51 | ||
|
|
9866095090 | ||
|
|
41532af120 | ||
|
|
4d90a255ab | ||
|
|
fa1687eedf | ||
|
|
918772e8ed | ||
|
|
9fa7295ea6 | ||
|
|
6d09c5069c | ||
|
|
c7fe2a479d | ||
|
|
6eadc423fd | ||
|
|
2502cb5467 | ||
|
|
916b99cd1f | ||
|
|
c8b88a23a1 | ||
|
|
a22cb3d822 | ||
|
|
49a5373fa2 | ||
|
|
610ec99314 | ||
|
|
c555672b56 | ||
|
|
d417b835b0 | ||
|
|
4e35526836 | ||
|
|
3094b3e02f | ||
|
|
071dfbb228 | ||
|
|
d98742d1cb | ||
|
|
20f26da670 | ||
|
|
1b284b7532 | ||
|
|
74a6b48bf6 | ||
|
|
005e028be7 | ||
|
|
882cac2672 | ||
|
|
e6b39f3d0f | ||
|
|
08b54d1166 | ||
|
|
b1aabef2cf | ||
|
|
044f06a9c6 | ||
|
|
183342276b | ||
|
|
ba4c143c9d | ||
|
|
95748dc79d | ||
|
|
009a94b4d0 | ||
|
|
c1a23c6a1f | ||
|
|
79f0fef906 | ||
|
|
22325c2575 | ||
|
|
37981b4fca | ||
|
|
a4ad65c372 | ||
|
|
4781d91473 | ||
|
|
04a3c76c10 | ||
|
|
e8414db9a5 | ||
|
|
fbe41cca76 | ||
|
|
553f0058ee | ||
|
|
c4ab2fea70 | ||
|
|
47ef5ce7b3 | ||
|
|
824d3c431e | ||
|
|
d2c8ba2787 | ||
|
|
8370cf558d | ||
|
|
257bc77e69 | ||
|
|
c7b4dfab8b | ||
|
|
0171216a13 | ||
|
|
f0a323fdce | ||
|
|
6a3a18eba5 | ||
|
|
0242af0fdb | ||
|
|
4f8ac61c76 | ||
|
|
d7c01bcd05 | ||
|
|
789cabd832 | ||
|
|
6545c44f0a | ||
|
|
b22e901c45 | ||
|
|
c60c82d960 | ||
|
|
67bfa46a3d | ||
|
|
513ff0541f | ||
|
|
d4a565447f | ||
|
|
6f7b8156dc | ||
|
|
a21324bf78 | ||
|
|
a39f6adf9f | ||
|
|
b2dd74729f | ||
|
|
5ea160c706 | ||
|
|
8a7fef3ec6 | ||
|
|
84118adcf9 | ||
|
|
0ec775a9b9 | ||
|
|
caf9c8de8b | ||
|
|
135c1f72b1 | ||
|
|
c07b649e7b | ||
|
|
c70ad1bab2 | ||
|
|
4358f546d8 | ||
|
|
6b79b722d3 | ||
|
|
eba89475f6 | ||
|
|
64ef08c60a | ||
|
|
bc71452511 | ||
|
|
fb9276c4a6 | ||
|
|
ce2b01e005 | ||
|
|
c2a370cd67 | ||
|
|
0a31f5de5d | ||
|
|
1129aa51f2 | ||
|
|
4ad6272409 | ||
|
|
70e181a966 | ||
|
|
496d276873 | ||
|
|
32ad05fe64 | ||
|
|
b2dd18c916 | ||
|
|
dc9327501c | ||
|
|
b2021313ab | ||
|
|
41b351d770 | ||
|
|
3fbc536eba | ||
|
|
7342c32b1e | ||
|
|
0f0551351a | ||
|
|
c99d119543 | ||
|
|
a60bd414ed | ||
|
|
53d83510d7 | ||
|
|
58b595835f | ||
|
|
438c12d54a | ||
|
|
fb813b7988 | ||
|
|
58f942aa62 | ||
|
|
67aa8ca4b7 | ||
|
|
b8ac6de3d0 | ||
|
|
db92b5cf2e | ||
|
|
18a8326ff0 | ||
|
|
b1de6f8556 | ||
|
|
d2ed8a334b | ||
|
|
c583679407 | ||
|
|
e6ff55e758 | ||
|
|
7d45de75f6 | ||
|
|
84e7aee82f | ||
|
|
dfb7e2647e | ||
|
|
c070c2a258 | ||
|
|
ba7318322a | ||
|
|
b7f52b6c78 | ||
|
|
4d7be007da | ||
|
|
14280d1c03 | ||
|
|
2bf03bcfc6 | ||
|
|
ea2e2f2970 | ||
|
|
f5892400de | ||
|
|
874184f066 | ||
|
|
501dddf7b5 | ||
|
|
1f6eb8eceb | ||
|
|
087bf2535b | ||
|
|
7a408c7eb3 | ||
|
|
7b213b331b | ||
|
|
d62508ca40 | ||
|
|
a1ad0f4cbc | ||
|
|
9c54fc1446 | ||
|
|
fbde8c47a3 | ||
|
|
481207f29d | ||
|
|
e3f9ed8134 | ||
|
|
4add275c07 | ||
|
|
5f39de62f8 | ||
|
|
830065bd62 | ||
|
|
31b2be75f4 | ||
|
|
195f103ceb | ||
|
|
96b8c1c58b | ||
|
|
de30199f1f | ||
|
|
14ed0bfa28 | ||
|
|
bf54864f37 | ||
|
|
61893e1950 | ||
|
|
b6777d494c | ||
|
|
434d9b223e | ||
|
|
802a2e2120 | ||
|
|
83f437ec89 | ||
|
|
3bae0c1cdb | ||
|
|
aa2c33e5a9 | ||
|
|
c26f801e20 | ||
|
|
7b1d234029 | ||
|
|
7361228721 | ||
|
|
05dda70d5c | ||
|
|
17fecc43ec | ||
|
|
0d8409ea36 | ||
|
|
4281ebbcb1 | ||
|
|
3843ada39b | ||
|
|
ed17e883e5 | ||
|
|
a0ca3766b3 | ||
|
|
1a7b691293 | ||
|
|
3ebe82eb5e | ||
|
|
e9708b91ae | ||
|
|
9f28b67cbc | ||
|
|
2ddf619270 | ||
|
|
27da3abc76 | ||
|
|
a6e831e8ca | ||
|
|
ecd8b5db7b | ||
|
|
ffadc1d8de | ||
|
|
06d7d3e9a6 | ||
|
|
e4e2c2d9d7 | ||
|
|
dba4269b25 | ||
|
|
7888d77bbd | ||
|
|
94aa34729c | ||
|
|
51ef42c9f5 | ||
|
|
a57a77d4c5 | ||
|
|
d0dbc425ee | ||
|
|
6e67012f78 | ||
|
|
79ab962f36 | ||
|
|
43f636055e | ||
|
|
76e76b7697 | ||
|
|
4c467c1485 | ||
|
|
f9b8b60873 | ||
|
|
259870a313 | ||
|
|
b864439f5c | ||
|
|
cd7c14e776 | ||
|
|
85dd661854 | ||
|
|
b7f512d037 | ||
|
|
62ff8ba0c2 | ||
|
|
4680b9a270 | ||
|
|
29c67c62d7 | ||
|
|
0866c5bfaa | ||
|
|
68680e0665 | ||
|
|
78d6825d3b | ||
|
|
be1f9c0a1f | ||
|
|
f329ff6e81 | ||
|
|
8f330f5e26 | ||
|
|
a6ee9f22a4 | ||
|
|
cf95e5a37a | ||
|
|
1469c44e81 | ||
|
|
d184ccbfb4 | ||
|
|
0adadeed56 | ||
|
|
b3dbe51f1a | ||
|
|
b1a17b688f | ||
|
|
3adb7b5055 | ||
|
|
92c65bc00b | ||
|
|
61b83a4927 | ||
|
|
84d46c47f4 | ||
|
|
ae760626cf | ||
|
|
c2d2e93500 | ||
|
|
995746d24e | ||
|
|
21671b9b66 | ||
|
|
e2079632f3 | ||
|
|
22f774fb9f | ||
|
|
d847fa225e | ||
|
|
6a91bc63f6 | ||
|
|
a8628f3969 | ||
|
|
d46178a145 | ||
|
|
489d61cd10 | ||
|
|
f71bf017a7 | ||
|
|
da8845c810 | ||
|
|
7605fd3c8a | ||
|
|
51b1933480 | ||
|
|
d0fc72a7ba | ||
|
|
e4950a63b5 | ||
|
|
7b7e2a7ff6 | ||
|
|
1f57c527a2 | ||
|
|
450938fe00 | ||
|
|
a9917af050 | ||
|
|
9757882dda | ||
|
|
e85e15ee14 | ||
|
|
5abe5745ce | ||
|
|
522597264c | ||
|
|
78bec40359 | ||
|
|
d3508c9d18 | ||
|
|
366ecb731e | ||
|
|
0dac42909e | ||
|
|
3f33f90f31 | ||
|
|
e7dc3bf319 | ||
|
|
34cc9214d9 | ||
|
|
3cef779801 | ||
|
|
ad958edfce | ||
|
|
a3ee0d1ae2 | ||
|
|
f0ab199fa3 | ||
|
|
8ef485cb08 | ||
|
|
7417fbbb0f | ||
|
|
e1fccab746 | ||
|
|
0081098f4f | ||
|
|
99917717fd | ||
|
|
87dc3b203e | ||
|
|
cbe03ab801 | ||
|
|
a969c01e57 | ||
|
|
b1eb5ffb5e | ||
|
|
2dd637028a | ||
|
|
ab0dcf391c | ||
|
|
f4ac3b9ef5 | ||
|
|
967d608eb5 | ||
|
|
51359bf825 | ||
|
|
121a43de5b | ||
|
|
571473749e | ||
|
|
6fc57857c8 | ||
|
|
2d9790c374 | ||
|
|
9621688eae | ||
|
|
3ced0353e1 | ||
|
|
7e402c7529 | ||
|
|
ea7fe218ea | ||
|
|
eb3ae58fd4 | ||
|
|
bd7c07aea1 | ||
|
|
6c37ffb1eb | ||
|
|
4876dc7fbd | ||
|
|
ca6a949a24 | ||
|
|
ba775deed9 | ||
|
|
17da903053 | ||
|
|
e253cac545 | ||
|
|
6985800d23 | ||
|
|
08d6f87dca | ||
|
|
401eabf292 | ||
|
|
320af8dbe1 | ||
|
|
0b0011e053 | ||
|
|
187a36e16c | ||
|
|
2573d54c4d | ||
|
|
752b78cd18 | ||
|
|
20f91f5bdf | ||
|
|
69f3ccbba8 | ||
|
|
29c5c19d67 | ||
|
|
903edaffc7 | ||
|
|
34c6eeff8d | ||
|
|
8725caa4a3 | ||
|
|
3e3975d3a0 | ||
|
|
77d00e0ee1 | ||
|
|
9cda9db296 | ||
|
|
500e150132 | ||
|
|
416db1b645 | ||
|
|
8baa46395f | ||
|
|
2f08031e75 | ||
|
|
e9f07d8837 | ||
|
|
3c79eca060 | ||
|
|
a1aa614bf1 | ||
|
|
71abe1c4c9 | ||
|
|
5ca9917471 | ||
|
|
37c8061088 | ||
|
|
d53ba37903 | ||
|
|
5073f8e7c2 | ||
|
|
0df3151f01 | ||
|
|
92eb57fd08 | ||
|
|
f1fb526f3f | ||
|
|
b4ecd20dba | ||
|
|
161c127926 | ||
|
|
de328db448 | ||
|
|
e3d1ee90c3 | ||
|
|
3138201a56 | ||
|
|
0600244e11 | ||
|
|
3b0257ff33 | ||
|
|
1591f99189 | ||
|
|
1ffd5f8d4a | ||
|
|
3b2ce5cb83 | ||
|
|
e2f2fe1f09 | ||
|
|
cfae52c97d | ||
|
|
0e47c8613c | ||
|
|
d7986fc26c | ||
|
|
1812618f10 | ||
|
|
e7172b9a8a | ||
|
|
b211131dec | ||
|
|
bbc587e2a6 | ||
|
|
f1ad785403 | ||
|
|
e3653ada4b | ||
|
|
167e479382 | ||
|
|
81abc0d81b | ||
|
|
eb8a7e311c | ||
|
|
040150d486 | ||
|
|
b7e49e84b3 | ||
|
|
168e39e5a4 | ||
|
|
0fe7ede07e | ||
|
|
5b24de412e | ||
|
|
5dad217316 | ||
|
|
2ad2694407 | ||
|
|
4622fef6ce | ||
|
|
061985fb6b | ||
|
|
b8334518b3 | ||
|
|
2b612d51fa | ||
|
|
472399cb33 | ||
|
|
25b86d2a1d | ||
|
|
dd3dedddae | ||
|
|
04e04e8119 | ||
|
|
e3749fc2d0 | ||
|
|
020eba42ff | ||
|
|
1a339aebb4 | ||
|
|
5d46607ec4 | ||
|
|
456aa68148 | ||
|
|
83ada40e06 | ||
|
|
b36fa16a15 | ||
|
|
04cd0ca6fd | ||
|
|
05cbdfd9ff | ||
|
|
e66ba81d3f | ||
|
|
8633e63909 | ||
|
|
8bf97aa275 | ||
|
|
a2960ce55d | ||
|
|
48b211621d | ||
|
|
c39e70fc85 | ||
|
|
0a1d913690 | ||
|
|
91a75c8103 | ||
|
|
c55e7a83e6 | ||
|
|
129b6ad2f9 | ||
|
|
fc3146206a | ||
|
|
b682a1fd06 | ||
|
|
6bdd6769d1 | ||
|
|
6a6dfd7f58 | ||
|
|
4c600213dc | ||
|
|
af4cacc45f | ||
|
|
8d75a12b48 | ||
|
|
ba179cb3d1 | ||
|
|
30458a8e0b | ||
|
|
6d27b1a4a1 | ||
|
|
faf55fad76 | ||
|
|
9d5789162f | ||
|
|
cdef8012e9 | ||
|
|
8bca61f529 | ||
|
|
4dd74c36d5 | ||
|
|
83381d344a | ||
|
|
46050e5c4b | ||
|
|
6d2f0d7759 | ||
|
|
4073aa4274 | ||
|
|
95388461a7 | ||
|
|
53b22e61f2 | ||
|
|
f641b83a2f | ||
|
|
8544a588c1 | ||
|
|
9964e4e88c | ||
|
|
49ef461bc3 | ||
|
|
2bfc68964b | ||
|
|
ddb8fa164b | ||
|
|
8d9a614e15 | ||
|
|
0e4d52a5aa | ||
|
|
d25db5fa8f | ||
|
|
9abd324244 | ||
|
|
77dc3e75b9 | ||
|
|
8082743bb8 | ||
|
|
4f4827a7c0 | ||
|
|
54cf516adf | ||
|
|
3db40dabac | ||
|
|
4ea1fe935a | ||
|
|
9a2d6902f4 | ||
|
|
8a2e47f8c3 | ||
|
|
c4cd11c5ff | ||
|
|
3a7a3b4b95 | ||
|
|
72ef3083e7 | ||
|
|
1ec83a1a2f | ||
|
|
27672b2448 | ||
|
|
67d5297c08 | ||
|
|
4c1dfa6367 | ||
|
|
ccf405de52 | ||
|
|
da072c3e74 | ||
|
|
1580f46cee | ||
|
|
ab58acfa09 | ||
|
|
c013dff332 | ||
|
|
e976e6aa69 | ||
|
|
f03da28fb5 | ||
|
|
48f0ad7496 | ||
|
|
d48ca8d3ec | ||
|
|
425f6d990d | ||
|
|
e3878d2b83 | ||
|
|
a1b04eaa52 | ||
|
|
f98d9c2515 | ||
|
|
d8f1a821c7 | ||
|
|
b400a7bbb8 | ||
|
|
c84c1b9e44 | ||
|
|
bee380b2e8 | ||
|
|
dc266c5e55 | ||
|
|
95bfd5af43 | ||
|
|
c7bb1c9636 | ||
|
|
463552ac36 | ||
|
|
870bbffddf | ||
|
|
48fca374b3 | ||
|
|
11323ff0dd | ||
|
|
5833546550 | ||
|
|
a2d8bbdb4d | ||
|
|
98e617806b | ||
|
|
4f6dbbb5fd | ||
|
|
882bacb858 | ||
|
|
3487354a1b | ||
|
|
991b590021 | ||
|
|
549748efec | ||
|
|
bf7ce2509c | ||
|
|
f5c9da1b70 | ||
|
|
a6d1534889 | ||
|
|
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 | ||
|
|
3c9c0219b8 | ||
|
|
b185aaf839 | ||
|
|
03439ff33f | ||
|
|
93573f56e6 | ||
|
|
cb1c530240 | ||
|
|
dc5f5852dd | ||
|
|
b4cb84ea5d | ||
|
|
faebf07b9a | ||
|
|
acc1233da0 | ||
|
|
c1a0484d81 | ||
|
|
f6f7e9414e | ||
|
|
1de5a93974 | ||
|
|
9f43aa6ec1 | ||
|
|
f2e2c78c4b | ||
|
|
fe22b29c5f | ||
|
|
7f86031339 | ||
|
|
10fcb05b15 | ||
|
|
1a05479d99 | ||
|
|
fc0acd93b9 | ||
|
|
5c2e7eb296 | ||
|
|
cc7f9e2688 | ||
|
|
a67df42aa8 | ||
|
|
27dea96335 | ||
|
|
3c5aeef936 | ||
|
|
bcf2aa3b03 | ||
|
|
87d5e537e2 | ||
|
|
08eb9ccbb2 | ||
|
|
e31df586db | ||
|
|
9386f754f4 | ||
|
|
865fcf21eb | ||
|
|
175d2eabe6 | ||
|
|
a18747a686 | ||
|
|
bbe04de28d | ||
|
|
ead0870d33 | ||
|
|
f670da8602 | ||
|
|
b3302eeef3 | ||
|
|
1b8c2047dd | ||
|
|
1405e7e8cb | ||
|
|
f1e8793b7a | ||
|
|
951e6b230d | ||
|
|
f55fabaac6 | ||
|
|
faa032ec12 | ||
|
|
989a377de9 | ||
|
|
78b0a6929c | ||
|
|
870bec1839 | ||
|
|
e819a03435 | ||
|
|
77c0a29922 | ||
|
|
d66a7d3bf9 | ||
|
|
5efc89e5ea | ||
|
|
010134fb8e | ||
|
|
08b8d71ece | ||
|
|
d05c629fc0 | ||
|
|
5c41ef2f08 | ||
|
|
f33b5f8551 | ||
|
|
1955eea91d | ||
|
|
4bac1b4da0 | ||
|
|
17a13fd901 | ||
|
|
a937df1bb7 | ||
|
|
b6488c5773 | ||
|
|
6db58aa0c0 | ||
|
|
aeba356814 | ||
|
|
b95bfbbb37 | ||
|
|
3383d8a9f1 | ||
|
|
be96af974d | ||
|
|
0c7ad0e0f0 | ||
|
|
91cb502355 | ||
|
|
1342420920 | ||
|
|
d46ecf3ab1 | ||
|
|
664980b32b | ||
|
|
349556de8a | ||
|
|
c984354a97 | ||
|
|
a1dae5ad32 | ||
|
|
e98df65d23 | ||
|
|
654e1745f9 | ||
|
|
869160692f | ||
|
|
554159685b | ||
|
|
8286638f79 | ||
|
|
13dc60f05c | ||
|
|
2813a0961d | ||
|
|
dd2d40a5f5 | ||
|
|
b917ca74c1 | ||
|
|
03070810eb | ||
|
|
ee05e88fa0 | ||
|
|
81aae389b3 | ||
|
|
8803a95a2d | ||
|
|
adef1253bb | ||
|
|
ff271a34e8 | ||
|
|
52d50bd830 | ||
|
|
6ebd483b14 | ||
|
|
eff8661a58 | ||
|
|
be2d9021bf | ||
|
|
acf8e9950d | ||
|
|
4b772c030c | ||
|
|
3794d9718e | ||
|
|
3f9fc816bf | ||
|
|
97daa4b3ed | ||
|
|
7b03696d8c | ||
|
|
bbad606bc3 | ||
|
|
8a58d674b7 | ||
|
|
ddeab752da | ||
|
|
81ed00867e | ||
|
|
473942d205 | ||
|
|
ef81c547af | ||
|
|
8654ed1319 | ||
|
|
4d1b530601 | ||
|
|
3d53abc13a | ||
|
|
2ee73a0d33 | ||
|
|
7777eba6e4 | ||
|
|
49f89569d0 | ||
|
|
64960989a1 | ||
|
|
408dcc0367 | ||
|
|
16160b1e4b | ||
|
|
e414882ffe | ||
|
|
b4f129911d | ||
|
|
3ecce1f442 | ||
|
|
4722d7d2fe | ||
|
|
81a367be13 | ||
|
|
dbc0c30fe1 | ||
|
|
caf58cd52a | ||
|
|
ee3ec16a52 | ||
|
|
989fa17544 | ||
|
|
aaecdd6313 | ||
|
|
5d43bb5414 | ||
|
|
509bfce556 | ||
|
|
2c6d291c9b | ||
|
|
d750887f3c | ||
|
|
63f5623990 | ||
|
|
eccf146bca | ||
|
|
1a0b33f671 | ||
|
|
0ee236e6a4 | ||
|
|
523c905c6d | ||
|
|
ce2f7789f4 | ||
|
|
539d9ce9d6 | ||
|
|
b9e2eaf05c | ||
|
|
007970517b | ||
|
|
ccf6340262 | ||
|
|
0c461485fb | ||
|
|
a830b61074 | ||
|
|
f0933342d4 | ||
|
|
1131c3120d | ||
|
|
b6a4fd1266 | ||
|
|
41e2164cd0 | ||
|
|
861bed3fdd | ||
|
|
6010893891 | ||
|
|
8427de0edb | ||
|
|
1789fd7b4d | ||
|
|
83676d584a | ||
|
|
db6a9105de | ||
|
|
d6a8db16b4 | ||
|
|
82325753a8 | ||
|
|
048f21dc77 | ||
|
|
7addc314f9 | ||
|
|
f718a26338 | ||
|
|
ec29711caf | ||
|
|
2bce6ed613 | ||
|
|
859e03246f | ||
|
|
0a29a6d73a | ||
|
|
0c7ea7278c | ||
|
|
f674177095 | ||
|
|
a29663bd95 | ||
|
|
03b20a6ca9 | ||
|
|
a7e02482fe | ||
|
|
e27a3bbdfc | ||
|
|
c93359d997 | ||
|
|
cb0aeadd2f | ||
|
|
2e9699c519 | ||
|
|
4e79e67534 | ||
|
|
0f83ea9cf4 | ||
|
|
4afcb2812f | ||
|
|
834c8054cf | ||
|
|
d789f82465 | ||
|
|
540bd57931 | ||
|
|
6da8a86a41 | ||
|
|
11790205d1 | ||
|
|
a3758cd90c | ||
|
|
b73210feeb | ||
|
|
74345b2e25 | ||
|
|
0759433433 | ||
|
|
8619e257a7 | ||
|
|
c158887d9a | ||
|
|
0859a447b6 | ||
|
|
df07115145 | ||
|
|
6e55462d5a | ||
|
|
af9dca95de | ||
|
|
6eb03bf4ea | ||
|
|
4b30633e03 | ||
|
|
9d005a6a40 | ||
|
|
a761f276d5 | ||
|
|
0bef53685f | ||
|
|
f0b5298dc4 | ||
|
|
95d1c1b4be | ||
|
|
b664721fb1 | ||
|
|
fa3eb9f303 | ||
|
|
1abb47e788 | ||
|
|
2c7df2fb96 | ||
|
|
6f6bf92576 | ||
|
|
d6e7695538 | ||
|
|
f2c9880298 | ||
|
|
1392290eec | ||
|
|
afaea9484c | ||
|
|
b66f579e7b | ||
|
|
609aa80e5e | ||
|
|
cdec6b459f | ||
|
|
3310e9f5ee | ||
|
|
554a7d689e | ||
|
|
2c32076416 | ||
|
|
19b8dfece6 | ||
|
|
a5f3120d59 | ||
|
|
82567c2c61 | ||
|
|
376a714e73 | ||
|
|
7df90b72cf | ||
|
|
9a81b9a88d | ||
|
|
100dfb3c42 | ||
|
|
e88b44df12 | ||
|
|
fadbfdf0e6 | ||
|
|
bc0c9e4da5 | ||
|
|
117c098553 | ||
|
|
104fa6133d | ||
|
|
7f8283a77f | ||
|
|
833082618a | ||
|
|
b687f1cd6f | ||
|
|
c7b4310dc1 | ||
|
|
50041c808c | ||
|
|
c0c42caf95 | ||
|
|
778ccf6db3 | ||
|
|
8f8bec4ad7 | ||
|
|
12a29586d0 | ||
|
|
ace0cc6a10 | ||
|
|
832462d0cf | ||
|
|
da295eb0c5 | ||
|
|
022be202c1 | ||
|
|
824a5e2c1d | ||
|
|
a620ad3587 | ||
|
|
7612fe17db | ||
|
|
f4862c6b0e | ||
|
|
7fd2dc9127 | ||
|
|
f420ef4d6a | ||
|
|
6a35fc23a7 | ||
|
|
cf0f6876b9 | ||
|
|
979077101f | ||
|
|
c120c09423 | ||
|
|
925ec333cf | ||
|
|
61ef4aab3c | ||
|
|
1336bc27cb | ||
|
|
f94aecace7 | ||
|
|
366b89341d | ||
|
|
0c7f425e91 | ||
|
|
02bcba5f71 | ||
|
|
a525210f48 | ||
|
|
3b0469da57 | ||
|
|
892235af06 | ||
|
|
0320a14c0a | ||
|
|
e14f85661b | ||
|
|
2d986748df | ||
|
|
c80709b51e | ||
|
|
78126b013a | ||
|
|
d7ec5e2ed2 | ||
|
|
6997afcc34 | ||
|
|
72f0577d0c | ||
|
|
3cda5d277b | ||
|
|
d3096ed0fb | ||
|
|
02c2bb66e4 | ||
|
|
d593088a31 | ||
|
|
0074cb6ac6 | ||
|
|
3c44fc6443 | ||
|
|
154982988a | ||
|
|
525a6a8f89 | ||
|
|
6102a64112 | ||
|
|
477bda7726 | ||
|
|
cf6d23c918 | ||
|
|
80eef0e4ac | ||
|
|
5e097aa288 | ||
|
|
417cc45a1c | ||
|
|
ff7d032da6 | ||
|
|
531a0d1f1d | ||
|
|
0aaef7a5bd | ||
|
|
ae0f30fa23 | ||
|
|
55da823f01 | ||
|
|
f7eadd7781 | ||
|
|
ecab532500 | ||
|
|
be5fe3d36f | ||
|
|
f053740960 | ||
|
|
7581392111 | ||
|
|
9cdc60b2c1 | ||
|
|
2973a2f4f3 | ||
|
|
8e90f8f336 | ||
|
|
1121b3146c | ||
|
|
04e8e61e82 | ||
|
|
36a64b39c4 | ||
|
|
64e9f2d24f | ||
|
|
bf95e83642 | ||
|
|
bec88fd149 | ||
|
|
1b34471bc8 | ||
|
|
44badab540 | ||
|
|
52773d2f7b | ||
|
|
e209b4f6fd | ||
|
|
68de4560b5 | ||
|
|
3ecc43c062 | ||
|
|
2be939832b | ||
|
|
3b73a84082 | ||
|
|
2525eaee12 | ||
|
|
dc515b6128 | ||
|
|
a11e4daae6 | ||
|
|
ed14477f19 | ||
|
|
53e520e805 | ||
|
|
1603a5f34f | ||
|
|
d5239891f6 | ||
|
|
9c7ec843b6 | ||
|
|
777fedb14a | ||
|
|
02de1488cb | ||
|
|
01a6084673 | ||
|
|
a848e90b3a | ||
|
|
b1c6aafc33 | ||
|
|
45299ba839 | ||
|
|
77af00b4e5 | ||
|
|
78ea592cf4 | ||
|
|
c1a20368dc | ||
|
|
999f0c0973 | ||
|
|
6117f95e1c | ||
|
|
32d4d32292 | ||
|
|
6c8a6bd6f7 | ||
|
|
9c05751014 | ||
|
|
fe2b22792d | ||
|
|
6d51d93bb6 | ||
|
|
fe69231544 | ||
|
|
dd20b23d4d | ||
|
|
59e818424c | ||
|
|
ab35bfa946 | ||
|
|
02e7bbc640 | ||
|
|
e3db9896fb |
@@ -21,4 +21,6 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as ci.yml: the UI glyph tests need its CJK and Arabic fonts.
|
||||
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
secrets: inherit
|
||||
secrets:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
SONAR_CLOUD_PAT: ${{ secrets.SONAR_CLOUD_PAT }}
|
||||
|
||||
@@ -73,7 +73,7 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
|
||||
- `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`.
|
||||
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
|
||||
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: plain `wordcraft-cli mcp` reaches the open window while ArtCraft Launcher › Settings › AI agents is on (`crates/ui-egui/src/agents.rs`, `crates/mcp/src/live.rs`); `--headless`, or the switch off, needs `--automation-read-root DIR --automation-write-root DIR`; see `docs/mcp.md`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
|
||||
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
|
||||
Generated
+173
-146
File diff suppressed because it is too large
Load Diff
+56
-56
@@ -13,7 +13,7 @@ run_slots = 3
|
||||
test_threads = 4
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.1"
|
||||
version = "0.20.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -37,22 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
wordcraft-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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -75,7 +75,7 @@ regex-automata = { version = "0.4", default-features = false, features = ["std",
|
||||
|
||||
# text / rendering / formats
|
||||
skrifa = "0.47"
|
||||
harfrust = "0.13"
|
||||
harfrust = "0.15"
|
||||
# WOFF / WOFF2 web fonts added by the user (#582): pure Rust (MIT); its brotli and zlib decoders
|
||||
# (brotli-decompressor, flate2) are already in the tree.
|
||||
wuff = "0.2.9"
|
||||
@@ -85,28 +85,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-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 = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -174,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 = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
|
||||
|
||||
|
||||
@@ -205,13 +205,17 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
|
||||
|
||||
WordCraft was designed to be driven by people *and* by AI agents.
|
||||
|
||||
With ArtCraft Launcher › Settings › AI agents on, AI apps reach the open WordCraft window through
|
||||
the launcher's one `ArtCraft` entry: tool calls act in the window, and files go to the agent folder
|
||||
(`Documents/ArtCraft/Agents/WordCraft`, or the folders in File › Options › Agents). Without the
|
||||
launcher:
|
||||
|
||||
```sh
|
||||
# headless documents; the agent reads only inside the first folder and writes only inside the second
|
||||
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
```
|
||||
|
||||
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
|
||||
the app confines its control channel to the same roots (#3695).
|
||||
A headless server needs both roots.
|
||||
|
||||
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
|
||||
`render_page` and `save_document`. Agents
|
||||
@@ -386,9 +390,12 @@ emerge --ask app-office/wordcraft-bin
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `wordcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
| aarch64 | `wordcraft-<ver>-freebsd-aarch64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
|
||||
+9
-1
File diff suppressed because one or more lines are too long
+209
-50
@@ -54,16 +54,25 @@ USAGE:
|
||||
wordcraft-cli commands [--json] list every command
|
||||
wordcraft-cli parity [--markdown] feature-catalog parity
|
||||
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
|
||||
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
|
||||
MCP server on stdio, with a headless session.
|
||||
Both roots are required: the agent's commands read
|
||||
files (open, insert text or picture, mail-merge data,
|
||||
templates…) only inside the read root and write them
|
||||
(save, export, merge output…) only inside the write
|
||||
root, links followed; the same folder may be both.
|
||||
--connect HOST:PORT (bridge to the running app) is
|
||||
refused until the app confines its control channel
|
||||
(#3695, #5819).
|
||||
wordcraft-cli mcp [--automation-read-root DIR --automation-write-root DIR] [--headless]
|
||||
[--when-closed launch|headless|error] [--author NAME]
|
||||
MCP server on stdio. While AI agents are on in
|
||||
ArtCraft Launcher › Settings › AI agents, each tool
|
||||
call goes to the open WordCraft window, working in
|
||||
its agent folder (File › Options › Agents); while
|
||||
WordCraft is closed, --when-closed or that page's
|
||||
choice decides: open it, work without a window, or
|
||||
ask to open it. Otherwise, and with --headless, a
|
||||
headless session, which needs both roots: the
|
||||
agent's commands read files (open, insert text or
|
||||
picture, mail-merge data, templates…) only inside
|
||||
the read root and write them (save, export, merge
|
||||
output…) only inside the write root, links followed;
|
||||
the same folder may be both. Given with AI agents
|
||||
on, the roots replace the agent folder for headless
|
||||
work. --author names the author of a headless
|
||||
session's tracked changes and comments.
|
||||
--connect HOST:PORT is deprecated and ignored.
|
||||
wordcraft-cli zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
|
||||
run a Zotero command on a document (Zotero must be
|
||||
running): addEditCitation, addEditBibliography,
|
||||
@@ -261,6 +270,17 @@ fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp --author NAME`: absent is the default author; a flag without a name, or given twice, is a
|
||||
/// usage error, never an unnamed session or the next option taken as the name.
|
||||
fn mcp_author(args: &[String]) -> Result<Option<String>, String> {
|
||||
match find_option_arg(args, "--author") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
OptionArg::Duplicate => Err("mcp: duplicate --author option".into()),
|
||||
OptionArg::MissingValue => Err("mcp: --author requires a name".into()),
|
||||
OptionArg::Value(name) => Ok(Some(name.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
|
||||
match find_option_arg(args, "--page") {
|
||||
OptionArg::Absent => Ok(None),
|
||||
@@ -376,13 +396,86 @@ const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_val
|
||||
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
|
||||
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
|
||||
|
||||
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
|
||||
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
|
||||
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
|
||||
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
|
||||
--automation-read-root DIR --automation-write-root DIR";
|
||||
/// Why `mcp` won't start while the suite's AI-MCP flag is on but the launcher's switch keeps agents
|
||||
/// out of the window: without roots it would have no folders to work in.
|
||||
const MCP_NEEDS_ROOTS_OR_AGENTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR, or \
|
||||
turn on AI agents in ArtCraft Launcher › Settings › AI agents to work in WordCraft's open window and its agent folder";
|
||||
|
||||
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }];
|
||||
/// `--connect HOST:PORT`, from before plain `mcp` found the window by itself: kept for one release,
|
||||
/// ignored with this note on stderr, then removed.
|
||||
const MCP_CONNECT_DEPRECATED: &str = "wordcraft-cli: --connect is deprecated and will be removed in the next release: \
|
||||
plain `wordcraft-cli mcp` finds the open WordCraft window by itself while AI agents are on in ArtCraft Launcher › \
|
||||
Settings › AI agents. The address given is not used.";
|
||||
|
||||
const MCP_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--headless", takes_value: false },
|
||||
OptionSpec { name: "--when-closed", takes_value: true },
|
||||
OptionSpec { name: "--author", takes_value: true },
|
||||
];
|
||||
|
||||
/// Takes the deprecated `--connect` out of `args`, with its value (written apart, unless it is
|
||||
/// another option, or as `--connect=…`): whether it was there.
|
||||
fn take_connect(args: &mut Vec<String>) -> bool {
|
||||
let mut found = false;
|
||||
let mut i = 0;
|
||||
while let Some(arg) = args.get(i) {
|
||||
if arg == "--connect" {
|
||||
found = true;
|
||||
let with_value = args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
|
||||
args.drain(i..if with_value { i + 2 } else { i + 1 });
|
||||
} else if arg.starts_with("--connect=") {
|
||||
found = true;
|
||||
args.remove(i);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The suite's AI-MCP flag and whether the ArtCraft Launcher's switch lets agents use WordCraft.
|
||||
#[cfg(not(test))]
|
||||
fn agents_state() -> (bool, bool) {
|
||||
let flag = wordcraft_mcp::live::mcp_flag();
|
||||
(flag, flag && wordcraft_mcp::live::agents_allowed_now())
|
||||
}
|
||||
|
||||
/// Unit tests run `mcp` as without the suite's flag, whatever this machine's flags say; the plan
|
||||
/// itself is tested for every combination (`mcp_plan`), and the binary's tests set the flag.
|
||||
#[cfg(test)]
|
||||
fn agents_state() -> (bool, bool) {
|
||||
(false, false)
|
||||
}
|
||||
|
||||
/// How `mcp` runs.
|
||||
#[derive(Debug)]
|
||||
enum McpPlan {
|
||||
/// A headless session confined to both roots.
|
||||
Headless(std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>),
|
||||
/// The open window while agents may use it, otherwise a headless session in the given roots
|
||||
/// or the app's agent folder ([`wordcraft_mcp::Live`]).
|
||||
Live(Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>),
|
||||
}
|
||||
|
||||
/// `mcp`'s plan. With `--headless`, or without the suite's AI-MCP flag (`flag`), a headless session
|
||||
/// that needs both roots (shared rule 18). With the flag, the live client when the launcher's
|
||||
/// switch lets agents in (`switch`) or both roots are given, so nothing it does is unconfined;
|
||||
/// otherwise a refusal.
|
||||
fn mcp_plan(
|
||||
roots: Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>,
|
||||
headless: bool,
|
||||
flag: bool,
|
||||
switch: bool,
|
||||
) -> Result<McpPlan, &'static str> {
|
||||
let both = roots.clone().filter(|r| r.read_root().is_some() && r.write_root().is_some());
|
||||
if headless || !flag {
|
||||
return both.map(McpPlan::Headless).ok_or(MCP_NEEDS_ROOTS);
|
||||
}
|
||||
if switch || both.is_some() {
|
||||
return Ok(McpPlan::Live(roots));
|
||||
}
|
||||
Err(MCP_NEEDS_ROOTS_OR_AGENTS)
|
||||
}
|
||||
const ZOTERO_OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec { name: "--cmd", takes_value: true },
|
||||
OptionSpec { name: "--save", takes_value: true },
|
||||
@@ -517,8 +610,10 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
let markup = rest.iter().any(|a| a == "--markup");
|
||||
let strict = rest.iter().any(|a| a == "--strict");
|
||||
// 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 strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
let lower_output = o.to_ascii_lowercase();
|
||||
let to_png = lower_output.ends_with(".png");
|
||||
let rendered = to_png || lower_output.ends_with(".pdf");
|
||||
if strict && !rendered {
|
||||
return Err("convert: --strict needs a .pdf or .png output".into());
|
||||
}
|
||||
let password = password_from(rest)?;
|
||||
@@ -538,8 +633,12 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
if let Err(e) = r {
|
||||
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
eprintln!("wrote {o}");
|
||||
Ok(())
|
||||
// A refusal already returned its report. Word, text and other non-rendered copies need no layout.
|
||||
if rendered {
|
||||
report_missing_metric_fonts(&s, markup, to_png);
|
||||
}
|
||||
// The confirmation is a result, so it goes to stdout with the others (#7070).
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))
|
||||
}
|
||||
|
||||
fn load_run_script(rest: &[String], script_path: Option<&Path>) -> Result<Option<script::Script>, Failure> {
|
||||
@@ -563,6 +662,28 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
|
||||
(from_file, from_template)
|
||||
}
|
||||
|
||||
fn report_missing_metric_fonts(s: &Session, markup: bool, to_png: bool) {
|
||||
for (word, used) in wordcraft_engine::cmd::font::output_metric_font_notices(s, markup, to_png) {
|
||||
let used = escape_peer(&used);
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"note: {word} is drawn in {used}, which measures differently, so lines and pages may not match Word's; uncovered characters may use glyph fallback"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show a successful command's result, or its warning when results aren't printed.
|
||||
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
|
||||
if print {
|
||||
return write_stdout(|o| writeln!(o, "{id}: {result}"));
|
||||
}
|
||||
if let Some(warning) = result.get("warning").and_then(Value::as_str) {
|
||||
let _ = writeln!(std::io::stderr().lock(), "wordcraft-cli: warning: {}", escape_text(warning, false));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the subcommand named by `args` (the command line after the program name). Files named
|
||||
/// there are opened by their real names, which may not be valid Unicode.
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
@@ -666,9 +787,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
let print = rest.iter().any(|a| a == "--print");
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
|
||||
if print {
|
||||
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
report_run_result(id, &r, print)?;
|
||||
}
|
||||
let mut i = 0;
|
||||
while i < rest.len() {
|
||||
@@ -681,9 +800,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
None => (spec.clone(), json!({})),
|
||||
};
|
||||
let r = s.run(&id, ¶ms).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
if print {
|
||||
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
report_run_result(&id, &r, print)?;
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
@@ -717,7 +834,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
eprintln!("wrote {out}");
|
||||
// A reader that hung up only loses the confirmation; the remaining saves still run.
|
||||
match write_stdout(|w| writeln!(w, "wrote {out}")) {
|
||||
Ok(()) | Err(Failure::StdoutClosed) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -747,28 +868,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
"validate" => run_validate(file.as_deref(), &rest),
|
||||
"mcp" => {
|
||||
let (roots, rest) = automation_roots("mcp", &rest)?;
|
||||
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
|
||||
// "unknown option": a bare trailing `--connect` must not slip past either.
|
||||
if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
validate_options("mcp", &rest, MCP_OPTIONS)?;
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined.
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(MCP_NEEDS_ROOTS.into());
|
||||
};
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, arg_value(&rest, "--author").as_deref())?);
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), std::io::stdout())?)
|
||||
}
|
||||
"mcp" => run_mcp(&rest),
|
||||
"zotero" => {
|
||||
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
|
||||
let paths = positionals(&rest, ZOTERO_OPTIONS);
|
||||
@@ -808,7 +908,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
eprintln!("{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = arg_value(&rest, "--save") {
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
eprintln!("wrote {o}");
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -818,6 +918,60 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `wordcraft-cli mcp`: serves MCP on stdin and stdout, headless or through the open window.
|
||||
fn run_mcp(rest: &[String]) -> Result<(), Failure> {
|
||||
let (roots, mut rest) = automation_roots("mcp", rest)?;
|
||||
// Taken out before the option check, with or without a value, so it never reads as unknown.
|
||||
if take_connect(&mut rest) {
|
||||
eprintln!("{MCP_CONNECT_DEPRECATED}");
|
||||
}
|
||||
validate_options("mcp", &rest, MCP_OPTIONS)?;
|
||||
let when_closed = match (rest.iter().any(|a| a == "--when-closed"), arg_value(&rest, "--when-closed")) {
|
||||
(false, _) => None,
|
||||
(true, value) => {
|
||||
Some(value.as_deref().and_then(wordcraft_mcp::live::WhenAppClosed::parse).ok_or("mcp: --when-closed takes launch, headless or error")?)
|
||||
}
|
||||
};
|
||||
let author = mcp_author(&rest)?;
|
||||
let (flag, switch) = agents_state();
|
||||
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = match mcp_plan(roots, rest.iter().any(|a| a == "--headless"), flag, switch)? {
|
||||
McpPlan::Headless(roots) => {
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. Every thread of this process,
|
||||
// not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
Box::new(headless_mcp(roots, author.as_deref())?)
|
||||
}
|
||||
McpPlan::Live(roots) => {
|
||||
let mut config = wordcraft_mcp::LiveConfig::installed()
|
||||
.ok_or("mcp: can't find WordCraft's settings folder (no home folder; set WORDCRAFT_PROFILE_DIR)")?;
|
||||
if let Some(roots) = &roots {
|
||||
config.read_root = roots.read_root().map(std::path::Path::to_path_buf);
|
||||
config.write_root = roots.write_root().map(std::path::Path::to_path_buf);
|
||||
// Both roots given: every headless session works in them, so the whole process is confined to
|
||||
// them. Calls to the window run in the app, inside its agent folders.
|
||||
if config.read_root.is_some() && config.write_root.is_some() {
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
}
|
||||
}
|
||||
config.when_closed = when_closed;
|
||||
config.author = author;
|
||||
config.launch = std::env::current_exe().ok().and_then(|exe| wordcraft_mcp::live::launcher(&exe));
|
||||
eprintln!(
|
||||
"wordcraft-cli: tool calls go to the open WordCraft window while AI agents are on in ArtCraft Launcher, otherwise to a headless session (read root {}, write root {}; none: WordCraft's agent folder)",
|
||||
show(config.read_root.as_deref()),
|
||||
show(config.write_root.as_deref())
|
||||
);
|
||||
Box::new(wordcraft_mcp::Live::new(config))
|
||||
}
|
||||
};
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), std::io::stdout())?)
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
@@ -1063,6 +1217,11 @@ fn main() -> ExitCode {
|
||||
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
// The engine logs this, but the command line installs no logger, and it is where a
|
||||
// reproducible build runs.
|
||||
if let Some(problem) = wordcraft_engine::cmd::source_date_epoch_problem() {
|
||||
eprintln!("wordcraft-cli: warning: {problem}");
|
||||
}
|
||||
// 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);
|
||||
|
||||
+118
-21
@@ -38,7 +38,7 @@ fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--headless", "--when-closed", "launch"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
@@ -326,18 +326,32 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
|
||||
/// to it is refused, with roots or without, before anything connects.
|
||||
/// `mcp`'s plan never runs anything unconfined (shared rule 18): headless needs both roots, and
|
||||
/// with the suite's AI-MCP flag the live client runs without them only while the launcher's switch
|
||||
/// lets agents into the window, which confines them to its agent folder.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
fn mcp_never_plans_an_unconfined_session() {
|
||||
let scratch = Scratch::new("mcp-plan");
|
||||
let root = |read: bool, write: bool| {
|
||||
let (r, w) = (read.then_some(scratch.0.as_path()), write.then_some(scratch.0.as_path()));
|
||||
wordcraft_engine::file_access::AutomationRoots::new(r, w).unwrap()
|
||||
};
|
||||
let both = || root(true, true);
|
||||
// --headless, or no flag: both roots or nothing.
|
||||
for (headless, flag, switch) in [(true, true, true), (true, false, false), (false, false, true), (false, false, false)] {
|
||||
assert!(matches!(mcp_plan(both(), headless, flag, switch), Ok(McpPlan::Headless(_))));
|
||||
for partial in [None, root(true, false), root(false, true)] {
|
||||
assert_eq!(mcp_plan(partial, headless, flag, switch).unwrap_err(), MCP_NEEDS_ROOTS);
|
||||
}
|
||||
}
|
||||
// The flag and the switch: the window, with or without roots.
|
||||
for roots in [None, root(true, false), both()] {
|
||||
assert!(matches!(mcp_plan(roots, false, true, true), Ok(McpPlan::Live(_))));
|
||||
}
|
||||
// The flag without the switch: only with both roots, which confine its headless sessions.
|
||||
assert!(matches!(mcp_plan(both(), false, true, false), Ok(McpPlan::Live(Some(_)))));
|
||||
for partial in [None, root(true, false), root(false, true)] {
|
||||
assert_eq!(mcp_plan(partial, false, true, false).unwrap_err(), MCP_NEEDS_ROOTS_OR_AGENTS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,19 +366,38 @@ fn mcp_headless_session_takes_the_author_flag() {
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
|
||||
/// `mcp --author` without a name is refused, also when another option follows it, instead of
|
||||
/// starting with the default author or that option as the name.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_without_a_value_too() {
|
||||
let scratch = Scratch::new("connect-bare");
|
||||
let dir = scratch.0.to_string_lossy().into_owned();
|
||||
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
|
||||
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
|
||||
let line = args(&[&["mcp"][..], &roots, &tail].concat());
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
fn mcp_author_needs_a_name() {
|
||||
assert_eq!(mcp_author(&args(&["--headless", "--author", "Claude"])), Ok(Some("Claude".to_string())));
|
||||
assert_eq!(mcp_author(&args(&["--headless"])), Ok(None));
|
||||
for given in [vec!["--author"], vec!["--author", "--headless"], vec!["--author", "A", "--author", "B"]] {
|
||||
assert!(mcp_author(&args(&given)).is_err(), "{given:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The deprecated `--connect` is taken out with its value, whether it has one, written apart or as
|
||||
/// `--connect=…`, and leaves the other options as they were.
|
||||
#[test]
|
||||
fn mcp_connect_is_taken_out_with_its_value() {
|
||||
for (given, left) in [
|
||||
(vec!["--connect", "127.0.0.1:9", "--author", "Claude"], vec!["--author", "Claude"]),
|
||||
(vec!["--connect"], vec![]),
|
||||
(vec!["--connect", "--author", "Claude"], vec!["--author", "Claude"]),
|
||||
(vec!["--headless", "--connect=127.0.0.1:9"], vec!["--headless"]),
|
||||
(vec!["--connect=", "--connect", "x"], vec![]),
|
||||
] {
|
||||
let mut rest = args(&given);
|
||||
assert!(take_connect(&mut rest), "{given:?}");
|
||||
assert_eq!(rest, args(&left), "{given:?}");
|
||||
assert!(validate_options("mcp", &rest, MCP_OPTIONS).is_ok());
|
||||
}
|
||||
let mut rest = args(&["--author", "Claude"]);
|
||||
assert!(!take_connect(&mut rest));
|
||||
assert_eq!(rest, args(&["--author", "Claude"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
@@ -710,6 +743,70 @@ fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
assert!(script::load_from(&b"{"[..], "-", None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_result_warnings_use_stderr_without_print() {
|
||||
use std::process::Command;
|
||||
|
||||
const CHILD_ARGS: &str = "WORDCRAFT_CLI_WARNING_TEST_ARGS";
|
||||
const STORE: &str = "WORDCRAFT_CLI_WARNING_TEST_STORE";
|
||||
const WARNING: &str = "added for this session only: couldn't store it";
|
||||
if let Ok(argv) = std::env::var(CHILD_ARGS) {
|
||||
let store = PathBuf::from(std::env::var_os(STORE).unwrap());
|
||||
wordcraft_fonts::FontDb::global().load_user_fonts(&store);
|
||||
run(&serde_json::from_str::<Vec<String>>(&argv).unwrap()).unwrap();
|
||||
// Bypass the test harness summary so the parent sees only the same header and the CLI's
|
||||
// output. Each child has its own font database and never configures a real user store.
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
let dir = script_dir("run-warnings");
|
||||
let store = dir.join("not-a-directory");
|
||||
std::fs::write(&store, b"blocked font store").unwrap();
|
||||
// Like the engine's font.add fixture, rename the bundled JetBrains Mono family in memory
|
||||
// so it is treated as a new face. No additional font asset is used.
|
||||
let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec();
|
||||
let utf16 = |name: &str| name.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for (old, new) in [(b"JetBrains Mono".to_vec(), b"Cli Fixture 42".to_vec()), (utf16("JetBrains Mono"), utf16("Cli Fixture 42"))] {
|
||||
let mut start = 0;
|
||||
while let Some(at) = font[start..].windows(old.len()).position(|bytes| bytes == old) {
|
||||
let range = start + at..start + at + old.len();
|
||||
start = range.end;
|
||||
font[range].copy_from_slice(&new);
|
||||
}
|
||||
}
|
||||
let path = dir.join("fixture.ttf");
|
||||
std::fs::write(&path, font).unwrap();
|
||||
let params = json!({"path": path.to_string_lossy()});
|
||||
let spec = format!("font.add={params}");
|
||||
let script = write_script(&dir, &json!({"commands": [{"command": "font.add", "params": params}]}).to_string());
|
||||
|
||||
let child = |argv: &[&str]| {
|
||||
let out = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "tests::run_result_warnings_use_stderr_without_print", "--nocapture"])
|
||||
.env(CHILD_ARGS, json!(argv).to_string())
|
||||
.env(STORE, &store)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
(String::from_utf8(out.stdout).unwrap(), String::from_utf8(out.stderr).unwrap())
|
||||
};
|
||||
let (header, quiet_stderr) = child(&["run", "--cmd", "caret.docEnd"]);
|
||||
assert!(quiet_stderr.is_empty(), "{quiet_stderr}");
|
||||
for argv in [["run", "--cmd", &spec], ["run", "--script", &script]] {
|
||||
let (stdout, stderr) = child(&argv);
|
||||
assert_eq!(stdout, header);
|
||||
assert!(stderr.starts_with(&format!("wordcraft-cli: warning: {WARNING}")), "{stderr}");
|
||||
assert_eq!(stderr.lines().count(), 1, "{stderr}");
|
||||
|
||||
let (stdout, stderr) = child(&[argv[0], argv[1], argv[2], "--print"]);
|
||||
assert!(stderr.is_empty(), "{stderr}");
|
||||
let result = stdout.strip_prefix(&header).unwrap().strip_prefix("font.add: ").unwrap();
|
||||
let result: Value = serde_json::from_str(result).unwrap();
|
||||
let warning = result["warning"].as_str().unwrap();
|
||||
assert!(warning.starts_with(WARNING), "{result}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_commands_run_before_cmd_flags() {
|
||||
let dir = script_dir("order");
|
||||
|
||||
@@ -37,3 +37,27 @@ fn run_saves_the_document_opened_last() {
|
||||
let stdout = String::from_utf8_lossy(&listed.stdout);
|
||||
assert_eq!(stdout.matches("\"id\"").count(), 1, "{stdout}");
|
||||
}
|
||||
|
||||
struct TempFile(std::path::PathBuf);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_run_commands_still_exit_with_an_error() {
|
||||
let script = TempFile(std::env::temp_dir().join(format!("wordcraft-cli-run-error-{}.json", std::process::id())));
|
||||
std::fs::write(&script.0, r#"{"commands":["no.such.command"]}"#).unwrap();
|
||||
let script_path = script.0.to_string_lossy();
|
||||
let cases = [(["run", "--cmd", "no.such.command"], "no.such.command:"), (["run", "--script", &script_path], "command 1 (no.such.command):")];
|
||||
for (args, expected) in cases {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "{out:?}");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(stderr.starts_with("wordcraft-cli: ") && stderr.contains(expected), "{stderr}");
|
||||
assert!(!stderr.contains("wordcraft-cli: warning:"), "{stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Conversion notes are scoped to rendered output and to the core fonts it uses.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
|
||||
const NOTE: &str = "lines and pages may not match Word's";
|
||||
|
||||
fn convert(input: &Path, output: &Path, flags: &[&str]) -> String {
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(input).arg(output).args(flags).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(run.status.success(), "{output:?}: {stderr}");
|
||||
assert!(output.is_file(), "{output:?}");
|
||||
assert_eq!(String::from_utf8_lossy(&run.stdout).trim_end(), format!("wrote {}", output.display()));
|
||||
stderr.into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_font_notes_follow_the_output_format_and_pages() {
|
||||
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-convert-font-notices-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let input = dir.join("input.json");
|
||||
let mut doc = Document::new();
|
||||
|
||||
// Pick a real non-metric core substitution available on this runner, when there is one.
|
||||
// WordCraft's own bundled Source Sans 3 is the font on the first page.
|
||||
let (font, expected) = ["Cambria", "Calibri", "Arial", "Times New Roman", "Courier New"]
|
||||
.into_iter()
|
||||
.find_map(|font| {
|
||||
let primary = wordcraft_engine::cmd::font::shown_as(&doc, font)?;
|
||||
wordcraft_engine::cmd::font::warns(font, &primary).then_some((font, Some(format!("note: {font} is drawn in {primary},"))))
|
||||
})
|
||||
.unwrap_or(("Arial", None));
|
||||
let paragraph =
|
||||
|text: &str, family: &str| Paragraph::with_text(text, wordcraft_doc::CharProps { font: Some(family.into()), ..Default::default() });
|
||||
let mut later_page = paragraph("This uses an Office family", font);
|
||||
later_page.props.page_break_before = Some(true);
|
||||
doc.body = vec![para_block(paragraph("Bundled font only", "Source Sans 3")), para_block(later_page)];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
|
||||
for (target, flags) in [
|
||||
("out.docx", &[][..]),
|
||||
("out.odt", &[][..]),
|
||||
("out.rtf", &[][..]),
|
||||
("out.txt", &[][..]),
|
||||
("out.xml", &["--format", "wordml2003"][..]),
|
||||
("flat.xml", &["--format", "flatopc"][..]),
|
||||
("first.PNG", &[][..]),
|
||||
] {
|
||||
let stderr = convert(&input, &dir.join(target), flags);
|
||||
assert!(!stderr.contains(NOTE), "{target}: {stderr}");
|
||||
}
|
||||
let xml = std::fs::read_to_string(dir.join("out.xml")).unwrap();
|
||||
assert!(xml.contains("http://schemas.microsoft.com/office/word/2003/wordml"));
|
||||
let flat = std::fs::read_to_string(dir.join("flat.xml")).unwrap();
|
||||
assert!(flat.contains("http://schemas.microsoft.com/office/2006/xmlPackage"));
|
||||
assert!(std::fs::read(dir.join("first.PNG")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
|
||||
let whole = dir.join("whole.PDF");
|
||||
let stderr = convert(&input, &whole, &["--update-fields"]);
|
||||
assert!(std::fs::read(&whole).unwrap().starts_with(b"%PDF-"));
|
||||
let notes: Vec<_> = stderr.lines().filter(|line| line.contains(NOTE)).collect();
|
||||
if let Some(prefix) = expected {
|
||||
assert_eq!(notes.len(), 1, "{stderr}");
|
||||
assert!(notes[0].starts_with(&prefix), "{stderr}");
|
||||
|
||||
// A one-page image does report a non-metric core font when that page uses it.
|
||||
doc.body = vec![para_block(paragraph("This uses an Office family", font))];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let stderr = convert(&input, &dir.join("used.png"), &[]);
|
||||
assert_eq!(stderr.lines().filter(|line| line.starts_with(&prefix)).count(), 1, "{stderr}");
|
||||
|
||||
// The two pages can share a single shaped paragraph. Its later font must still
|
||||
// stay out of a first-page image's notices, but appear in the complete PDF.
|
||||
let mut split = paragraph(&"Bundled line\n".repeat(16), "Source Sans 3");
|
||||
split
|
||||
.insert_text(split.len(), "Office family only on page two", &wordcraft_doc::CharProps { font: Some(font.into()), ..Default::default() })
|
||||
.unwrap();
|
||||
split.props.line_spacing = Some(wordcraft_doc::props::LineSpacing::Exactly(17.0));
|
||||
let section = doc.last_section.clone();
|
||||
doc.last_section.page_h = 240.0;
|
||||
doc.last_section.margin_top = 24.0;
|
||||
doc.last_section.margin_bottom = 24.0;
|
||||
doc.body = vec![para_block(split)];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let stderr = convert(&input, &dir.join("split.png"), &[]);
|
||||
assert!(!stderr.contains(NOTE), "{stderr}");
|
||||
let stderr = convert(&input, &dir.join("split.pdf"), &[]);
|
||||
assert_eq!(stderr.lines().filter(|line| line.starts_with(&prefix)).count(), 1, "{stderr}");
|
||||
doc.last_section = section;
|
||||
} else {
|
||||
assert!(notes.is_empty(), "{stderr}");
|
||||
}
|
||||
|
||||
doc.body = vec![para_block(paragraph("Bundled font only", "Source Sans 3"))];
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let stderr = convert(&input, &dir.join("unused.pdf"), &["--strict"]);
|
||||
assert!(!stderr.contains(NOTE), "{stderr}");
|
||||
|
||||
let invalid = dir.join("invalid.pdf");
|
||||
let run =
|
||||
Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&invalid).args(["--format", "wordml2003"]).output().unwrap();
|
||||
assert!(!run.status.success());
|
||||
assert!(!invalid.exists());
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(stderr.contains("only for an .xml file") && !stderr.contains(NOTE), "{stderr}");
|
||||
assert!(run.stdout.is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Removes the temporary test folder when the test finishes or panics.
|
||||
struct TempRoot(PathBuf);
|
||||
|
||||
impl TempRoot {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_saves_home_relative_paths_and_can_clear_the_override() {
|
||||
let root = TempRoot(std::env::temp_dir().join(format!("wc-custom-dictionary-{}", std::process::id())));
|
||||
let home = root.0.join("home");
|
||||
let profile = root.0.join("profile");
|
||||
for folder in [&home, &profile] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
std::fs::write(folder.join("custom.dic"), "wordcraftdictionary\n").unwrap();
|
||||
}
|
||||
let (preferred, fallback) = if cfg!(windows) { (&profile, &home) } else { (&home, &profile) };
|
||||
let options = |home: Option<&Path>, profile: Option<&Path>, paths: &[&str]| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(home) = home {
|
||||
cli.env("HOME", home);
|
||||
}
|
||||
if let Some(profile) = profile {
|
||||
cli.env("USERPROFILE", profile);
|
||||
}
|
||||
cli.args(["run", "--print"]);
|
||||
for path in paths {
|
||||
cli.args(["--cmd", &format!("file.options={}", json!({"customDictionary": path})), "--cmd", "file.options"]);
|
||||
}
|
||||
cli.output().unwrap()
|
||||
};
|
||||
let assert_saved = |home, profile, paths: &[&str], expected: &[Option<&Path>]| {
|
||||
let report = options(home, profile, paths);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), expected.len() * 2, "{out}");
|
||||
for (pair, expected) in reads.as_chunks::<2>().0.iter().zip(expected) {
|
||||
for read in pair {
|
||||
assert_eq!(read["customDictionary"].as_str().map(Path::new), *expected, "{out}");
|
||||
}
|
||||
}
|
||||
};
|
||||
let assert_refused = |home, profile, path, reason: &str| {
|
||||
let report = options(home, profile, &[path]);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
|
||||
let dic = preferred.join("custom.dic");
|
||||
let absolute = dic.to_str().unwrap();
|
||||
assert_saved(Some(&home), Some(&profile), &["~/custom.dic"], &[Some(&dic)]);
|
||||
assert_saved(None, None, &[absolute, "auto", absolute, ""], &[Some(&dic), None, Some(&dic), None]);
|
||||
let empty = Path::new("");
|
||||
let (empty_home, empty_profile) = if cfg!(windows) { (fallback.as_path(), empty) } else { (empty, fallback.as_path()) };
|
||||
assert_saved(Some(empty_home), Some(empty_profile), &["~/custom.dic"], &[Some(&fallback.join("custom.dic"))]);
|
||||
assert_refused(None, None, "~/custom.dic", "cannot expand");
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(&home), Some(&profile), &[r"~\custom.dic"], &[Some(&dic)]);
|
||||
assert_refused(None, None, r"~\custom.dic", "cannot expand");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\C:\custom.dic", "relative to the home folder");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\\custom.dic", "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(&home), Some(&profile), r"~\custom.dic", "isn't a full path");
|
||||
}
|
||||
root.remove().unwrap();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn folder_options_save_home_relative_paths_and_validate_before_reading() {
|
||||
let profile = std::env::temp_dir().join(format!("wc-folder-options-profile-{}", std::process::id()));
|
||||
let templates = profile.join("Templates").join("Personal");
|
||||
let dictionaries = profile.join("Dictionaries");
|
||||
std::fs::create_dir_all(&templates).unwrap();
|
||||
std::fs::create_dir_all(&dictionaries).unwrap();
|
||||
let options = |profile: Option<&Path>, params: Value| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(profile) = profile {
|
||||
cli.env(if cfg!(windows) { "USERPROFILE" } else { "HOME" }, profile);
|
||||
}
|
||||
cli.args(["run", "--print", "--cmd", &format!("file.options={params}"), "--cmd", "file.options"]).output().unwrap()
|
||||
};
|
||||
let assert_saved = |profile, params| {
|
||||
let report = options(profile, params);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), 2, "{out}");
|
||||
for read in reads {
|
||||
assert_eq!(Path::new(read["userTemplatesFolder"].as_str().unwrap()), templates);
|
||||
assert_eq!(Path::new(read["dictionariesFolder"].as_str().unwrap()), dictionaries);
|
||||
}
|
||||
};
|
||||
assert_saved(Some(profile.as_path()), json!({"userTemplatesFolder": "~/Templates/Personal", "dictionariesFolder": "~/Dictionaries"}));
|
||||
assert_saved(None, json!({"userTemplatesFolder": templates, "dictionariesFolder": dictionaries}));
|
||||
|
||||
let win_params = json!({"userTemplatesFolder": r"~\Templates/Personal", "dictionariesFolder": r"~\Dictionaries"});
|
||||
let assert_refused = |profile, params, reason: &str| {
|
||||
let report = options(profile, params);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(profile.as_path()), win_params.clone());
|
||||
assert_refused(None, win_params, "cannot expand");
|
||||
assert_refused(Some(profile.as_path()), json!({"userTemplatesFolder": r"~\C:\Templates"}), "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(profile.as_path()), win_params, "isn't a full path");
|
||||
}
|
||||
assert_refused(None, json!({"dictionariesFolder": "~/Dictionaries"}), "cannot expand");
|
||||
assert_refused(None, json!({"userTemplatesFolder": r"\\unreachable.invalid\share"}), "can't be a network folder");
|
||||
std::fs::remove_dir_all(profile).unwrap();
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
#[cfg(unix)]
|
||||
mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_font_notices;
|
||||
mod convert_region;
|
||||
mod custom_dictionary;
|
||||
mod folder_options;
|
||||
mod help;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
@@ -9,5 +12,7 @@ mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
mod picture_then_typing;
|
||||
mod reproducible_pdf;
|
||||
mod strict;
|
||||
mod text_tracked;
|
||||
mod wrote_on_stdout;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
|
||||
//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop
|
||||
//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files
|
||||
//! outside them, through the real binary.
|
||||
//! `--automation-read-root` and `--automation-write-root` unless the ArtCraft Launcher's switch
|
||||
//! lets agents into WordCraft's window (which confines them to its agent folder), takes the
|
||||
//! deprecated `--connect` with a note, and with both roots refuses files outside them, through the
|
||||
//! real binary. Each run gets its own suite flags, launcher folder and settings folder, so this
|
||||
//! machine's own never count.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -48,11 +50,17 @@ fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
|
||||
/// Run `wordcraft-cli mcp <args>` without the suite's AI-MCP flag, send `lines` on stdin, then hang up.
|
||||
fn mcp(args: &[String], lines: &[Value]) -> Output {
|
||||
mcp_with(args, lines, &[("CRAFT_FLAGS", "-AI-MCP".into())])
|
||||
}
|
||||
|
||||
/// [`mcp`] with these environment variables.
|
||||
fn mcp_with(args: &[String], lines: &[Value], env: &[(&str, std::ffi::OsString)]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.envs(env.iter().map(|(k, v)| (*k, v)))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -99,17 +107,60 @@ fn mcp_refuses_to_start_without_both_roots() {
|
||||
assert!(reply.get("error").is_none(), "{reply}");
|
||||
}
|
||||
|
||||
/// `--connect` is kept for one release: it says it is deprecated and is otherwise ignored, so a
|
||||
/// client configuration that still has it keeps working, and it opens no way around the roots.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
fn mcp_connect_is_a_deprecated_alias_of_plain_mcp() {
|
||||
let folders = Folders::new("connect");
|
||||
let base = folders.0.clone();
|
||||
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
|
||||
let why = ["--connect", "#3695", "#5819"];
|
||||
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why);
|
||||
refused_at_start(
|
||||
let out = mcp(
|
||||
&["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write],
|
||||
&why,
|
||||
&[serde_json::from_str(PING).unwrap()],
|
||||
);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "stderr: {stderr}");
|
||||
assert!(stderr.contains("--connect is deprecated"), "{stderr}");
|
||||
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
|
||||
assert_eq!(reply["id"], 1, "{reply}");
|
||||
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &["--connect is deprecated", "--automation-read-root"]);
|
||||
}
|
||||
|
||||
/// With the suite's AI-MCP flag: while the launcher's switch keeps agents out, `mcp` still needs
|
||||
/// both roots and says how to let agents in; once the launcher's list names WordCraft, plain `mcp`
|
||||
/// starts without roots and follows the closed-app choice (here: ask to open WordCraft).
|
||||
#[test]
|
||||
fn with_the_flag_the_launcher_switch_lets_plain_mcp_start() {
|
||||
let folders = Folders::new("switch");
|
||||
let base = folders.0.clone();
|
||||
let launcher = base.join("launcher");
|
||||
let settings = base.join("settings");
|
||||
std::fs::create_dir_all(&launcher).unwrap();
|
||||
std::fs::create_dir_all(&settings).unwrap();
|
||||
std::fs::write(settings.join("config.toml"), "schema_version = 1\n[integrations]\nwhenAppClosed = \"error\"\n").unwrap();
|
||||
let env = [
|
||||
("CRAFT_FLAGS", std::ffi::OsString::from("AI-MCP")),
|
||||
("CRAFT_MCP_DIR", launcher.clone().into_os_string()),
|
||||
("WORDCRAFT_PROFILE_DIR", settings.into_os_string()),
|
||||
];
|
||||
let ping: Value = serde_json::from_str(PING).unwrap();
|
||||
let off = mcp_with(&[], std::slice::from_ref(&ping), &env);
|
||||
let stderr = String::from_utf8_lossy(&off.stderr);
|
||||
assert!(!off.status.success() && off.stdout.is_empty(), "started with the switch off: {stderr}");
|
||||
assert!(stderr.contains("ArtCraft Launcher") && stderr.contains("--automation-read-root"), "{stderr}");
|
||||
|
||||
let cli = s(Path::new(env!("CARGO_BIN_EXE_wordcraft-cli")));
|
||||
let list = json!({"version": 1, "apps": [{"id": "wordcraft", "name": "WordCraft", "command": cli, "args": ["mcp"]}]});
|
||||
std::fs::write(launcher.join("apps.json"), list.to_string()).unwrap();
|
||||
let on = mcp_with(&[], &[ping, tool(2, "list_documents", json!({}))], &env);
|
||||
let stderr = String::from_utf8_lossy(&on.stderr);
|
||||
assert!(on.status.success(), "stderr: {stderr}");
|
||||
let replies: Vec<Value> =
|
||||
String::from_utf8_lossy(&on.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert!(replies.iter().any(|r| r["id"] == 1 && r.get("error").is_none()), "{replies:?}");
|
||||
let call = replies.iter().find(|r| r["id"] == 2).expect("the tool call is answered");
|
||||
assert_eq!(call["result"]["isError"], true, "{call}");
|
||||
assert!(call.to_string().contains("isn't running"), "the closed-app choice answers: {call}");
|
||||
}
|
||||
|
||||
/// `tools/call` request `id` for `name` with `arguments`.
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Direct PDF exports use the saved timestamp without changing the source document.
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn direct_pdf_exports_use_the_pinned_epoch() {
|
||||
check_creation_date("", "20261005140300");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_pdf_exports_preserve_an_existing_creation_date() {
|
||||
check_creation_date("2000-01-01T00:00:00Z", "20000101000000");
|
||||
}
|
||||
|
||||
/// A .docx records `dcterms:created` as text and the reader takes it as it finds it, so a
|
||||
/// document can arrive holding something that is not a date at all. The PDF writer cannot put
|
||||
/// that in a document and fell back to the clock, so two exports of the same file differed even
|
||||
/// with `SOURCE_DATE_EPOCH` set -- the one thing it is there to stop (noted in review).
|
||||
#[test]
|
||||
fn direct_pdf_exports_use_the_pinned_epoch_when_the_existing_date_is_unreadable() {
|
||||
for created in ["not-a-date", "", " ", "2000-13-01T00:00:00Z", "2000-01-32T00:00:00Z", "99-01-01", "today"] {
|
||||
check_creation_date(created, "20261005140300");
|
||||
}
|
||||
}
|
||||
|
||||
fn check_creation_date(created: &str, expected: &str) {
|
||||
// A sequence number, not the clock alone: `as_nanos` carries microsecond granularity on
|
||||
// macOS, so two of these tests starting in the same microsecond took the same directory,
|
||||
// wrote each other's `input.json` and failed the preservation assertion below -- a flake in
|
||||
// this harness, not in the export. `create_dir` rather than `create_dir_all` so that if a
|
||||
// name ever does repeat it fails here instead of quietly sharing a directory again.
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-pdf-date-{}-{unique}-{seq}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
||||
let mut doc = wordcraft_doc::Document::from_text("Original reproducible PDF check.");
|
||||
doc.core.created = created.into();
|
||||
let input = dir.join("input.json");
|
||||
let source = serde_json::to_vec(&doc).unwrap();
|
||||
std::fs::write(&input, &source).unwrap();
|
||||
for command in ["file.exportPdf", "file.printPdf"] {
|
||||
let output = dir.join(format!("{command}.pdf"));
|
||||
let params = serde_json::json!({"path": output});
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.arg("run")
|
||||
.arg("--file")
|
||||
.arg(&input)
|
||||
.arg("--cmd")
|
||||
.arg(format!("{command}={params}"))
|
||||
.env("SOURCE_DATE_EPOCH", "1791208980")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(run.status.success(), "{command}: {}", String::from_utf8_lossy(&run.stderr));
|
||||
let bytes = std::fs::read(output).unwrap();
|
||||
let date = format!("/CreationDate(D:{expected}");
|
||||
assert!(bytes.windows(date.len()).any(|part| part == date.as_bytes()), "{command} must use {expected}");
|
||||
assert_eq!(std::fs::read(&input).unwrap(), source, "export must preserve its source file");
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh directory for one test's files.
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-{name}-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
||||
dir
|
||||
}
|
||||
|
||||
fn cli(env: &str, cmds: &[String]) -> std::process::Output {
|
||||
let mut run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
run.arg("run").env("SOURCE_DATE_EPOCH", env);
|
||||
for c in cmds {
|
||||
run.arg("--cmd").arg(c);
|
||||
}
|
||||
run.output().unwrap()
|
||||
}
|
||||
|
||||
/// The pinned date is the file's, not the edits': a comment and a tracked change made in the
|
||||
/// same run keep the time they were made, so a pinned epoch cannot back-date them (noted in
|
||||
/// review). Saved as flat XML, which holds both in plain text.
|
||||
#[test]
|
||||
fn a_pinned_epoch_dates_the_file_and_not_the_edits_in_it() {
|
||||
let out = scratch("pinned-edits").join("edits.xml");
|
||||
let before = wordcraft_engine::cmd::now_iso();
|
||||
let run = cli(
|
||||
"1791208980",
|
||||
&[
|
||||
r#"review.trackChanges={"value": true}"#.to_string(),
|
||||
r#"text.insert={"text": "tracked"}"#.to_string(),
|
||||
r#"review.newComment={"text": "note"}"#.to_string(),
|
||||
format!("file.saveAs={}", serde_json::json!({"path": out})),
|
||||
],
|
||||
);
|
||||
let after = wordcraft_engine::cmd::now_iso();
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
let xml = std::fs::read_to_string(&out).unwrap();
|
||||
assert!(xml.contains(r#"<dcterms:modified xsi:type="dcterms:W3CDTF">2026-10-05T14:03:00Z</dcterms:modified>"#), "the file's date is pinned");
|
||||
|
||||
let dates: Vec<&str> = xml.split(r#"w:date=""#).skip(1).filter_map(|rest| rest.split('"').next()).collect();
|
||||
assert!(xml.contains("<w:ins ") && xml.contains("<w:comment "), "a tracked insertion and a comment were saved");
|
||||
assert!(dates.len() >= 2, "both carry a date: {dates:?}");
|
||||
for date in dates {
|
||||
assert!((before.as_str()..=after.as_str()).contains(&date), "{date} is the clock's, between {before} and {after}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A value that is set and cannot be used is said out loud, and the run still succeeds: the
|
||||
/// files take the clock's date, as they would with the variable unset (noted in review).
|
||||
#[test]
|
||||
fn an_unusable_epoch_is_reported_on_stderr() {
|
||||
let dir = scratch("epoch-warning");
|
||||
let save = |name: &str| format!("file.exportPdf={}", serde_json::json!({"path": dir.join(name)}));
|
||||
let run = cli("later", &[save("later.pdf")]);
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(stderr.contains(r#"warning: SOURCE_DATE_EPOCH="later" is not a whole number of seconds"#), "{stderr}");
|
||||
let pdf = std::fs::read(dir.join("later.pdf")).unwrap();
|
||||
let pinned = b"/CreationDate(D:20261005140300";
|
||||
assert!(pdf.windows(b"/CreationDate(D:".len()).any(|w| w == b"/CreationDate(D:"), "the export has a creation date");
|
||||
assert!(!pdf.windows(pinned.len()).any(|w| w == pinned), "and it is the clock's, not a pinned one");
|
||||
|
||||
for quiet in ["1791208980", ""] {
|
||||
let run = cli(quiet, &[save("quiet.pdf")]);
|
||||
assert!(run.status.success());
|
||||
assert!(!String::from_utf8_lossy(&run.stderr).contains("SOURCE_DATE_EPOCH"), "{quiet:?} says nothing");
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,8 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(!text.contains("lines and pages may not match Word's"), "{text}");
|
||||
assert!(r.stdout.is_empty());
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! A write's `wrote <path>` confirmation is a result, so it goes to stdout, where a script that
|
||||
//! captures the output finds it; stderr keeps errors and diagnostics (#7070).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("wc-cli-wrote-{name}-{}", std::process::id()));
|
||||
// A failed run leaves its directory behind (cleanup runs only after the assertions), and a
|
||||
// later process can reuse the PID: start clean so a stale file cannot pass a check.
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The confirmation is on stdout and not on stderr, and the file is there.
|
||||
fn assert_wrote_on_stdout(run: &Output, out: &Path) {
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
assert!(out.is_file(), "{} was not written", out.display());
|
||||
let line = format!("wrote {}", out.display());
|
||||
assert!(stdout.lines().any(|l| l == line), "stdout lacks `{line}`: {stdout:?}");
|
||||
assert!(!stderr.contains("wrote "), "the confirmation is on stderr too: {stderr:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_confirms_the_write_on_stdout() {
|
||||
let d = dir("convert");
|
||||
let (input, out) = (d.join("in.txt"), d.join("out.docx"));
|
||||
std::fs::write(&input, "Hello").unwrap();
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&out).output().unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_confirms_each_save_on_stdout() {
|
||||
let d = dir("run");
|
||||
let out = d.join("out.docx");
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.args(["run", "--template", "blank", "--cmd", r#"text.insert={"text":"x"}"#, "--save"])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A reader that has already hung up does not stop the job: every save still runs, though its
|
||||
/// confirmation has nowhere to go. A PNG is written only in the confirming loop, so it shows a
|
||||
/// save that was skipped.
|
||||
#[test]
|
||||
fn run_keeps_saving_after_stdout_closes() {
|
||||
let d = dir("closed");
|
||||
let job = d.join("job.json");
|
||||
std::fs::write(
|
||||
&job,
|
||||
r#"{"template": "blank", "commands": [{"command": "text.insert", "params": {"text": "x"}}], "save": ["first.docx", "second.png"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (reader, writer) = std::io::pipe().unwrap();
|
||||
drop(reader);
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(["run", "--script"]).arg(&job).stdout(writer).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
for out in ["first.docx", "second.png"] {
|
||||
assert!(d.join(out).is_file(), "{out} was not written; stderr: {stderr}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const POLL_MS: i32 = 16;
|
||||
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (queue, requests) = channel::<ControlRequest>();
|
||||
let request: Request = Rc::new(move |method, params| {
|
||||
let params = super::page_params::control_params(&method, params);
|
||||
let (control, reply) = ControlRequest::new(method, params);
|
||||
if queue.send(control).is_err() {
|
||||
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
|
||||
|
||||
@@ -23,6 +23,8 @@ mod prefs;
|
||||
mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod page_params;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
use serde_json::Value;
|
||||
|
||||
pub(super) fn control_params(method: &str, mut params: Value) -> Value {
|
||||
// The page helper asks for inline data. A screenshot without a path already returns it.
|
||||
if method == "ui.screenshot"
|
||||
&& let Some(fields) = params.as_object_mut()
|
||||
&& !fields.contains_key("path")
|
||||
&& fields.get("data") == Some(&Value::Bool(true))
|
||||
{
|
||||
fields.remove("data");
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::automation::screenshot::ScreenshotParams;
|
||||
use serde_json::json;
|
||||
|
||||
use super::control_params;
|
||||
|
||||
#[test]
|
||||
fn page_helper_requests_the_same_capture_as_a_direct_request() {
|
||||
for (helper, direct) in
|
||||
[(json!({"data": true}), json!({})), (json!({"data": true, "region": [10, 20, 100, 200]}), json!({"region": [10, 20, 100, 200]}))]
|
||||
{
|
||||
let params = control_params("ui.screenshot", helper);
|
||||
assert_eq!(params, direct);
|
||||
assert!(ScreenshotParams::from_params(¶ms).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_helper_keeps_screenshot_validation() {
|
||||
for (input, expected) in [
|
||||
(json!({"data": true, "region": [100, 200, 10, 20]}), json!({"region": [100, 200, 10, 20]})),
|
||||
(json!({"data": true, "viewport": "other"}), json!({"viewport": "other"})),
|
||||
(json!({"data": true, "path": "capture.png"}), json!({"data": true, "path": "capture.png"})),
|
||||
(json!({"data": true, "path": null}), json!({"data": true, "path": null})),
|
||||
(json!({"data": false}), json!({"data": false})),
|
||||
(json!({"data": "true"}), json!({"data": "true"})),
|
||||
] {
|
||||
let params = control_params("ui.screenshot", input);
|
||||
assert_eq!(params, expected);
|
||||
assert!(ScreenshotParams::from_params(¶ms).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_requests_keep_their_parameters() {
|
||||
for (method, params) in [("ui.screenshot", json!({"path": "capture.png"})), ("file.new", json!({"data": true}))] {
|
||||
assert_eq!(control_params(method, params.clone()), params);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ craft = { workspace = true, features = [
|
||||
"ui-app",
|
||||
"dialogs",
|
||||
"automation",
|
||||
"automation-agents",
|
||||
"gpu-startup",
|
||||
"print",
|
||||
"settings",
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
//! A connection authenticates once with the token (`docs/control-protocol.md`, Token). When no
|
||||
//! token or token file is supplied, the app generates a token and writes it to
|
||||
//! `<settings>/control-key.<instance>` (mode 0600) after the port is bound, and removes the file
|
||||
//! when the window closes.
|
||||
//! when the window closes. The server itself goes to the agent link for the run
|
||||
//! (`AgentLink::from_launch`), so File › Options › Agents says the launch options manage it.
|
||||
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Receiver;
|
||||
|
||||
use craft::automation::AutomationError;
|
||||
use craft::automation::args::ControlOptions;
|
||||
use craft::automation::control::ControlRequest;
|
||||
use craft::automation::server::{Listening, serve};
|
||||
@@ -24,11 +26,28 @@ pub struct Control {
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// The server, for the agent link to keep for the whole run (`AgentLink::from_launch`), and the
|
||||
/// token file this run wrote, which the app removes when the window closes.
|
||||
pub fn split(self) -> (Listening, TokenFile) {
|
||||
(self.listening, TokenFile(self.created))
|
||||
}
|
||||
|
||||
/// Stop accepting connections and remove the token file this run wrote, if any.
|
||||
#[cfg(test)]
|
||||
pub fn shut_down(self) {
|
||||
let Self { listening, created } = self;
|
||||
let (listening, file) = self.split();
|
||||
drop(listening);
|
||||
remove(created.as_deref());
|
||||
file.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/// The default token file a run wrote, if any; a token file the user supplied is never removed.
|
||||
pub struct TokenFile(Option<PathBuf>);
|
||||
|
||||
impl TokenFile {
|
||||
/// Removes the file this run wrote.
|
||||
pub fn remove(self) {
|
||||
remove(self.0.as_deref());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +57,22 @@ fn remove(path: Option<&Path>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why starting the control server did not succeed.
|
||||
enum StartError {
|
||||
/// Windows external-tool timeout while creating or checking the owner-only token file.
|
||||
TokenTimeout(String),
|
||||
/// Any other bind, token, or accept-thread error.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl StartError {
|
||||
fn message(&self) -> &str {
|
||||
match self {
|
||||
Self::TokenTimeout(msg) | Self::Other(msg) => msg,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
|
||||
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
|
||||
///
|
||||
@@ -45,35 +80,50 @@ fn remove(path: Option<&Path>) {
|
||||
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
|
||||
/// settings folder a fresh token is generated and reported by the log.
|
||||
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
return None;
|
||||
match start_with(options, port, host, settings, ControlOptions::server_token, serve) {
|
||||
Ok(started) => Some(started),
|
||||
Err(err) => {
|
||||
log::error!("{}", err.message());
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn start_with(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
|
||||
serve: impl FnOnce(TcpListener, String, WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
|
||||
let listener =
|
||||
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
|
||||
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
|
||||
// The port was free, so no other run owns a file left here.
|
||||
remove(created.as_deref());
|
||||
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
|
||||
let token = match effective.server_token() {
|
||||
let token = match token_for(&effective) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
remove(created.as_deref());
|
||||
log::error!("control server off: {e}");
|
||||
return None;
|
||||
let msg = format!("control server off: {e}");
|
||||
return Err(if matches!(&e, AutomationError::Io(text) if text.contains("did not finish within ")) {
|
||||
StartError::TokenTimeout(msg)
|
||||
} else {
|
||||
StartError::Other(msg)
|
||||
});
|
||||
}
|
||||
};
|
||||
let notice = effective.token_notice(&token);
|
||||
match serve(listener, token, host) {
|
||||
Ok((rx, listening)) => {
|
||||
log::info!("control server listening on {}, {notice}", listening.addr);
|
||||
Some((rx, Control { listening, created }))
|
||||
Ok((rx, Control { listening, created }))
|
||||
}
|
||||
Err(e) => {
|
||||
remove(created.as_deref());
|
||||
log::error!("control server off: cannot start the accept thread ({e})");
|
||||
None
|
||||
Err(StartError::Other(format!("control server off: cannot start the accept thread ({e})")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +137,52 @@ mod tests {
|
||||
WindowHost::of(&egui::Context::default())
|
||||
}
|
||||
|
||||
/// Attempts for `start_with` when Windows `owner_only` hits its 10 s external-tool limit on
|
||||
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
|
||||
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
|
||||
|
||||
fn try_start_retrying_token_timeout_with(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
mut serve: impl FnMut(TcpListener, String, WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
match start_with(options, port, host.clone(), settings, &mut token_for, &mut serve) {
|
||||
Ok(started) => return Ok(started),
|
||||
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
|
||||
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
|
||||
attempt += 1;
|
||||
}
|
||||
Err(err) => return Err((attempt, err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
|
||||
try_start_retrying_token_timeout_with(options, port, host, settings, token_for, serve)
|
||||
}
|
||||
|
||||
fn start_retrying_token_timeout(
|
||||
options: &ControlOptions,
|
||||
port: u16,
|
||||
host: WindowHost,
|
||||
settings: Option<&Path>,
|
||||
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
|
||||
) -> (Receiver<ControlRequest>, Control) {
|
||||
try_start_retrying_token_timeout(options, port, host, settings, token_for)
|
||||
.unwrap_or_else(|(attempt, err)| panic!("control server start failed on attempt {attempt}: {}", err.message()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
|
||||
@@ -101,7 +197,7 @@ mod tests {
|
||||
drop(taken);
|
||||
|
||||
// Bound: the default file holds the token that opens the port.
|
||||
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
|
||||
let path = control.created.clone().unwrap();
|
||||
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
|
||||
let token = std::fs::read_to_string(&path).unwrap();
|
||||
@@ -117,13 +213,61 @@ mod tests {
|
||||
// A token file the user supplied stays.
|
||||
let supplied = dir.join("supplied-token");
|
||||
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
|
||||
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
|
||||
assert!(control.created.is_none());
|
||||
control.shut_down();
|
||||
assert!(supplied.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transient_token_file_timeout_retries_while_other_errors_stop() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-control-retry-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let options = ControlOptions::default();
|
||||
|
||||
// A Windows `owner_only` external-tool timeout retries and recovers on a later attempt.
|
||||
let mut timeout_then_ok = 0usize;
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), |effective| {
|
||||
timeout_then_ok += 1;
|
||||
if timeout_then_ok == 1 {
|
||||
let path = effective.token_file.as_ref().unwrap();
|
||||
Err(AutomationError::Io(format!(
|
||||
"{}: cannot create the control token file for its owner only: powershell.exe did not finish within 10 s and was ended",
|
||||
path.display()
|
||||
)))
|
||||
} else {
|
||||
Ok(TOKEN.to_string())
|
||||
}
|
||||
});
|
||||
assert_eq!(timeout_then_ok, 2);
|
||||
control.shut_down();
|
||||
|
||||
// Repeated timeouts stop after `TOKEN_TIMEOUT_ATTEMPTS` instead of looping forever.
|
||||
let mut exhausted = 0usize;
|
||||
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
|
||||
exhausted += 1;
|
||||
Err(AutomationError::Io("powershell.exe did not finish within 10 s and was ended".into()))
|
||||
}) else {
|
||||
panic!("exhausted timeouts must fail");
|
||||
};
|
||||
assert_eq!((attempt, exhausted), (TOKEN_TIMEOUT_ATTEMPTS, TOKEN_TIMEOUT_ATTEMPTS));
|
||||
assert!(matches!(err, StartError::TokenTimeout(_)));
|
||||
|
||||
// Non-timeout failures stop on the first attempt.
|
||||
let mut other = 0usize;
|
||||
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
|
||||
other += 1;
|
||||
Err(AutomationError::Io("permission denied".into()))
|
||||
}) else {
|
||||
panic!("non-timeout error must fail");
|
||||
};
|
||||
assert_eq!((attempt, other), (1, 1));
|
||||
assert!(matches!(err, StartError::Other(msg) if msg.contains("permission denied")));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
|
||||
@@ -286,4 +430,64 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
struct TempDir(std::path::PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_key_file_is_replaced() {
|
||||
let dir = TempDir::new("wordcraft-control-stale");
|
||||
std::fs::create_dir_all(&dir.0).unwrap();
|
||||
let p = wordcraft_control_key::key_path(&dir.0, 0);
|
||||
std::fs::write(&p, "old").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}
|
||||
|
||||
let options = ControlOptions::default();
|
||||
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir.0), ControlOptions::server_token);
|
||||
let token = std::fs::read_to_string(&p).unwrap();
|
||||
assert_ne!(token.trim(), "old");
|
||||
assert_eq!(token.trim().len(), 64);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
assert!(ControlClient::connect(control.listening.addr, token.trim()).is_ok());
|
||||
control.shut_down();
|
||||
assert!(!p.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_accept_thread_spawn_failure_aborts_start_and_removes_the_key() {
|
||||
let dir = TempDir::new("wordcraft-control-spawn-fail");
|
||||
let path = wordcraft_control_key::key_path(&dir.0, 0);
|
||||
let options = ControlOptions::default();
|
||||
let result =
|
||||
try_start_retrying_token_timeout_with(&options, 0, host(), Some(&dir.0), ControlOptions::server_token, |_listener, _token, _host| {
|
||||
assert!(path.exists(), "startup wrote the token file before spawning");
|
||||
Err(std::io::Error::other("injected accept thread spawn failure"))
|
||||
});
|
||||
assert!(
|
||||
matches!(result, Err((_, StartError::Other(ref msg))) if msg.contains("cannot start the accept thread")),
|
||||
"a server without its accept thread must not report success"
|
||||
);
|
||||
assert!(!path.exists(), "failed startup must remove its published key");
|
||||
}
|
||||
}
|
||||
|
||||
+277
-140
@@ -67,8 +67,8 @@ struct App {
|
||||
settings: SharedSettings<Prefs>,
|
||||
/// The print spool, a handle on the one in the app's services: jobs being sent finish first.
|
||||
spool: Spool,
|
||||
/// The control server, when `--control` started one; it removes the token file it made.
|
||||
control: Option<control_server::Control>,
|
||||
/// The token file `--control` wrote, removed at exit; its server runs in the agent link.
|
||||
control: Option<control_server::TokenFile>,
|
||||
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
|
||||
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
|
||||
exit: Option<Box<dyn FnOnce()>>,
|
||||
@@ -118,8 +118,8 @@ impl App {
|
||||
if let Err(e) = self.settings.lock().flush() {
|
||||
log::warn!("preferences: {e}");
|
||||
}
|
||||
if let Some(control) = self.control.take() {
|
||||
control.shut_down();
|
||||
if let Some(file) = self.control.take() {
|
||||
file.remove();
|
||||
}
|
||||
if !launch_profile::current().is_nightly() {
|
||||
self.app.start_pending_update();
|
||||
@@ -152,6 +152,21 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Files dropped on a document window. eframe hands `raw_input_hook` only the root's and deferred
|
||||
/// viewports' input, and document windows are immediate viewports (every one under the windowless
|
||||
/// root), so their drops come through this hook. It runs first and takes the batch, so nothing reads
|
||||
/// it twice.
|
||||
struct ChildDrops(IntakeSender);
|
||||
|
||||
impl eframe::ViewportHooks for ChildDrops {
|
||||
fn raw_input(&self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
if raw.viewport_id != egui::ViewportId::ROOT && !raw.dropped_files.is_empty() {
|
||||
self.0.dropped(dropped_files(raw));
|
||||
raw.dropped_files.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -463,6 +478,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
|
||||
}
|
||||
|
||||
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
|
||||
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
|
||||
/// cell for a retry with the visible root: the app always starts.
|
||||
fn run_with_visible_root_fallback(
|
||||
creator: eframe::AppCreator<'static>,
|
||||
windowless: Arc<std::sync::atomic::AtomicBool>,
|
||||
mut options: eframe::NativeOptions,
|
||||
) -> eframe::Result {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
|
||||
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
|
||||
let run = |options: eframe::NativeOptions| {
|
||||
let creator = creator.clone();
|
||||
eframe::run_native(
|
||||
name,
|
||||
options,
|
||||
Box::new(move |cc| match creator.borrow_mut().take() {
|
||||
Some(create) => create(cc),
|
||||
None => Err("the app was already created".into()),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let on = windowless.load(Relaxed);
|
||||
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
|
||||
let mut visible_root = on.then(|| options.clone());
|
||||
if on {
|
||||
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
|
||||
}
|
||||
let result = run(options);
|
||||
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
|
||||
&& let Some(options) = visible_root.take()
|
||||
&& creator.borrow().is_some()
|
||||
{
|
||||
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
|
||||
windowless.store(false, Relaxed);
|
||||
return run(options);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
/// geometry, opens requested documents or the Start screen, starts the control server when
|
||||
/// asked, and runs the eframe event loop.
|
||||
@@ -676,6 +731,7 @@ fn main() -> eframe::Result {
|
||||
// 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();
|
||||
options.viewport_hooks = Some(Arc::new(ChildDrops(drops.clone())));
|
||||
#[cfg(target_os = "macos")]
|
||||
let _apple_events = craft::platform::open::apple_events::install(sender);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -705,147 +761,180 @@ 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 = {
|
||||
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
|
||||
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
|
||||
// is read by the app creator, which runs once the mode is settled.
|
||||
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
|
||||
let windowless_in_app = windowless.clone();
|
||||
let creator: eframe::AppCreator<'static> = 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 mut 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);
|
||||
// The runtime and eframe must agree on the root.
|
||||
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
spec = spec.windowless_root();
|
||||
}
|
||||
// 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());
|
||||
// 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);
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
// 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}");
|
||||
}
|
||||
}
|
||||
// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents)
|
||||
// names WordCraft, the agent link serves them and publishes where, so `wordcraft-cli mcp`
|
||||
// finds the window. `--control` runs its own server for the whole run instead. Allow
|
||||
// Agent Control off (File › Options › Agents) refuses both. A Nightly window serves none.
|
||||
let mut control_server = None;
|
||||
if !nightly {
|
||||
let settings_dir = wordcraft_control_key::settings_dir();
|
||||
// A file a crashed launch left behind names a port nothing serves; before this
|
||||
// launch's own listener, so it doesn't keep it.
|
||||
if let Some(dir) = &settings_dir {
|
||||
craft::automation::agents::remove_stale_connection(dir);
|
||||
}
|
||||
let allow = settings.lock().get().integrations.allow_agent_control;
|
||||
let launched = match control.port {
|
||||
Some(port) if !allow => {
|
||||
complain(format_args!("File › Options › Agents › Allow Agent Control is off: not listening on port {port}"));
|
||||
None
|
||||
}
|
||||
Some(port) => control_server::start(&control, port, WindowHost::of(&ctx), settings_dir.as_deref()),
|
||||
None => None,
|
||||
};
|
||||
let link = match launched {
|
||||
Some((rx, started)) => {
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
let (listening, token_file) = started.split();
|
||||
control_server = Some(token_file);
|
||||
craft::automation::agents::AgentLink::from_launch(listening)
|
||||
}
|
||||
None => craft::automation::agents::AgentLink::new(settings_dir, format!("WordCraft {}", env!("CARGO_PKG_VERSION"))),
|
||||
};
|
||||
let switch = craft::automation::agents::AgentSwitch::watch(wordcraft_ui_egui::agents::LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// 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);
|
||||
});
|
||||
app = app.with_agents(wordcraft_ui_egui::agents::Agents::new(link, switch));
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// 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);
|
||||
}
|
||||
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());
|
||||
// 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);
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
// 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}");
|
||||
}
|
||||
}
|
||||
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,
|
||||
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 = run_with_visible_root_fallback(creator, windowless, options);
|
||||
// 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.
|
||||
@@ -1210,6 +1299,54 @@ mod smoke {
|
||||
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
|
||||
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
|
||||
}
|
||||
|
||||
/// With a modal dialog open, Quit stays enabled and ⌘Q / menu Quit still run `ui.quit`:
|
||||
/// a clean document quits and a modified one opens Save Changes (#8792).
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn native_quit_works_while_a_modal_dialog_is_open() {
|
||||
use craft::menu::{ItemRole, NativeMenu};
|
||||
|
||||
let mut clean = Run::new();
|
||||
let fake = native_menu::FakeBackend::default();
|
||||
let synced = fake.synced.clone();
|
||||
let events = fake.events.clone();
|
||||
let dispatch_cell = fake.dispatch.clone();
|
||||
clean.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
|
||||
clean.app.app.run("ui.dialog", json!({"name": "about"})).unwrap();
|
||||
clean.settle();
|
||||
assert!(clean.app.app.dialog_host_mut().shows_modal());
|
||||
let quit = {
|
||||
let bars = synced.borrow();
|
||||
let bar = bars.last().unwrap();
|
||||
let about = bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
|
||||
let quit = bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
|
||||
assert!(!about.enabled, "About is greyed while About is open");
|
||||
assert!(quit.enabled, "Quit stays enabled while About is open");
|
||||
quit.clone()
|
||||
};
|
||||
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
|
||||
let cmd_q = quit.shortcut.unwrap();
|
||||
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None));
|
||||
clean.settle();
|
||||
assert!(clean.app.app.quit_requested, "Cmd+Q quits a clean document while About is open");
|
||||
|
||||
let mut dirty = Run::new();
|
||||
let fake = native_menu::FakeBackend::default();
|
||||
let events = fake.events.clone();
|
||||
let dispatch_cell = fake.dispatch.clone();
|
||||
dirty.app.native_menu = Some(NativeMenu::new(Box::new(fake)));
|
||||
dirty.app.app.run("text.insert", json!({"text": "unsaved"})).unwrap();
|
||||
dirty.app.app.run("ui.dialog", json!({"name": "paragraph"})).unwrap();
|
||||
dirty.settle();
|
||||
assert!(dirty.app.app.dialog_host_mut().shows_modal());
|
||||
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
|
||||
events.borrow_mut().push(dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None));
|
||||
dirty.settle();
|
||||
assert!(!dirty.app.app.quit_requested, "Quit asks Save Changes first for a modified document");
|
||||
dirty.app.app.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert!(dirty.app.app.quit_requested, "Don't Save completes the quit");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
//! The macOS application menu uses the same About dialog as File › About.
|
||||
|
||||
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
|
||||
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, ModalRules, NativeMenu, mac_layout};
|
||||
use serde_json::json;
|
||||
use wordcraft_ui_egui::{WordApp, i18n};
|
||||
|
||||
const APP_NAME: &str = "WordCraft";
|
||||
const ABOUT: &str = "About WordCraft";
|
||||
const QUIT: &str = "Quit WordCraft";
|
||||
|
||||
/// The application menu, with `tr` the translation of an English string.
|
||||
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
|
||||
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
|
||||
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
|
||||
// Without its own Quit `mac_layout` adds one whose click only closes the root window: it must ask about every document.
|
||||
let quit = Item::new(CommandRef::new("ui.quit"), tr(QUIT)).role(ItemRole::Quit);
|
||||
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into(), quit.into()]).role(MenuRole::App)]);
|
||||
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
|
||||
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
|
||||
let label = |s: &'static str| {
|
||||
tr(match s {
|
||||
"About {app}" => ABOUT,
|
||||
"Quit {app}" => QUIT,
|
||||
s => s,
|
||||
})
|
||||
};
|
||||
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
|
||||
// WordCraft's document menus live in its ribbon; keep only the application menu.
|
||||
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
|
||||
@@ -27,15 +36,24 @@ fn layout_in(lang: i18n::Lang) -> Layout {
|
||||
layout(&|s| i18n::tr(lang, s).to_owned())
|
||||
}
|
||||
|
||||
/// Commands that still run from the application menu while a modal dialog is open: `ui.quit` asks
|
||||
/// about unsaved documents through `WordApp::quit`, matching the built-in Quit item and the Dock.
|
||||
fn modal_rules() -> ModalRules {
|
||||
ModalRules::default().in_dialogs(["ui.quit"])
|
||||
}
|
||||
|
||||
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
|
||||
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
|
||||
if menu.is_none() {
|
||||
let mut menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
|
||||
if let Some(menu) = &mut menu {
|
||||
menu.set_modal_rules(modal_rules());
|
||||
} else {
|
||||
log::warn!("the WordCraft application menu could not be installed");
|
||||
}
|
||||
menu
|
||||
}
|
||||
|
||||
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
|
||||
menu.set_modal_rules(modal_rules());
|
||||
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
|
||||
for command in menu.take_clicks(ctx) {
|
||||
if let Err(error) = app.run(&command.id, command.params) {
|
||||
@@ -49,6 +67,29 @@ pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Conte
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
pub(super) struct FakeBackend {
|
||||
pub(super) synced: std::rc::Rc<std::cell::RefCell<Vec<MenuBar>>>,
|
||||
pub(super) events: std::rc::Rc<std::cell::RefCell<Vec<craft::menu::Event>>>,
|
||||
pub(super) dispatch: std::rc::Rc<std::cell::RefCell<Option<craft::menu::Dispatch>>>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl craft::menu::Backend for FakeBackend {
|
||||
fn sync(&mut self, bar: &MenuBar) {
|
||||
self.synced.borrow_mut().push(bar.clone());
|
||||
}
|
||||
|
||||
fn attach(&mut self, dispatch: craft::menu::Dispatch) {
|
||||
*self.dispatch.borrow_mut() = Some(dispatch);
|
||||
}
|
||||
|
||||
fn drain(&mut self) -> Vec<craft::menu::Event> {
|
||||
std::mem::take(&mut *self.events.borrow_mut())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -61,4 +102,45 @@ mod tests {
|
||||
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
|
||||
assert_eq!(about.label, "Über WordCraft");
|
||||
}
|
||||
|
||||
/// ⌘Q and the menu's Quit run `ui.quit`, which asks about unsaved documents; craft's built-in Quit only closes the root window (#8709).
|
||||
#[test]
|
||||
fn quit_runs_the_command_that_asks_about_documents() {
|
||||
let layout = layout(&|s| s.to_owned());
|
||||
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
|
||||
assert_eq!(quit.command.id, "ui.quit");
|
||||
}
|
||||
|
||||
/// Quit stays enabled while a modal dialog is open, and both a menu click and ⌘Q pass the gate (#8792).
|
||||
#[test]
|
||||
fn quit_stays_enabled_and_runs_under_modal_rules() {
|
||||
let fake = FakeBackend::default();
|
||||
let synced = fake.synced.clone();
|
||||
let events = fake.events.clone();
|
||||
let dispatch_cell = fake.dispatch.clone();
|
||||
let mut menu = NativeMenu::new(Box::new(fake));
|
||||
menu.set_modal_rules(modal_rules());
|
||||
menu.set_gate(Gate::default().modal(true));
|
||||
let ctx = egui::Context::default();
|
||||
menu.sync_with("en", || layout(&|s| s.to_owned()));
|
||||
|
||||
let bar = synced.borrow();
|
||||
let last = bar.last().unwrap();
|
||||
let about = last.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().clone();
|
||||
let quit = last.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap().clone();
|
||||
drop(bar);
|
||||
|
||||
assert!(!about.enabled, "About is greyed while a modal dialog is open");
|
||||
assert!(quit.enabled, "Quit stays enabled while a modal dialog is open");
|
||||
|
||||
let dispatch = dispatch_cell.borrow().as_ref().unwrap().clone();
|
||||
let cmd_q = quit.shortcut.unwrap();
|
||||
events.borrow_mut().extend([
|
||||
dispatch.chosen(&about.command, about.shortcut.as_ref(), about.layout_shortcut, false, Default::default(), None),
|
||||
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, false, Default::default(), None),
|
||||
dispatch.chosen(&quit.command, Some(&cmd_q), quit.layout_shortcut, true, cmd_q.mods, None),
|
||||
]);
|
||||
menu.poll(&ctx);
|
||||
assert_eq!(menu.take_clicks(&ctx), vec![quit.command.clone(), quit.command]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,6 +206,10 @@ display_name = "entropybeater"
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
|
||||
@@ -813,8 +813,14 @@ impl Document {
|
||||
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
|
||||
/// JSON, whose run lengths may overflow, fall short or split a character.
|
||||
pub fn normalize_runs(&mut self) {
|
||||
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
let separators = [&mut self.footnote_separators, &mut self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&mut s.separator, &mut s.continuation_separator, &mut s.continuation_notice])
|
||||
.flatten();
|
||||
let stories = std::iter::once(&mut self.body)
|
||||
.chain(self.parts.values_mut().map(|part| &mut part.blocks))
|
||||
.chain(separators)
|
||||
.chain(self.glossary.iter_mut().map(|entry| &mut entry.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
|
||||
|
||||
@@ -387,6 +387,14 @@ impl Counters {
|
||||
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
|
||||
}
|
||||
|
||||
/// The values counted so far for `num`, including implicitly counted ancestors and zero starts.
|
||||
/// An unstarted level has no value even when its definition has a default start.
|
||||
pub fn counted_values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> [Option<u32>; 9] {
|
||||
let Some(abs) = numbering.abstract_of(num) else { return [None; 9] };
|
||||
let (Some(values), Some(flags)) = (self.state.get(&abs.id), self.flags.get(&abs.id)) else { return [None; 9] };
|
||||
std::array::from_fn(|level| flags[level].started.then_some(values[level]))
|
||||
}
|
||||
|
||||
fn next_label_from(&mut self, n: &Num, abs: &AbstractNum, level: u8) -> Option<(String, Level)> {
|
||||
let num = n.id;
|
||||
let lv = (level as usize).min(8);
|
||||
@@ -493,16 +501,19 @@ impl Counters {
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholder_level(digit: char) -> Option<usize> {
|
||||
digit.to_digit(10).filter(|d| (1..=9).contains(d)).map(|d| (d - 1) as usize)
|
||||
}
|
||||
|
||||
/// The zero-based levels a label template shows (`"%1.%2"` → `[0, 1]`, `"(%3)"` → `[2]`).
|
||||
pub fn template_levels(text: &str) -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
let mut chars = text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
if !out.contains(&k) {
|
||||
out.push(k);
|
||||
}
|
||||
@@ -518,10 +529,9 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
|
||||
let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
&& let Some(k) = chars.peek().copied().and_then(placeholder_level)
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
let val = vals.get(k).copied().unwrap_or(0);
|
||||
let counted = started.get(k).is_some_and(|f| f.started);
|
||||
let level = level_def(k);
|
||||
@@ -842,6 +852,61 @@ mod tests {
|
||||
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_zero_counters_increment_properly() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(a) = n.abstracts.first_mut() {
|
||||
a.levels[0].start = 0;
|
||||
a.levels[0].text = "Item %1.".into();
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 0.");
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 1.");
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 2.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_override_of_zero_starts_at_zero() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
|
||||
num.start_overrides = vec![(0, 0)];
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
let labels: Vec<String> = (0..3).map(|_| c.next_label(&n, id, 0).unwrap().0).collect();
|
||||
assert_eq!(labels, ["0.", "1.", "2."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_counted_zero_ancestor_replaces_the_unstarted_fallback() {
|
||||
let mut numbering = Numbering::default();
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
numbering.abstracts[0].levels[0].start = 7;
|
||||
numbering.abstracts[0].levels[1] = Level { text: "%1.%2.".into(), ..Default::default() };
|
||||
numbering.nums[0].start_overrides = vec![(0, 0)];
|
||||
let index = NumberingIndex::new(&numbering);
|
||||
let mut counters = Counters::default();
|
||||
|
||||
assert_eq!(counters.counted_values_indexed(&index, num)[0], None);
|
||||
assert_eq!(counters.current_label(&numbering, num, 1).as_deref(), Some("7.1."));
|
||||
let (label, _) = counters.next_label_indexed(&index, num, 1).unwrap();
|
||||
assert_eq!(label, "0.1.");
|
||||
assert_eq!(counters.counted_values_indexed(&index, num)[0], Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_percent_zero_is_preserved_as_literal() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(a) = n.abstracts.first_mut() {
|
||||
a.levels[0].text = "%0 %1.".into();
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "%0 1.");
|
||||
assert_eq!(template_levels("%0 %2. %9 %2"), [1, 8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
|
||||
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
|
||||
|
||||
+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)) {
|
||||
|
||||
+24
-1
@@ -23,7 +23,8 @@ mod para_props;
|
||||
mod table_props;
|
||||
|
||||
pub use char_props::{
|
||||
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, Underline, VertAlign,
|
||||
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
|
||||
VertAlign,
|
||||
};
|
||||
pub use color::{Rgb, TextColor};
|
||||
pub use para_props::{
|
||||
@@ -200,4 +201,26 @@ mod tests {
|
||||
assert_eq!(changed.sym_font.as_deref(), Some("Wingdings"));
|
||||
assert_eq!(p.cleared().sym_font.as_deref(), Some("Wingdings"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_east_asian_font_replaces_theme_slot_and_minus_round_trips() {
|
||||
let mut base = CharProps { font_ea: Some("Times New Roman".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
|
||||
let named = CharProps { font_ea: Some("SimSun".into()), ..Default::default() };
|
||||
base.overlay(&named);
|
||||
assert_eq!(base.font_ea.as_deref(), Some("SimSun"));
|
||||
assert_eq!(base.font_ea_theme, None);
|
||||
|
||||
// Changing only `font_ea` while keeping `font_ea_theme` preserves the slot across minus/overlay.
|
||||
let themed_base = CharProps { font_ea: Some("SimSun".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
|
||||
let run = CharProps { font_ea: Some("MS Mincho".into()), ..themed_base.clone() };
|
||||
let mut back = themed_base.clone();
|
||||
back.overlay(&run.clone().minus(&themed_base));
|
||||
assert_eq!(back, run);
|
||||
|
||||
// Clearing `font_ea_theme` while keeping the same `font_ea` preserves `font_ea` in the patch.
|
||||
let cleared_slot = CharProps { font_ea_theme: None, ..themed_base.clone() };
|
||||
let mut back_cleared = themed_base.clone();
|
||||
back_cleared.overlay(&cleared_slot.clone().minus(&themed_base));
|
||||
assert_eq!(back_cleared, cleared_slot);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,6 +329,10 @@ pub struct CharProps {
|
||||
/// inherit, then `font`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea: Option<String>,
|
||||
/// The theme font slot of the East Asian font (`w:rFonts/@w:eastAsiaTheme`: `minorEastAsia`,
|
||||
/// `majorEastAsia`…), taking precedence over `font_ea` when set.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea_theme: Option<ThemeFont>,
|
||||
/// Complex-script size, points (`w:szCs`). `None` leaves the inherited value unchanged.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub size_cs: Option<f32>,
|
||||
@@ -450,6 +454,62 @@ impl CombineBrackets {
|
||||
}
|
||||
}
|
||||
|
||||
/// A theme font slot in `w:rFonts` (`ST_Theme`, ECMA-376 §17.18.96).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ThemeFont {
|
||||
MajorEastAsia,
|
||||
MajorBidi,
|
||||
MajorAscii,
|
||||
MajorHAnsi,
|
||||
MinorEastAsia,
|
||||
MinorBidi,
|
||||
MinorAscii,
|
||||
MinorHAnsi,
|
||||
}
|
||||
|
||||
impl ThemeFont {
|
||||
const ALL: [ThemeFont; 8] = [
|
||||
ThemeFont::MajorEastAsia,
|
||||
ThemeFont::MajorBidi,
|
||||
ThemeFont::MajorAscii,
|
||||
ThemeFont::MajorHAnsi,
|
||||
ThemeFont::MinorEastAsia,
|
||||
ThemeFont::MinorBidi,
|
||||
ThemeFont::MinorAscii,
|
||||
ThemeFont::MinorHAnsi,
|
||||
];
|
||||
|
||||
/// The OOXML `ST_Theme` value.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ThemeFont::MajorEastAsia => "majorEastAsia",
|
||||
ThemeFont::MajorBidi => "majorBidi",
|
||||
ThemeFont::MajorAscii => "majorAscii",
|
||||
ThemeFont::MajorHAnsi => "majorHAnsi",
|
||||
ThemeFont::MinorEastAsia => "minorEastAsia",
|
||||
ThemeFont::MinorBidi => "minorBidi",
|
||||
ThemeFont::MinorAscii => "minorAscii",
|
||||
ThemeFont::MinorHAnsi => "minorHAnsi",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an OOXML `ST_Theme` value (`None` for any value outside the schema).
|
||||
pub fn parse(s: &str) -> Option<ThemeFont> {
|
||||
ThemeFont::ALL.into_iter().find(|t| t.as_str() == s)
|
||||
}
|
||||
|
||||
/// Whether this slot picks the theme's major (heading) font rather than minor (body).
|
||||
pub fn is_major(self) -> bool {
|
||||
matches!(self, ThemeFont::MajorEastAsia | ThemeFont::MajorBidi | ThemeFont::MajorAscii | ThemeFont::MajorHAnsi)
|
||||
}
|
||||
|
||||
/// Whether this is one of the Latin theme slots (`ascii` / `hAnsi`).
|
||||
pub fn is_latin(self) -> bool {
|
||||
matches!(self, ThemeFont::MajorAscii | ThemeFont::MajorHAnsi | ThemeFont::MinorAscii | ThemeFont::MinorHAnsi)
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracked formatting change (ECMA-376 §17.13.5: `w:rPrChange`, `w:pPrChange`,
|
||||
/// `w:tblPrChange`, `w:trPrChange`, `w:tcPrChange`, `w:sectPrChange`): the properties as they
|
||||
/// were before the change, and the revision (author, date) that made it.
|
||||
@@ -509,7 +569,16 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn minus_script_style(&mut self, base: &CharProps) {
|
||||
drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
// A theme slot stays while its named font does; a same font stays when its slot differs.
|
||||
let keep = self.font_ea_theme;
|
||||
let ea = self.font_ea.clone();
|
||||
drop_same_fields!(self, base; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
if self.font_ea.is_none() && keep != base.font_ea_theme {
|
||||
self.font_ea = ea;
|
||||
}
|
||||
if self.font_ea.is_some() {
|
||||
self.font_ea_theme = keep;
|
||||
}
|
||||
}
|
||||
|
||||
fn minus_document_marks(&mut self, base: &CharProps) {
|
||||
@@ -540,7 +609,12 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn overlay_script_style(&mut self, patch: &CharProps) {
|
||||
overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
// A named East Asian font without a theme slot replaces the slot too: Word gives the slot
|
||||
// precedence over the named font, so keeping it would hide the font just chosen.
|
||||
if patch.font_ea.is_some() && patch.font_ea_theme.is_none() {
|
||||
self.font_ea_theme = None;
|
||||
}
|
||||
overlay_fields!(self, patch; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
|
||||
}
|
||||
|
||||
fn overlay_document_marks(&mut self, patch: &CharProps) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::{
|
||||
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign,
|
||||
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, ThemeFont, Underline, VertAlign,
|
||||
};
|
||||
use crate::styles::{StyleKind, StyleSheet};
|
||||
|
||||
@@ -71,6 +71,10 @@ pub struct ResolvedChar {
|
||||
/// East Asian font (Chinese, Japanese and Korean text), when one is set.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea: Option<String>,
|
||||
/// Theme font slot for the East Asian font (`w:eastAsiaTheme`), taking precedence over
|
||||
/// `font_ea` when set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub font_ea_theme: Option<ThemeFont>,
|
||||
pub size_cs: f32,
|
||||
pub bold_cs: bool,
|
||||
pub italic_cs: bool,
|
||||
@@ -117,6 +121,7 @@ impl ResolvedChar {
|
||||
cs: c.cs.unwrap_or(false),
|
||||
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
|
||||
font_ea: c.font_ea.clone(),
|
||||
font_ea_theme: c.font_ea_theme,
|
||||
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
|
||||
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
|
||||
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
|
||||
|
||||
@@ -296,6 +296,7 @@ impl NumFormat {
|
||||
use crate::cjk_numbers as cjk;
|
||||
match self {
|
||||
NumFormat::DecimalZero => format!("{n:02}"),
|
||||
NumFormat::Hex => format!("{n:X}"),
|
||||
NumFormat::ThaiNumbers => thai_digits(n),
|
||||
NumFormat::UpperRoman => roman(n).to_uppercase(),
|
||||
NumFormat::LowerRoman => roman(n),
|
||||
@@ -341,7 +342,6 @@ impl NumFormat {
|
||||
NumFormat::Chosung => cjk::chosung(n),
|
||||
NumFormat::Decimal
|
||||
| NumFormat::DecimalHalfWidth
|
||||
| NumFormat::Hex
|
||||
| NumFormat::VietnameseCounting
|
||||
| NumFormat::Hebrew1
|
||||
| NumFormat::Hebrew2
|
||||
@@ -496,13 +496,21 @@ pub fn cardinal_text(n: u32) -> String {
|
||||
let h = format!("{} hundred", words(n / 100));
|
||||
if n.is_multiple_of(100) { h } else { format!("{h} {}", words(n % 100)) }
|
||||
}
|
||||
_ => {
|
||||
1_000..=999_999 => {
|
||||
let th = format!("{} thousand", words(n / 1000));
|
||||
if n.is_multiple_of(1000) { th } else { format!("{th} {}", words(n % 1000)) }
|
||||
}
|
||||
1_000_000..=999_999_999 => {
|
||||
let m = format!("{} million", words(n / 1_000_000));
|
||||
if n.is_multiple_of(1_000_000) { m } else { format!("{m} {}", words(n % 1_000_000)) }
|
||||
}
|
||||
_ => {
|
||||
let b = format!("{} billion", words(n / 1_000_000_000));
|
||||
if n.is_multiple_of(1_000_000_000) { b } else { format!("{b} {}", words(n % 1_000_000_000)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
capitalize(&words(n.min(999_999)))
|
||||
capitalize(&words(n))
|
||||
}
|
||||
|
||||
/// English ordinal words (`Twenty-First`).
|
||||
@@ -765,6 +773,10 @@ pub struct SectionProps {
|
||||
pub page_w: f32,
|
||||
pub page_h: f32,
|
||||
pub landscape: bool,
|
||||
/// Top and bottom margins, points. Negative is Word's exact margin (`w:pgMar` `w:top` /
|
||||
/// `w:bottom` below zero, ECMA-376 §17.6.11; DOC `dyaTop` / `dyaBottom`): the text starts
|
||||
/// (ends) at the absolute value from the page edge even when the header (footer) is taller,
|
||||
/// and overlaps it.
|
||||
pub margin_top: f32,
|
||||
pub margin_bottom: f32,
|
||||
pub margin_left: f32,
|
||||
@@ -904,17 +916,21 @@ impl SectionProps {
|
||||
pub fn text_width(&self) -> f32 {
|
||||
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
|
||||
}
|
||||
/// Height of the text area between the margins, points (a negative, exact margin counts at
|
||||
/// its size).
|
||||
pub fn text_height(&self) -> f32 {
|
||||
(self.page_h - self.margin_top - self.margin_bottom).max(18.0)
|
||||
(self.page_h - self.margin_top.abs() - self.margin_bottom.abs()).max(18.0)
|
||||
}
|
||||
/// Swap to landscape/portrait (keeps margins relative to the paper as Word does: rotates them).
|
||||
/// An exact (negative) top or bottom turns into a side at its size, as in Word: only the top
|
||||
/// and bottom can be exact.
|
||||
pub fn set_landscape(&mut self, on: bool) {
|
||||
if on == self.landscape {
|
||||
return;
|
||||
}
|
||||
self.landscape = on;
|
||||
std::mem::swap(&mut self.page_w, &mut self.page_h);
|
||||
let (t, b, l, r) = (self.margin_top, self.margin_bottom, self.margin_left, self.margin_right);
|
||||
let (t, b, l, r) = (self.margin_top.abs(), self.margin_bottom.abs(), self.margin_left, self.margin_right);
|
||||
if on {
|
||||
self.margin_top = l;
|
||||
self.margin_bottom = r;
|
||||
@@ -1004,6 +1020,17 @@ mod tests {
|
||||
assert_eq!(NumFormat::from_ooxml("klingon"), NumFormat::Decimal, "unknown formats are decimal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_and_large_number_text() {
|
||||
assert_eq!(NumFormat::Hex.format(10), "A");
|
||||
assert_eq!(NumFormat::Hex.format(15), "F");
|
||||
assert_eq!(NumFormat::Hex.format(16), "10");
|
||||
assert_eq!(NumFormat::Hex.format(255), "FF");
|
||||
assert_eq!(NumFormat::CardinalText.format(1_000_000), "One Million");
|
||||
assert_eq!(NumFormat::OrdinalText.format(1_000_000), "One Millionth");
|
||||
assert_eq!(NumFormat::CardinalText.format(2_000_000_000), "Two Billion");
|
||||
}
|
||||
|
||||
/// #5757: Thai numbers are the decimal number in Thai digits, every digit, at any length.
|
||||
#[test]
|
||||
fn thai_numbers_use_thai_digits() {
|
||||
|
||||
@@ -959,6 +959,25 @@ fn normalize_runs_reconciles_objects_with_markers() {
|
||||
// Deleting the first marker keeps B on the second.
|
||||
p.delete(1, 4).unwrap();
|
||||
assert_eq!(p.objects, vec![fs("B")]);
|
||||
|
||||
let mut d = build();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects.push(fs("Surplus"));
|
||||
p.runs[0].len = 1;
|
||||
d.footnote_separators.continuation_notice = Some(d.body.clone());
|
||||
d.endnote_separators.separator = Some(d.body.clone());
|
||||
d.glossary.push(BuildingBlock { name: "Quick Parts example".into(), blocks: d.body.clone(), ..Default::default() });
|
||||
d.normalize_runs();
|
||||
for (name, blocks) in [
|
||||
("footnote continuation notice", d.footnote_separators.continuation_notice.as_ref().unwrap()),
|
||||
("endnote separator", d.endnote_separators.separator.as_ref().unwrap()),
|
||||
("Quick Parts entry", &d.glossary[0].blocks),
|
||||
] {
|
||||
edit::each_para(&blocks[0], 0, &mut |p| {
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")], "{name} drops the surplus object");
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len(), "{name} repairs its runs");
|
||||
});
|
||||
}
|
||||
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
|
||||
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
|
||||
let reconcile = |extra: usize| {
|
||||
|
||||
@@ -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<_, _>>()?;
|
||||
|
||||
@@ -1330,6 +1330,8 @@ fn hinted_east_asian_or_cs_font_does_not_replace_the_latin_font() {
|
||||
assert_eq!((ea.font.as_str(), ea.font_ea.as_deref()), ("Times New Roman", Some("宋体")));
|
||||
let cs = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[1].props);
|
||||
assert_eq!((cs.font.as_str(), cs.font_cs.as_str()), ("Times New Roman", "Arial"));
|
||||
assert_eq!(ea.font_ea_theme, None, "named w:eastAsia replaces Heading2's w:eastAsiaTheme");
|
||||
assert_eq!(cs.font_ea_theme, Some(wordcraft_doc::props::ThemeFont::MajorEastAsia));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2444,6 +2446,54 @@ fn note_separators_and_continuation_notice_round_trip() {
|
||||
check(&wordcraft_docx::read(&out).unwrap());
|
||||
}
|
||||
|
||||
/// A hyperlinked nested group in a footnote or endnote separator is flattened through the block
|
||||
/// mapping just as it is in the document body.
|
||||
#[test]
|
||||
fn linked_nested_group_in_a_note_separator_is_flattened() {
|
||||
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Frame"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
|
||||
let group = format!(
|
||||
r#"<w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></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>{group}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
|
||||
};
|
||||
let footnotes = notes("footnotes", "footnote");
|
||||
let endnotes = notes("endnotes", "endnote");
|
||||
let link_rels = rels(&[("rId9", "hyperlink", "https://example.com/")]);
|
||||
let bytes = docx(
|
||||
&format!("<w:p>{group}</w:p>"),
|
||||
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml"), ("rId9", "hyperlink", "https://example.com/")],
|
||||
&[
|
||||
("word/footnotes.xml", &footnotes),
|
||||
("word/_rels/footnotes.xml.rels", &link_rels),
|
||||
("word/endnotes.xml", &endnotes),
|
||||
("word/_rels/endnotes.xml.rels", &link_rels),
|
||||
],
|
||||
);
|
||||
let d = wordcraft_docx::read(&bytes).unwrap();
|
||||
let flattened = |p: &Paragraph| -> Vec<(f32, f32, ShapeKind, f32)> {
|
||||
let Some(children) = p.objects.iter().find_map(|o| match o {
|
||||
InlineObject::Group { children, .. } => Some(children),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("{:?}", p.objects);
|
||||
};
|
||||
children
|
||||
.iter()
|
||||
.map(|c| match &c.obj {
|
||||
InlineObject::Shape { kind, w, .. } => (c.x, c.y, *kind, *w),
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let in_body = flattened(d.body[0].as_para().unwrap());
|
||||
assert_eq!(in_body, [(50.0, 0.0, ShapeKind::Frame, 50.0)]);
|
||||
for separators in [&d.footnote_separators, &d.endnote_separators] {
|
||||
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
|
||||
assert_eq!(flattened(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]
|
||||
|
||||
@@ -132,6 +132,7 @@ fn every_char_prop_round_trips() {
|
||||
cs: Some(true),
|
||||
font_cs: Some("B Nazanin".into()),
|
||||
font_ea: Some("宋体".into()),
|
||||
font_ea_theme: Some(wordcraft_doc::props::ThemeFont::MinorEastAsia),
|
||||
size_cs: Some(13.0),
|
||||
bold_cs: Some(false),
|
||||
italic_cs: Some(true),
|
||||
|
||||
@@ -93,6 +93,84 @@ fn run_and_style_snap_to_grid_and_web_hidden_survive_two_saves() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps run and style emphasis values intact across repeated DOCX saves.
|
||||
#[test]
|
||||
fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
use wordcraft_doc::props::EmphasisMark;
|
||||
|
||||
let styles = r#"
|
||||
<w:style w:type="character" w:styleId="Dot"><w:rPr><w:em w:val="dot"/></w:rPr></w:style>
|
||||
<w:style w:type="character" w:styleId="Comma"><w:rPr><w:em w:val="comma"/></w:rPr></w:style>
|
||||
<w:style w:type="character" w:styleId="Circle"><w:rPr><w:em w:val="circle"/></w:rPr></w:style>
|
||||
<w:style w:type="character" w:styleId="UnderDot"><w:rPr><w:em w:val="underDot"/></w:rPr></w:style>
|
||||
<w:style w:type="character" w:styleId="NoMark"><w:rPr><w:em w:val="none"/></w:rPr></w:style>
|
||||
"#;
|
||||
let body = r#"
|
||||
<w:p>
|
||||
<w:r><w:rPr><w:rStyle w:val="Dot"/></w:rPr><w:t>default dot</w:t></w:r>
|
||||
<w:r><w:rPr><w:rStyle w:val="Comma"/></w:rPr><w:t>comma</w:t></w:r>
|
||||
<w:r><w:rPr><w:rStyle w:val="Circle"/></w:rPr><w:t>circle</w:t></w:r>
|
||||
<w:r><w:rPr><w:rStyle w:val="UnderDot"/></w:rPr><w:t>under dot</w:t></w:r>
|
||||
<w:r><w:rPr><w:rStyle w:val="Dot"/><w:em w:val="none"/></w:rPr><w:t>explicit none</w:t></w:r>
|
||||
<w:r><w:rPr><w:rStyle w:val="NoMark"/></w:rPr><w:t>style none</w:t></w:r>
|
||||
<w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>run dot</w:t></w:r>
|
||||
<w:r><w:rPr><w:em w:val="comma"/></w:rPr><w:t>run comma</w:t></w:r>
|
||||
<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>run circle</w:t></w:r>
|
||||
<w:r><w:rPr><w:em w:val="underDot"/></w:rPr><w:t>run under dot</w:t></w:r>
|
||||
<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>run none</w:t></w:r>
|
||||
<w:r><w:t>inherit absent</w:t></w:r>
|
||||
</w:p>
|
||||
"#;
|
||||
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
|
||||
let expected_styles = [
|
||||
("Dot", Some(EmphasisMark::Dot)),
|
||||
("Comma", Some(EmphasisMark::Comma)),
|
||||
("Circle", Some(EmphasisMark::Circle)),
|
||||
("UnderDot", Some(EmphasisMark::UnderDot)),
|
||||
("NoMark", Some(EmphasisMark::None)),
|
||||
];
|
||||
let expected_runs = [
|
||||
(Some("Dot"), None, EmphasisMark::Dot),
|
||||
(Some("Comma"), None, EmphasisMark::Comma),
|
||||
(Some("Circle"), None, EmphasisMark::Circle),
|
||||
(Some("UnderDot"), None, EmphasisMark::UnderDot),
|
||||
(Some("Dot"), Some(EmphasisMark::None), EmphasisMark::None),
|
||||
(Some("NoMark"), None, EmphasisMark::None),
|
||||
(None, Some(EmphasisMark::Dot), EmphasisMark::Dot),
|
||||
(None, Some(EmphasisMark::Comma), EmphasisMark::Comma),
|
||||
(None, Some(EmphasisMark::Circle), EmphasisMark::Circle),
|
||||
(None, Some(EmphasisMark::UnderDot), EmphasisMark::UnderDot),
|
||||
(None, Some(EmphasisMark::None), EmphasisMark::None),
|
||||
(None, None, EmphasisMark::None),
|
||||
];
|
||||
let assert_state = |doc: &wordcraft_doc::Document, stage: &str| {
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "{stage}: style {id}");
|
||||
}
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
let actual: Vec<_> = p
|
||||
.runs
|
||||
.iter()
|
||||
.map(|r| (r.props.style.as_deref(), r.props.emphasis, doc.styles.resolve_char(p.props.style.as_deref(), &r.props).emphasis))
|
||||
.collect();
|
||||
assert_eq!(actual, expected_runs, "{stage}");
|
||||
};
|
||||
assert_state(&doc, "initial read");
|
||||
|
||||
for pass in 0..2 {
|
||||
let out = wordcraft_docx::write(&doc).unwrap();
|
||||
let style_xml = part(&out, "word/styles.xml");
|
||||
for value in ["dot", "comma", "circle", "underDot", "none"] {
|
||||
assert!(style_xml.contains(&format!(r#"<w:em w:val="{value}"/>"#)), "pass {pass}: {style_xml}");
|
||||
}
|
||||
let document_xml = part(&out, "word/document.xml");
|
||||
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
|
||||
assert!(document_xml.contains("default dot"));
|
||||
doc = wordcraft_docx::read(&out).unwrap();
|
||||
assert_state(&doc, &format!("pass {pass}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_paragraph_and_run_changes_keep_independent_authors() {
|
||||
let styles = r#"
|
||||
|
||||
+109
-1
@@ -513,6 +513,7 @@ fn split_para_as(s: &mut Session, at: &Pos, enter: bool) -> Result<Pos, CmdError
|
||||
let para = s.doc.para_mut(at.story, &at.path)?;
|
||||
if n.level > 0 {
|
||||
para.props.numbering = Some(wordcraft_doc::props::NumRef { num: n.num, level: n.level - 1 });
|
||||
para::drop_direct_indents(&mut para.props);
|
||||
para.touch();
|
||||
} else {
|
||||
leave_list(para);
|
||||
@@ -580,11 +581,65 @@ pub fn now_unix() -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO-8601 timestamp (UTC, seconds).
|
||||
/// ISO-8601 timestamp (UTC, seconds): the clock, for an event that happened now -- a comment, a
|
||||
/// tracked change, a version. Not for what a saved or exported file records: see [`saved_iso`].
|
||||
pub fn now_iso() -> String {
|
||||
iso_from_unix_secs(now_unix())
|
||||
}
|
||||
|
||||
/// The timestamp a saved or exported file records (its created and modified properties):
|
||||
/// `SOURCE_DATE_EPOCH` when it holds a non-negative whole number of seconds, else the clock. With
|
||||
/// it set, separate conversions of unchanged input can produce the same bytes. Repeated saves
|
||||
/// of one session still advance the document revision
|
||||
/// (<https://reproducible-builds.org/specs/source-date-epoch/>).
|
||||
///
|
||||
/// The clock stays in [`now_iso`]: an editing event's time is not the file's, and pinning it would
|
||||
/// misdate comments and tracked changes.
|
||||
///
|
||||
/// A value that is set but not one of those is ignored with a warning, so a build that meant to
|
||||
/// pin its dates hears that it did not.
|
||||
pub fn saved_iso() -> String {
|
||||
let raw = std::env::var("SOURCE_DATE_EPOCH").ok();
|
||||
if let Some(problem) = epoch_problem(raw.as_deref()) {
|
||||
log::warn!("{problem}");
|
||||
}
|
||||
iso_from_unix_secs(pinned_or(|_| raw.clone(), now_unix))
|
||||
}
|
||||
|
||||
/// Why `SOURCE_DATE_EPOCH` is set and still not used, for a caller with no logger to say so (the
|
||||
/// command line). `None` when it is unset, empty, or a value [`saved_iso`] takes.
|
||||
pub fn source_date_epoch_problem() -> Option<String> {
|
||||
epoch_problem(std::env::var("SOURCE_DATE_EPOCH").ok().as_deref())
|
||||
}
|
||||
|
||||
/// An empty value counts as unset, as a CI file's `SOURCE_DATE_EPOCH=` with nothing after it
|
||||
/// means; anything else that does not pin a date is worth a warning.
|
||||
fn epoch_problem(value: Option<&str>) -> Option<String> {
|
||||
let v = value?;
|
||||
if v.trim().is_empty() || pinned(v).is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"SOURCE_DATE_EPOCH={v:?} is not a whole number of seconds from 1970 to 9999-12-31, so saved and exported files take the clock's date"
|
||||
))
|
||||
}
|
||||
|
||||
/// The seconds a `SOURCE_DATE_EPOCH` value pins, if it pins any.
|
||||
fn pinned(v: &str) -> Option<u64> {
|
||||
v.trim().parse::<u64>().ok().filter(|secs| *secs <= LAST_DATE)
|
||||
}
|
||||
|
||||
/// [`saved_iso`]'s choice, with the environment and the clock given so a test can show which wins.
|
||||
pub(crate) fn pinned_or(get: impl Fn(&str) -> Option<String>, clock: impl Fn() -> u64) -> u64 {
|
||||
get("SOURCE_DATE_EPOCH").as_deref().and_then(pinned).unwrap_or_else(clock)
|
||||
}
|
||||
|
||||
/// The last date a document can record, as Unix seconds: 9999-12-31T23:59:59Z. A year runs to
|
||||
/// four digits in `xsd:dateTime`, which is what a .docx core property holds, so a value past this
|
||||
/// would be written as something no reader accepts -- `292277026596-12-04T15:30:07Z` for
|
||||
/// `i64::MAX`. Such a value is left to the clock, as a malformed one is.
|
||||
const LAST_DATE: u64 = 253_402_300_799;
|
||||
|
||||
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
|
||||
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
|
||||
pub fn local_offset_secs(unix: u64) -> i64 {
|
||||
@@ -735,3 +790,56 @@ mod iso_tests {
|
||||
let _ = (civil_from_days(i64::MAX), civil_from_days(i64::MIN));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod saved_time_tests {
|
||||
use super::{epoch_problem, iso_from_unix_secs, pinned_or};
|
||||
|
||||
/// What a saved or exported file records: `SOURCE_DATE_EPOCH` when it holds a non-negative
|
||||
/// whole number of seconds, the clock whenever it does not. The environment and the clock are
|
||||
/// given here rather than set, so no test changes this process's environment -- that is
|
||||
/// `unsafe` under edition 2024 and would reach every test beside it.
|
||||
#[test]
|
||||
fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() {
|
||||
let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned);
|
||||
let clock = || 1_000_000;
|
||||
assert_eq!(pinned_or(env(Some("1791208980")), clock), 1_791_208_980, "the variable wins");
|
||||
assert_eq!(pinned_or(env(Some("0")), clock), 0, "the epoch itself counts");
|
||||
assert_eq!(pinned_or(env(Some(" 1791208980 ")), clock), 1_791_208_980, "spaces around it are allowed");
|
||||
// The last date a document can write is honoured; past it the year would not fit
|
||||
// `xsd:dateTime` and the clock answers instead.
|
||||
assert_eq!(pinned_or(env(Some("253402300799")), clock), 253_402_300_799);
|
||||
assert_eq!(iso_from_unix_secs(253_402_300_799), "9999-12-31T23:59:59Z");
|
||||
for ignored in [
|
||||
None,
|
||||
Some(""),
|
||||
Some(" "),
|
||||
Some("-1"),
|
||||
Some("later"),
|
||||
Some("1791208980.5"),
|
||||
Some("99999999999999999999"),
|
||||
Some("253402300800"),
|
||||
Some("9223372036854775807"),
|
||||
] {
|
||||
assert_eq!(pinned_or(env(ignored), clock), 1_000_000, "{ignored:?} leaves it to the clock");
|
||||
}
|
||||
// Only that variable is read.
|
||||
assert_eq!(pinned_or(|name: &str| (name == "TZ").then(|| "1791208980".to_owned()), clock), 1_000_000);
|
||||
// And it reaches the stamp as that instant, not as something near it.
|
||||
assert_eq!(iso_from_unix_secs(pinned_or(env(Some("1791208980")), clock)), "2026-10-05T14:03:00Z");
|
||||
}
|
||||
|
||||
/// A value that is set and still ignored is reported, so a build that meant to pin its dates
|
||||
/// hears that it did not (noted in review). Unset and empty say nothing: an empty value is
|
||||
/// how a CI file leaves the variable off.
|
||||
#[test]
|
||||
fn a_set_but_unusable_epoch_is_reported_and_nothing_else_is() {
|
||||
for quiet in [None, Some(""), Some(" "), Some("0"), Some("1791208980"), Some(" 1791208980 "), Some("253402300799")] {
|
||||
assert_eq!(epoch_problem(quiet), None, "{quiet:?}");
|
||||
}
|
||||
for loud in ["later", "-1", "1791208980.5", "1e9", "253402300800", "99999999999999999999"] {
|
||||
let problem = epoch_problem(Some(loud)).unwrap_or_else(|| panic!("{loud:?} should be reported"));
|
||||
assert!(problem.contains(&format!("{loud:?}")) && problem.contains("clock"), "{problem}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,8 +363,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
|
||||
return Err(CmdError::Failed("the member vanished".into()));
|
||||
}
|
||||
let text = f.clipboard_text();
|
||||
let r = super::edit::copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
let r = super::edit::copy_result(s, f, text)?;
|
||||
if let Some(f) = &s.clipboard {
|
||||
s.clip_history.push(f, &s.clipboard_text);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
+230
-47
@@ -2,8 +2,9 @@
|
||||
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::{InlineObject, Pos, StoryRef};
|
||||
use wordcraft_doc::para::{NBSP, OBJ};
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_doc::{InlineObject, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
use super::{parse_pos, sel_result};
|
||||
@@ -53,7 +54,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("caret.set", "Set Caret", "Navigation", set)
|
||||
.params(r#"{"pos": Pos, "extend"?: bool} | {"page": n, "x": pt, "y": pt}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all).key("Mod+A").pure(),
|
||||
CommandSpec::new("select.all", "Select All", "Home › Editing › Select", select_all)
|
||||
.key("Mod+A")
|
||||
.params(r#"{"whole"?: bool (default true: select the whole story; false: grow through the cell, row and table first)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("select.range", "Select Range", "Navigation", select_range).params(r#"{"anchor": Pos, "focus": Pos}"#).pure(),
|
||||
CommandSpec::new("select.word", "Select Word", "Navigation", select_word).pure(),
|
||||
CommandSpec::new("select.sentence", "Select Sentence", "Navigation", select_sentence).pure(),
|
||||
@@ -110,7 +114,49 @@ fn bidi_para(s: &Session) -> bool {
|
||||
|
||||
/// Left/Right: with a selection and no Shift, collapse to its edge.
|
||||
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if !extend(v) && !s.sel.is_collapsed() {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Left/Right change line; top-to-bottom lines stack leftwards.
|
||||
return line_step(s, v, (t == TextDirection::Down) == is_left, is_left);
|
||||
}
|
||||
lr_along(s, v, is_left)
|
||||
}
|
||||
|
||||
/// The text direction at the caret when it is in turned (vertical) text.
|
||||
fn turn(s: &mut Session) -> Option<TextDirection> {
|
||||
let l = s.layout();
|
||||
l.turn_at(&s.sel.focus, s.page_hint)
|
||||
}
|
||||
|
||||
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
|
||||
/// such line in the caret's flow (a table cell's only line, the last column), Left/Right step along
|
||||
/// the text as they did before (`is_left`: backwards).
|
||||
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
s.sel = Selection::caret(if next { b } else { a });
|
||||
s.goal_x = None;
|
||||
return sel_result(s);
|
||||
}
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
let to = match l.turned_line(&from, s.goal_x, next, s.page_hint) {
|
||||
Some((p, g)) => {
|
||||
s.goal_x = Some(g);
|
||||
p
|
||||
}
|
||||
None => return lr_along(s, v, is_left),
|
||||
};
|
||||
let gx = s.goal_x;
|
||||
apply(s, to, ext);
|
||||
s.goal_x = gx;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Left/Right as a step along the text (`is_left`: backwards).
|
||||
fn lr_along(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
if !ext && !s.sel.is_collapsed() {
|
||||
let (a, b) = s.sel.ordered();
|
||||
// The left edge of a selection in right-to-left text is its logical end.
|
||||
let to_start = is_left != rtl_para(s);
|
||||
@@ -121,26 +167,33 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
if bidi_para(s) {
|
||||
return visual_lr(s, v, is_left);
|
||||
}
|
||||
if !extend(v)
|
||||
let from = s.sel.focus.clone();
|
||||
// Equation entry and the grapheme step start at the same visible edge.
|
||||
let hidden = s.layout_hides_deleted(from.story);
|
||||
let edge = logical_edge(s, &from, is_left, hidden);
|
||||
if !ext
|
||||
&& !s.math_left
|
||||
&& let Some(r) = into_equation(s, is_left)
|
||||
&& let Some(r) = into_equation(s, &from, edge, is_left, hidden)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
mv(s, v, if is_left { left } else { right })
|
||||
s.goal_x = None;
|
||||
let to = step_from_edge(s, &from, edge, is_left);
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
|
||||
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
|
||||
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
|
||||
/// while editing one) moves on too.
|
||||
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
|
||||
let f = s.sel.focus.clone();
|
||||
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
|
||||
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
|
||||
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> Option<CmdResult> {
|
||||
let off = if is_left { edge.checked_sub(OBJ.len_utf8())? } else { edge };
|
||||
let para = s.doc.para_at(from)?;
|
||||
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (hidden.any() && hidden.hides(&s.doc, para.props_of_char(off).del)) {
|
||||
return None;
|
||||
}
|
||||
s.sel = Selection::caret(Pos { off, ..f });
|
||||
s.sel = Selection::caret(Pos { off, ..from.clone() });
|
||||
s.goal_x = None;
|
||||
s.pending = None;
|
||||
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
|
||||
@@ -159,63 +212,189 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
|
||||
Some(wordcraft_layout::VisualStep::Edge { start, stop, last_line, rtl }) => {
|
||||
let at = |off| Pos { off, ..from.clone() };
|
||||
if is_left != rtl {
|
||||
match s.doc.para_at(&from) {
|
||||
Some(para) if start > 0 => at(para.prev_boundary(start)),
|
||||
_ => left(s, &at(0)),
|
||||
}
|
||||
logical_step(s, &at(start), true)
|
||||
} else if !last_line {
|
||||
at(stop)
|
||||
} else {
|
||||
let len = s.doc.para_at(&from).map_or(stop, |p| p.len());
|
||||
right(s, &at(len))
|
||||
logical_step(s, &at(len), false)
|
||||
}
|
||||
}
|
||||
None if is_left => left(s, &from),
|
||||
None => right(s, &from),
|
||||
None => logical_step(s, &from, is_left),
|
||||
};
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn left(s: &mut Session, p: &Pos) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(p)
|
||||
&& p.off > 0
|
||||
{
|
||||
return Pos { off: para.prev_boundary(p.off), ..p.clone() };
|
||||
/// Find the run containing `byte` from the nearer end of `para`.
|
||||
fn run_at_byte(para: &Paragraph, byte: usize) -> Option<(usize, std::ops::Range<usize>)> {
|
||||
if byte >= para.len() {
|
||||
return None;
|
||||
}
|
||||
match s.doc.prev_para(p.story, &p.path) {
|
||||
Some(q) => {
|
||||
let off = s.doc.para(p.story, &q).map(|x| x.len()).unwrap_or(0);
|
||||
Pos { story: p.story, path: q, off }
|
||||
}
|
||||
None => p.clone(),
|
||||
if byte < para.len() / 2 {
|
||||
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
|
||||
} else {
|
||||
let mut end = para.len();
|
||||
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
|
||||
let start = end.saturating_sub(run.len);
|
||||
let range = start..end;
|
||||
end = start;
|
||||
range.contains(&byte).then_some((i, range))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn right(s: &mut Session, p: &Pos) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(p)
|
||||
&& p.off < para.len()
|
||||
/// The two ends of a hidden deletion share a caret position. Cross the hidden
|
||||
/// span before taking the normal grapheme step, including adjacent deletions.
|
||||
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool, hides: impl Fn(Option<u32>) -> bool) -> usize {
|
||||
// At a run boundary, inspect the byte on the side the caret is moving toward.
|
||||
let Some(byte) = off.checked_sub(usize::from(is_left)) else { return off };
|
||||
let Some((i, range)) = run_at_byte(para, byte) else { return off };
|
||||
if !hides(para.runs[i].props.del) {
|
||||
return off;
|
||||
}
|
||||
if is_left {
|
||||
range.start - para.runs[..i].iter().rev().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
|
||||
} else {
|
||||
range.end + para.runs[i + 1..].iter().take_while(|run| hides(run.props.del)).map(|run| run.len).sum::<usize>()
|
||||
}
|
||||
}
|
||||
|
||||
fn logical_edge(s: &Session, from: &Pos, is_left: bool, hidden: wordcraft_layout::HideDeleted) -> usize {
|
||||
if hidden.any()
|
||||
&& let Some(para) = s.doc.para_at(from)
|
||||
{
|
||||
return Pos { off: para.next_boundary(p.off), ..p.clone() };
|
||||
return hidden_deletion_edge(para, from.off, is_left, |del| hidden.hides(&s.doc, del));
|
||||
}
|
||||
match s.doc.next_para(p.story, &p.path) {
|
||||
Some(q) => Pos { story: p.story, path: q, off: 0 },
|
||||
None => p.clone(),
|
||||
from.off
|
||||
}
|
||||
|
||||
fn logical_step(s: &Session, from: &Pos, is_left: bool) -> Pos {
|
||||
let edge = logical_edge(s, from, is_left, s.layout_hides_deleted(from.story));
|
||||
step_from_edge(s, from, edge, is_left)
|
||||
}
|
||||
|
||||
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
|
||||
if let Some(para) = s.doc.para_at(from) {
|
||||
if is_left && edge > 0 {
|
||||
return Pos { off: para.prev_boundary(edge), ..from.clone() };
|
||||
}
|
||||
if !is_left && edge < para.len() {
|
||||
return Pos { off: para.next_boundary(edge), ..from.clone() };
|
||||
}
|
||||
}
|
||||
step_to_neighbor(s, from, is_left, !s.view.show_markup)
|
||||
}
|
||||
|
||||
fn step_to_neighbor(s: &Session, from: &Pos, is_left: bool, skip_deleted: bool) -> Pos {
|
||||
let story = from.story;
|
||||
let neighbor = if is_left { s.doc.prev_para(story, &from.path) } else { s.doc.next_para(story, &from.path) };
|
||||
let Some(mut path) = neighbor else { return from.clone() };
|
||||
// Layout collapses a wholly deleted paragraph in No Markup. A surviving mark still gives
|
||||
// even a paragraph without visible text a caret stop.
|
||||
let deleted = |path: &Path| s.doc.para(story, path).is_some_and(|p| p.mark.del.is_some() && p.runs.iter().all(|r| r.props.del.is_some()));
|
||||
if skip_deleted && deleted(&path) {
|
||||
// Get the story's paths once for the rest of the walk, even across many deleted paragraphs.
|
||||
let paths = s.doc.para_paths(story);
|
||||
let Ok(i) = paths.binary_search(&path) else { return from.clone() };
|
||||
let stop = if is_left { paths[..i].iter().rev().find(|p| !deleted(p)) } else { paths[i + 1..].iter().find(|p| !deleted(p)) };
|
||||
let Some(stop) = stop else { return from.clone() };
|
||||
path = stop.clone();
|
||||
}
|
||||
let off = if is_left { s.doc.para(story, &path).map_or(0, Paragraph::len) } else { 0 };
|
||||
Pos { story, path, off }
|
||||
}
|
||||
|
||||
fn visible_word_start(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let byte = off.checked_sub(1)?;
|
||||
let (i, range) = run_at_byte(para, byte)?;
|
||||
let mut idx = off;
|
||||
let mut seen_word = false;
|
||||
let mut seen_visible = false;
|
||||
let mut end = range.end;
|
||||
for run in para.runs[..=i].iter().rev() {
|
||||
let start = end.saturating_sub(run.len);
|
||||
let range_end = end.min(off);
|
||||
end = start;
|
||||
if hides(run.props.del) {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..range_end) else { continue };
|
||||
for (rel, c) in slice.char_indices().rev() {
|
||||
seen_visible = true;
|
||||
if wordcraft_doc::bidi::is_word_char(c) {
|
||||
seen_word = true;
|
||||
idx = start + rel;
|
||||
} else if seen_word {
|
||||
return Some(idx);
|
||||
} else {
|
||||
idx = start + rel;
|
||||
}
|
||||
}
|
||||
}
|
||||
seen_visible.then_some(idx)
|
||||
}
|
||||
|
||||
fn visible_word_end(para: &Paragraph, off: usize, hides: impl Fn(Option<u32>) -> bool) -> Option<usize> {
|
||||
let off = para.clamp(off);
|
||||
let (i, range) = run_at_byte(para, off)?;
|
||||
let mut first_word = None;
|
||||
let mut in_space = false;
|
||||
let mut last_end = None;
|
||||
let mut run_start = range.start;
|
||||
for run in ¶.runs[i..] {
|
||||
let run_end = run_start.saturating_add(run.len);
|
||||
let start = run_start.max(off);
|
||||
run_start = run_end;
|
||||
if hides(run.props.del) {
|
||||
continue;
|
||||
}
|
||||
let Some(slice) = para.text.get(start..run_end) else { continue };
|
||||
for (rel, c) in slice.char_indices() {
|
||||
let abs = start + rel;
|
||||
last_end = Some(abs + c.len_utf8());
|
||||
let is_first = first_word.is_none();
|
||||
let fw = *first_word.get_or_insert_with(|| wordcraft_doc::bidi::is_word_char(c) && c != '\'');
|
||||
let w = wordcraft_doc::bidi::is_word_char(c);
|
||||
if c == ' ' || c == NBSP {
|
||||
in_space = true;
|
||||
continue;
|
||||
}
|
||||
if in_space || (fw && !w) || (!fw && !is_first) {
|
||||
return Some(abs);
|
||||
}
|
||||
}
|
||||
}
|
||||
last_end
|
||||
}
|
||||
|
||||
fn word_left(s: &mut Session, p: &Pos) -> Pos {
|
||||
match s.doc.para_at(p) {
|
||||
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
|
||||
_ => left(s, p),
|
||||
let hidden = s.layout_hides_deleted(p.story);
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if hidden.any() {
|
||||
if let Some(off) = visible_word_start(para, p.off, |del| hidden.hides(&s.doc, del)) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off > 0 {
|
||||
return Pos { off: para.word_start(p.off), ..p.clone() };
|
||||
}
|
||||
}
|
||||
step_to_neighbor(s, p, true, false)
|
||||
}
|
||||
|
||||
fn word_right(s: &mut Session, p: &Pos) -> Pos {
|
||||
match s.doc.para_at(p) {
|
||||
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
|
||||
_ => right(s, p),
|
||||
let hidden = s.layout_hides_deleted(p.story);
|
||||
if let Some(para) = s.doc.para_at(p) {
|
||||
if hidden.any() {
|
||||
if let Some(off) = visible_word_end(para, p.off, |del| hidden.hides(&s.doc, del)) {
|
||||
return Pos { off, ..p.clone() };
|
||||
}
|
||||
} else if p.off < para.len() {
|
||||
return Pos { off: para.word_end(p.off), ..p.clone() };
|
||||
}
|
||||
}
|
||||
step_to_neighbor(s, p, false, false)
|
||||
}
|
||||
|
||||
fn para_up(s: &mut Session, p: &Pos) -> Pos {
|
||||
@@ -239,6 +418,10 @@ fn para_down(s: &mut Session, p: &Pos) -> Pos {
|
||||
}
|
||||
|
||||
fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
if let Some(t) = turn(s) {
|
||||
// Vertical text (#8986): Up/Down step along the line (top-to-bottom text runs down).
|
||||
return lr_along(s, v, (dir < 0) == (t == TextDirection::Down));
|
||||
}
|
||||
let ext = extend(v);
|
||||
let l = s.layout();
|
||||
let from = s.sel.focus.clone();
|
||||
@@ -253,7 +436,7 @@ fn vert(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
};
|
||||
if let Some(c) = l.caret_on(&to, s.page_hint) {
|
||||
s.page_hint = c.page;
|
||||
s.set_page_hint(c.page);
|
||||
}
|
||||
let gx = s.goal_x;
|
||||
apply(s, to, ext);
|
||||
@@ -305,7 +488,7 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
s.page_hint = np;
|
||||
s.set_page_hint(np);
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
}
|
||||
@@ -328,7 +511,7 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let story = super::story_param(s, v);
|
||||
let l = s.layout();
|
||||
let page = usize::try_from(pg).unwrap_or(usize::MAX);
|
||||
s.page_hint = page;
|
||||
s.set_page_hint(page);
|
||||
l.hit(page, x, y, story).ok_or_else(|| CmdError::Params("no text on that page".into()))?
|
||||
} else {
|
||||
return Err(CmdError::Params("`pos` or `page`/`x`/`y` required".into()));
|
||||
@@ -345,7 +528,7 @@ fn select_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.column_mode = false;
|
||||
return sel_result(s);
|
||||
}
|
||||
if !p::bool(v, "whole").unwrap_or(false)
|
||||
if !p::bool(v, "whole").unwrap_or(true)
|
||||
&& let Some(r) = super::table::grow_select_all(s)
|
||||
{
|
||||
return r;
|
||||
|
||||
@@ -26,6 +26,7 @@ use generated::ENTRY_STYLE;
|
||||
pub(crate) use generated::generated_list;
|
||||
use generated::table_of_figures;
|
||||
pub use generated::{figures_instr, update_generated};
|
||||
pub(super) use generated::{is_list_entry, wrapped_list};
|
||||
pub use render::{cite, entry};
|
||||
pub use sources::update_citations;
|
||||
use sources::{citation, sources};
|
||||
|
||||
@@ -65,6 +65,7 @@ fn generated_list_with(s: &mut Session, instr: &str, title: &str, leader: Option
|
||||
seed.props.tabs = Some(vec![TabStop { pos: 0.0, align: TabAlign::Right, leader }]);
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i.saturating_add(1)), Block::Para(seed))?;
|
||||
}
|
||||
s.touch();
|
||||
update_generated(s)
|
||||
}
|
||||
|
||||
@@ -74,7 +75,7 @@ const MAX_WRAPPED: usize = 10_000;
|
||||
/// A generated list (index, bibliography, table of figures or authorities) held as a complex
|
||||
/// field that starts at body block `i` and runs over its entries: its field code and the block
|
||||
/// it ends in. `None` for anything else (a TOC has its own update).
|
||||
fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
|
||||
pub(in crate::cmd) fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> {
|
||||
let p = s.doc.body.get(i)?.as_para()?;
|
||||
let (k, off, instr) = p.objects_with_offsets().enumerate().find_map(|(k, (off, o))| match o {
|
||||
InlineObject::FieldStart { instr, .. } => {
|
||||
@@ -197,9 +198,15 @@ fn caption_body(p: &Paragraph, label: &str) -> String {
|
||||
|
||||
pub(super) const ENTRY_STYLE: &str = "ListEntry";
|
||||
|
||||
/// A result paragraph can share its style with a field header split out of an imported list.
|
||||
pub(in crate::cmd) fn is_list_entry(p: &Paragraph) -> bool {
|
||||
p.props.style.as_deref() == Some(ENTRY_STYLE) && list_kind(p).is_none()
|
||||
}
|
||||
|
||||
/// Rebuild every generated list.
|
||||
pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
let mut i = 0;
|
||||
let mut relocated_index_leader = None;
|
||||
while i < s.doc.body.len() {
|
||||
// A list held as a field around its entries (as Word and ODT files hold them): made the
|
||||
// field's own paragraph, as WordCraft inserts one, its old entries rebuilt below.
|
||||
@@ -207,7 +214,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
// break, are the document's and stay.
|
||||
// (The field it is made: what comes before it in its paragraph may hold other fields.)
|
||||
let mut converted = None;
|
||||
let mut index_leader = None;
|
||||
if let Some((instr, start, last, end)) = wrapped_list(s, i) {
|
||||
if instr.starts_with("INDEX") {
|
||||
index_leader = crate::cmd::index::wrapped_entry_leader(s, i, start, last, end);
|
||||
}
|
||||
// The entries between its first and last paragraphs go.
|
||||
for _ in i.saturating_add(1)..last {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
@@ -247,9 +258,14 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
|
||||
if p.objects_with_offsets().any(|(off, o)| off < start && list_field(o).is_some()) {
|
||||
let list = p.split_off(start)?;
|
||||
// Rebuilding the preceding list can shift the new paragraph's block index.
|
||||
if let Some(leader) = index_leader.take() {
|
||||
relocated_index_leader = Some((list.rev, leader));
|
||||
}
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1), Block::Para(list))?;
|
||||
converted = None;
|
||||
}
|
||||
s.touch();
|
||||
}
|
||||
let kind = converted.or_else(|| s.doc.body.get(i).and_then(|b| b.as_para()).and_then(list_kind));
|
||||
let Some(kind) = kind else {
|
||||
@@ -258,7 +274,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
};
|
||||
add_entry_style(s);
|
||||
if kind.starts_with("INDEX") {
|
||||
crate::cmd::index::rebuild_from(s, i, None, kind)?;
|
||||
let index_leader = index_leader.or_else(|| {
|
||||
let rev = s.doc.body.get(i)?.as_para()?.rev;
|
||||
relocated_index_leader.take_if(|(relocated, _)| *relocated == rev).map(|(_, leader)| leader)
|
||||
});
|
||||
crate::cmd::index::rebuild_from(s, i, index_leader, kind)?;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -290,11 +310,11 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
.body
|
||||
.get(i + 1)
|
||||
.and_then(|b| b.as_para())
|
||||
.filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE))
|
||||
.filter(|p| is_list_entry(p))
|
||||
.and_then(|p| p.props.tabs.as_ref()?.last().map(|t| t.leader))
|
||||
.or(saved_leader)
|
||||
.unwrap_or(TabLeader::Dot);
|
||||
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
|
||||
while s.doc.body.get(i + 1).and_then(|b| b.as_para()).is_some_and(is_list_entry) {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
}
|
||||
let lines = entries_for(s, &kind);
|
||||
@@ -310,6 +330,7 @@ pub fn update_generated(s: &mut Session) -> Result<(), CmdError> {
|
||||
}
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i + 1 + k), Block::Para(para))?;
|
||||
}
|
||||
s.touch();
|
||||
i += 1;
|
||||
}
|
||||
s.touch();
|
||||
@@ -563,4 +584,56 @@ mod tests {
|
||||
assert_eq!(lists, [Some("INDEX".to_string()), Some("BIBLIOGRAPHY".to_string())]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_index_keeps_its_leader_when_split_from_a_bibliography() {
|
||||
let old_entry = "Old entry\t1";
|
||||
let mut s = wrapped("Old entry\t1\n\nKilns are hot.", 0, 0, old_entry.len());
|
||||
s.run("select.text", &serde_json::json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &serde_json::json!({})).unwrap();
|
||||
s.doc.sources.push(wordcraft_doc::Source { tag: "a".into(), kind: "book".into(), title: "Listed Source".into(), ..Default::default() });
|
||||
|
||||
let props = CharProps::default();
|
||||
let instr = "INDEX \\e \"\t\"";
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects[0] = InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false };
|
||||
p.insert_object(
|
||||
0,
|
||||
InlineObject::Field {
|
||||
instr: "BIBLIOGRAPHY".into(),
|
||||
result: String::new(),
|
||||
locked: false,
|
||||
dirty: false,
|
||||
code: false,
|
||||
form: String::new(),
|
||||
},
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
p.props.style = Some(ENTRY_STYLE.into());
|
||||
p.props.tabs = Some(vec![TabStop { pos: 120.0, align: TabAlign::Right, leader: TabLeader::Hyphen }]);
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
// A separate INDEX with the same instruction has no prior result and must get the default.
|
||||
p.insert_object(
|
||||
0,
|
||||
InlineObject::Field { instr: instr.into(), result: String::new(), locked: false, dirty: false, code: false, form: String::new() },
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
s.touch();
|
||||
let (_, start, last, end) = wrapped_list(&s, 0).unwrap();
|
||||
assert_eq!(crate::cmd::index::wrapped_entry_leader(&mut s, 0, start, last, end), Some(TabLeader::Hyphen));
|
||||
|
||||
for _ in 0..2 {
|
||||
update_generated(&mut s).unwrap();
|
||||
let paras: Vec<_> = s.doc.body.iter().filter_map(|b| b.as_para()).collect();
|
||||
assert_eq!(list_kind(paras[0]).as_deref(), Some("BIBLIOGRAPHY"));
|
||||
assert!(paras[1].plain_text().contains("Listed Source"), "the bibliography inserts an entry before the relocated index");
|
||||
for (header, leader) in [(2, TabLeader::Hyphen), (4, TabLeader::Dot)] {
|
||||
assert_eq!(list_kind(paras[header]).as_deref(), Some(instr));
|
||||
assert_eq!(paras[header + 1].plain_text(), "Kilns\t1");
|
||||
assert_eq!(paras[header + 1].props.tabs.as_ref().unwrap()[0].leader, leader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
let text = rows.join("\n");
|
||||
let media = s.doc.media_of_blocks(&blocks);
|
||||
let f = Fragment { blocks, parts, media };
|
||||
super::edit::copy_result(s, &f, &text)
|
||||
super::edit::copy_result(s, f, text)
|
||||
}
|
||||
|
||||
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
|
||||
|
||||
@@ -332,46 +332,67 @@ mod tests {
|
||||
|
||||
/// Drawing commands must not search every page again for each glued connector.
|
||||
#[test]
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
let mut doc = Document::new();
|
||||
doc.body = (0..8000u32)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::default();
|
||||
p.props.page_break_before = Some(i > 0);
|
||||
let id = i * 2 + 1;
|
||||
for (kind, x, extra) in [
|
||||
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
|
||||
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
|
||||
(
|
||||
ShapeKind::ElbowConnector,
|
||||
0.0,
|
||||
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
|
||||
),
|
||||
] {
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
|
||||
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
|
||||
}
|
||||
para_block(p)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Session::new(doc);
|
||||
s.view.proofing = false;
|
||||
s.page_hint = 0;
|
||||
assert_eq!(s.layout().pages.len(), 8000);
|
||||
let started = std::time::Instant::now();
|
||||
assert!(reroute(&mut s));
|
||||
let elapsed = started.elapsed();
|
||||
eprintln!("8000-page reroute: {elapsed:?}");
|
||||
assert!(elapsed < std::time::Duration::from_secs(5), "reroute took {elapsed:?}");
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
let para = s.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
|
||||
fn glued_pages(n: u32) -> Session {
|
||||
let mut doc = Document::new();
|
||||
doc.body = (0..n)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::default();
|
||||
p.props.page_break_before = Some(i > 0);
|
||||
let id = i * 2 + 1;
|
||||
for (kind, x, extra) in [
|
||||
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
|
||||
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
|
||||
(
|
||||
ShapeKind::ElbowConnector,
|
||||
0.0,
|
||||
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
|
||||
),
|
||||
] {
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
|
||||
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
|
||||
}
|
||||
para_block(p)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Session::new(doc);
|
||||
s.view.proofing = false;
|
||||
s.page_hint = 0;
|
||||
assert_eq!(s.layout().pages.len(), n as usize);
|
||||
s
|
||||
}
|
||||
const SMALL: u32 = 32;
|
||||
const SCALE: u32 = 8;
|
||||
let mut small = glued_pages(SMALL);
|
||||
let mut big = glued_pages(SMALL * SCALE);
|
||||
let layout = big.layout();
|
||||
let small_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut small)));
|
||||
let big_steps = wordcraft_doc::work::count(|| assert!(reroute(&mut big)));
|
||||
// One layout walk to build the index plus bounded work per connector: roughly 8x the
|
||||
// steps for 8x the pages. Allow room for fixed differences in the first and last pages.
|
||||
let budget = small_steps * 12;
|
||||
assert!(small_steps > 0 && big_steps > small_steps, "reroute steps: {small_steps} -> {big_steps}");
|
||||
assert!(big_steps <= budget, "reroute repeated lookup work: {small_steps} -> {big_steps} steps for {SCALE}x pages");
|
||||
|
||||
// The previous lookup starts at the caret's page for every connector. Run just that
|
||||
// part of the old route to verify it would exceed the same budget on this fixture.
|
||||
let connector_off = 2 * wordcraft_doc::para::OBJ.len_utf8();
|
||||
let scan_steps = wordcraft_doc::work::count(|| {
|
||||
for page in 0..layout.pages.len() {
|
||||
let hit = layout.object(&Pos::body(page, connector_off), 0).unwrap();
|
||||
assert_eq!(hit.page, page);
|
||||
}
|
||||
});
|
||||
assert!(scan_steps > budget, "per-connector scans took only {scan_steps} steps for a budget of {budget}");
|
||||
|
||||
for path in big.doc.para_paths(StoryRef::Body) {
|
||||
let para = big.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(connector_off).unwrap() else { panic!("connector") };
|
||||
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
|
||||
}
|
||||
s.touch();
|
||||
assert!(!reroute(&mut s), "rerouting must settle after refreshing the layout");
|
||||
big.touch();
|
||||
assert!(!reroute(&mut big), "rerouting must settle after refreshing the layout");
|
||||
}
|
||||
|
||||
/// The per-case shape/geometry of one scaled-group reroute case.
|
||||
|
||||
@@ -521,6 +521,13 @@ fn place(s: &mut Session, layout: &DocLayout, obj: InlineObject, page: usize, (x
|
||||
float.y = y - origin.y;
|
||||
}
|
||||
para.touch();
|
||||
if !on_page && let Some(offset) = super::objects::shifted_float_offset(s, &at, page, y, origin.y) {
|
||||
super::objects::edit_obj(s, &at, |o| {
|
||||
if let Some(float) = o.float_mut() {
|
||||
float.y = offset;
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
use super::{delete_selection, find_pattern, pos_json, sel_result};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
|
||||
|
||||
/// Ribbon location of the linked Cut, Copy and Paste commands.
|
||||
pub const LINKED_CLIPBOARD_LOCATION: &str = "Home › Clipboard";
|
||||
|
||||
/// Browsers reserve Mod+Shift+C for their inspector. Keep the desktop binding, but
|
||||
/// advertise a web alternative through the same registry/keymap as every other command.
|
||||
/// Mod+Alt+C already inserts copyright, and Mod+Alt+Shift+V is Keep Text Only.
|
||||
@@ -72,8 +75,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
.key("Mod+Y / Mod+Shift+Z")
|
||||
.pure(),
|
||||
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
CommandSpec::new("edit.cut", "Cut", LINKED_CLIPBOARD_LOCATION, cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", LINKED_CLIPBOARD_LOCATION, copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
|
||||
// Parts and AutoText insert it without emptying it, as in Word.
|
||||
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
|
||||
@@ -86,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("the Spike is empty")
|
||||
}
|
||||
}),
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
|
||||
CommandSpec::new("edit.paste", "Paste", LINKED_CLIPBOARD_LOCATION, paste)
|
||||
.key("Mod+V / Shift+Insert")
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
|
||||
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
|
||||
@@ -161,7 +164,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted); replaces in the main text, headers, footers, footnotes, endnotes and text boxes, wherever the caret is"#),
|
||||
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
|
||||
.key("Mod+Alt+G / F5")
|
||||
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
|
||||
@@ -209,8 +212,10 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
None => s.doc.copy_range(&a, &b),
|
||||
};
|
||||
let text = f.clipboard_text();
|
||||
let r = copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
let r = copy_result(s, f, text)?;
|
||||
if let Some(f) = &s.clipboard {
|
||||
s.clip_history.push(f, &s.clipboard_text);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -220,7 +225,7 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
///
|
||||
/// 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 {
|
||||
pub(crate) fn copy_result(s: &mut Session, f: Fragment, text: String) -> CmdResult {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
@@ -243,8 +248,8 @@ pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResul
|
||||
}
|
||||
// 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_text = text;
|
||||
s.clipboard = Some(f);
|
||||
s.clipboard_html = html;
|
||||
s.clipboard_rtf = rtf;
|
||||
Ok(r)
|
||||
@@ -827,16 +832,57 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
/// the replacement (`^p`) splits the paragraph.
|
||||
/// The stories Replace All covers, as in Word: the main text, then the headers, footers,
|
||||
/// footnotes, endnotes and text boxes the document shows. Hidden stories (a removed header, a
|
||||
/// deleted note's text) and comments keep their words.
|
||||
fn replace_stories(s: &Session) -> Vec<StoryRef> {
|
||||
s.doc.shown_stories()
|
||||
}
|
||||
|
||||
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
|
||||
/// stay valid (one undo step). A `\r` in the replacement (`^p`) splits the paragraph. Locked
|
||||
/// content in any story stops it before anything changes.
|
||||
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
need_query(s, v)?;
|
||||
read_opts(s, v);
|
||||
let story = s.sel.focus.story;
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
let n = results.len();
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
let mut found = Vec::new();
|
||||
// A protected document only lets the editable regions change: matches elsewhere (in a header,
|
||||
// say) stay as they are, so they don't make the whole command fail.
|
||||
let editable = super::protect::editable_ranges(s);
|
||||
for story in replace_stories(s) {
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let mut results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
if let Some(ranges) = &editable {
|
||||
results.retain(|f| ranges.iter().any(|(from, to)| f.a.story == from.story && f.a >= *from && f.b <= *to));
|
||||
}
|
||||
if results.is_empty() {
|
||||
continue;
|
||||
}
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
found.push(results);
|
||||
}
|
||||
let n: usize = found.iter().map(Vec::len).sum();
|
||||
let saved_sel = s.sel.clone();
|
||||
let orig_story = saved_sel.focus.story;
|
||||
let mut orig_story_sel = None;
|
||||
// The main text comes last, so under Track Changes keep the selection from the caret's own
|
||||
// story (or restore the saved selection if that story had no match, #9063 / #9186).
|
||||
for results in found.into_iter().rev() {
|
||||
let is_orig = results[0].a.story == orig_story;
|
||||
replace_found(s, results)?;
|
||||
if s.doc.settings.track_changes && is_orig {
|
||||
orig_story_sel = Some(s.sel.clone());
|
||||
}
|
||||
}
|
||||
if s.doc.settings.track_changes {
|
||||
s.sel = orig_story_sel.unwrap_or(saved_sel);
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
}
|
||||
|
||||
/// Replace the matches of one story, last first.
|
||||
fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
|
||||
for Found { a, b, rep, .. } in results.into_iter().rev() {
|
||||
let with = rep.unwrap_or_default();
|
||||
if s.doc.settings.track_changes {
|
||||
@@ -857,8 +903,7 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
}
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
@@ -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)
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Mod+W / Mod+F4")
|
||||
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the shown document, then close it; it does not apply to a background `doc`, which needs force or its own save first), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
|
||||
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
|
||||
@@ -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.
|
||||
|
||||
@@ -186,6 +186,23 @@ pub fn missing_fonts(doc: &Document, layout: &DocLayout) -> Vec<MissingFont> {
|
||||
out.into_values().collect()
|
||||
}
|
||||
|
||||
/// Core Word fonts that actually need a non-metric substitute in a PDF or first-page PNG.
|
||||
pub fn output_metric_font_notices(s: &Session, markup: bool, first_page_png: bool) -> Vec<(&'static str, String)> {
|
||||
if first_page_png {
|
||||
let layout = s.export_layout_with(markup);
|
||||
return metric_font_notices(layout.pages.get(..1).unwrap_or(&[]));
|
||||
}
|
||||
let opts = super::file::export_options(s, &json!({"markup": markup}));
|
||||
let out = super::references::output_fields(&s.doc);
|
||||
let doc = out.as_ref().unwrap_or(&s.doc);
|
||||
let layout = crate::strict::pdf_layout(doc, &crate::strict::pdf_options(&opts));
|
||||
metric_font_notices(&layout.pages)
|
||||
}
|
||||
|
||||
fn metric_font_notices(pages: &[wordcraft_layout::Page]) -> Vec<(&'static str, String)> {
|
||||
DocLayout::metric_font_notices_on(pages).into_iter().map(|(core, face)| (core, face.family.clone())).collect()
|
||||
}
|
||||
|
||||
/// A font name as [`missing_fonts`] lists it: as layout records it (at most 256 characters),
|
||||
/// trimmed.
|
||||
fn shown_name(font: &str) -> &str {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
//! Character formatting (Home › Font).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, PoisonError};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
|
||||
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
|
||||
use wordcraft_doc::resolve::ResolvedChar;
|
||||
use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
|
||||
use wordcraft_doc::{Document, InlineObject, PartKind, Pos, RevisionKind, StoryRef};
|
||||
|
||||
use super::sel_result;
|
||||
use super::tools::{is_turkic, lower_char, upper_char};
|
||||
@@ -209,7 +210,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 +353,19 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a toggle without a `value` turns its format on. A selection (including a selected
|
||||
/// text box or a non-empty column block, whose `sel` is non-collapsed) follows its first
|
||||
/// character in document order, as Word does: one that starts formatted loses the format, all of
|
||||
/// it (#6516). A collapsed caret (including an empty column block) requires the whole word to
|
||||
/// carry the format before toggling it off.
|
||||
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
|
||||
let chars = resolved(s);
|
||||
if !s.sel.is_collapsed() {
|
||||
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 +381,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 +391,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))
|
||||
@@ -413,6 +428,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
if let Some(n) = &ea {
|
||||
c.font_ea = Some(n.clone());
|
||||
c.font_ea_theme = None;
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -940,6 +956,21 @@ pub fn state(s: &Session) -> Value {
|
||||
(*cached_state(s)).clone()
|
||||
}
|
||||
|
||||
/// The common East Asian family shown by the font controls. A theme slot without a face uses
|
||||
/// the run's ordinary font, as layout does. Resolve each theme slot once per selection.
|
||||
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
|
||||
let mut themes = HashMap::new();
|
||||
let mut fonts = runs.iter().map(|run| match run.font_ea_theme {
|
||||
Some(slot) => {
|
||||
let face = *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run));
|
||||
Some(face.unwrap_or(&run.font))
|
||||
}
|
||||
None => run.font_ea.as_deref(),
|
||||
});
|
||||
let first = fonts.next().flatten()?;
|
||||
fonts.all(|font| font == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
fn compute_state(s: &Session) -> Value {
|
||||
let all = resolved(s);
|
||||
let first = all.first().cloned();
|
||||
@@ -960,7 +991,7 @@ fn compute_state(s: &Session) -> Value {
|
||||
json!({
|
||||
"font": font,
|
||||
"fontShownAs": shown_as,
|
||||
"fontEastAsia": same(&|r| json!(r.font_ea)),
|
||||
"fontEastAsia": selection_east_asian_font(&s.doc, &all),
|
||||
"size": same(&|r| json!(r.size)),
|
||||
"bold": all.iter().all(shown_bold),
|
||||
"italic": all.iter().all(shown_italic),
|
||||
|
||||
@@ -9,6 +9,8 @@ use wordcraft_doc::para::InlineObject;
|
||||
use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
use wordcraft_doc::{Block, Paragraph, Path, Pos, StoryRef};
|
||||
use wordcraft_layout::para::ClKind;
|
||||
use wordcraft_layout::{DocLayout, Placed, ViewMode};
|
||||
|
||||
use super::references::{FieldCode, field_arg, leader, page_at, page_formats, page_text};
|
||||
use super::sel_result;
|
||||
@@ -136,6 +138,98 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
|
||||
})
|
||||
}
|
||||
|
||||
fn laid_out_leader(layout: &DocLayout, path: Path, offset: usize) -> Option<TabLeader> {
|
||||
layout.index.get(&(StoryRef::Body, path))?.iter().find_map(|&(page, item)| {
|
||||
let Placed::Lines { para, l0, l1, .. } = layout.pages.get(page)?.items.get(item)? else { return None };
|
||||
para.lines.get(*l0..*l1)?.iter().find_map(|line| {
|
||||
let tab = (line.c0..line.c1).find(|&i| para.clusters.get(i).is_some_and(|c| c.start == offset && c.kind == ClKind::Tab))?;
|
||||
Some(line.leaders.iter().find(|&&(i, _)| i == tab).map_or(TabLeader::None, |&(_, leader)| leader))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Read the leader of the first page-number tab that is laid out. Layout chooses the next
|
||||
/// stop after the text, including inherited and non-right stops.
|
||||
fn entry_leader(s: &mut Session, tabs: &[(usize, usize)]) -> Option<TabLeader> {
|
||||
if tabs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let from_layout = |layout: &DocLayout| tabs.iter().find_map(|&(block, offset)| laid_out_leader(layout, Path::top(block), offset));
|
||||
// A screen view can reflow the index to a different width or hide its result.
|
||||
if !s.view.read_mode
|
||||
&& s.view.mode == ViewMode::Print
|
||||
&& !s.view.field_codes
|
||||
&& let Some(leader) = from_layout(&s.layout())
|
||||
{
|
||||
return Some(leader);
|
||||
}
|
||||
if let Some(leader) = from_layout(&s.output_layout_of(&s.doc, false, false)) {
|
||||
return Some(leader);
|
||||
}
|
||||
// Measure hidden separators without revealing other hidden text, which could move the tab
|
||||
// past a different stop. The measurement leaves the document and view unchanged.
|
||||
let mut measurement = s.doc.clone();
|
||||
for &(block, offset) in tabs {
|
||||
if let Ok(p) = measurement.para_mut(StoryRef::Body, &Path::top(block)) {
|
||||
let _ = p.format(offset, offset + 1, &|props| props.hidden = Some(false));
|
||||
}
|
||||
}
|
||||
if let Some(leader) = from_layout(&s.output_layout_of(&measurement, false, false)) {
|
||||
return Some(leader);
|
||||
}
|
||||
// If the tab is still absent, retain an unambiguous saved leader.
|
||||
let mut saved = tabs
|
||||
.iter()
|
||||
.filter_map(|&(block, _)| s.doc.body.get(block)?.as_para())
|
||||
.flat_map(|p| s.doc.styles.resolve_para(&p.props).tabs)
|
||||
.map(|tab| tab.leader);
|
||||
let leader = saved.next()?;
|
||||
saved.all(|other| other == leader).then_some(leader)
|
||||
}
|
||||
|
||||
fn inline_entry_leader(s: &mut Session, i: usize) -> Option<TabLeader> {
|
||||
let tabs: Vec<_> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(i + 1)
|
||||
.map_while(|(j, b)| Some((j, b.as_para().filter(|p| super::citations::is_list_entry(p))?)))
|
||||
.filter_map(|(j, p)| p.text.rfind('\t').map(|offset| (j, offset)))
|
||||
.collect();
|
||||
entry_leader(s, &tabs)
|
||||
}
|
||||
|
||||
/// Read the leader before replacing a wrapped INDEX result, within the field's bounds.
|
||||
pub(in crate::cmd) fn wrapped_entry_leader(s: &mut Session, i: usize, start: usize, last: usize, end: usize) -> Option<TabLeader> {
|
||||
let tabs: Vec<_> = (i..=last)
|
||||
.filter_map(|j| {
|
||||
let p = s.doc.body.get(j)?.as_para()?;
|
||||
let from = if j == i { start } else { 0 };
|
||||
let to = if j == last { end } else { p.len() };
|
||||
p.text.get(from..to)?.rfind('\t').map(|offset| (j, from + offset))
|
||||
})
|
||||
.collect();
|
||||
entry_leader(s, &tabs)
|
||||
}
|
||||
|
||||
/// The index Insert Index will update and the leader its current result shows.
|
||||
pub fn index_settings(s: &mut Session) -> Option<(FieldCode, Option<TabLeader>)> {
|
||||
if let Some((i, instr)) = index_field(s) {
|
||||
let leader = inline_entry_leader(s, i);
|
||||
return Some((FieldCode::parse(&instr), leader));
|
||||
}
|
||||
|
||||
(0..s.doc.body.len()).find_map(|i| {
|
||||
let (instr, start, last, end) = super::citations::wrapped_list(s, i)?;
|
||||
let field = FieldCode::parse(&instr);
|
||||
if field.name != "INDEX" {
|
||||
return None;
|
||||
}
|
||||
Some((field, wrapped_entry_leader(s, i, start, last, end)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
|
||||
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
|
||||
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
|
||||
@@ -188,6 +282,7 @@ fn range_index_after_text(s: &Session) -> bool {
|
||||
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let instr = index_instr(v);
|
||||
check_index_reachable(s)?;
|
||||
let leader = p::str(v, "tabLeader").map(leader).or_else(|| index_settings(s).and_then(|(_, leader)| leader)).unwrap_or(TabLeader::Dot);
|
||||
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
|
||||
// Update Index makes it, so it takes the new settings rather than a second index being added
|
||||
// beside it (#8034).
|
||||
@@ -213,7 +308,7 @@ fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
None => super::citations::generated_list(s, &instr, "Index")?,
|
||||
}
|
||||
if let Some((i, _)) = index_field(s) {
|
||||
rebuild(s, i, p::str(v, "tabLeader").map(leader))?;
|
||||
rebuild(s, i, Some(leader))?;
|
||||
}
|
||||
s.clamp_selection();
|
||||
sel_result(s)
|
||||
@@ -339,16 +434,18 @@ pub fn rebuild(s: &mut Session, i: usize, leader: Option<TabLeader>) -> Result<(
|
||||
pub fn rebuild_from(s: &mut Session, i: usize, leader: Option<TabLeader>, instr: String) -> Result<(), CmdError> {
|
||||
let f = FieldCode::parse(&instr);
|
||||
// Old entries go; keep their leader and the section their columns had.
|
||||
let mut old_leader = None;
|
||||
let leader = leader.or_else(|| inline_entry_leader(s, i)).unwrap_or(TabLeader::Dot);
|
||||
let old_len = s.doc.body.len();
|
||||
let mut old_sect = None;
|
||||
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) {
|
||||
old_leader = old_leader.or_else(|| p.props.tabs.as_ref().and_then(|t| t.last()).map(|t| t.leader));
|
||||
while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| super::citations::is_list_entry(p)) {
|
||||
if p.section.is_some() {
|
||||
old_sect = p.section.clone();
|
||||
}
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(i + 1))?;
|
||||
}
|
||||
let leader = leader.or(old_leader).unwrap_or(TabLeader::Dot);
|
||||
if s.doc.body.len() != old_len {
|
||||
s.touch();
|
||||
}
|
||||
let cols = f.arg('c').and_then(|c| c.trim().parse::<u32>().ok()).unwrap_or(1).clamp(1, 4);
|
||||
let sep = f.arg('e').map(str::to_string).unwrap_or_else(|| ", ".into());
|
||||
let run_in = f.has('r');
|
||||
@@ -545,6 +642,86 @@ mod tests {
|
||||
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keeps_the_leader_used_by_the_page_number_tab() {
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("references.markEntry", &json!({"entry": "Kilns"})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
let path = Path::top(i + 1);
|
||||
assert_eq!(s.doc.para(StoryRef::Body, &path).unwrap().plain_text(), "Kilns\t1");
|
||||
|
||||
for (align, leader, inherit_later_stop) in
|
||||
[(TabAlign::Left, TabLeader::Underscore, false), (TabAlign::Right, TabLeader::Hyphen, true), (TabAlign::Left, TabLeader::None, true)]
|
||||
{
|
||||
let generated_pos = s.doc.para(StoryRef::Body, &path).unwrap().props.tabs.as_ref().unwrap()[0].pos;
|
||||
Arc::make_mut(&mut s.doc.styles).get_mut(ENTRY_STYLE).unwrap().para.tabs =
|
||||
inherit_later_stop.then(|| vec![TabStop { pos: generated_pos + 0.75, align: TabAlign::Right, leader: TabLeader::Dot }]);
|
||||
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
|
||||
// The text already runs past the first stop. The next one wins over the later style stop.
|
||||
entry.props.tabs = Some(vec![TabStop { pos: 5.0, align: TabAlign::Right, leader: TabLeader::Dot }, TabStop { pos: 90.0, align, leader }]);
|
||||
entry.touch();
|
||||
s.touch();
|
||||
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "{align:?}, {inherit_later_stop}");
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(leader), "kept on update: {align:?}, {inherit_later_stop}");
|
||||
}
|
||||
|
||||
// Updating an imported field consumes the result, so its tab must be read before conversion.
|
||||
let (_, instr) = index_field(&s).unwrap();
|
||||
let header = s.doc.para_mut(StoryRef::Body, &Path::top(i)).unwrap();
|
||||
let offset = header.object_offsets()[0];
|
||||
header.delete(0, offset).unwrap();
|
||||
header.objects[0] = InlineObject::FieldStart { instr, locked: false, dirty: false };
|
||||
header.touch();
|
||||
let entry = s.doc.para_mut(StoryRef::Body, &path).unwrap();
|
||||
entry.props.tabs = Some(vec![TabStop { pos: 90.0, align: TabAlign::Center, leader: TabLeader::Hyphen }]);
|
||||
entry.insert_object(entry.len(), InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
s.touch();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen));
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert!(s.doc.field_ranges(StoryRef::Body).is_empty());
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(TabLeader::Hyphen), "kept through wrapped field conversion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_keeps_the_page_number_leader_when_the_first_tab_is_hidden() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns and wheels."));
|
||||
s.view.marks = false;
|
||||
s.prefs.marks.hidden = false;
|
||||
for entry in ["Kilns", "Wheels"] {
|
||||
s.run("references.markEntry", &json!({"entry": entry})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"rightAlign": true, "headings": false, "tabLeader": "hyphen"})).unwrap();
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
assert_eq!(index_lines(&s), ["Kilns\t1", "Wheels\t1"]);
|
||||
|
||||
for (first, second, hide_second, expected) in [
|
||||
(TabLeader::Dot, TabLeader::Hyphen, false, TabLeader::Hyphen),
|
||||
(TabLeader::Hyphen, TabLeader::Hyphen, true, TabLeader::Hyphen),
|
||||
(TabLeader::Hyphen, TabLeader::None, false, TabLeader::None),
|
||||
] {
|
||||
for (block, leader, hidden) in [(i + 1, first, true), (i + 2, second, hide_second)] {
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(block)).unwrap();
|
||||
p.props.tabs.as_mut().unwrap()[0].leader = leader;
|
||||
let tab = p.text.rfind('\t').unwrap();
|
||||
p.format(tab, tab + 1, &|props| props.hidden = Some(hidden)).unwrap();
|
||||
}
|
||||
s.touch();
|
||||
let l = s.layout();
|
||||
assert_eq!(laid_out_leader(&l, Path::top(i + 1), "Kilns".len()), None, "the hidden tab has no layout leader");
|
||||
assert_eq!(laid_out_leader(&l, Path::top(i + 2), "Wheels".len()), (!hide_second).then_some(second));
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected));
|
||||
s.run("references.updateIndex", &json!({})).unwrap();
|
||||
assert_eq!(index_settings(&mut s).unwrap().1, Some(expected), "kept on update");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
|
||||
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
|
||||
/// second index at the caret.
|
||||
|
||||
@@ -14,14 +14,14 @@ mod links;
|
||||
mod objects;
|
||||
|
||||
pub(crate) use header_footer::saved_copy;
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, remove_first_hf, strip_headers};
|
||||
pub use items::{
|
||||
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
|
||||
format_date_parts_in,
|
||||
DropCapState, default_date_picture, default_time_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in,
|
||||
format_date_parts, format_date_parts_in,
|
||||
};
|
||||
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};
|
||||
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.then_some("text boxes can't go inside a text box")
|
||||
}),
|
||||
CommandSpec::new("insert.link", "Link", "Insert › Links", link).key("Mod+K").params(
|
||||
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document)"#,
|
||||
r#"{"url": string} | {"bookmark": name} | {"heading": block (see link.targets)} | {"top": true}, "text"?: string (Place in This Document: a bookmark, a heading or the top of the document); for every target, the result has a "warning" when a selection keeps its own text instead of "text""#,
|
||||
),
|
||||
CommandSpec::new("link.targets", "Link", "Insert › Links", link_targets).pure(),
|
||||
CommandSpec::new("insert.removeLink", "Remove Hyperlink", "Insert › Links", |s, _| super::format::apply(s, &|c| {
|
||||
@@ -86,6 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("insert.closeHeader", "Close Header and Footer", "Header & Footer", |s, _| {
|
||||
// Back where the caret was in the body, as Word does, not on page 1.
|
||||
let back = s.hf_return.take().filter(|_| s.in_header_footer());
|
||||
s.hf_section = None;
|
||||
if !new_empty_headers(s).is_empty() {
|
||||
// Its own undo step; a protected document keeps it, and the caret still leaves.
|
||||
let _ = s.run("insert.removeEmptyHeaders", &json!({}));
|
||||
@@ -102,6 +103,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.removeHeader", "Remove Header", "Insert › Header & Footer › Header", |s, _| {
|
||||
if remove_first_hf(s, true)? {
|
||||
return sel_result(s);
|
||||
}
|
||||
s.doc.last_section.headers = Default::default();
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
if s.doc.para(StoryRef::Body, &path).is_some_and(|p| p.section.is_some())
|
||||
@@ -114,7 +118,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.removeFooter", "Remove Footer", "Insert › Header & Footer › Footer", |s, _| {
|
||||
s.doc.last_section.footers = Default::default();
|
||||
if !remove_first_hf(s, false)? {
|
||||
s.doc.last_section.footers = Default::default();
|
||||
}
|
||||
sel_result(s)
|
||||
}),
|
||||
CommandSpec::new("insert.dateTime", "Date & Time", "Insert › Text", date_time).params(r#"{"format"?: "M/d/yyyy", "update"?: bool, "language"?: "en-US|pt-BR"}"#),
|
||||
|
||||
@@ -3,6 +3,44 @@ use super::{
|
||||
json, p, para_block,
|
||||
};
|
||||
|
||||
fn slot_of(slot: wordcraft_layout::HfSlot, set: &wordcraft_doc::section::HeaderSet) -> Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => set.first,
|
||||
wordcraft_layout::HfSlot::Even => set.even,
|
||||
wordcraft_layout::HfSlot::Default => set.default,
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_of_mut(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => &mut set.first,
|
||||
wordcraft_layout::HfSlot::Even => &mut set.even,
|
||||
wordcraft_layout::HfSlot::Default => &mut set.default,
|
||||
}
|
||||
}
|
||||
|
||||
/// The header (or footer) shown on the caret's page/section (including an inherited one from an
|
||||
/// earlier section), or a newly created one in the caret's section if none exists yet (#5855).
|
||||
pub(super) fn shown_or_create_hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let sec = crate::cmd::page::hf_section_of_focus(s);
|
||||
let slot = {
|
||||
let layout = s.layout();
|
||||
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
|
||||
page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default()
|
||||
};
|
||||
let sections = s.doc.sections();
|
||||
if let Some(id) = sections
|
||||
.iter()
|
||||
.take(sec + 1)
|
||||
.rev()
|
||||
.find_map(|(_, sp)| slot_of(slot, if header { &sp.headers } else { &sp.footers }))
|
||||
.filter(|id| s.doc.parts.contains_key(id))
|
||||
{
|
||||
return id;
|
||||
}
|
||||
hf_part(s, header)
|
||||
}
|
||||
|
||||
/// The header (or footer) of the caret's section in the slot the caret's page uses (first page,
|
||||
/// even page or the default), made when there is none: with Different First Page on, a header
|
||||
/// inserted on page 1 is the one page 1 shows (#2826).
|
||||
@@ -11,22 +49,15 @@ pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let layout = s.layout();
|
||||
let page = if s.sel.focus.story == StoryRef::Body { layout.page_of(&s.sel.focus) } else { Some(s.page_hint) };
|
||||
let slot = page.and_then(|pg| layout.pages.get(pg)).map(|pg| pg.hf_slot).unwrap_or_default();
|
||||
fn slot_of(slot: wordcraft_layout::HfSlot, set: &mut wordcraft_doc::section::HeaderSet) -> &mut Option<u32> {
|
||||
match slot {
|
||||
wordcraft_layout::HfSlot::First => &mut set.first,
|
||||
wordcraft_layout::HfSlot::Even => &mut set.even,
|
||||
wordcraft_layout::HfSlot::Default => &mut set.default,
|
||||
}
|
||||
}
|
||||
let mut sect = s.doc.section_mut(block).clone();
|
||||
let existing = *slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers });
|
||||
let sect = s.doc.section_mut(block).clone();
|
||||
let existing = slot_of(slot, if header { §.headers } else { §.footers });
|
||||
if let Some(id) = existing.filter(|id| s.doc.parts.contains_key(id)) {
|
||||
return id;
|
||||
}
|
||||
let style = if header { "Header" } else { "Footer" };
|
||||
let id = s.doc.add_part(if header { PartKind::Header } else { PartKind::Footer }, vec![para_block(Paragraph::new().styled(style))]);
|
||||
let sect = s.doc.section_mut(block);
|
||||
*slot_of(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
|
||||
*slot_of_mut(slot, if header { &mut sect.headers } else { &mut sect.footers }) = Some(id);
|
||||
id
|
||||
}
|
||||
|
||||
@@ -88,6 +119,7 @@ pub(super) fn header_footer(s: &mut Session, v: &Value, header: bool) -> CmdResu
|
||||
Ok(json!({"story": id}))
|
||||
}
|
||||
|
||||
/// Edit the header or footer shown on `page`, or at the caret's current body position.
|
||||
pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let mut page = p::u64(v, "page").map(|page| usize::try_from(page).unwrap_or(usize::MAX));
|
||||
if page.is_none() && s.sel.focus.story == StoryRef::Body {
|
||||
@@ -113,13 +145,46 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
return s.run(cmd, ¶ms);
|
||||
};
|
||||
if let Some(page) = page {
|
||||
// The page's section is what section commands act on; the body position Close Header and
|
||||
// Footer returns to stays where it was (#3331).
|
||||
s.page_hint = page;
|
||||
let sec = s.layout().pages.get(page).map(|pg| pg.section);
|
||||
s.hf_section = sec.map(|sec| sec.min(s.doc.sections().len().saturating_sub(1)));
|
||||
}
|
||||
s.touch();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Part(id)));
|
||||
Ok(json!({"story": id}))
|
||||
}
|
||||
|
||||
/// Remove the first-page variant while it is being edited, keeping the other page variants.
|
||||
pub(super) fn remove_first_hf(s: &mut Session, header: bool) -> Result<bool, CmdError> {
|
||||
let StoryRef::Part(story) = s.sel.focus.story else { return Ok(false) };
|
||||
let page = s.page_hint;
|
||||
let layout = s.layout();
|
||||
let Some(page) = layout.pages.get(page) else { return Ok(false) };
|
||||
let shown = if header { page.header_story } else { page.footer_story };
|
||||
if page.hf_slot != wordcraft_layout::HfSlot::First || shown != Some(story) {
|
||||
return Ok(false);
|
||||
}
|
||||
let index = page.section;
|
||||
let sections = s.doc.sections();
|
||||
let Some(&(end, _)) = sections.get(index) else { return Ok(false) };
|
||||
let last = index + 1 == sections.len();
|
||||
let inherits_first = sections[..index].iter().any(|(_, sec)| if header { sec.headers.first.is_some() } else { sec.footers.first.is_some() });
|
||||
// An absent slot would show the previous section's first-page story again.
|
||||
let replacement = if inherits_first {
|
||||
let (kind, style) = if header { (PartKind::Header, "Header") } else { (PartKind::Footer, "Footer") };
|
||||
Some(s.doc.try_add_part(kind, vec![para_block(Paragraph::new().styled(style))])?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let section = if last { &mut s.doc.last_section } else { s.doc.section_mut(end) };
|
||||
let set = if header { &mut section.headers } else { &mut section.footers };
|
||||
set.first = replacement;
|
||||
s.sel = s.hf_return.take().unwrap_or_else(|| Selection::caret(s.doc.start_of(StoryRef::Body)));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The header (or footer) page `page` shows, if any; an error for a page that isn't there.
|
||||
fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, CmdError> {
|
||||
let layout = s.layout();
|
||||
@@ -128,11 +193,14 @@ fn shown_hf(s: &mut Session, page: usize, header: bool) -> Result<Option<u32>, C
|
||||
Ok(shown.filter(|id| s.doc.parts.contains_key(id)))
|
||||
}
|
||||
|
||||
/// Create and edit a header or footer on `page`, or in the caret's section.
|
||||
pub(super) fn create_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let id = match p::u64(v, "page") {
|
||||
Some(page) => {
|
||||
let page = usize::try_from(page).unwrap_or(usize::MAX);
|
||||
let sec = s.layout().pages.get(page).map(|pg| pg.section).ok_or_else(|| CmdError::Params(format!("no page {page}")))?;
|
||||
s.page_hint = page;
|
||||
s.hf_section = Some(sec.min(s.doc.sections().len().saturating_sub(1)));
|
||||
page_hf_part(s, page, header)?
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::PartKind;
|
||||
use super::header_footer::hf_part;
|
||||
use super::header_footer::shown_or_create_hf_part;
|
||||
use super::{
|
||||
Align, Block, CharProps, CmdError, CmdResult, InlineObject, Paragraph, Rgb, Selection, Session, StoryRef, TabAlign, TabStop, TextColor, Value,
|
||||
delete_selection, json, p, para_block, sel_result, type_text, type_text_with_lang,
|
||||
@@ -85,7 +85,7 @@ pub(super) fn page_number(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return sel_result(s);
|
||||
}
|
||||
let header = position == "top";
|
||||
let id = hf_part(s, header);
|
||||
let id = shown_or_create_hf_part(s, header);
|
||||
let story = StoryRef::Part(id);
|
||||
let style = if header { "Header" } else { "Footer" };
|
||||
let mut para = page_number_paragraph(style, align, x_of_y)?;
|
||||
@@ -205,36 +205,79 @@ 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,
|
||||
/// The picture of a `TIME` field without `\@`.
|
||||
default_time: &'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",
|
||||
default_time: "h:mm am/pm",
|
||||
};
|
||||
|
||||
/// Portuguese (observed in Word for Mac with a pt-BR document): lower-case names, `MMM` = `out`,
|
||||
/// `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",
|
||||
default_time: "h:mm am/pm",
|
||||
};
|
||||
|
||||
/// 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",
|
||||
default_time: "HH:mm",
|
||||
};
|
||||
|
||||
/// 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",
|
||||
default_time: "HH:mm",
|
||||
};
|
||||
|
||||
/// 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.
|
||||
@@ -242,6 +285,12 @@ pub fn default_date_picture(lang: Option<&str>) -> &'static str {
|
||||
date_names(lang).default
|
||||
}
|
||||
|
||||
/// The picture Word gives a `TIME` field that has no `\@` switch, in the field's language: German
|
||||
/// shows the 24-hour clock (#8562).
|
||||
pub fn default_time_picture(lang: Option<&str>) -> &'static str {
|
||||
date_names(lang).default_time
|
||||
}
|
||||
|
||||
/// Format a date and time with a Word picture; `days_since` (days since 1970-01-01) gives the weekday.
|
||||
pub fn format_date_parts(fmt: &str, y: i64, m: usize, d: u32, hms: (u32, u32, u32), days_since: i64) -> String {
|
||||
format_date_parts_in(fmt, None, y, m, d, hms, days_since)
|
||||
@@ -252,9 +301,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 +348,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 +626,65 @@ 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");
|
||||
}
|
||||
|
||||
/// A `TIME` field without `\@` shows the 24-hour clock in a German document and the 12-hour
|
||||
/// clock in an English one (#8562).
|
||||
#[test]
|
||||
fn bare_time_field_follows_the_document_language() {
|
||||
let refreshed = |lang: &str| {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": "TIME", "result": "stale"})).unwrap();
|
||||
crate::cmd::references::refresh_date_fields(&mut s.doc);
|
||||
let path = s.doc.para_paths(StoryRef::Body).remove(0);
|
||||
let p = s.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let result = p.objects.iter().find_map(|o| if let InlineObject::Field { result, .. } = o { Some(result.clone()) } else { None });
|
||||
result.expect("a TIME field")
|
||||
};
|
||||
for lang in ["de-DE", "de-AT", "de-CH"] {
|
||||
let time = refreshed(lang);
|
||||
assert!(time != "stale" && !time.contains("AM") && !time.contains("PM"), "{lang}: {time}");
|
||||
}
|
||||
let time = refreshed("en-US");
|
||||
assert!(time.contains("AM") || time.contains("PM"), "en-US: {time}");
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
|
||||
@@ -75,34 +75,64 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.sel = Selection::caret(end);
|
||||
s.pending = Some(CharProps::default());
|
||||
} else {
|
||||
// A Text to display that differs from the selection but can't retype it is not applied:
|
||||
// the caller is told so rather than left to think it was (#8541).
|
||||
let kept = p::str(v, "text").is_some_and(|t| !t.is_empty() && one_line_selection(s) != Some(t) && s.selected_text() != t);
|
||||
let (a, b) = s.sel.ordered();
|
||||
s.doc.format_range(&a, &b, &|c| {
|
||||
c.link = Some(url.clone());
|
||||
c.style = style.clone();
|
||||
})?;
|
||||
if kept {
|
||||
const KEPT: &str = "Text to display was not applied: the selection is linked with its own text.";
|
||||
s.status = KEPT.into();
|
||||
let mut out = sel_result(s)?;
|
||||
out["warning"] = json!(KEPT);
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
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) {
|
||||
|
||||
@@ -133,6 +133,108 @@ fn different_first_page_header_is_reachable_from_page_one() {
|
||||
assert_eq!((s.doc.last_section.footers.first, s.doc.last_section.footers.default), (Some(foot), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_first_page_header_or_footer_keeps_the_default() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
for (cmd, page, text) in [
|
||||
("insert.editHeader", 0, "Cover header"),
|
||||
("insert.editHeader", 1, "Default header"),
|
||||
("insert.editFooter", 0, "Cover footer"),
|
||||
("insert.editFooter", 1, "Default footer"),
|
||||
] {
|
||||
s.run(cmd, &json!({"page": page})).unwrap();
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
}
|
||||
let page_stories = |s: &mut Session| {
|
||||
let pages = &s.layout().pages;
|
||||
assert_eq!(pages.len(), 2);
|
||||
[(pages[0].header_story, pages[0].footer_story), (pages[1].header_story, pages[1].footer_story)]
|
||||
};
|
||||
let [first, default] = page_stories(&mut s);
|
||||
assert!(first.0.is_some() && first.1.is_some());
|
||||
assert!(default.0.is_some() && default.1.is_some());
|
||||
assert_ne!(first, default);
|
||||
|
||||
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.removeHeader", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [(None, first.1), default]);
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Body);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [first, default]);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.removeFooter", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [(first.0, None), default]);
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Body);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(page_stories(&mut s), [first, default]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_first_page_removal_keeps_the_selection_for_close_header_and_footer() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
for (edit, text) in [("insert.editHeader", "Cover header"), ("insert.editFooter", "Cover footer")] {
|
||||
s.run(edit, &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
}
|
||||
s.run("select.text", &json!({"text": "Two"})).unwrap();
|
||||
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let body_selection = s.sel.clone();
|
||||
assert_eq!(s.selected_text(), "Two");
|
||||
let before = s.doc.clone();
|
||||
|
||||
for (edit, remove) in [("insert.editHeader", "insert.removeHeader"), ("insert.editFooter", "insert.removeFooter")] {
|
||||
s.run(edit, &json!({"page": 0})).unwrap();
|
||||
let editing = s.sel.clone();
|
||||
assert!(s.in_header_footer());
|
||||
let error = s.run(remove, &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("only the editable regions"), "{error}");
|
||||
assert_eq!(s.doc, before);
|
||||
assert_eq!(s.sel, editing, "the refusal leaves the editor in the first-page story");
|
||||
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, body_selection, "explicit Close returns to the saved selection after {remove}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_an_inherited_first_page_header_keeps_the_previous_section() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
let first = s.run("insert.editHeader", &json!({"page": 0})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("text.insert", &json!({"text": "Cover header"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section two"})).unwrap();
|
||||
s.run("layout.differentFirstPage", &json!({"value": true})).unwrap();
|
||||
// Start with a linked first-page slot in the later section.
|
||||
s.doc.last_section.headers.first = None;
|
||||
s.touch();
|
||||
let page = s.layout().pages.iter().position(|page| page.section == 1).unwrap();
|
||||
assert_eq!(s.layout().pages[page].header_story, Some(first));
|
||||
s.run("insert.editHeader", &json!({"page": page})).unwrap();
|
||||
s.run("insert.removeHeader", &json!({})).unwrap();
|
||||
let blank = s.doc.last_section.headers.first.unwrap();
|
||||
assert_ne!(blank, first);
|
||||
assert_eq!(s.layout().pages[0].header_story, Some(first));
|
||||
assert_eq!(s.layout().pages[page].header_story, Some(blank));
|
||||
assert!(s.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
|
||||
|
||||
let saved = wordcraft_docx::write(&s.doc).unwrap();
|
||||
let mut reopened = Session::new(wordcraft_docx::read(&saved).unwrap());
|
||||
let reopened_layout = reopened.layout();
|
||||
let cover = reopened_layout.pages[0].header_story.unwrap();
|
||||
let blank = reopened_layout.pages.iter().find(|page| page.section == 1).unwrap().header_story.unwrap();
|
||||
assert_eq!(reopened.doc.para(StoryRef::Part(cover), &Path(vec![0])).unwrap().text.as_str(), "Cover header");
|
||||
assert!(reopened.doc.para(StoryRef::Part(blank), &Path(vec![0])).unwrap().text.is_empty());
|
||||
}
|
||||
|
||||
fn two_pages() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("text.insert", &json!({"text": "One"})).unwrap();
|
||||
@@ -214,6 +316,24 @@ fn new_header_links_to_previous_and_even_pages_edit_what_they_show() {
|
||||
assert_eq!(s.doc.sections()[0].1.headers.even, None, "nothing made");
|
||||
}
|
||||
|
||||
/// Edit Header from the body on a later section's page makes the header in the first section,
|
||||
/// linked through to every page, as on main: the caret's page selects the page, not the section.
|
||||
#[test]
|
||||
fn edit_header_from_the_body_links_to_previous_sections() {
|
||||
let mut s = two_pages();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Three"})).unwrap();
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 3 && s.layout().pages[pages - 1].section == 1, "a second section");
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
let id = s.run("insert.editHeader", &json!({})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("text.insert", &json!({"text": "Draft"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert!(s.layout().pages.iter().all(|p| p.header_story == Some(id)), "every page shows it");
|
||||
assert_eq!(s.doc.sections()[0].1.headers.default, Some(id), "made in the first section");
|
||||
assert_eq!(s.doc.sections()[1].1.headers.default, None, "the later section inherits it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_round_trip() {
|
||||
let data = b"hello world!?";
|
||||
@@ -418,6 +538,54 @@ fn local_civil_date_follows_the_utc_offset() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Close Header and Footer restores the body selection, with or without a page argument.
|
||||
#[test]
|
||||
fn close_header_preserves_original_body_selection() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("First paragraph.\nSecond paragraph with more text."));
|
||||
// Place caret at offset 7 in the second paragraph.
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path::top(1), 7));
|
||||
let original = s.sel.clone();
|
||||
|
||||
// Edit footer from ribbon without a page argument.
|
||||
s.run("insert.editFooter", &json!({})).unwrap();
|
||||
assert!(s.in_header_footer());
|
||||
|
||||
// Close header and footer.
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, original, "original body selection was preserved without page argument");
|
||||
|
||||
// Edit footer explicitly specifying the page of the current section.
|
||||
s.sel = original.clone();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
assert!(s.in_header_footer());
|
||||
|
||||
// Close header and footer.
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, original, "original body selection was preserved with same-section page argument");
|
||||
}
|
||||
|
||||
/// Entering a header or footer on another section's page leaves the body caret that Close Header
|
||||
/// and Footer returns to where it was (#3331); the page only picks the section commands act on.
|
||||
#[test]
|
||||
fn closing_a_header_on_another_sections_page_returns_to_the_body_caret() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
// The body caret stays in the first section, page 1 belongs to the second.
|
||||
let before = Selection::caret(Pos::new(StoryRef::Body, Path::top(0), 2));
|
||||
s.sel = before.clone();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
// A click into the footer on page 1's page, while the footer is open.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert!(s.in_header_footer());
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_base64_preserves_command_payload_bytes() {
|
||||
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
|
||||
|
||||
@@ -668,6 +668,18 @@ fn recipient_lists_in_legacy_and_utf16_encodings() {
|
||||
assert_eq!(s.merge.rows, [["José"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipient_list_with_generic_utf32_uses_its_big_endian_bom() {
|
||||
let mut data = vec![0x00, 0x00, 0xFE, 0xFF];
|
||||
for c in "Name,City\nAda,A🌍\n".chars() {
|
||||
data.extend_from_slice(&(c as u32).to_be_bytes());
|
||||
}
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("mailings.recipients", &json!({"path": "list.csv", "data": b64(&data), "encoding": "utf-32"})).unwrap();
|
||||
assert_eq!(s.merge.headers, ["Name", "City"]);
|
||||
assert_eq!(s.merge.rows, [["Ada", "A🌍"]]);
|
||||
}
|
||||
|
||||
/// #778: legacy Excel 97–2003 workbooks are recipient lists; a CSV named .xls reads as text.
|
||||
#[test]
|
||||
fn recipients_from_an_xls_workbook() {
|
||||
|
||||
@@ -908,4 +908,29 @@ mod tests {
|
||||
let spec = s.registry.get(TEXT).unwrap();
|
||||
assert!(spec.mutates, "view.markdownSourceText mutates session and dirty state");
|
||||
}
|
||||
|
||||
/// Verifies entering and applying Markdown Source keep the document intact and report errors
|
||||
/// when Markdown conversion fails.
|
||||
#[test]
|
||||
fn failed_markdown_conversion_keeps_document_and_reports_error() {
|
||||
let mut s = session(SAMPLE);
|
||||
s.md_file = FileText::default();
|
||||
let err = wordcraft_formats::with_shared_conversion_error("bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("bridge failed"), "{err}");
|
||||
assert!(s.md_source.is_none());
|
||||
|
||||
for skip in [1, 2] {
|
||||
let err = wordcraft_formats::with_shared_conversion_error_after(skip, "bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
|
||||
assert!(err.to_string().contains("bridge failed"), "skip={skip}: {err}");
|
||||
assert!(s.md_source.is_none());
|
||||
}
|
||||
|
||||
let mut s = session(SAMPLE);
|
||||
s.run(TOGGLE, &json!({})).unwrap();
|
||||
let before = body_text(&s);
|
||||
set_text(&mut s, "# Replaced\n");
|
||||
wordcraft_formats::with_shared_conversion_error("bridge failed", || apply(&mut s));
|
||||
assert_eq!(body_text(&s), before, "failed apply leaves the document intact");
|
||||
assert!(s.status.contains("bridge failed"), "{}", s.status);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ mod shape;
|
||||
mod specs;
|
||||
|
||||
pub use arrange::moves_with_text;
|
||||
pub(crate) use arrange::{anchor_paragraph, nearest_line};
|
||||
pub(crate) use arrange::{anchor_paragraph, nearest_line, shifted_float_offset};
|
||||
#[cfg(test)]
|
||||
use group::ungroup;
|
||||
pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, original_size};
|
||||
@@ -33,7 +33,9 @@ pub(crate) use select::select_object;
|
||||
pub(crate) use select::{edit_obj, has_shape_or_canvas};
|
||||
#[cfg(test)]
|
||||
use select::{has_group, holds_ink, obj_size, with_obj};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
|
||||
pub use select::{
|
||||
has_picture_format_target, min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use shape::can_link;
|
||||
pub(crate) use shape::set_text_body;
|
||||
|
||||
@@ -212,9 +212,29 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
|
||||
f.x = (x - origin.x).clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
f.y = (y - origin.y).clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
})?;
|
||||
if let Some(offset) = shifted_float_offset(s, &at, page, y, origin.y) {
|
||||
edit_float(s, &at, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// A page-to-paragraph conversion can make a float move from the unpushed paragraph top to
|
||||
/// the pushed first line. Once layout has resolved that choice, offset from the origin it used.
|
||||
/// Leave other layout effects, such as wrapping settlement or a change of page, to the caller.
|
||||
pub(crate) fn shifted_float_offset(s: &mut Session, at: &Pos, page: usize, y: f32, old_origin: f32) -> Option<f32> {
|
||||
let offset = y - old_origin;
|
||||
if offset >= 0.0
|
||||
|| at.story != StoryRef::Body
|
||||
|| at.path.depth() != 0
|
||||
|| (!s.view.read_mode && !matches!(s.view.mode, wordcraft_layout::ViewMode::Print | wordcraft_layout::ViewMode::Read))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
s.touch();
|
||||
let hit = s.layout().object(at, page)?;
|
||||
(hit.page == page && hit.origin.y > old_origin + 0.01 && (hit.rect.y - hit.origin.y - offset).abs() < 0.01).then_some(y - hit.origin.y)
|
||||
}
|
||||
|
||||
/// Turn the selected floating object's alignment (left, centred, …) into an offset from its
|
||||
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
|
||||
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
|
||||
@@ -245,6 +265,12 @@ pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
|
||||
f.y = oy.clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
}
|
||||
})?;
|
||||
if float.v_align.is_some()
|
||||
&& float.v_rel != Anchor::Page
|
||||
&& let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y)
|
||||
{
|
||||
edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -268,11 +294,14 @@ pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
|
||||
let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?;
|
||||
// Paragraph offsets start at the paragraph's top (the hit's origin), page offsets at the page's.
|
||||
let y = if with_text { hit.rect.y - hit.origin.y } else { hit.rect.y };
|
||||
let o = edit_float(s, &pos, |f| {
|
||||
let mut o = edit_float(s, &pos, |f| {
|
||||
f.v_rel = if with_text { Anchor::Paragraph } else { Anchor::Page };
|
||||
f.v_align = None;
|
||||
f.y = y.clamp(-MAX_OFFSET, MAX_OFFSET);
|
||||
})?;
|
||||
if with_text && let Some(offset) = shifted_float_offset(s, &pos, hit.page, hit.rect.y, hit.origin.y) {
|
||||
o = edit_float(s, &pos, |f| f.y = offset.clamp(-MAX_OFFSET, MAX_OFFSET))?;
|
||||
}
|
||||
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
|
||||
use super::select::{edit_obj, has_picture, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
@@ -186,6 +186,30 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
|
||||
(side(w), side(h))
|
||||
}
|
||||
|
||||
/// Runs a one-picture command on each selected picture in turn (several selected with Shift or
|
||||
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
|
||||
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
|
||||
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
|
||||
if picks.is_empty() || (picks.len() == 1 && has_picture(s).is_none()) {
|
||||
return run(s);
|
||||
}
|
||||
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
|
||||
// The failed command's rollback restores the document but not these maps: put them back too.
|
||||
let (originals, looks) = (s.originals.clone(), s.picture_looks.clone());
|
||||
let mut out = Ok(Value::Null);
|
||||
for (pos, _) in &picks {
|
||||
select_object(s, pos);
|
||||
s.also_selected.clear();
|
||||
out = run(s);
|
||||
if out.is_err() {
|
||||
(s.originals, s.picture_looks) = (originals, looks);
|
||||
break;
|
||||
}
|
||||
}
|
||||
(s.sel, s.also_selected) = (sel, also);
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply an image operation to the selected picture's bitmap (stored as a new PNG).
|
||||
pub(super) fn adjust(s: &mut Session, f: impl Fn(image::DynamicImage) -> Result<image::DynamicImage, CmdError>) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
|
||||
|
||||
@@ -7,6 +7,16 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether commands that already format multiple pictures have a target. A secondary
|
||||
/// picture counts when objects were explicitly picked, even if the primary object is a shape.
|
||||
pub fn has_picture_format_target(s: &Session) -> bool {
|
||||
has_picture(s).is_none() || (!s.also_selected.is_empty() && !target_objects(s, |o| matches!(o, InlineObject::Image { .. })).is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn has_any_picture(s: &Session) -> Option<&'static str> {
|
||||
(!has_picture_format_target(s)).then_some("select a picture first")
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a picture, shape, or active text box is selected.
|
||||
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
|
||||
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
|
||||
use super::group::{add_object, group, ungroup};
|
||||
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, shape_size, size};
|
||||
use super::picture::{
|
||||
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
|
||||
};
|
||||
use super::select::{
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
|
||||
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
|
||||
with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_picture, has_any_shape, has_floating, has_group, has_movable, has_object,
|
||||
has_picture, has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box,
|
||||
target_objects, with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
};
|
||||
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
|
||||
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
|
||||
@@ -58,98 +60,112 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"text"?: string, "title"?: string, "decorative"?: bool} (the selected picture, shape, text box, group or chart)"#)
|
||||
.when(has_object),
|
||||
CommandSpec::new("picture.corrections", "Corrections", "Picture Format › Adjust", |s, v| {
|
||||
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
// Absolute from the original (like transparency): re-setting all three to 0
|
||||
// restores the original pixels instead of stacking on the last pass.
|
||||
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, clear_lum, move |img| {
|
||||
let mut img = img;
|
||||
if b != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
|
||||
}
|
||||
if c != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
|
||||
}
|
||||
if sharpen > 0.0 {
|
||||
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
|
||||
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
|
||||
// `blur` asserts on a subnormal width.
|
||||
img = img.blur(-sharpen / 25.0);
|
||||
}
|
||||
Ok(img)
|
||||
each_picture(s, |s| {
|
||||
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
// Absolute from the original (like transparency): re-setting all three to 0
|
||||
// restores the original pixels instead of stacking on the last pass.
|
||||
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, clear_lum, move |img| {
|
||||
let mut img = img;
|
||||
if b != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
|
||||
}
|
||||
if c != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
|
||||
}
|
||||
if sharpen > 0.0 {
|
||||
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
|
||||
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
|
||||
// `blur` asserts on a subnormal width.
|
||||
img = img.blur(-sharpen / 25.0);
|
||||
}
|
||||
Ok(img)
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
|
||||
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
|
||||
let sat = p::f32(v, "saturation").unwrap_or(100.0);
|
||||
// Absolute from the original (like transparency): saturation 100 restores it.
|
||||
// Color and Corrections are independent, as in Word: only Washout, which Word stores
|
||||
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
|
||||
let base = original_media(s)?;
|
||||
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
|
||||
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
|
||||
each_picture(s, |s| {
|
||||
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
|
||||
let sat = p::f32(v, "saturation").unwrap_or(100.0);
|
||||
// Absolute from the original (like transparency): saturation 100 restores it.
|
||||
// Color and Corrections are independent, as in Word: only Washout, which Word stores
|
||||
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
|
||||
let base = original_media(s)?;
|
||||
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
|
||||
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
|
||||
})
|
||||
})
|
||||
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
|
||||
// One colour everywhere, transparency kept: recolours an inserted icon or other
|
||||
// one-colour line art without redrawing it.
|
||||
adjust(s, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0 = [c.0, c.1, c.2, px.0[3]];
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
|
||||
// One colour everywhere, transparency kept: recolours an inserted icon or other
|
||||
// one-colour line art without redrawing it.
|
||||
adjust(s, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0 = [c.0, c.1, c.2, px.0[3]];
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
let e = p::str(v, "effect").unwrap_or("blur").to_string();
|
||||
relook(s, move |l| l.effect = (e != "none").then_some(e))
|
||||
each_picture(s, |s| {
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
let e = p::str(v, "effect").unwrap_or("blur").to_string();
|
||||
relook(s, move |l| l.effect = (e != "none").then_some(e))
|
||||
})
|
||||
})
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
// Absolute, not compounding: 0% is always the original pixels fully opaque.
|
||||
// The base is the pre-edit original (kept for Reset Picture), so dragging a
|
||||
// slider back and forth never fades what a previous pass already faded.
|
||||
// (Combining with other pixel edits then re-setting transparency drops those
|
||||
// edits; a full live-effect stack is future work.)
|
||||
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
|
||||
// into the pixels from here on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
each_picture(s, |s| {
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
// Absolute, not compounding: 0% is always the original pixels fully opaque.
|
||||
// The base is the pre-edit original (kept for Reset Picture), so dragging a
|
||||
// slider back and forth never fades what a previous pass already faded.
|
||||
// (Combining with other pixel edits then re-setting transparency drops those
|
||||
// edits; a full live-effect stack is future work.)
|
||||
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
|
||||
// into the pixels from here on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"percent": 0..100}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
adjust(s, move |img| Ok(remove_background(img, tol)))
|
||||
each_picture(s, |s| {
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
adjust(s, move |img| Ok(remove_background(img, tol)))
|
||||
})
|
||||
})
|
||||
.params(r#"{"tolerance"?: 0..255}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
|
||||
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
|
||||
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
|
||||
each_picture(s, |s| {
|
||||
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
|
||||
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
|
||||
})
|
||||
})
|
||||
.params(r#"{"maxPixels"?: n}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", reset).when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_any_picture),
|
||||
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
|
||||
@@ -184,23 +200,27 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"path"?: string, "data"?: base64}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.style", "Picture Styles", "Picture Format › Picture Styles", |s, v| {
|
||||
// A style replaces the picture's style and border, as Word's gallery does (#2052).
|
||||
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
|
||||
relook(s, move |l| {
|
||||
l.style = Some(style);
|
||||
l.border = None;
|
||||
each_picture(s, |s| {
|
||||
// A style replaces the picture's style and border, as Word's gallery does (#2052).
|
||||
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
|
||||
relook(s, move |l| {
|
||||
l.style = Some(style);
|
||||
l.border = None;
|
||||
})
|
||||
})
|
||||
})
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
|
||||
// Replaces the picture's border, keeping its style (#2052).
|
||||
relook(s, move |l| l.border = Some((c, w)))
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
|
||||
// Replaces the picture's border, keeping its style (#2052).
|
||||
relook(s, move |l| l.border = Some((c, w)))
|
||||
})
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
|
||||
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
|
||||
// picture's pixels are never rewritten. A flip mirrors what is on the page, so a
|
||||
|
||||
@@ -432,6 +432,81 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
|
||||
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_border_uses_picked_pictures_even_when_a_shape_is_primary() {
|
||||
for (picked, expected) in
|
||||
[(&[2, 0][..], [true, false]), (&[2, 0, 1][..], [true, true]), (&[0, 2, 1][..], [true, true]), (&[2][..], [false, false])]
|
||||
{
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
for w in [20, 24] {
|
||||
let data = super::super::insert::base64_encode(&png(w, 10));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
for index in picked {
|
||||
s.run("select.addObject", &json!({"index": index})).unwrap();
|
||||
}
|
||||
let selection = s.sel.clone();
|
||||
let extras = s.also_selected.clone();
|
||||
let undo = s.undo_depth();
|
||||
let shape = |s: &Session| {
|
||||
let (_, object) = all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).unwrap();
|
||||
serde_json::to_value(object).unwrap()
|
||||
};
|
||||
let shape_before = shape(&s);
|
||||
let borders = |s: &Session| {
|
||||
all_objects(s)
|
||||
.into_iter()
|
||||
.filter_map(|(_, o)| match o {
|
||||
InlineObject::Image { media, .. } => Some(s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let result = s.run("picture.border", &json!({"width": 3}));
|
||||
if expected == [false, false] {
|
||||
assert!(result.is_err(), "a shape alone cannot take a picture border");
|
||||
assert_eq!(s.undo_depth(), undo);
|
||||
} else {
|
||||
result.unwrap();
|
||||
assert_eq!(s.undo_depth(), undo + 1);
|
||||
}
|
||||
assert_eq!(s.sel, selection);
|
||||
assert_eq!(s.also_selected, extras);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
assert_eq!(borders(&s), expected);
|
||||
if expected != [false, false] {
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(borders(&s), [false, false]);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #8832: a picture command on several selected pictures changes each, in one undo step.
|
||||
#[test]
|
||||
fn picture_border_applies_to_every_selected_picture() {
|
||||
let data = super::super::insert::base64_encode(&png(20, 10));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
let media = |s: &Session| {
|
||||
all_objects(s)
|
||||
.into_iter()
|
||||
.map(|(_, o)| matches!(o, InlineObject::Image { media, .. } if s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(media(&s), [false, false]);
|
||||
s.run("picture.border", &json!({"width": 3})).unwrap();
|
||||
assert_eq!(media(&s), [true, true]);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(media(&s), [false, false]);
|
||||
}
|
||||
|
||||
/// #2019: Insert › Shapes adds each new shape beside the selected one, as Word draws it, so
|
||||
/// shapes inserted in a row are all kept (the second used to replace the first, which stays
|
||||
/// selected after its insert). Selected text stays too, and the new shape is selected.
|
||||
@@ -2245,3 +2320,55 @@ fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
|
||||
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
|
||||
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_format_commands_stay_enabled_when_shape_is_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then one picture added.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.border", &json!({"color": "FF0000", "width": 3})).unwrap();
|
||||
assert!(matches!(
|
||||
&all_objects(&s)[1].1,
|
||||
InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.border.is_some())
|
||||
));
|
||||
|
||||
// Shape clicked first, then two pictures added.
|
||||
s.run("select.addObject", &json!({"index": 2})).unwrap();
|
||||
s.run("picture.style", &json!({"style": "rounded"})).unwrap();
|
||||
let objs = all_objects(&s);
|
||||
for idx in [1, 2] {
|
||||
assert!(
|
||||
matches!(&objs[idx].1, InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.style.as_deref() == Some("rounded"))),
|
||||
"picture {idx} should get rounded style"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_object_picture_commands_need_the_picture_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then the picture added: Crop, Change Picture and Alt Text would act on the shape.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
for (cmd, args) in [("picture.crop", json!({"left": 0.1})), ("picture.altText", json!({"text": "x"})), ("picture.change", json!({"data": data}))]
|
||||
{
|
||||
assert!(matches!(s.run(cmd, &args), Err(CmdError::Disabled(_))), "{cmd}");
|
||||
}
|
||||
|
||||
// Picture first: enabled.
|
||||
s.run("select.objects", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.crop", &json!({"left": 0.1})).unwrap();
|
||||
}
|
||||
|
||||
@@ -287,9 +287,39 @@ fn prepare_custom_dictionary(s: &Session, setting: Option<&str>) -> Result<(Opti
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's home folder: `USERPROFILE` first on Windows, `HOME` first elsewhere, skipping
|
||||
/// empty values. The recent list reads it in the same order (#8865), so `~/…` means one folder.
|
||||
fn home_dir() -> Option<std::path::PathBuf> {
|
||||
home_from(std::env::var_os("HOME"), std::env::var_os("USERPROFILE"))
|
||||
}
|
||||
|
||||
/// [`home_dir`] without the environment: the order the two values are read in depends on the
|
||||
/// platform, so it takes them as they are read.
|
||||
fn home_from(home: Option<std::ffi::OsString>, userprofile: Option<std::ffi::OsString>) -> Option<std::path::PathBuf> {
|
||||
let set = |v: Option<std::ffi::OsString>| v.filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let (first, second) = if cfg!(windows) { (userprofile, home) } else { (home, userprofile) };
|
||||
set(first).or_else(|| set(second))
|
||||
}
|
||||
|
||||
/// Expand a file or folder path under the home folder with the saved settings' platform-specific prefix.
|
||||
fn expand_home(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<std::path::PathBuf, CmdError> {
|
||||
let prefix = if cfg!(windows) && f.starts_with("~\\") { "~\\" } else { "~/" };
|
||||
let Some(rest) = f.strip_prefix(prefix) else { return Ok(std::path::PathBuf::from(f)) };
|
||||
let Some(home) = home else {
|
||||
return Err(CmdError::Params(format!("`{key}`: cannot expand `{prefix}` because HOME or USERPROFILE is not set")));
|
||||
};
|
||||
// A Windows drive, device or root in the suffix would replace the home path on join.
|
||||
if prefix == "~\\"
|
||||
&& matches!(std::path::Path::new(rest).components().next(), Some(std::path::Component::Prefix(_) | std::path::Component::RootDir))
|
||||
{
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} must be relative to the home folder")));
|
||||
}
|
||||
Ok(home.join(rest))
|
||||
}
|
||||
|
||||
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/`. With
|
||||
/// `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
/// With `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// that it exists would make Windows authenticate to that host.
|
||||
fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
@@ -299,11 +329,7 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
|
||||
return Err(CmdError::Params(format!("`{key}` isn't a folder path")));
|
||||
}
|
||||
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let path = match (f.strip_prefix("~/"), home) {
|
||||
(Some(rest), Some(h)) => h.join(rest),
|
||||
_ => std::path::PathBuf::from(f),
|
||||
};
|
||||
let path = expand_home(key, f, home_dir().as_deref())?;
|
||||
if local_only && (super::templates::is_network_path(f) || super::templates::is_network_path(&path.to_string_lossy())) {
|
||||
return Err(CmdError::Params(format!("`{key}` can't be a network folder")));
|
||||
}
|
||||
@@ -319,8 +345,12 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
}
|
||||
|
||||
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
|
||||
/// file, given as an absolute path or one starting with `~/`.
|
||||
/// file, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
file_setting_in(key, f, home_dir().as_deref())
|
||||
}
|
||||
|
||||
fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
|
||||
return Ok(None);
|
||||
@@ -328,15 +358,7 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
|
||||
return Err(CmdError::Params(format!("`{key}` isn't a file path")));
|
||||
}
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let path = if let Some(rest) = f.strip_prefix("~/") {
|
||||
match home {
|
||||
Some(h) => h.join(rest),
|
||||
None => return Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
|
||||
}
|
||||
} else {
|
||||
std::path::PathBuf::from(f)
|
||||
};
|
||||
let path = expand_home(key, f, home)?;
|
||||
if !path.is_absolute() {
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} isn't a full path")));
|
||||
}
|
||||
@@ -355,3 +377,90 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
pub fn use_dictionaries_folder(folder: Option<&str>) {
|
||||
wordcraft_proof::set_dictionaries_folder(folder.map(std::path::PathBuf::from));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{expand_home, file_setting_in, home_from};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn os(s: &str) -> Option<OsString> {
|
||||
Some(OsString::from(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_home_folder_is_the_profile_folder_on_windows_and_home_elsewhere() {
|
||||
let home = home_from(os("/home/u"), os("C:\\Users\\u"));
|
||||
let expected = if cfg!(windows) { PathBuf::from("C:\\Users\\u") } else { PathBuf::from("/home/u") };
|
||||
assert_eq!(home, Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_home_folder_is_skipped_for_the_other_one() {
|
||||
assert_eq!(home_from(os(""), os("C:\\Users\\u")), Some(PathBuf::from("C:\\Users\\u")));
|
||||
assert_eq!(home_from(os(""), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_home_folder_at_all_expands_to_nothing() {
|
||||
assert_eq!(home_from(None, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilde_path_expands_under_the_home_folder() {
|
||||
let home = Path::new("/home/u");
|
||||
assert_eq!(expand_home("dictionariesFolder", "~/dic", Some(home)).unwrap(), PathBuf::from("/home/u/dic"));
|
||||
assert_eq!(expand_home("dictionariesFolder", "/abs/dic", Some(home)).unwrap(), PathBuf::from("/abs/dic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilde_path_without_a_home_folder_is_refused() {
|
||||
let err = expand_home("dictionariesFolder", "~/dic", None).unwrap_err();
|
||||
assert!(format!("{err:?}").contains("cannot expand"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_expands_tilde_with_the_same_platform_prefix() {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
struct TempHome(PathBuf);
|
||||
impl TempHome {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
impl Drop for TempHome {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
let dir = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let candidate = std::env::temp_dir().join(format!("wc-options-home-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break TempHome(candidate),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", candidate.display()),
|
||||
}
|
||||
};
|
||||
let dic = dir.0.join("custom.dic");
|
||||
std::fs::write(&dic, "wordcraftdictionary\n").unwrap();
|
||||
let expected = dic.to_string_lossy().into_owned();
|
||||
|
||||
assert_eq!(file_setting_in("customDictionary", "~/custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let missing_home = file_setting_in("customDictionary", "~/custom.dic", None).unwrap_err();
|
||||
assert!(format!("{missing_home:?}").contains("cannot expand"), "{missing_home:?}");
|
||||
if cfg!(windows) {
|
||||
assert_eq!(file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let drive = file_setting_in("customDictionary", r"~\C:\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{drive:?}").contains("relative to the home folder"), "{drive:?}");
|
||||
} else {
|
||||
let backslash = file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{backslash:?}").contains("isn't a full path"), "{backslash:?}");
|
||||
}
|
||||
dir.remove().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::packs::{Backend, FixedBackend};
|
||||
|
||||
/// Tests that set the process-wide backend take turns.
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
|
||||
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
|
||||
|
||||
/// Puts the process back to no backend and no background thread when dropped, even when
|
||||
/// the test panicked.
|
||||
|
||||
@@ -224,8 +224,51 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
|
||||
}
|
||||
|
||||
/// Whether `sec` displays header/footer part `id` (directly or inherited from an earlier section).
|
||||
pub(crate) fn section_uses_hf_part(sections: &[(usize, &SectionProps)], sec: usize, id: u32) -> bool {
|
||||
let slice = sections.get(..=sec).unwrap_or(sections);
|
||||
[
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.headers.default),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.headers.first),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.headers.even),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.footers.default),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.footers.first),
|
||||
slice.iter().rev().find_map(|(_, sp)| sp.footers.even),
|
||||
]
|
||||
.contains(&Some(id))
|
||||
}
|
||||
|
||||
/// Resolve the section index associated with a header, footer, or note part `id`.
|
||||
pub(crate) fn section_of_part(s: &Session, id: u32) -> usize {
|
||||
let sections = s.doc.sections();
|
||||
if s.doc.parts.get(&id).is_some_and(|p| matches!(p.kind, wordcraft_doc::PartKind::Header | wordcraft_doc::PartKind::Footer)) {
|
||||
let uses_hf = |sec: usize| section_uses_hf_part(§ions, sec, id);
|
||||
// The section of the page whose header or footer was opened decides: a footer inherited from
|
||||
// an earlier section still belongs to the later section that shows it. It is kept apart
|
||||
// from the page hint because a taller footer can repaginate the pages under it.
|
||||
if let Some(sec) = s.hf_section.map(|sec| sec.min(sections.len().saturating_sub(1)))
|
||||
&& uses_hf(sec)
|
||||
{
|
||||
return sec;
|
||||
}
|
||||
// Entered without a page (Insert › Header, a page number): the page the hint names.
|
||||
if let Some(pg) = s.cached_layout().and_then(|l| l.pages.get(s.page_hint)) {
|
||||
let sec = pg.section.min(sections.len().saturating_sub(1));
|
||||
if uses_hf(sec) {
|
||||
return sec;
|
||||
}
|
||||
}
|
||||
// Neither names a section that uses it (a stale page hint): the body position the header
|
||||
// was entered from.
|
||||
if let Some(ret) = &s.hf_return
|
||||
&& ret.focus.story == wordcraft_doc::StoryRef::Body
|
||||
{
|
||||
let sec = s.doc.section_index_of(ret.focus.path.0.first().copied().unwrap_or(0) as usize);
|
||||
if uses_hf(sec) {
|
||||
return sec;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, (_, sp)) in sections.iter().enumerate() {
|
||||
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
|
||||
return i;
|
||||
@@ -289,8 +332,15 @@ fn selected_section_ends(s: &Session) -> Vec<usize> {
|
||||
(first..=last).map(|k| ends.get(k).copied().unwrap_or(0)).collect()
|
||||
}
|
||||
|
||||
/// Apply to the section(s) of the selection.
|
||||
/// Apply a mutation to each section touched by the current selection.
|
||||
///
|
||||
/// When the caret or selection is outside the body (such as in a header, footer, or note),
|
||||
/// refreshes the layout so the section resolved from the cached layout reflects the current
|
||||
/// document state before mutating section properties.
|
||||
pub(crate) fn with_sect(s: &mut Session, f: impl Fn(&mut SectionProps)) -> CmdResult {
|
||||
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
|
||||
let _ = s.layout();
|
||||
}
|
||||
for block in selected_section_ends(s) {
|
||||
f(s.doc.section_mut(block));
|
||||
}
|
||||
@@ -514,26 +564,31 @@ fn border_sides_mut(b: &mut Borders) -> impl Iterator<Item = &mut Border> {
|
||||
|
||||
fn margins(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let preset = p::str(v, "preset");
|
||||
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
|
||||
let _ = s.layout();
|
||||
}
|
||||
let (t, b, l, r) = match preset {
|
||||
Some(x) => match MARGIN_PRESETS.iter().find(|(id, _)| *id == x) {
|
||||
Some((_, [t, b, l, r])) => (*t, *b, *l, *r),
|
||||
None => return Err(CmdError::Params(format!("unknown preset `{x}`"))),
|
||||
},
|
||||
None => {
|
||||
// A negative margin given counts as zero; one left out keeps its value, so an exact
|
||||
// (negative) top or bottom from the file stays exact when another side changes, as
|
||||
// in Word.
|
||||
let c = sect(s);
|
||||
let given = |k: &str| p::f32(v, k).map(|m| m.max(0.0));
|
||||
(
|
||||
p::f32(v, "top").unwrap_or(c.margin_top),
|
||||
p::f32(v, "bottom").unwrap_or(c.margin_bottom),
|
||||
p::f32(v, "left").unwrap_or(c.margin_left),
|
||||
p::f32(v, "right").unwrap_or(c.margin_right),
|
||||
given("top").unwrap_or(c.margin_top),
|
||||
given("bottom").unwrap_or(c.margin_bottom),
|
||||
given("left").unwrap_or(c.margin_left.max(0.0)),
|
||||
given("right").unwrap_or(c.margin_right.max(0.0)),
|
||||
)
|
||||
}
|
||||
};
|
||||
// Negative margins count as zero before the fit check, so one can't offset another.
|
||||
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
|
||||
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
|
||||
let cur = sect(s);
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t.abs(), b.abs(), l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
return Err(CmdError::Params("margins leave no room for text".into()));
|
||||
}
|
||||
// A preset picks mirrored or not, as does `mirror` (Page Setup's Multiple pages); plain numbers
|
||||
@@ -569,6 +624,7 @@ pub fn margins_fit(page: (f32, f32), (t, b, l, r): (f32, f32, f32, f32), gutter:
|
||||
pub const MIN_PAGE_SIDE: f32 = 7.2;
|
||||
pub const MAX_PAGE_SIDE: f32 = 1584.0;
|
||||
|
||||
/// Change paper size of the selected section(s) to the given dimensions or preset name.
|
||||
fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (w, h) = if let Some(n) = p::str(v, "name") {
|
||||
let (_, w, h) = wordcraft_geom::PAPER_SIZES
|
||||
@@ -583,12 +639,15 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (w, h) = (w.clamp(MIN_PAGE_SIDE, MAX_PAGE_SIDE), h.clamp(MIN_PAGE_SIDE, MAX_PAGE_SIDE));
|
||||
// Each section keeps its orientation: the long side across in landscape, down in portrait.
|
||||
let oriented = |x: &SectionProps| if x.landscape { (w.max(h), w.min(h)) } else { (w.min(h), w.max(h)) };
|
||||
if s.sel.focus.story != wordcraft_doc::StoryRef::Body {
|
||||
let _ = s.layout();
|
||||
}
|
||||
let sections = s.doc.sections();
|
||||
let fits = |block: usize| {
|
||||
sections
|
||||
.iter()
|
||||
.find(|(e, _)| *e == block)
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), x.gutter))
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top.abs(), x.margin_bottom.abs(), x.margin_left, x.margin_right), x.gutter))
|
||||
};
|
||||
if !selected_section_ends(s).into_iter().all(fits) {
|
||||
return Err(CmdError::Params(MARGINS_DONT_FIT.into()));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
fn doc() -> Session {
|
||||
Session::new(wordcraft_doc::Document::from_text("one\ntwo\nthree"))
|
||||
@@ -417,7 +418,6 @@ fn hyphenation_options_and_manual_hyphenation() {
|
||||
/// section" (#1113).
|
||||
#[test]
|
||||
fn page_number_format_keeps_or_clears_the_start() {
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
let mut s = doc();
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "upperRoman", "start": 3})).unwrap();
|
||||
let x = sect(&s);
|
||||
@@ -432,4 +432,458 @@ fn page_number_format_keeps_or_clears_the_start() {
|
||||
let back = s.run("layout.pageNumberFormat", &json!({"format": "decimal", "start": 1})).unwrap();
|
||||
assert_eq!(back["pageNumFormat"], "decimal");
|
||||
assert_eq!(back["pageNumStart"], 1);
|
||||
|
||||
// #5855: from a linked footer on a later section's page, `sect` and `layout.pageNumberFormat`
|
||||
// read and update that page's section, not the earlier section that defined the footer.
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 5})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(5)));
|
||||
assert_eq!(s.layout().pages[1].number, 5);
|
||||
}
|
||||
|
||||
/// Section commands from an inherited footer target the active section rather than section 0.
|
||||
#[test]
|
||||
fn section_command_from_inherited_footer_targets_active_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert!(!secs[0].1.landscape);
|
||||
assert!(secs[1].1.landscape);
|
||||
|
||||
// layout.size also targets the active section from an inherited footer.
|
||||
s.run("layout.size", &json!({"name": "A5"})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
let a5 = wordcraft_geom::PAPER_SIZES.iter().find(|(n, _, _)| *n == "A5").unwrap();
|
||||
assert_ne!((secs[0].1.page_w, secs[0].1.page_h), (a5.1.max(a5.2), a5.1.min(a5.2)));
|
||||
assert_eq!((secs[1].1.page_w, secs[1].1.page_h), (a5.1.max(a5.2), a5.1.min(a5.2)));
|
||||
}
|
||||
|
||||
/// Inserting a page number while editing an inherited footer preserves the inherited content
|
||||
/// and keeps both sections sharing the footer part without unlinking.
|
||||
#[test]
|
||||
fn inherited_footer_preserves_content_when_numbering_from_inherited_footer() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Edit the inherited footer from section 1's page.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Insert page number at bottom of page.
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom", "align": "right"})).unwrap();
|
||||
|
||||
// Verify footer text retains "Footer on sec 0" as well as the PAGE field.
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!(secs[1].1.footers.default, None, "section 1 continues to inherit footer from section 0");
|
||||
let fid = secs[0].1.footers.default.expect("section 0 footer exists");
|
||||
let footer_text = s.doc.plain_text(wordcraft_doc::StoryRef::Part(fid));
|
||||
assert!(footer_text.contains("Footer on sec 0"), "inherited footer content was preserved");
|
||||
let has_page_field = s.doc.story(wordcraft_doc::StoryRef::Part(fid)).is_some_and(|blocks| {
|
||||
blocks.iter().any(|b| match &**b {
|
||||
wordcraft_doc::Block::Para(p) => p.objects.iter().any(|obj| match obj {
|
||||
wordcraft_doc::InlineObject::Field { instr, .. } | wordcraft_doc::InlineObject::FieldStart { instr, .. } => {
|
||||
instr.split_whitespace().next().is_some_and(|name| name.eq_ignore_ascii_case("PAGE"))
|
||||
}
|
||||
_ => false,
|
||||
}),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
assert!(has_page_field, "footer contains the PAGE field");
|
||||
|
||||
// Both page 0 and page 1 render the shared footer with page numbers.
|
||||
let l = s.layout();
|
||||
assert_eq!(l.pages[0].footer_story, Some(fid));
|
||||
assert_eq!(l.pages[1].footer_story, Some(fid));
|
||||
}
|
||||
|
||||
/// Inserting a page number into the footer while editing an inherited header preserves the
|
||||
/// inherited footer content and keeps both sections sharing the footer part without unlinking.
|
||||
#[test]
|
||||
fn inherited_footer_preserves_content_when_numbering_from_inherited_header() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
// Set up header and footer in section 0.
|
||||
s.run("insert.editHeader", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Header on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on sec 0"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Edit the inherited header from section 1's page.
|
||||
s.run("insert.editHeader", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Insert page number at bottom of page (into the footer).
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom", "align": "right"})).unwrap();
|
||||
|
||||
// Verify footer text retains "Footer on sec 0" as well as the PAGE field.
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!(secs[1].1.footers.default, None, "section 1 continues to inherit footer from section 0");
|
||||
let fid = secs[0].1.footers.default.expect("section 0 footer exists");
|
||||
let footer_text = s.doc.plain_text(wordcraft_doc::StoryRef::Part(fid));
|
||||
assert!(footer_text.contains("Footer on sec 0"), "inherited footer content was preserved");
|
||||
let has_page_field = s.doc.story(wordcraft_doc::StoryRef::Part(fid)).is_some_and(|blocks| {
|
||||
blocks.iter().any(|b| match &**b {
|
||||
wordcraft_doc::Block::Para(p) => p.objects.iter().any(|obj| match obj {
|
||||
wordcraft_doc::InlineObject::Field { instr, .. } | wordcraft_doc::InlineObject::FieldStart { instr, .. } => {
|
||||
instr.split_whitespace().next().is_some_and(|name| name.eq_ignore_ascii_case("PAGE"))
|
||||
}
|
||||
_ => false,
|
||||
}),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
assert!(has_page_field, "footer contains the PAGE field");
|
||||
|
||||
// Both page 0 and page 1 render the shared footer with page numbers.
|
||||
let l = s.layout();
|
||||
assert_eq!(l.pages[0].footer_story, Some(fid));
|
||||
assert_eq!(l.pages[1].footer_story, Some(fid));
|
||||
}
|
||||
|
||||
/// When a shared footer grows and repagination causes the preceding section to expand
|
||||
/// onto the hinted page, the active section being edited is preserved rather than
|
||||
/// reverting to the preceding section.
|
||||
#[test]
|
||||
fn repagination_during_shared_footer_edit_preserves_active_section() {
|
||||
// Determine the line count that exactly fills 1 page with a single-line footer.
|
||||
let mut n_lines: usize = 10;
|
||||
while n_lines < 100 {
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
if s.layout().pages.len() == 1 {
|
||||
n_lines += 1;
|
||||
} else {
|
||||
n_lines = n_lines.saturating_sub(3);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section 1 body"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Verify initial layout: Section 0 is on page 0, Section 1 is on page 1.
|
||||
let l = s.layout();
|
||||
assert_eq!(l.pages.len(), 2);
|
||||
assert_eq!(l.pages[0].section, 0);
|
||||
assert_eq!(l.pages[1].section, 1);
|
||||
|
||||
// Edit inherited footer from section 1's page.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Expand the shared footer so section 0 no longer fits on 1 page and spills onto page 1.
|
||||
for _ in 0..8 {
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Expanded footer row"})).unwrap();
|
||||
}
|
||||
|
||||
// Verify repagination: Section 0 now occupies page 0 and page 1; Section 1 is pushed to page 2.
|
||||
let l = s.layout();
|
||||
assert!(l.pages.len() >= 3);
|
||||
assert_eq!(l.pages[0].section, 0);
|
||||
assert_eq!(l.pages[1].section, 0, "page 1 now occupied by section 0");
|
||||
assert_eq!(l.pages[2].section, 1, "section 1 pushed to page 2");
|
||||
|
||||
// The active section being edited remains section 1 despite page 1 now holding section 0.
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Formatting page numbers updates section 1 rather than section 0.
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 10})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(10)));
|
||||
}
|
||||
|
||||
/// Section commands follow the page whose header or footer is open, not the body caret's section.
|
||||
#[test]
|
||||
fn section_commands_follow_the_page_being_edited() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
let body_end = s.doc.end_of(StoryRef::Body);
|
||||
s.sel = Selection::caret(body_end.clone());
|
||||
// Page 0 is the first section's, page 1 the second's.
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer on the first section"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
assert_eq!(s.sel, Selection::caret(body_end), "close returns to the body caret");
|
||||
// Editing page 1's footer (inherited) acts on section 1...
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
// ...and going back to page 0's own footer acts on section 0, though the body caret is in 1.
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 0);
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert!(secs[0].1.landscape, "the section whose footer is open");
|
||||
assert!(!secs[1].1.landscape);
|
||||
}
|
||||
|
||||
/// #5855: an out-of-range `insert.createFooter` page leaves the active header/footer section intact.
|
||||
#[test]
|
||||
fn create_footer_out_of_range_page_preserves_active_hf_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Edit page 1's inherited footer (active section 1), then fail `insert.createFooter` with an
|
||||
// out-of-range page number.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
assert!(s.run("insert.createFooter", &json!({"page": 99})).is_err());
|
||||
|
||||
// Section targeting still points at section 1 rather than falling back to section 0.
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 7})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(7)));
|
||||
}
|
||||
|
||||
/// #5855: `take_view`/`put_view` preserves `hf_section` when section structure matches, and clears
|
||||
/// it when a section break is added or removed across another edit.
|
||||
#[test]
|
||||
fn take_view_put_view_tracks_hf_section_across_revisions_and_section_breaks() {
|
||||
// Build a two-section document whose expanded shared footer causes section 0 to spill onto
|
||||
// page 1 and push section 1 to page 2.
|
||||
let mut n_lines: usize = 10;
|
||||
while n_lines < 100 {
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
if s.layout().pages.len() == 1 {
|
||||
n_lines += 1;
|
||||
} else {
|
||||
n_lines = n_lines.saturating_sub(3);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let lines = (0..n_lines).map(|i| format!("Line {i}")).collect::<Vec<_>>().join("\n");
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(&lines));
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section 1 body"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
// Open section 1's inherited footer on page 1, then expand the footer so page 1 belongs to
|
||||
// section 0 while `hf_section` still targets section 1.
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
for _ in 0..8 {
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Expanded footer row"})).unwrap();
|
||||
}
|
||||
assert_eq!(s.layout().pages[1].section, 0);
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Same revision (`current == true`): `put_view` restores `hf_section`.
|
||||
let same_rev_view = s.take_view();
|
||||
s.put_view(same_rev_view);
|
||||
assert_eq!(section_index_of_focus(&s), 1, "same-revision view swap keeps hf_section");
|
||||
|
||||
// Revision changed without changing section breaks: `put_view` still preserves `hf_section`.
|
||||
let view_before_format = s.take_view();
|
||||
s.run("select.text", &json!({"text": "Line 0"})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
s.put_view(view_before_format);
|
||||
assert_eq!(section_index_of_focus(&s), 1, "unchanged section breaks preserve hf_section across revision bump");
|
||||
|
||||
// Revision changed with a section break added: stale `hf_section` is cleared and resolution
|
||||
// falls back to `page_hint` (page 1 -> section 0) once layout is refreshed.
|
||||
let view_before_added_break = s.take_view();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Section 2"})).unwrap();
|
||||
s.put_view(view_before_added_break);
|
||||
assert_eq!(s.hf_section, None);
|
||||
let _ = s.layout();
|
||||
assert_eq!(section_index_of_focus(&s), 0, "adding a section break clears stale hf_section");
|
||||
|
||||
// Revision changed with a section break removed in a 3-section document: stale `hf_section`
|
||||
// (`Some(2)`) is cleared rather than clamping onto section 1, both before and after relayout.
|
||||
let mut s3 = Session::new(wordcraft_doc::Document::from_text("s0\ns1\ns2"));
|
||||
s3.run("select.text", &json!({"text": "s0"})).unwrap();
|
||||
s3.run("caret.end", &json!({})).unwrap();
|
||||
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s3.run("select.text", &json!({"text": "s1"})).unwrap();
|
||||
s3.run("caret.end", &json!({})).unwrap();
|
||||
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s3.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s3.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s3.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s3.run("caret.docStart", &json!({})).unwrap();
|
||||
s3.run("insert.editFooter", &json!({"page": 2})).unwrap();
|
||||
assert_eq!(section_index_of_focus(&s3), 2);
|
||||
let view3 = s3.take_view();
|
||||
s3.run("select.all", &json!({})).unwrap();
|
||||
s3.run("text.insert", &json!({"text": "a"})).unwrap();
|
||||
s3.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s3.run("text.insert", &json!({"text": "b"})).unwrap();
|
||||
s3.put_view(view3);
|
||||
assert_eq!(s3.hf_section, None);
|
||||
assert_eq!(section_index_of_focus(&s3), 0, "stale cached layout does not clamp onto section 1");
|
||||
let _ = s3.layout();
|
||||
assert_eq!(section_index_of_focus(&s3), 0, "removing a section break clears stale hf_section");
|
||||
}
|
||||
|
||||
/// #5855: `preview_layout` copies the active header/footer section context so previews target the
|
||||
/// section whose inherited footer is being edited.
|
||||
#[test]
|
||||
fn preview_layout_formats_active_inherited_section_footer() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
let (doc, _sel, layout) = s.preview_layout("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 7})).unwrap();
|
||||
let secs = doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(7)));
|
||||
let page1_footer: String = layout.pages[1]
|
||||
.footer
|
||||
.iter()
|
||||
.flat_map(|it| match it {
|
||||
crate::layout::Placed::Lines { para, .. } => para.shown.iter().map(|part| part.1.clone()).collect::<Vec<_>>(),
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
assert!(page1_footer.contains("vii"), "preview renders section 1 footer as vii, got {page1_footer:?}");
|
||||
}
|
||||
|
||||
/// #5855: Moving the caret into a linked footer on another page (via click or keyboard without
|
||||
/// re-running `editFooter`) updates `hf_section` so section commands target that page's section.
|
||||
#[test]
|
||||
fn linked_footer_caret_move_updates_hf_section_without_edit_footer() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
|
||||
// Enter footer on page 0 (section 0) and insert a page number; section 1 inherits it.
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("insert.pageNumber", &json!({"position": "bottom"})).unwrap();
|
||||
assert_eq!(s.hf_section, Some(0));
|
||||
assert_eq!(section_index_of_focus(&s), 0);
|
||||
|
||||
// Move caret into the same linked footer on page 1 without calling `insert.editFooter`.
|
||||
let (x, y) = {
|
||||
let l = s.layout();
|
||||
let c = l.caret_on(&s.sel.focus, 1).expect("linked footer laid out on page 1");
|
||||
(c.x, c.top + c.height * 0.5)
|
||||
};
|
||||
let story = match s.sel.focus.story {
|
||||
wordcraft_doc::StoryRef::Part(id) => format!("part:{id}"),
|
||||
wordcraft_doc::StoryRef::Body => "body".to_string(),
|
||||
};
|
||||
s.run("caret.set", &json!({"page": 1, "x": x, "y": y, "story": story})).unwrap();
|
||||
assert_eq!(s.hf_section, Some(1));
|
||||
assert_eq!(section_index_of_focus(&s), 1);
|
||||
|
||||
// Formatting page numbers now updates section 1, leaving section 0 untouched.
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 5})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!((secs[0].1.page_num_format, secs[0].1.page_num_start), (NumFormat::Decimal, None));
|
||||
assert_eq!((secs[1].1.page_num_format, secs[1].1.page_num_start), (NumFormat::LowerRoman, Some(5)));
|
||||
}
|
||||
|
||||
/// #5855: `layout.margins` refreshes layout before reading existing edges when editing a header/footer.
|
||||
#[test]
|
||||
fn margins_from_inherited_footer_targets_active_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("front\nbody"));
|
||||
s.run("select.text", &json!({"text": "front"})).unwrap();
|
||||
s.run("caret.end", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("layout.margins", &json!({"top": 108.0})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 0})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Shared footer"})).unwrap();
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
|
||||
s.run("insert.editFooter", &json!({"page": 1})).unwrap();
|
||||
s.run("layout.margins", &json!({"left": 90.0})).unwrap();
|
||||
let secs = s.doc.sections();
|
||||
assert_eq!(secs[0].1.margin_left, SectionProps::default().margin_left);
|
||||
assert_eq!(secs[1].1.margin_left, 90.0);
|
||||
assert_eq!(secs[1].1.margin_top, 108.0);
|
||||
}
|
||||
|
||||
/// An exact (negative) top or bottom margin survives Margins and Orientation: changing another
|
||||
/// margin keeps it exact, and turning the page moves its size, as a plain margin, to the side it
|
||||
/// goes to.
|
||||
#[test]
|
||||
fn exact_margins_survive_margins_and_orientation() {
|
||||
let mut s = doc();
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.doc.last_section.margin_bottom = -40.0;
|
||||
s.run("layout.margins", &json!({"left": 80.0})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0));
|
||||
// A negative margin given still counts as zero.
|
||||
s.run("layout.margins", &json!({"top": -30.0})).unwrap();
|
||||
assert_eq!((s.doc.last_section.margin_top, s.doc.last_section.margin_bottom), (0.0, -40.0));
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert!(x.margin_left >= 0.0 && x.margin_right >= 0.0, "{x:?}");
|
||||
let mut sides = [x.margin_left, x.margin_right];
|
||||
sides.sort_by(f32::total_cmp);
|
||||
assert_eq!(sides, [40.0, 60.0], "the exact margins' sizes go to the sides");
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ mod styles;
|
||||
mod tabs_borders;
|
||||
mod tools;
|
||||
|
||||
pub(super) use format::drop_direct_indents;
|
||||
use format::{align, asian_typography, cur, direction, line_spacing, ls, set_align, set_props, tog};
|
||||
pub use format::{cur as selection_para, fmt, indent, outdent};
|
||||
pub use lists::{ListButtons, list_buttons, manage_list, touch_all};
|
||||
@@ -166,13 +167,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("para.heading3", "Heading 3", "Home › Styles", |s, _| apply_style(s, &json!({"style": "Heading3"}))).key("Mod+Alt+3"),
|
||||
CommandSpec::new("para.bullets", "Bullets", "Home › Paragraph", |s, v| list(s, v, ListKind::Bullet)).params(r#"{"kind"?: "bullet" | single char, "off"?: bool}"#).key("Mod+Shift+L"),
|
||||
CommandSpec::new("para.numbering", "Numbering", "Home › Paragraph", |s, v| list(s, v, ListKind::Numbered))
|
||||
.params(r#"{"kind"?: "numbered|numberedParen|upperLetter|lowerLetter|lowerRoman|outline", "off"?: bool}"#),
|
||||
.params(r#"{"kind"?: "numbered|numberedParen|outline|upperLetter|lowerLetter|lowerLetterDot|lowerRoman", "off"?: bool}"#),
|
||||
CommandSpec::new("para.multilevel", "Multilevel List", "Home › Paragraph", |s, v| list(s, v, ListKind::Legal)).params(r#"{"kind"?: "legal|outline"}"#),
|
||||
CommandSpec::new("para.listLevel", "Change List Level", "Home › Paragraph › Bullets", |s, v| {
|
||||
let lvl = p::u64(v, "level").unwrap_or(0).min(8) as u8;
|
||||
fmt(s, &|p| {
|
||||
if let Some(n) = p.numbering.as_mut() {
|
||||
let moved = n.level != lvl;
|
||||
n.level = lvl;
|
||||
if moved {
|
||||
format::drop_direct_indents(p);
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -163,6 +163,16 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// A list item that moves to another level takes that level's indents: a direct indent (a ruler
|
||||
/// drag, a pasted block, a Word file's `w:ind`) would otherwise win over them and leave the item
|
||||
/// out of line with its level (#4287).
|
||||
pub(in crate::cmd) fn drop_direct_indents(p: &mut ParaProps) {
|
||||
p.indent_left = None;
|
||||
p.indent_first = None;
|
||||
p.indent_left_chars = None;
|
||||
p.indent_first_chars = None;
|
||||
}
|
||||
|
||||
pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let a = s.sel.ordered().0;
|
||||
let paths = crate::cmd::selected_paths(s);
|
||||
@@ -174,7 +184,13 @@ pub fn indent(s: &mut Session, _: &Value) -> CmdResult {
|
||||
};
|
||||
let para = s.doc.para_mut(a.story, &path)?;
|
||||
match num {
|
||||
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) }),
|
||||
Some(n) => {
|
||||
let level = n.level.saturating_add(1).min(8);
|
||||
para.props.numbering = Some(NumRef { num: n.num, level });
|
||||
if level != n.level {
|
||||
drop_direct_indents(&mut para.props);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
para.props.indent_left = Some(((left / tab).floor() + 1.0) * tab);
|
||||
para.props.cancel_char_indents(true, false, false);
|
||||
@@ -196,7 +212,13 @@ pub fn outdent(s: &mut Session, _: &Value) -> CmdResult {
|
||||
};
|
||||
let para = s.doc.para_mut(a.story, &path)?;
|
||||
match num {
|
||||
Some(n) => para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) }),
|
||||
Some(n) => {
|
||||
let level = n.level.saturating_sub(1);
|
||||
para.props.numbering = Some(NumRef { num: n.num, level });
|
||||
if level != n.level {
|
||||
drop_direct_indents(&mut para.props);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
para.props.indent_left = Some((((left / tab).ceil() - 1.0) * tab).max(0.0));
|
||||
para.props.cancel_char_indents(true, false, false);
|
||||
|
||||
@@ -13,13 +13,24 @@ pub(super) fn list(s: &mut Session, v: &Value, default: ListKind) -> CmdResult {
|
||||
.map(|p| s.doc.para(a.story, p).and_then(|x| s.doc.styles.resolve_para(&x.props).numbering).filter(|n| n.num != 0))
|
||||
.collect();
|
||||
let same_kind = |n: &NumRef| {
|
||||
s.doc.numbering.level(n.num, n.level).is_some_and(|l| {
|
||||
let want = wordcraft_doc::numbering::levels_for(kind);
|
||||
want.get(usize::from(n.level)).is_some_and(|w| {
|
||||
let want = wordcraft_doc::numbering::levels_for(kind);
|
||||
// Is the list's level `i` (with this list's own overrides) the preset's level `i`?
|
||||
let level_is = |i: u8, with_text: bool| match (s.doc.numbering.level(n.num, i), want.get(usize::from(i))) {
|
||||
(Some(l), Some(w)) => {
|
||||
(w.format == wordcraft_doc::section::NumFormat::Bullet) == (l.format == wordcraft_doc::section::NumFormat::Bullet)
|
||||
&& (p::str(v, "kind").is_none() || w.text == l.text)
|
||||
})
|
||||
})
|
||||
// A named preset is the same one only in its number style and text: "1." and "A." are
|
||||
// both `%1.`, so picking one over the other changes the list, not switches it off (#4281).
|
||||
&& (!with_text || (w.text == l.text && w.format == l.format))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let named = p::str(v, "kind").is_some();
|
||||
// A named preset is told by its first level as well as the paragraph's own, as deeper levels of
|
||||
// two presets can look alike; unless the list starts with the other kind of marker (a bullet
|
||||
// above numbers, or the reverse), where the paragraph's own level decides.
|
||||
let is_bullet = |i: u8| s.doc.numbering.level(n.num, i).map(|l| l.format == wordcraft_doc::section::NumFormat::Bullet);
|
||||
let one_kind_throughout = is_bullet(0) == is_bullet(n.level);
|
||||
level_is(n.level, named) && (!named || !one_kind_throughout || level_is(0, true))
|
||||
};
|
||||
let remove = off || (!current.is_empty() && current.iter().all(|n| n.as_ref().is_some_and(same_kind)));
|
||||
if remove {
|
||||
|
||||
@@ -113,7 +113,7 @@ pub(super) fn outline_step(s: &mut Session, promote: bool) -> CmdResult {
|
||||
// Outline view: the headings hidden under a collapsed heading move a level with it.
|
||||
let carried = crate::cmd::outline::hidden_subheadings(s);
|
||||
let (a, b) = s.sel.ordered();
|
||||
let paths = s.doc.paths_between(&a, &b);
|
||||
let paths = if s.cell_range().is_some_and(|range| !range.stream) { crate::cmd::selected_paths(s) } else { s.doc.paths_between(&a, &b) };
|
||||
// The heading before the selection, for promoted body text.
|
||||
let before = s
|
||||
.doc
|
||||
|
||||
@@ -54,7 +54,13 @@ type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
|
||||
const RESETS: [Reset; 24] = [
|
||||
(|c| c.font.is_some(), |c| c.font = None),
|
||||
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
|
||||
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
|
||||
(
|
||||
|c| c.font_ea.is_some() || c.font_ea_theme.is_some(),
|
||||
|c| {
|
||||
c.font_ea = None;
|
||||
c.font_ea_theme = None;
|
||||
},
|
||||
),
|
||||
(|c| c.size.is_some(), |c| c.size = None),
|
||||
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
|
||||
(|c| c.color.is_some(), |c| c.color = None),
|
||||
@@ -181,12 +187,170 @@ pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"id": id}))
|
||||
}
|
||||
|
||||
/// Deserialize `T` from `v`, rejecting unknown fields on `T` and any nested structs (#9203, #9291).
|
||||
fn deserialize_strict<T: serde::de::DeserializeOwned>(section: &str, v: &Value) -> Result<T, CmdError> {
|
||||
use serde::de::{DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};
|
||||
|
||||
struct StrictDe<'a>(&'a Value);
|
||||
struct StrictSeq<'a>(std::slice::Iter<'a, Value>);
|
||||
struct StrictMap<'a>(serde_json::map::Iter<'a>, Option<&'a Value>);
|
||||
struct StrictEnum<'a>(&'a str, &'a Value);
|
||||
|
||||
// Internally tagged enums buffer their fields before decoding them, bypassing StrictMap.
|
||||
fn validate_text_fill(fill: &Value) -> Result<(), serde_json::Error> {
|
||||
let tag = fill.get("type").or_else(|| fill.get(0));
|
||||
// Serde's numeric variant indices follow the TextFill declaration order.
|
||||
let fields: &[_] = match (tag.and_then(Value::as_str), tag.and_then(Value::as_u64)) {
|
||||
(Some("none"), _) | (_, Some(0)) => &["type"],
|
||||
(Some("solid"), _) | (_, Some(1)) => &["type", "color", "transparency"],
|
||||
(Some("gradient"), _) | (_, Some(2)) => &["type", "stops", "angle"],
|
||||
_ => return Ok(()), // The regular decoder reports missing or unknown tags.
|
||||
};
|
||||
let stops = if let Some(map) = fill.as_object() {
|
||||
if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) {
|
||||
return Err(serde::de::Error::custom(format!("`textEffects.fill`: unknown field `{key}`")));
|
||||
}
|
||||
map.get("stops")
|
||||
} else if fields.contains(&"stops") {
|
||||
fill.get(1)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(stops) = stops.and_then(Value::as_array) {
|
||||
for stop in stops {
|
||||
<wordcraft_doc::wordart::GradStop as serde::Deserialize>::deserialize(StrictDe(stop))
|
||||
.map_err(|e| serde::de::Error::custom(format!("`textEffects.fill.stops`: {e}")))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<'de> SeqAccess<'de> for StrictSeq<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error> {
|
||||
self.0.next().map(|v| seed.deserialize(StrictDe(v))).transpose()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> MapAccess<'de> for StrictMap<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> {
|
||||
let Some((k, v)) = self.0.next() else { return Ok(None) };
|
||||
self.1 = Some(v);
|
||||
seed.deserialize(k.as_str().into_deserializer()).map(Some)
|
||||
}
|
||||
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Self::Error> {
|
||||
let v = self.1.take().ok_or_else(|| serde::de::Error::custom("missing map value"))?;
|
||||
seed.deserialize(StrictDe(v))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> VariantAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn unit_variant(self) -> Result<(), Self::Error> {
|
||||
serde::Deserialize::deserialize(self.1)
|
||||
}
|
||||
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Self::Error> {
|
||||
seed.deserialize(StrictDe(self.1))
|
||||
}
|
||||
fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
serde::Deserializer::deserialize_tuple(StrictDe(self.1), len, visitor)
|
||||
}
|
||||
fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> {
|
||||
serde::Deserializer::deserialize_struct(StrictDe(self.1), "", fields, visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> EnumAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
type Variant = Self;
|
||||
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> {
|
||||
let val = seed.deserialize(self.0.into_deserializer())?;
|
||||
Ok((val, self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserializer<'de> for StrictDe<'_> {
|
||||
type Error = serde_json::Error;
|
||||
|
||||
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
match self.0 {
|
||||
Value::Null => visitor.visit_unit(),
|
||||
Value::Bool(b) => visitor.visit_bool(*b),
|
||||
Value::Number(n) => n.deserialize_any(visitor),
|
||||
Value::String(s) => visitor.visit_str(s),
|
||||
Value::Array(arr) => visitor.visit_seq(StrictSeq(arr.iter())),
|
||||
Value::Object(map) => visitor.visit_map(StrictMap(map.iter(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
if self.0.is_null() { visitor.visit_none() } else { visitor.visit_some(self) }
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V: Visitor<'de>>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
match self.0 {
|
||||
Value::String(s) => visitor.visit_enum(s.as_str().into_deserializer()),
|
||||
Value::Object(map) if map.len() == 1 => {
|
||||
if let Some((k, v)) = map.iter().next() {
|
||||
visitor.visit_enum(StrictEnum(k, v))
|
||||
} else {
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V: Visitor<'de>>(
|
||||
self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
if name == "TextEffects" {
|
||||
let fill = match self.0 {
|
||||
Value::Array(values) => fields.iter().position(|&field| field == "fill").and_then(|index| values.get(index)),
|
||||
_ => self.0.get("fill"),
|
||||
};
|
||||
if let Some(fill) = fill {
|
||||
validate_text_fill(fill)?;
|
||||
}
|
||||
}
|
||||
if let Value::Object(map) = self.0 {
|
||||
for key in map.keys() {
|
||||
if !fields.contains(&key.as_str()) {
|
||||
return Err(serde::de::Error::custom(format!("unknown field `{key}`")));
|
||||
}
|
||||
}
|
||||
return visitor.visit_map(StrictMap(map.iter(), None));
|
||||
}
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
|
||||
unit unit_struct seq tuple tuple_struct map identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
T::deserialize(StrictDe(v)).map_err(|e| CmdError::Params(format!("`{section}`: {e}")))
|
||||
}
|
||||
|
||||
/// Modify a style's character and paragraph formatting, display name or next-paragraph style.
|
||||
pub(super) fn modify_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = style_id(s, p::req_str(v, "style")?)?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let para: Option<ParaProps> =
|
||||
v.get("para").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| deserialize_strict("chr", c)).transpose()?;
|
||||
let para: Option<ParaProps> = v.get("para").map(|c| deserialize_strict("para", c)).transpose()?;
|
||||
let next = p::str(v, "next").map(str::to_string);
|
||||
let name = p::str(v, "name").map(str::to_string);
|
||||
let d = &s.doc.styles.default_chr;
|
||||
|
||||
@@ -337,7 +337,7 @@ fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
|
||||
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
|
||||
match text {
|
||||
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
|
||||
_ => Err(CmdError::Failed("the clipboard is empty".into())),
|
||||
_ => Err(CmdError::ClipboardEmpty),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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`].
|
||||
|
||||
@@ -695,6 +695,27 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
|
||||
Pos { off, ..p.clone() }
|
||||
}
|
||||
|
||||
/// The ranges, in any story, that a document protected as read only, comments only or forms
|
||||
/// lets this author edit; `None` when the protection doesn't limit where edits may land. A command
|
||||
/// that searches the whole document keeps only its matches inside them, so a match in protected
|
||||
/// content (a header repeating a placeholder) is left alone instead of failing the command.
|
||||
pub(crate) fn editable_ranges(s: &Session) -> Option<Vec<(Pos, Pos)>> {
|
||||
match s.doc.settings.protection.as_deref()? {
|
||||
"forms" => {
|
||||
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
|
||||
Some(
|
||||
stories
|
||||
.flat_map(|story| s.doc.control_ranges(story))
|
||||
.filter(|r| r.control.lock.can_edit())
|
||||
.map(|r| (r.content_start(), r.end))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
"readOnly" | "comments" => Some(s.doc.perm_ranges().into_iter().filter(|r| editable_by(r, &s.author)).map(|r| (r.start, r.end)).collect()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first position in an editable range after `from` (wrapping round), for Find Next Region
|
||||
/// I Can Edit; with it, the range's end. Filling in forms: the next fillable control's content.
|
||||
pub fn next_region(s: &Session, from: &Pos) -> Option<(Pos, Pos)> {
|
||||
|
||||
@@ -32,6 +32,30 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
|
||||
assert_eq!(s.doc.settings.protection.as_deref(), Some("readOnly"));
|
||||
}
|
||||
|
||||
/// Replace All covers every story, but in a protected document only the editable regions change:
|
||||
/// the same placeholder in a header, a footnote or the locked body text is left as it is, and
|
||||
/// the replacement in the editable region still goes through.
|
||||
#[test]
|
||||
fn replace_all_in_a_protected_document_skips_protected_matches() {
|
||||
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
|
||||
let header = s.run("insert.header", &json!({"text": "Header [NAME]"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
let note = s.run("references.footnote", &json!({"text": "Note [NAME]"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
s.sel = Selection::caret(Pos::body(0, 0));
|
||||
select(&mut s, "Fill [NAME] in.");
|
||||
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let r = s.run("edit.replaceAll", &json!({"text": "[NAME]", "with": "Jane"})).unwrap();
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
let body = s.doc.plain_text(StoryRef::Body).replace(OBJ, "");
|
||||
assert!(body.contains("Locked [NAME]."), "{body}");
|
||||
assert!(body.contains("Fill Jane in."), "{body}");
|
||||
for id in [header, note] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(s.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exception that starts a line: Home, Left and Down put the caret before its start
|
||||
/// marker, and Enter and typing there go inside the exception. A caret after the end marker at
|
||||
/// the end of the line goes back inside it too.
|
||||
|
||||
@@ -20,7 +20,8 @@ use fields::caption;
|
||||
#[cfg(test)]
|
||||
use fields::output_fields_with;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, caption_preview, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in,
|
||||
update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
|
||||
@@ -27,12 +27,29 @@ pub const CHAPTER_SEPARATORS: [&str; 5] = ["-", ".", ":", "\u{2014}", "\u{2013}"
|
||||
/// a chapter number (`STYLEREF n \s` and a separator) and a `SEQ label \* format \s n` number
|
||||
/// (ECMA-376 §17.16.5.56, §17.16.5.59).
|
||||
pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let text = p::str(v, "text").unwrap_or("");
|
||||
s.doc.insert_block(story, &at, Block::Para(caption_paragraph(v, text)?))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story, path: at, off });
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Number a prospective caption at its insertion site without changing the document or selection.
|
||||
pub fn caption_preview(s: &Session, v: &Value) -> Result<String, CmdError> {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let mut doc = s.doc.clone();
|
||||
doc.insert_block(story, &at, Block::Para(caption_paragraph(v, "")?))?;
|
||||
update_seq_in(&mut doc)?;
|
||||
Ok(doc.para(story, &at).map_or_else(String::new, Paragraph::plain_text))
|
||||
}
|
||||
|
||||
fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
|
||||
let label: String = p::str(v, "label").unwrap_or("Figure").chars().filter(|c| !matches!(c, '"' | '\\') && !c.is_control()).take(40).collect();
|
||||
let label = if label.trim().is_empty() { "Figure".to_string() } else { label.trim().to_string() };
|
||||
// SEQ identifiers are one word: Word joins a multi-word label with underscores.
|
||||
let ident = label.split_whitespace().collect::<Vec<_>>().join("_");
|
||||
let text = p::str(v, "text").unwrap_or("").to_string();
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let format = seq_format(p::str(v, "format").unwrap_or("ARABIC"));
|
||||
let chapter = p::u64(v, "chapter").filter(|l| (1..=9).contains(l));
|
||||
let sep = p::str(v, "separator").and_then(|x| CHAPTER_SEPARATORS.iter().find(|s| **s == x)).copied().unwrap_or("-");
|
||||
@@ -51,10 +68,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if !text.is_empty() {
|
||||
para.insert_text(para.len(), &format!(": {text}"), &CharProps::default())?;
|
||||
}
|
||||
Ok(para)
|
||||
}
|
||||
|
||||
fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
// A selected picture, shape or chart: next to the paragraph holding it, in the same cell or
|
||||
// text box (#1230). Otherwise next to the caret's top-level block: a paragraph, or the whole
|
||||
// table it is in.
|
||||
let f = s.sel.focus.clone();
|
||||
let f = &s.sel.focus;
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let at = match crate::cmd::objects::object_selection(s) {
|
||||
Some((pos, _)) => {
|
||||
let k = pos.path.last();
|
||||
@@ -65,11 +87,7 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Path::top(if above { top } else { top.saturating_add(1) })
|
||||
}
|
||||
};
|
||||
s.doc.insert_block(f.story, &at, Block::Para(para))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(f.story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story: f.story, path: at, off });
|
||||
sel_result(s)
|
||||
(f.story, at)
|
||||
}
|
||||
|
||||
/// Renumber the body's SEQ fields in document order, honouring `\* format`, `\s level` (restart
|
||||
@@ -78,11 +96,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// the last level-n heading's number, or its count when the heading isn't numbered) and the
|
||||
/// text or number of the nearest paragraph of a style.
|
||||
pub fn update_seq(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_seq_in(&mut s.doc)
|
||||
}
|
||||
|
||||
fn update_seq_in(doc: &mut wordcraft_doc::Document) -> Result<(), CmdError> {
|
||||
// Numbers first: a STYLEREF to a heading that holds a SEQ field shows its new number.
|
||||
let numbers = seq_results(&s.doc);
|
||||
apply_results(&mut s.doc, numbers)?;
|
||||
let refs = styleref_results(&s.doc);
|
||||
apply_results(&mut s.doc, refs)
|
||||
let numbers = seq_results(doc);
|
||||
apply_results(doc, numbers)?;
|
||||
let refs = styleref_results(doc);
|
||||
apply_results(doc, refs)
|
||||
}
|
||||
|
||||
/// A field's fresh result: its story and paragraph, its object index there and the text.
|
||||
@@ -402,7 +424,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
}
|
||||
let mut updates: Vec<(usize, String)> = Vec::new();
|
||||
for (k, o) in p.objects.iter().enumerate() {
|
||||
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
|
||||
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
|
||||
// A table formula reads the cells around its own cell again.
|
||||
if instr.trim_start().starts_with('=') {
|
||||
if let Some((tp, r, c)) = path.cell()
|
||||
@@ -422,7 +444,22 @@ 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 any result
|
||||
// it already has; when inserted with none, it shows today's date (the date
|
||||
// a save would stamp).
|
||||
let text = if name == "CREATEDATE"
|
||||
&& let Some((unix, offset)) = created_at(created)
|
||||
{
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
|
||||
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
updates.push((k, text_result(instr, text)));
|
||||
}
|
||||
"REF" | "PAGEREF" => {
|
||||
let f = FieldCode::parse(instr);
|
||||
@@ -572,9 +609,27 @@ 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() }
|
||||
if name == "TIME" { crate::cmd::insert::default_time_picture(lang).into() } else { crate::cmd::insert::default_date_picture(lang).into() }
|
||||
}
|
||||
/// Most names SET fields give values.
|
||||
const MAX_SET: usize = 10_000;
|
||||
|
||||
@@ -506,6 +506,76 @@ 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"));
|
||||
}
|
||||
|
||||
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
|
||||
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
|
||||
/// existing field with a cached result keeps it.
|
||||
#[test]
|
||||
fn createdate_inserted_into_opened_file_without_creation_date() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
|
||||
s.path = Some(std::env::temp_dir().join("notes.txt"));
|
||||
s.doc.core.created.clear();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
|
||||
let expected = crate::cmd::insert::format_date("yyyy-MM");
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
|
||||
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
|
||||
s.doc.core.created = "sometime in May".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_tabs_ignore_nonentries() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
|
||||
@@ -627,6 +697,96 @@ fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
|
||||
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
|
||||
}
|
||||
|
||||
/// Inserting a table of contents in the middle of a document places the caret in the paragraph
|
||||
/// right after the table and leaves the text above and below it unchanged.
|
||||
#[test]
|
||||
fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAfter TOC\nChapter One\nBody below."));
|
||||
s.run("select.text", &json!({"text": "Chapter One"})).unwrap();
|
||||
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
let (start, end) = toc_range(&s).unwrap();
|
||||
assert_eq!(start, 1, "the TOC must immediately follow Intro without an extra blank paragraph");
|
||||
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
|
||||
assert_eq!(
|
||||
s.sel.focus,
|
||||
Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 },
|
||||
"the caret must land in the paragraph right after the TOC"
|
||||
);
|
||||
let below: Vec<String> = s.doc.body[end + 1..].iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect();
|
||||
assert_eq!(below, ["After TOC", "Chapter One", "Body below."]);
|
||||
}
|
||||
|
||||
/// One undo removes both the table of contents and the empty paragraph `caret_after_toc` adds
|
||||
/// when the table ends the document or comes right before a table, leaving no stray blank
|
||||
/// paragraph behind.
|
||||
#[test]
|
||||
fn undoing_a_toc_removes_both_the_table_and_the_added_paragraph() {
|
||||
let toc_instr = |s: &Session, i: usize| {
|
||||
s.doc.body[i].as_para().and_then(|p| {
|
||||
p.objects.iter().find_map(|o| match o {
|
||||
InlineObject::Field { instr, .. } => Some(instr.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
// Fresh insert on an empty document undoes in one step.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
assert!(toc_range(&s).is_some());
|
||||
assert_eq!(s.undo_depth(), 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.undo_depth(), 0);
|
||||
assert!(toc_range(&s).is_none());
|
||||
assert_eq!(s.doc.body.len(), 1);
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "");
|
||||
|
||||
// Table ending the document: `caret_after_toc` appends an empty paragraph, and one undo
|
||||
// removes both the replaced table and that added paragraph.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
let (start, end) = toc_range(&s).unwrap();
|
||||
while s.doc.body.len() > end + 1 {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
|
||||
}
|
||||
let before_blocks = s.doc.body.len();
|
||||
let depth = s.undo_depth();
|
||||
s.run("references.toc", &json!({"levels": 3})).unwrap();
|
||||
let (_, new_end) = toc_range(&s).unwrap();
|
||||
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
|
||||
assert_eq!(s.doc.body.len(), before_blocks + 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added trailing paragraph");
|
||||
assert_eq!(toc_range(&s), Some((start, end)));
|
||||
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
|
||||
|
||||
// Table right before another table: `caret_after_toc` inserts an empty paragraph before the
|
||||
// table, and one undo removes both the replaced TOC and that added paragraph.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let (start, end) = toc_range(&s).unwrap();
|
||||
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
|
||||
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
|
||||
}
|
||||
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
|
||||
let before_blocks = s.doc.body.len();
|
||||
let depth = s.undo_depth();
|
||||
s.run("references.toc", &json!({"levels": 3})).unwrap();
|
||||
let (_, new_end) = toc_range(&s).unwrap();
|
||||
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
|
||||
assert_eq!(s.doc.body.len(), before_blocks + 1);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added paragraph before the table");
|
||||
assert_eq!(toc_range(&s), Some((start, end)));
|
||||
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
|
||||
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
|
||||
}
|
||||
|
||||
/// A fresh scratch directory for the file-name tests below.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
|
||||
@@ -969,6 +1129,36 @@ fn a_missing_references_error_is_in_the_interface_language() {
|
||||
assert_eq!(shown, [french, "Target"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_context_ref_keeps_an_ancestor_when_the_label_contains_literal_percent_zero() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::numbering::Level;
|
||||
use wordcraft_doc::props::NumRef;
|
||||
use wordcraft_doc::{Document, ListKind};
|
||||
|
||||
for (template, own, full) in [("%0-%2.", "%0-1", "1%0-1"), ("%1-%2.", "1-1", "1-1"), ("(%2).", "(1)", "1(1)")] {
|
||||
let mut doc = Document::from_text("Parent\nTarget\nRefs ");
|
||||
let numbering = Arc::make_mut(&mut doc.numbering);
|
||||
let num = numbering.add_list(ListKind::Numbered);
|
||||
numbering.nums[0].level_overrides = vec![(1, Level { text: template.into(), ..Default::default() })];
|
||||
for level in 0..=1u8 {
|
||||
doc.para_mut(StoryRef::Body, &Path::top(usize::from(level))).unwrap().props.numbering = Some(NumRef { num, level });
|
||||
}
|
||||
|
||||
let mut s = Session::new(doc);
|
||||
s.run("select.text", &json!({"text": "Target"})).unwrap();
|
||||
s.run("insert.bookmark", &json!({"name": "Mark"})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
for instr in [r"REF Mark \n", r"REF Mark \w"] {
|
||||
s.run("insert.field", &json!({"instr": instr})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " "})).unwrap();
|
||||
}
|
||||
let refs = stale_last_paragraph(&mut s, "stale");
|
||||
update_fields(&mut s).unwrap();
|
||||
assert_eq!(results_in(&s.doc, &refs), [own, full], "{template}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A REF showing the bookmarked paragraph's number (`\r`, `\n`, `\w`), which output doesn't
|
||||
/// compute, keeps its stored number when printed or exported rather than show the paragraph's
|
||||
/// text; a plain REF to the same bookmark is filled in.
|
||||
|
||||
@@ -439,6 +439,8 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.doc.remove_block(StoryRef::Body, &at.path)?;
|
||||
}
|
||||
at.path.last()
|
||||
} else if at.off == 0 {
|
||||
at.path.last()
|
||||
} else {
|
||||
s.doc.split_paragraph(&at)?.path.last()
|
||||
};
|
||||
|
||||
@@ -12,16 +12,15 @@ 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::{
|
||||
DELETION_TEXT_CHARS, DeletionBalloon, deletion_balloons, format_changes, has_deletions, has_format_changes, move_changes, tracking_json,
|
||||
};
|
||||
use changes::{list_changes, nav_change, resolve_all_then, resolve_sel_then, tracking_options};
|
||||
use comments::{
|
||||
comment_at_caret, comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, validate_comment_id,
|
||||
};
|
||||
pub use comments::{comment_list, comment_range_at_caret};
|
||||
use comments::{comments_change, delete_comment, edit_comment, list_comments, nav_comment, new_comment, reply, resolve_comment};
|
||||
use proofing::{all_issues, issue_at, next_issue, suggestions, thesaurus, word_count};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -36,14 +35,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
|
||||
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
|
||||
),
|
||||
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
let c = s.doc.comments.get_mut(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
|
||||
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
|
||||
sel_result(s)
|
||||
})
|
||||
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
|
||||
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", resolve_comment)
|
||||
.params(r#"{"id"?: non-negative 32-bit JSON integer (a comment or reply; omit to use the caret), "value"?: bool (omit to toggle the whole thread)}"#),
|
||||
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
|
||||
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
|
||||
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
|
||||
|
||||
@@ -26,7 +26,8 @@ fn resolve_runs(para: &mut wordcraft_doc::Paragraph, from: usize, to: usize, pro
|
||||
}
|
||||
|
||||
/// Accept or reject a revision range in one paragraph; `mark` includes its paragraph mark (and
|
||||
/// the section break on it), `props` the paragraph's own formatting change.
|
||||
/// the section break on it), `props` the paragraph's own formatting change. If the next
|
||||
/// paragraph moves into this path, return how many bytes of this paragraph precede it.
|
||||
fn resolve_para(
|
||||
s: &mut Session,
|
||||
story: StoryRef,
|
||||
@@ -34,11 +35,11 @@ fn resolve_para(
|
||||
(from, to): (usize, usize),
|
||||
(mark, props): (bool, bool),
|
||||
accept: bool,
|
||||
) -> Result<(), CmdError> {
|
||||
) -> Result<Option<usize>, CmdError> {
|
||||
let para = s.doc.para_mut(story, path)?;
|
||||
resolve_runs(para, from, to, props, accept)?;
|
||||
if !mark {
|
||||
return Ok(());
|
||||
return Ok(None);
|
||||
}
|
||||
if para.mark.fmt_change.is_some() || para.section.as_ref().is_some_and(|x| x.fmt_change.is_some()) {
|
||||
fmt_revisions::resolve_char(&mut para.mark, accept);
|
||||
@@ -49,14 +50,16 @@ fn resolve_para(
|
||||
}
|
||||
let (ins, del) = (para.mark.ins, para.mark.del);
|
||||
if ins.is_none() && del.is_none() {
|
||||
return Ok(());
|
||||
return Ok(None);
|
||||
}
|
||||
let prefix_len = para.len();
|
||||
// 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
|
||||
@@ -65,15 +68,35 @@ fn resolve_para(
|
||||
if sectioned {
|
||||
s.doc.remove_section_break(path.last());
|
||||
}
|
||||
if crate::cmd::remove_empty_para(s, story, path)? || crate::cmd::join_next_para(s, story, path)? {
|
||||
return Ok(());
|
||||
if crate::cmd::remove_empty_para(s, story, path)? {
|
||||
return Ok(Some(0));
|
||||
}
|
||||
if crate::cmd::join_next_para(s, story, path)? {
|
||||
return Ok(Some(prefix_len));
|
||||
}
|
||||
}
|
||||
let para = s.doc.para_mut(story, path)?;
|
||||
para.mark.ins = None;
|
||||
para.mark.del = None;
|
||||
para.touch();
|
||||
Ok(())
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -241,12 +264,73 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph.
|
||||
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
|
||||
let Some(para) = s.doc.para_at(end) else { return end.off };
|
||||
let removed: usize = para
|
||||
.run_ranges()
|
||||
.filter(|(_, c)| if accept { c.del.is_some() } else { c.ins.is_some() })
|
||||
.map(|(range, _)| end.off.min(range.end).saturating_sub(range.start))
|
||||
.sum();
|
||||
end.off - removed
|
||||
}
|
||||
|
||||
/// The next paragraph has moved into `path` (empty removal) or been appended to its surviving
|
||||
/// prefix (join). Later siblings, including a table containing an endpoint, shift one block back.
|
||||
fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcraft_doc::Path, prefix_len: usize, offsets: &mut [usize; 2]) {
|
||||
let depth = path.parent().len();
|
||||
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(offsets) {
|
||||
if end.story != story || !end.path.0.starts_with(path.parent()) {
|
||||
continue;
|
||||
}
|
||||
let Some(&block) = end.path.0.get(depth) else { continue };
|
||||
if block as usize > path.last() {
|
||||
let mut dest = end.path.clone();
|
||||
dest.0[depth] -= 1;
|
||||
// An endpoint in a terminal paragraph removed earlier still uses terminal clamping.
|
||||
if s.doc.para(story, &dest).is_none() {
|
||||
continue;
|
||||
}
|
||||
if &dest == path {
|
||||
*offset = offset.saturating_add(prefix_len);
|
||||
}
|
||||
end.path = dest;
|
||||
} else if &end.path == path {
|
||||
*offset = (*offset).min(prefix_len);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
end.off = *offset;
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
|
||||
s.sel.anchor.off = offsets[0];
|
||||
s.sel.focus.off = offsets[1];
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
// 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)?;
|
||||
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing && remove_trailing_para(s, st, &path)? {
|
||||
// Selection ends in the removed paragraph go to the end of the one before it;
|
||||
// keep that offset through any later remapping when earlier edits resolve.
|
||||
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(&mut offsets) {
|
||||
if end.story == st && end.path == path {
|
||||
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
|
||||
*offset = end.off;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(prefix_len) = prefix_len {
|
||||
remap_after_middle_paragraph(s, st, &path, prefix_len, &mut offsets);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Tables, rows, cells, sections and style definitions.
|
||||
@@ -931,7 +1015,7 @@ fn resolve_sel(s: &mut Session, accept: bool, next: bool) -> CmdResult {
|
||||
// A paragraph's mark is in the selection when the selection goes on past it.
|
||||
let mark = path != b.path || caret_mark.as_ref() == Some(&path);
|
||||
let props = (ranged && (path != b.path || to > from)) || caret_props.as_ref() == Some(&path);
|
||||
resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
|
||||
let _ = resolve_para(s, a.story, &path, (from, to), (mark, props), accept)?;
|
||||
if ranged {
|
||||
resolve_cell(s, a.story, &path, accept)?;
|
||||
}
|
||||
|
||||
@@ -186,6 +186,29 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
|
||||
ids
|
||||
}
|
||||
|
||||
/// Resolve or reopen the whole discussion, even when the target is a reply. A toggle uses
|
||||
/// the target's state, matching its Resolve/Reopen button even in a mixed-state file.
|
||||
pub(super) fn resolve_comment(s: &mut Session, v: &Value) -> CmdResult {
|
||||
validate_comment_id(v)?;
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
|
||||
let c = s.doc.comments.get(&id).ok_or_else(|| CmdError::Params("no such comment".into()))?;
|
||||
let resolved = p::bool(v, "value").unwrap_or(!c.resolved);
|
||||
let mut root = id;
|
||||
let mut seen = BTreeSet::new();
|
||||
while seen.insert(root) {
|
||||
match s.doc.comments.get(&root).and_then(|c| c.parent).filter(|p| s.doc.comments.contains_key(p)) {
|
||||
Some(parent) => root = parent,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
for id in threads_of(s, [root]) {
|
||||
if let Some(c) = s.doc.comments.get_mut(&id) {
|
||||
c.resolved = resolved;
|
||||
}
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
|
||||
validate_comment_id(v)?;
|
||||
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -311,7 +311,7 @@ fn comment_range_at_caret_needs_the_caret_inside_the_range() {
|
||||
assert_eq!(super::comment_range_at_caret(&s), Some(id), "inside the commented text");
|
||||
s.run("select.text", &json!({"text": "three"})).unwrap();
|
||||
assert_eq!(super::comment_range_at_caret(&s), None, "elsewhere in the paragraph");
|
||||
assert_eq!(super::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
|
||||
assert_eq!(super::comments::comment_at_caret(&s), Some(id), "the older lookup still falls back to the paragraph's comment");
|
||||
}
|
||||
|
||||
fn glyph_text(d: &[Draw]) -> String {
|
||||
@@ -491,6 +491,148 @@ fn deletions_outside_the_body_stay_inline_when_revisions_go_in_balloons() {
|
||||
assert_eq!(deletion_balloons(&s), vec![DeletionBalloon { at: Pos::body(0, at), author: "Ana".into(), text: "zeta".into() }]);
|
||||
}
|
||||
|
||||
fn assert_revision_arrow_stops(s: &mut Session, story: wordcraft_doc::StoryRef, from: [usize; 2], to: [usize; 2]) {
|
||||
use wordcraft_doc::{Path, Pos};
|
||||
|
||||
let pos = |off| Pos::new(story, Path::top(0), off);
|
||||
for (key, start, end) in [("Right", from[0], to[0]), ("Left", from[1], to[1])] {
|
||||
let cmd = s.registry.by_shortcut(key).unwrap().id;
|
||||
for extend in [false, true] {
|
||||
s.run("caret.set", &json!({"pos": pos(start)})).unwrap();
|
||||
s.run(cmd, &json!({"extend": extend})).unwrap();
|
||||
assert_eq!(s.sel.focus, pos(end), "{key}, Shift {extend}, from {start}");
|
||||
assert_eq!(s.sel.anchor, pos(if extend { start } else { end }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_arrows_follow_revision_balloon_visibility_by_story() {
|
||||
use wordcraft_doc::{Path, Pos, StoryRef};
|
||||
|
||||
let mut s = Session::new(Document::from_text("AQRSZ"));
|
||||
let id = s.run("insert.header", &json!({"text": "ABCDZ"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
let header = StoryRef::Part(id);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
for story in [StoryRef::Body, header] {
|
||||
let at = |off| Pos::new(story, Path::top(0), off);
|
||||
s.run("select.range", &json!({"anchor": at(1), "focus": at(4)})).unwrap();
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
assert!(s.doc.para_at(&at(1)).unwrap().props_of_char(1).del.is_some());
|
||||
}
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
|
||||
assert!(s.revisions_in_balloons());
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [5, 0]);
|
||||
assert_revision_arrow_stops(&mut s, header, [1, 4], [2, 3]);
|
||||
|
||||
s.run("view.commentsPane", &json!({"value": true})).unwrap();
|
||||
assert!(!s.revisions_in_balloons());
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline"})).unwrap();
|
||||
s.run("view.commentsPane", &json!({"value": false})).unwrap();
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 4], [2, 3]);
|
||||
|
||||
s.run("review.markup", &json!({"value": "noMarkup"})).unwrap();
|
||||
for story in [StoryRef::Body, header] {
|
||||
assert_revision_arrow_stops(&mut s, story, [1, 4], [5, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_arrows_distinguish_hidden_deletions_from_hidden_move_sources() {
|
||||
use wordcraft_doc::{Pos, Revision, RevisionKind, StoryRef};
|
||||
|
||||
let mut doc = Document::from_text("AxyuvZuv");
|
||||
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
|
||||
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
|
||||
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
|
||||
doc.revisions.extend([deletion, source, destination]);
|
||||
doc.format_range(&Pos::body(0, 1), &Pos::body(0, 3), &|c| c.del = Some(0)).unwrap();
|
||||
doc.format_range(&Pos::body(0, 3), &Pos::body(0, 5), &|c| c.del = Some(1)).unwrap();
|
||||
doc.format_range(&Pos::body(0, 6), &Pos::body(0, 8), &|c| c.ins = Some(2)).unwrap();
|
||||
let mut s = Session::new(doc);
|
||||
|
||||
for (delete_mark, move_from_mark, expected) in [
|
||||
("strikethrough", "strikethrough", [2, 4]),
|
||||
("hidden", "strikethrough", [4, 4]),
|
||||
("strikethrough", "hidden", [2, 2]),
|
||||
("hidden", "hidden", [6, 0]),
|
||||
] {
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
|
||||
assert_revision_arrow_stops(&mut s, StoryRef::Body, [1, 5], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_moves_follow_layout_visibility_for_balloons_and_hidden_marks() {
|
||||
use wordcraft_doc::{Path, Pos, Revision, RevisionKind, StoryRef};
|
||||
|
||||
let mut s = Session::new(Document::from_text("one del two"));
|
||||
let id = s.run("insert.header", &json!({"text": "one del two"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
let header = StoryRef::Part(id);
|
||||
s.run("insert.closeHeader", &json!({})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
let del_start = "one ".len();
|
||||
let two_start = "one del ".len();
|
||||
for story in [StoryRef::Body, header] {
|
||||
s.run("select.range", &json!({"anchor": Pos::new(story, Path::top(0), del_start), "focus": Pos::new(story, Path::top(0), two_start)}))
|
||||
.unwrap();
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
s.run("review.trackingOptions", &json!({"balloons": "revisions"})).unwrap();
|
||||
assert!(s.revisions_in_balloons());
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, two_start), "Body in balloons skips deleted word on Ctrl+Right");
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Body in balloons skips deleted word on Ctrl+Left");
|
||||
|
||||
s.run("caret.set", &json!({"pos": Pos::new(header, Path::top(0), 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::new(header, Path::top(0), del_start), "Header inline keeps deleted word stop on Ctrl+Right");
|
||||
|
||||
s.run("view.commentsPane", &json!({"value": true})).unwrap();
|
||||
assert!(!s.revisions_in_balloons());
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, 0)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, del_start), "Body stops at deleted word once revisions move inline");
|
||||
|
||||
let mut doc = Document::from_text("one del mov two");
|
||||
let deletion = Revision::new(RevisionKind::Delete, "Author", "");
|
||||
let source = Revision { move_name: Some("Move1".into()), ..deletion.clone() };
|
||||
let destination = Revision { kind: RevisionKind::Insert, ..source.clone() };
|
||||
doc.revisions.extend([deletion, source, destination]);
|
||||
let mov_start = "one del ".len();
|
||||
let end_two_start = "one del mov ".len();
|
||||
doc.format_range(&Pos::body(0, del_start), &Pos::body(0, mov_start), &|c| c.del = Some(0)).unwrap();
|
||||
doc.format_range(&Pos::body(0, mov_start), &Pos::body(0, end_two_start), &|c| c.del = Some(1)).unwrap();
|
||||
doc.format_range(&Pos::body(0, end_two_start), &Pos::body(0, "one del mov two".len()), &|c| c.ins = Some(2)).unwrap();
|
||||
let mut s = Session::new(doc);
|
||||
|
||||
for (delete_mark, move_from_mark, right_from, right_to, left_to) in [
|
||||
("strikethrough", "strikethrough", del_start, mov_start, mov_start),
|
||||
("hidden", "strikethrough", 0, mov_start, mov_start),
|
||||
("strikethrough", "hidden", del_start, end_two_start, del_start),
|
||||
("hidden", "hidden", 0, end_two_start, 0),
|
||||
] {
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": delete_mark, "moveFromMark": move_from_mark})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, right_from)})).unwrap();
|
||||
s.run("caret.wordRight", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, right_to), "Ctrl+Right ({delete_mark}, {move_from_mark})");
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, end_two_start)})).unwrap();
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, left_to), "Ctrl+Left ({delete_mark}, {move_from_mark})");
|
||||
}
|
||||
s.run("review.trackingOptions", &json!({"balloons": "inline", "deleteMark": "hidden", "moveFromMark": "strikethrough"})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos::body(0, mov_start)})).unwrap();
|
||||
s.run("caret.wordLeft", &json!({})).unwrap();
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 0), "Ctrl+Left from mov skips hidden del");
|
||||
}
|
||||
|
||||
fn body_para(s: &Session) -> &wordcraft_doc::Paragraph {
|
||||
s.doc.para(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap()
|
||||
}
|
||||
@@ -925,6 +1067,71 @@ fn deleting_a_comment_deletes_replies_to_replies() {
|
||||
assert_eq!(anchors(&s).len(), 2);
|
||||
}
|
||||
|
||||
/// Resolving from the root, the caret or a nested reply changes the whole discussion in one
|
||||
/// undo step. Reopening is also thread-wide, and unrelated discussions stay untouched.
|
||||
#[test]
|
||||
fn resolving_a_comment_changes_its_whole_thread() {
|
||||
let mut s = Session::new(Document::from_text("first second"));
|
||||
s.run("select.text", &json!({"text": "first"})).unwrap();
|
||||
let root = s.run("review.newComment", &json!({"text": "root"})).unwrap()["id"].as_u64().unwrap();
|
||||
let reply = s.run("review.reply", &json!({"id": root, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
|
||||
let nested = s.run("review.reply", &json!({"id": reply, "text": "nested"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.run("review.reply", &json!({"id": root, "text": "sibling"})).unwrap();
|
||||
s.run("select.text", &json!({"text": "second"})).unwrap();
|
||||
let other = s.run("review.newComment", &json!({"text": "other"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
s.run("select.text", &json!({"text": "first"})).unwrap();
|
||||
let before = s.doc.comments.clone();
|
||||
let body = s.doc.body.clone();
|
||||
let parts = s.doc.parts.clone();
|
||||
let depth = s.undo_depth();
|
||||
let mut resolved = before.clone();
|
||||
for (id, c) in &mut resolved {
|
||||
c.resolved = *id != other;
|
||||
}
|
||||
|
||||
for params in [json!({"id": root, "value": true}), json!({}), json!({"id": nested})] {
|
||||
s.run("review.resolveComment", ¶ms).unwrap();
|
||||
assert_eq!(s.doc.comments, resolved, "{params}: all replies resolve, not the other discussion");
|
||||
assert_eq!(s.undo_depth(), depth + 1, "one undo step for the whole thread");
|
||||
s.run("review.resolveComment", &json!({"id": reply, "value": true})).unwrap();
|
||||
assert_eq!(s.undo_depth(), depth + 1, "resolving an already resolved thread adds no step");
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.comments, before, "one undo restores every comment");
|
||||
s.run("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.comments, resolved);
|
||||
s.run("review.resolveComment", &json!({"id": nested})).unwrap();
|
||||
assert_eq!(s.doc.comments, before, "toggling a reply reopens the whole thread");
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.comments, resolved);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.comments, before);
|
||||
}
|
||||
assert_eq!(s.doc.body, body, "resolution leaves the body and anchors alone");
|
||||
assert_eq!(s.doc.parts, parts, "resolution leaves the comments' text alone");
|
||||
}
|
||||
|
||||
/// Imported comments can have mixed resolved flags, missing parents or a parent cycle. A
|
||||
/// thread operation reconciles the connected comments without following a missing parent.
|
||||
#[test]
|
||||
fn resolving_a_comment_handles_mixed_state_and_broken_parent_links() {
|
||||
use wordcraft_doc::Comment;
|
||||
for parent in [None, Some(99), Some(2)] {
|
||||
let mut doc = Document::new();
|
||||
doc.comments.insert(0, Comment { resolved: true, parent, ..Default::default() });
|
||||
doc.comments.insert(1, Comment { parent: Some(0), ..Default::default() });
|
||||
doc.comments.insert(2, Comment { parent: Some(1), ..Default::default() });
|
||||
doc.comments.insert(3, Comment { parent: Some(99), ..Default::default() });
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.resolveComment", &json!({"id": 2})).unwrap();
|
||||
assert!(
|
||||
s.doc.comments.iter().all(|(id, c)| c.resolved == (*id != 3)),
|
||||
"a reply's Resolve action must not reopen its resolved parent: {parent:?}"
|
||||
);
|
||||
s.run("review.resolveComment", &json!({"id": 1, "value": false})).unwrap();
|
||||
assert!(s.doc.comments.values().all(|c| !c.resolved), "{parent:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A parent cycle (possible in a hostile file) doesn't hang Delete; both comments go.
|
||||
#[test]
|
||||
fn deleting_a_comment_in_a_parent_cycle_ends() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::cells::{cell, cell_at, grid_cols, row_ends, selected_cells};
|
||||
use super::{CmdError, CmdResult, Paragraph, Path, Pos, Selection, Session, StoryRef, Value, sel_result};
|
||||
|
||||
/// Ctrl+A in a table, as in Word: the cell, then its row, then the table. A nested table that
|
||||
/// Explicit staged select-all in a table: the cell, then its row, then the table. A nested table that
|
||||
/// is already fully selected grows to the cell around it. Returns `None` when the next step is
|
||||
/// the whole story (not in a table, or the top-level table is already selected).
|
||||
pub(crate) fn grow_select_all(s: &mut Session) -> Option<CmdResult> {
|
||||
|
||||
@@ -630,10 +630,10 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
|
||||
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
|
||||
return margin;
|
||||
};
|
||||
// A right-to-left table has its cells' start (left) margin on their right.
|
||||
let m = wordcraft_layout::cell_margins(doc, t, row, cell);
|
||||
let inset = if t.props.bidi_visual { m[1] } else { m[3] };
|
||||
(b.rect.right() - inset).min(margin)
|
||||
// A cell's right margin is on its right in a right-to-left table too, as the layout draws
|
||||
// it (#6941): Word doesn't mirror cell margins.
|
||||
let right_margin = wordcraft_layout::cell_margins(doc, t, row, cell)[3];
|
||||
(b.rect.right() - right_margin).min(margin)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -136,6 +136,30 @@ fn a_selected_column_is_edited_cell_by_cell() {
|
||||
assert_eq!(s.cell_range().map(|r| r.cols), Some((1, 1)), "undo brings the column selection back");
|
||||
}
|
||||
|
||||
/// Toggling a format on a selected table column follows the first character in document order (#8589).
|
||||
#[test]
|
||||
fn toggle_on_a_selected_table_column_follows_first_character() {
|
||||
let toggled = |bold_row: usize| -> Vec<bool> {
|
||||
let mut s = table_session(3, 3);
|
||||
fill(&mut s);
|
||||
let p = cell_pos(&s, bold_row, 1);
|
||||
s.sel = Selection { anchor: p.clone(), focus: Pos { off: 4, ..p } };
|
||||
s.run("format.bold", &json!({"value": true})).unwrap();
|
||||
// Start from the bottom row so the caret is not on row 0.
|
||||
s.sel = Selection::caret(cell_pos(&s, 2, 1));
|
||||
s.run("table.selectColumn", &json!({})).unwrap();
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
for r in 0..3 {
|
||||
assert!(!bold(&s, r, 0) && !bold(&s, r, 2), "row {r}'s other cells stay plain");
|
||||
}
|
||||
(0..3).map(|r| bold(&s, r, 1)).collect()
|
||||
};
|
||||
// First row bold, later rows plain: Bold turns off across the column.
|
||||
assert_eq!(toggled(0), vec![false, false, false]);
|
||||
// First row plain, middle row bold: Bold turns on across the column.
|
||||
assert_eq!(toggled(1), vec![true, true, true]);
|
||||
}
|
||||
|
||||
/// Numbering a column numbers its cells as one list, like Word.
|
||||
#[test]
|
||||
fn numbering_a_column_makes_one_list() {
|
||||
@@ -510,6 +534,46 @@ fn a_nested_tables_column_fits_within_its_cell() {
|
||||
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
|
||||
}
|
||||
|
||||
/// #8441: a right-to-left table keeps its cells' right margins on their right (#6941), so a
|
||||
/// nested table in such a cell fits up to that cell's right margin, not its left one, when the
|
||||
/// two differ.
|
||||
#[test]
|
||||
fn a_nested_tables_column_fits_within_a_right_to_left_cell() {
|
||||
let mut s = rtl_table_session(1, 2);
|
||||
s.sel = Selection::caret(cell_pos(&s, 0, 0));
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 2})).unwrap();
|
||||
let (inner, _, _) = s.sel.focus.path.cell().unwrap();
|
||||
let outer = table_path(&s);
|
||||
// A left margin of 20 pt and a right one of 2 pt; the nested table itself left to right.
|
||||
s.doc.table_mut(StoryRef::Body, &outer).unwrap().rows[0].cells[0].props.margins = Some([0.0, 20.0, 0.0, 2.0]);
|
||||
s.doc.table_mut(StoryRef::Body, &inner).unwrap().props.bidi_visual = false;
|
||||
s.touch();
|
||||
let rect = |s: &mut Session, table: &Path, cell: usize| {
|
||||
s.layout().pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|it| match it {
|
||||
Placed::Cell { rect, table: t, row: 0, cell: c, .. } if t == table && *c == cell => Some(*rect),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
for col in [1, 0] {
|
||||
let r = rect(&mut s, &inner, col);
|
||||
s.run("table.fitColumn", &json!({"page": 0, "x": r.right(), "y": mid_y(r)})).unwrap();
|
||||
}
|
||||
s.run("text.insert", &json!({"text": "word ".repeat(40)})).unwrap();
|
||||
let host = rect(&mut s, &outer, 0);
|
||||
let (a, b) = (rect(&mut s, &inner, 0), rect(&mut s, &inner, 1));
|
||||
assert!(b.right() < host.right() - 40.0, "{b:?} in {host:?}");
|
||||
s.run("table.fitColumn", &json!({"page": 0, "x": a.right(), "y": mid_y(a)})).unwrap();
|
||||
let b1 = rect(&mut s, &inner, 1);
|
||||
let text_right = host.right() - 2.0;
|
||||
assert!((b1.right() - text_right).abs() < 0.5, "the table fills its cell's text up to its right margin: {b1:?}, {text_right}");
|
||||
let host1 = rect(&mut s, &outer, 0);
|
||||
assert_eq!((host1.x, host1.w), (host.x, host.w), "the table around it keeps its columns");
|
||||
}
|
||||
|
||||
/// Pasting formatting onto a selected column leaves its text (it used to clear it).
|
||||
#[test]
|
||||
fn the_format_painter_keeps_a_selected_columns_text() {
|
||||
|
||||
@@ -123,12 +123,12 @@ pub(super) fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.push_undo("AutoFormat", doc, sel);
|
||||
// Undo right after it makes the capitalised word an exception.
|
||||
let depth = s.undo_steps_so_far();
|
||||
if let Some(c) = s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
c.depth = depth;
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.commit_depth(depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
s.set_ime_edit_outcome(outcome);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -87,22 +87,35 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
if f.off > 0 {
|
||||
let a = Pos { off: para.backspace_from(f.off), ..f.clone() };
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
let carried = deleted_char_props(s, &a, &f);
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome {
|
||||
classified: true,
|
||||
content_changed: effect.content_changed,
|
||||
state_changed: effect.state_changed,
|
||||
transformed: false,
|
||||
selection_changed: false,
|
||||
});
|
||||
let (content_changed, state_changed, transformed) = if let Some(start) =
|
||||
s.autocap.as_ref().and_then(|c| c.pronoun_before_separator(&a, &f, s.undo_steps_so_far()))
|
||||
&& matches!(para.text.get(start.off..f.off), Some("I " | "I," | "I." | "I;" | "I:" | "I!" | "I?"))
|
||||
{
|
||||
// This restores a letter in place. Ordinary typing over a selection removes its link.
|
||||
let props = para.props_of_char(start.off);
|
||||
let linked_letter = props.link.as_ref().map(|_| props.clone());
|
||||
s.sel = Selection { anchor: start.clone(), focus: f.clone() };
|
||||
let pending = std::mem::replace(&mut s.pending, linked_letter);
|
||||
let effect = crate::cmd::type_text_effect(s, "i");
|
||||
s.pending = pending;
|
||||
let effect = effect?;
|
||||
if let Some(c) = &mut s.autocap {
|
||||
c.note_backspace(&start, &f);
|
||||
}
|
||||
(effect.content_changed, effect.state_changed, true)
|
||||
} else {
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
(effect.content_changed, effect.state_changed, false)
|
||||
};
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome { classified: true, content_changed, state_changed, transformed, selection_changed: false });
|
||||
// As in Word, text typed next takes the deleted character's formatting until the caret
|
||||
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
|
||||
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
if content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
s.pending_at = carried.as_ref().map(|_| a.clone());
|
||||
s.pending = carried;
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
if let Some((doc, sel)) = plain {
|
||||
// Removes the marks, then AutoCorrects the word as without them.
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
let (done_doc, done_sel) = (std::mem::replace(&mut s.doc, doc), std::mem::replace(&mut s.sel, sel));
|
||||
let new = split_para(s, &at)?;
|
||||
let c = s.doc.para_at(&new).map(|p| p.mark.clone()).unwrap_or_default();
|
||||
@@ -165,7 +165,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
return Ok(());
|
||||
}
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
at = s.sel.focus.clone();
|
||||
}
|
||||
let new = split_para(s, &at)?;
|
||||
@@ -206,7 +206,11 @@ pub(super) fn tab(s: &mut Session, _: &Value) -> CmdResult {
|
||||
&& n.num != 0
|
||||
{
|
||||
let para = s.doc.para_mut(f.story, &f.path)?;
|
||||
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
|
||||
let level = n.level.saturating_add(1).min(8);
|
||||
para.props.numbering = Some(NumRef { num: n.num, level });
|
||||
if level != n.level {
|
||||
crate::cmd::para::drop_direct_indents(&mut para.props);
|
||||
}
|
||||
para.touch();
|
||||
return sel_result(s);
|
||||
}
|
||||
@@ -255,7 +259,11 @@ fn indent_by_tab(s: &mut Session, f: &Pos) -> CmdResult {
|
||||
&& let Some(n) = r.numbering.filter(|n| n.num != 0)
|
||||
{
|
||||
let p = s.doc.para_mut(f.story, &f.path)?;
|
||||
p.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_add(1).min(8) });
|
||||
let level = n.level.saturating_add(1).min(8);
|
||||
p.props.numbering = Some(NumRef { num: n.num, level });
|
||||
if level != n.level {
|
||||
crate::cmd::para::drop_direct_indents(&mut p.props);
|
||||
}
|
||||
p.touch();
|
||||
return sel_result(s);
|
||||
}
|
||||
@@ -288,7 +296,11 @@ pub(super) fn back_tab(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let f = s.sel.focus.clone();
|
||||
if let Some(n) = s.doc.para_at(&f).and_then(|x| x.props.numbering).filter(|n| n.num != 0) {
|
||||
let para = s.doc.para_mut(f.story, &f.path)?;
|
||||
para.props.numbering = Some(NumRef { num: n.num, level: n.level.saturating_sub(1) });
|
||||
let level = n.level.saturating_sub(1);
|
||||
para.props.numbering = Some(NumRef { num: n.num, level });
|
||||
if level != n.level {
|
||||
crate::cmd::para::drop_direct_indents(&mut para.props);
|
||||
}
|
||||
para.touch();
|
||||
return sel_result(s);
|
||||
}
|
||||
|
||||
@@ -268,6 +268,15 @@ fn plain_word(w: &str) -> bool {
|
||||
!w.trim().is_empty() && w.chars().count() <= MAX_FROM && !w.contains(|c: char| c.is_whitespace() || c == '\u{FFFC}')
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct PronounCap {
|
||||
depth: u64,
|
||||
story: wordcraft_doc::StoryRef,
|
||||
path: wordcraft_doc::Path,
|
||||
start: usize,
|
||||
backspaced: bool,
|
||||
}
|
||||
|
||||
/// The newest automatic capitalisation (a sentence capital, a TWo INitial CApitals fix), kept so
|
||||
/// that undoing it, or backspacing it and typing the word again, makes an exception (#1857).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -283,11 +292,64 @@ pub struct AutoCap {
|
||||
pub(super) prev: String,
|
||||
/// The TWo INitial CApitals word as typed ("TWo").
|
||||
pub(super) two_caps: Option<String>,
|
||||
/// The English replacement of lowercase i with uppercase I, kept alongside an earlier sentence
|
||||
/// capital so an automatic `I` does not wipe the pending first-letter exception.
|
||||
pub(super) pronoun: Option<PronounCap>,
|
||||
/// The user backspaced into the word after the change.
|
||||
pub(super) backspaced: bool,
|
||||
}
|
||||
|
||||
impl AutoCap {
|
||||
pub(crate) fn commit_depth(&mut self, depth: u64) {
|
||||
if self.depth == u64::MAX {
|
||||
self.depth = depth;
|
||||
}
|
||||
if let Some(p) = self.pronoun.as_mut().filter(|p| p.depth == u64::MAX) {
|
||||
p.depth = depth;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_uncommitted(slot: &mut Option<Self>) {
|
||||
if let Some(c) = slot.as_mut() {
|
||||
if c.pronoun.as_ref().is_some_and(|p| p.depth == u64::MAX) {
|
||||
c.pronoun = None;
|
||||
}
|
||||
if c.depth == u64::MAX {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn record_pronoun(slot: &mut Option<Self>, story: wordcraft_doc::StoryRef, path: wordcraft_doc::Path, start: usize) {
|
||||
let pronoun = PronounCap { depth: u64::MAX, story, path: path.clone(), start, backspaced: false };
|
||||
if let Some(c) = slot.as_mut().filter(|c| !c.prev.is_empty() || c.two_caps.is_some()) {
|
||||
c.pronoun = Some(pronoun);
|
||||
} else {
|
||||
*slot =
|
||||
Some(Self { depth: u64::MAX, story, path, start, prev: String::new(), two_caps: None, pronoun: Some(pronoun), backspaced: false });
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take_backspaced_pronoun(slot: &mut Option<Self>, english: bool, word: &str, f: &Pos, start: usize) -> bool {
|
||||
let Some(c) = slot.as_mut() else { return false };
|
||||
let Some(p) = c.pronoun.take() else { return false };
|
||||
if c.prev.is_empty() && c.two_caps.is_none() {
|
||||
*slot = None;
|
||||
}
|
||||
english && word == "i" && p.backspaced && p.story == f.story && p.path == f.path && p.start == start
|
||||
}
|
||||
|
||||
/// The start of a just-corrected I when Backspace removes the separator after it.
|
||||
pub(crate) fn pronoun_before_separator(&self, a: &Pos, f: &Pos, undo_steps: u64) -> Option<Pos> {
|
||||
let p = self.pronoun.as_ref()?;
|
||||
(!p.backspaced
|
||||
&& p.story == f.story
|
||||
&& p.path == f.path
|
||||
&& p.start.checked_add(1) == Some(a.off)
|
||||
&& p.depth.checked_add(1) == Some(undo_steps))
|
||||
.then(|| Pos { off: p.start, ..f.clone() })
|
||||
}
|
||||
|
||||
pub(crate) fn add_exceptions(self, ac: &mut AutoCorrectPrefs) {
|
||||
if ac.auto_add_first_letter && !self.prev.is_empty() {
|
||||
ac.add_exception(self.prev);
|
||||
@@ -304,6 +366,14 @@ impl AutoCap {
|
||||
if f.story == self.story && f.path == self.path && a.off <= self.start && f.off > self.start {
|
||||
self.backspaced = true;
|
||||
}
|
||||
if let Some(p) = &mut self.pronoun
|
||||
&& f.story == p.story
|
||||
&& f.path == p.path
|
||||
&& a.off <= p.start
|
||||
&& f.off > p.start
|
||||
{
|
||||
p.backspaced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -260,12 +260,12 @@ fn diff_notes(
|
||||
}
|
||||
for &new_id in ¬es.inserted {
|
||||
if let Some(part) = doc.parts.get_mut(&new_id) {
|
||||
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins)))).collect();
|
||||
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.ins = Some(ctx.ins), &|_| {}))).collect();
|
||||
}
|
||||
}
|
||||
for &orig_id in ¬es.deleted {
|
||||
if let Some(part) = doc.parts.get_mut(&orig_id) {
|
||||
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del)))).collect();
|
||||
part.blocks = part.blocks.iter().map(|b| Arc::new(mark_block(b, &|c| c.del = Some(ctx.del), &|_| {}))).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -443,14 +443,18 @@ 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| {
|
||||
// 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);
|
||||
})));
|
||||
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))));
|
||||
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins), &|c| c.del = None)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1622,13 +1626,18 @@ fn block_text(b: &Block, depth: usize) -> String {
|
||||
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
|
||||
/// iteratively, without recursion or depth truncation.
|
||||
///
|
||||
/// Known limitation: resolving a revision needs a following paragraph, so a paragraph inserted at
|
||||
/// the very end (rejected) or deleted from the very end (accepted) still leaves one empty
|
||||
/// paragraph. That is a separate follow-up, not handled here. A section-carrying inserted
|
||||
/// paragraph is not such a case: `resolve_para` removes the section break first (#5734, issue
|
||||
/// #5667), so rejecting it takes the paragraph out whole and the following paragraph keeps its
|
||||
/// own properties.
|
||||
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
|
||||
/// 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.
|
||||
///
|
||||
/// `mark` additionally updates each paragraph mark. A whole inserted block keeps only the
|
||||
/// compare's insertion on its mark: a `del` the revised document's mark already carried (a pending
|
||||
/// deletion by another author) must not survive next to the compare's `ins` — on accept the
|
||||
/// deletion branch would resolve the inserted paragraph away (#6899). Run-level revisions of the
|
||||
/// source block are left alone.
|
||||
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), mark: &dyn Fn(&mut CharProps)) -> Block {
|
||||
let mut out = b.clone();
|
||||
let mut todo = vec![&mut out];
|
||||
while let Some(blk) = todo.pop() {
|
||||
@@ -1637,6 +1646,7 @@ fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
|
||||
let len = p.len();
|
||||
let _ = p.format(0, len, f);
|
||||
f(&mut p.mark);
|
||||
mark(&mut p.mark);
|
||||
p.touch();
|
||||
}
|
||||
Block::Table(t) => {
|
||||
|
||||
@@ -55,6 +55,72 @@ fn compare_marks_a_whole_paragraph_and_its_mark() {
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
|
||||
for (original, revised, command) in [("A\nB\nC", "A\nNEW\nB\nC", "review.rejectAll"), ("A\nOLD\nB\nC", "A\nB\nC", "review.acceptAll")] {
|
||||
let mut s = Session::new(Document::from_text(original));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.sel = Selection::caret(Pos::body(2, 1));
|
||||
s.run(command, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB\nC");
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert_eq!(s.sel.focus, Pos::body(1, 1), "{command} keeps the caret after B");
|
||||
s.run("text.insert", &json!({"text": "!"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB!\nC");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_all_keeps_selection_with_surviving_multibyte_text_in_the_same_paragraph() {
|
||||
for (cmd, initial) in [("review.acceptAll", "雪漢字Q"), ("review.rejectAll", "漢字Q")] {
|
||||
let mut original = Session::new(Document::from_text(initial));
|
||||
let removed = "雪".len();
|
||||
let first_kept = "漢".len();
|
||||
original.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
if cmd == "review.acceptAll" {
|
||||
original.sel = Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, removed) };
|
||||
original.run("text.delete", &json!({})).unwrap();
|
||||
} else {
|
||||
original.sel = Selection::caret(Pos::body(0, 0));
|
||||
original.run("text.insert", &json!({"text": "雪"})).unwrap();
|
||||
}
|
||||
assert_eq!(original.doc.plain_text(StoryRef::Body), "雪漢字Q");
|
||||
|
||||
for (before, after, typed) in [
|
||||
(Selection::caret(Pos::body(0, removed)), Selection::caret(Pos::body(0, 0)), "!漢字Q"),
|
||||
(
|
||||
Selection { anchor: Pos::body(0, removed + first_kept), focus: Pos::body(0, removed) },
|
||||
Selection { anchor: Pos::body(0, first_kept), focus: Pos::body(0, 0) },
|
||||
"!字Q",
|
||||
),
|
||||
] {
|
||||
let mut s = Session::new(original.doc.clone());
|
||||
s.sel = before;
|
||||
s.run(cmd, &json!({"stopTracking": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "漢字Q", "{cmd}");
|
||||
assert_eq!(s.sel, after, "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "!"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), typed, "{cmd}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
|
||||
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.sel = Selection { anchor: Pos::body(1, "é".len()), focus: Pos::body(2, "X".len()) };
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
s.sel = Selection { anchor: Pos::body(2, "X🙂".len()), focus: Pos::body(1, 0) };
|
||||
|
||||
s.run("review.acceptAll", &json!({"stopTracking": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\né🙂B\nC");
|
||||
assert_eq!(s.sel.anchor, Pos::body(1, "é🙂".len()));
|
||||
assert_eq!(s.sel.focus, Pos::body(1, 0));
|
||||
s.run("text.insert", &json!({"text": "Q"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nQB\nC");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_an_empty_paragraphs_mark() {
|
||||
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
|
||||
@@ -105,31 +171,68 @@ fn compare_keeps_another_authors_deletion_stamp() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_the_terminal_inserted_paragraph_limitation() {
|
||||
// Characterizes the limitation documented on `mark_block` (compare.rs): resolving a revision
|
||||
// needs a following paragraph, so a paragraph inserted at the very end is rejected but leaves
|
||||
// one empty paragraph behind. Flip this test when the follow-up fix lands.
|
||||
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\n", "the rejected terminal paragraph still leaves a line");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 1, "the rejected terminal paragraph is left as one empty paragraph");
|
||||
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_pins_the_terminal_deleted_paragraph_limitation() {
|
||||
// The mirror of `compare_pins_the_terminal_inserted_paragraph_limitation`: a paragraph deleted
|
||||
// from the very end is accepted but still leaves one empty paragraph. Characterizes the
|
||||
// limitation documented on `mark_block` (compare.rs); flip when the follow-up fix lands.
|
||||
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\n", "the accepted terminal deletion still leaves a line");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 1, "the accepted terminal deletion is left as one empty paragraph");
|
||||
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 resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
|
||||
let keep = "A\nKeep this";
|
||||
// Both endpoints of the removed paragraph go to the preceding paragraph's end (#8500),
|
||||
// even if removing another paragraph subsequently shifts that paragraph up (#8913).
|
||||
for (changed, last) in [("A\nKeep this\nNEW", 2), ("A\nEarlier\nKeep this\nNEW", 3)] {
|
||||
for (orig, revised, cmd) in [(keep, changed, "review.rejectAll"), (changed, keep, "review.acceptAll")] {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(last, 0), "focus": Pos::body(last, 3)})).unwrap();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), keep, "{cmd}, last block {last}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}, last block {last}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}, last block {last}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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]
|
||||
@@ -201,6 +304,35 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_terminal_paragraph_when_insertion_accepted_or_deletion_rejected() {
|
||||
// Inserted last paragraph: accepting keeps it whole.
|
||||
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: rejecting keeps it whole.
|
||||
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.";
|
||||
@@ -1680,55 +1812,123 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), revised);
|
||||
}
|
||||
|
||||
fn assert_whole_block_mark_compare(from: &str, to: &str, expected_mid: &str, is_del: bool, preserve_bold: bool) {
|
||||
let expected_empty = |text: &str| text.split('\n').filter(|line| line.is_empty()).count();
|
||||
let from_len = from.split('\n').count();
|
||||
let to_len = to.split('\n').count();
|
||||
let mut s = Session::new(Document::from_text(from));
|
||||
if preserve_bold && let Some(Block::Para(p)) = s.doc.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.mark.bold = Some(true);
|
||||
}
|
||||
s.run("review.compare", &json!({"text": to})).unwrap();
|
||||
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().expect("block 1 must be paragraph");
|
||||
assert_eq!(mid.plain_text(), expected_mid);
|
||||
if expected_mid.is_empty() {
|
||||
assert_eq!(mid.len(), 0);
|
||||
}
|
||||
if is_del {
|
||||
assert!(mid.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
|
||||
} else {
|
||||
assert!(mid.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
|
||||
}
|
||||
if preserve_bold {
|
||||
assert_eq!(mid.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
|
||||
}
|
||||
|
||||
let mut s_rej = Session::new(s.doc.clone());
|
||||
s_rej.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s_rej.doc.plain_text(StoryRef::Body), from);
|
||||
assert_eq!(s_rej.doc.body.len(), from_len);
|
||||
assert_eq!(empty_paras(&s_rej), expected_empty(from), "rejecting a whole-block revision changed empty paragraph count");
|
||||
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), to);
|
||||
assert_eq!(s.doc.body.len(), to_len);
|
||||
assert_eq!(empty_paras(&s), expected_empty(to), "accepting a whole-block revision changed empty paragraph count");
|
||||
}
|
||||
|
||||
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
|
||||
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
|
||||
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
|
||||
/// and `review.rejectAll`.
|
||||
#[test]
|
||||
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
|
||||
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
|
||||
let orig_multi = "Keep start.\nDelete me.\nKeep end.";
|
||||
let rev_multi = "Keep start.\nKeep end.";
|
||||
let mut s2 = Session::new(Document::from_text(orig_multi));
|
||||
if let Some(Block::Para(p)) = s2.doc.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.mark.bold = Some(true);
|
||||
}
|
||||
s2.run("review.compare", &json!({"text": rev_multi})).unwrap();
|
||||
|
||||
// In s2.doc.body, block 1 was deleted whole.
|
||||
// Verify that p.mark.del is recorded by mark_block and formatting is preserved.
|
||||
let del_para = s2.doc.body[1].as_para().expect("block 1 must be paragraph");
|
||||
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
|
||||
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
|
||||
|
||||
// Accept all changes: deleted paragraph is removed
|
||||
s2.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
|
||||
|
||||
// Test whole-block insertion
|
||||
let mut s3 = Session::new(Document::from_text(rev_multi));
|
||||
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
|
||||
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
|
||||
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
|
||||
s3.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
|
||||
assert_whole_block_mark_compare(orig_multi, rev_multi, "Delete me.", true, true);
|
||||
assert_whole_block_mark_compare(rev_multi, orig_multi, "Delete me.", false, false);
|
||||
|
||||
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
|
||||
let orig_empty = "Before.\n\nAfter.";
|
||||
let rev_empty = "Before.\nAfter.";
|
||||
let mut s4 = Session::new(Document::from_text(orig_empty));
|
||||
s4.run("review.compare", &json!({"text": rev_empty})).unwrap();
|
||||
let empty_del = s4.doc.body[1].as_para().expect("empty paragraph block");
|
||||
assert_eq!(empty_del.len(), 0);
|
||||
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
|
||||
s4.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
|
||||
assert_whole_block_mark_compare(orig_empty, rev_empty, "", true, false);
|
||||
assert_whole_block_mark_compare(rev_empty, orig_empty, "", false, false);
|
||||
}
|
||||
|
||||
let mut s5 = Session::new(Document::from_text(rev_empty));
|
||||
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
|
||||
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
|
||||
assert_eq!(empty_ins.len(), 0);
|
||||
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
|
||||
s5.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
|
||||
/// Issue #6899: when the revised document's paragraph mark already carries another author's
|
||||
/// pending deletion, a whole-paragraph insertion by compare must not leave the mark with both
|
||||
/// `ins` and `del` — on accept the deletion branch would remove the inserted paragraph (or join
|
||||
/// it away), losing the inserted break. The revised clone's mark keeps only the compare's `ins`.
|
||||
#[test]
|
||||
fn compare_inserted_paragraph_mark_drops_a_foreign_del() {
|
||||
use wordcraft_doc::{Revision, RevisionKind};
|
||||
let mut rev = Document::from_text("Keep start.\nNew line.\nKeep end.");
|
||||
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
|
||||
if let Some(Block::Para(p)) = rev.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.mark.del = Some(0);
|
||||
}
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-6899-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
let check = crate::io::open_path(&path).unwrap();
|
||||
assert!(check.body[1].as_para().unwrap().mark.del.is_some(), "the foreign del must survive the docx round-trip, or this test proves nothing");
|
||||
|
||||
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let ins = s.doc.body[1].as_para().expect("block 1 is the inserted paragraph");
|
||||
assert!(ins.mark.ins.is_some(), "compare marks the whole inserted paragraph's mark");
|
||||
assert!(ins.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
|
||||
// Accepting keeps the inserted paragraph break: the text reads as the revised document's.
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Keep start.\nNew line.\nKeep end.");
|
||||
}
|
||||
|
||||
/// Issue #6899, inside a table: `mark_block` recurses into cells, so a paragraph mark there gets
|
||||
/// the same treatment — a foreign `del` does not sit next to the compare's `ins`.
|
||||
#[test]
|
||||
fn compare_inserted_table_cell_paragraph_mark_drops_a_foreign_del() {
|
||||
use wordcraft_doc::{Revision, RevisionKind, Table};
|
||||
let mut rev = Document::from_text("Keep start.\nKeep end.");
|
||||
rev.revisions.push(Revision { kind: RevisionKind::Delete, author: "Other".into(), date: String::new(), date_utc: None, move_name: None });
|
||||
let mut t = Table::new(1, 1, 200.0);
|
||||
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut())
|
||||
&& let Some(Block::Para(p)) = c.blocks.first_mut().map(Arc::make_mut)
|
||||
{
|
||||
p.mark.del = Some(0);
|
||||
}
|
||||
rev.body.insert(1, Arc::new(Block::Table(t)));
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-6899-table-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
let check = crate::io::open_path(&path).unwrap();
|
||||
let cell_marked = check.body.iter().any(|b| match &**b {
|
||||
Block::Table(t) => {
|
||||
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).any(|b| b.as_para().is_some_and(|p| p.mark.del.is_some()))
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(cell_marked, "the cell paragraph's foreign del must survive the docx round-trip, or this test proves nothing");
|
||||
|
||||
let mut s = Session::new(Document::from_text("Keep start.\nKeep end."));
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let Some(Block::Table(t)) = s.doc.body.get(1).map(|b| &**b) else { panic!("block 1 is the inserted table") };
|
||||
let cell_para = t.rows[0].cells[0].blocks[0].as_para().expect("the cell paragraph");
|
||||
assert!(cell_para.mark.ins.is_some(), "compare marks the inserted cell paragraph's mark");
|
||||
assert!(cell_para.mark.del.is_none(), "the foreign del does not sit next to the compare's ins");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert!(matches!(s.doc.body.get(1).map(|b| &**b), Some(Block::Table(_))), "accepting keeps the inserted table");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -74,6 +74,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
&& letters.chars().nth(1).is_some_and(char::is_uppercase)
|
||||
&& letters.chars().next().is_some_and(char::is_uppercase))
|
||||
.then(|| letters.clone()),
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
let fixed: String = reps.concat();
|
||||
@@ -84,7 +85,9 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
// A whole-word replacement, else "wait..." → "wait…". Proofing decides what is English the
|
||||
// same way (#835); every English (en-GB, en-CA…) counts (#1281).
|
||||
let english = s.doc.para_at(&f).is_none_or(|_| wordcraft_proof::ProofLang::from_tag(lang.as_deref()).is_english());
|
||||
let found = if ac.replace_text { ac.replacement_in(&word, english) } else { None };
|
||||
// A rejected pronoun is kept at this occurrence only, including at the start of a sentence.
|
||||
let keep_i = AutoCap::take_backspaced_pronoun(&mut s.autocap, english, &word, &f, start);
|
||||
let found = if ac.replace_text && !keep_i { ac.replacement_in(&word, english) } else { None };
|
||||
let (from, rep) = match found {
|
||||
Some(r) => (start, Some(r)),
|
||||
None if ac.replace_text && word.len() > 3 && word.ends_with("...") => (start + word.len() - 3, Some("…".to_string())),
|
||||
@@ -106,6 +109,9 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
para.insert_text(from, &rep, &props)?;
|
||||
caret = (f.off + rep.len()).saturating_sub(end - from);
|
||||
s.sel = Selection::caret(Pos { off: caret, ..f.clone() });
|
||||
if english && word == "i" && rep == "I" {
|
||||
AutoCap::record_pronoun(&mut s.autocap, f.story, f.path.clone(), start);
|
||||
}
|
||||
}
|
||||
let end = caret.saturating_sub(trigger);
|
||||
let Some(word) = s.doc.para_at(&f).and_then(|p| p.text.get(start..end)).map(str::to_string) else { return Ok(()) };
|
||||
@@ -147,7 +153,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
} else {
|
||||
last
|
||||
};
|
||||
let mut sentence = sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let mut sentence = !keep_i && sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let prev = if sentence { prev_token(before_word) } else { String::new() };
|
||||
// Typing the word again after backspacing an automatic capital: the user doesn't want it
|
||||
// (Word's "Automatically add words to list"); an exception, so no capital this time either.
|
||||
@@ -173,7 +179,16 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
match s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
Some(c) => c.prev = prev,
|
||||
None => {
|
||||
s.autocap = Some(AutoCap { depth: u64::MAX, story: f.story, path: f.path, start, prev, two_caps: None, backspaced: false })
|
||||
s.autocap = Some(AutoCap {
|
||||
depth: u64::MAX,
|
||||
story: f.story,
|
||||
path: f.path,
|
||||
start,
|
||||
prev,
|
||||
two_caps: None,
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -52,6 +52,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
Ok(json!({"paperColor": color}))
|
||||
}).params(r#"{"value": "document" | "green" | "cream" | "gray"}"#).pure(),
|
||||
// How the edges of page text are smoothed on screen. Screen only; never in the document.
|
||||
CommandSpec::new("view.textSmoothing", "Screen Text Smoothing", "View › Display", |s, v| {
|
||||
let smoothing: TextSmoothing = serde_json::from_value(v.get("value").cloned().unwrap_or(Value::Null))
|
||||
.map_err(|_| CmdError::Params("screen text smoothing must be system, grayscale, or subpixel".into()))?;
|
||||
s.prefs.text_smoothing = smoothing;
|
||||
Ok(json!({"textSmoothing": smoothing}))
|
||||
})
|
||||
.params(r#"{"value": "system" | "grayscale" | "subpixel"}"#)
|
||||
.pure(),
|
||||
// Print Layout: hide the white space (margins, headers, footers) between pages. Screen only.
|
||||
CommandSpec::new("view.hideWhiteSpace", "Hide White Space", "View › Show", |s, v| toggle(s, v, |x| &mut x.hide_white_space))
|
||||
.params(r#"{"value"?: bool}"#)
|
||||
@@ -349,6 +358,35 @@ fn read_line_spacing(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"spacing": spacing}))
|
||||
}
|
||||
|
||||
/// How the edges of page text are smoothed on screen, saved with user preferences, never in the
|
||||
/// document. Exports, prints and PDFs are not affected.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextSmoothing {
|
||||
/// As the system is set: subpixel where it asks for it (ClearType on Windows, `rgba`
|
||||
/// antialiasing on a Linux desktop) and the screen is not a high-density one, else
|
||||
/// greyscale. macOS never asks for it.
|
||||
#[default]
|
||||
System,
|
||||
/// Greyscale antialiasing: grey edges, no colour.
|
||||
Grayscale,
|
||||
/// Subpixel (LCD) antialiasing, whatever the system says: edges three times as fine
|
||||
/// sideways, with faint colour in them. In the system's stripe order, RGB when it gives none.
|
||||
Subpixel,
|
||||
}
|
||||
|
||||
impl TextSmoothing {
|
||||
pub const ALL: [Self; 3] = [Self::System, Self::Grayscale, Self::Subpixel];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "Use system setting",
|
||||
Self::Grayscale => "Grayscale",
|
||||
Self::Subpixel => "Subpixel (LCD)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen-only paper presets, saved with user preferences, never in the document.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -273,7 +273,7 @@ pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), Str
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir, dict_test_lock};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -282,6 +282,11 @@ mod tests {
|
||||
/// Test lock serializing tests that access the global proofing dictionary.
|
||||
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Acquire [`DICT_TEST_LOCK`], recovering cleanly if an earlier test panicked while holding it.
|
||||
pub(crate) fn dict_test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
DICT_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// RAII guard for temporary directories in dictionary tests.
|
||||
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! `/work`), exactly: on Windows what exists is resolved to its real case first.
|
||||
//! - Writing replaces or removes a directory entry, so for write access the entry itself (its
|
||||
//! folder's links followed, its own name as given) must lie inside the root as well: a link
|
||||
//! folder's links followed, its own name as it stands) must lie inside the root as well: a link
|
||||
//! outside the root that leads into it is not a way to write outside (#3735).
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
@@ -76,6 +76,12 @@ impl AutomationRoots {
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// Roots that grant no access at all: what an agent gets when its folders can't be used, so it
|
||||
/// is refused rather than left unconfined.
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: None, write: None })
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_ref().map(|r| r.shown.as_path())
|
||||
@@ -216,14 +222,24 @@ fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
|
||||
/// The directory entry `path` names: its folder resolved as [`resolve`] resolves it, then its own
|
||||
/// name as given, so a link there is the entry itself, not what it leads to. That entry is what
|
||||
/// replacing or removing the file changes.
|
||||
/// replacing or removing the file changes. What exists and isn't a link gets its real case, which
|
||||
/// is how the root is spelled when another spelling of the root is named.
|
||||
fn resolve_entry(path: &str) -> Result<PathBuf, String> {
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?;
|
||||
let (Some(folder), Some(name)) = (absolute.parent(), absolute.file_name()) else {
|
||||
return Err(format!("automation path rejected: not a file name: {path}"));
|
||||
};
|
||||
let mut entry = resolve_absolute(path, folder)?;
|
||||
entry.push(name);
|
||||
let resolved_folder = resolve_absolute(path, folder)?;
|
||||
let entry = resolved_folder.join(name);
|
||||
// Only accept `canonicalize` (for on-disk case) when it stays in `resolved_folder` under the
|
||||
// same name, so a symlink swapped in after `symlink_metadata` cannot redirect outside -> inside (#9292).
|
||||
if std::fs::symlink_metadata(&entry).is_ok_and(|m| !m.file_type().is_symlink())
|
||||
&& let Ok(canon) = std::fs::canonicalize(&entry)
|
||||
&& canon.parent() == Some(resolved_folder.as_path())
|
||||
&& canon.file_name().is_some_and(|c| c.to_string_lossy().eq_ignore_ascii_case(&name.to_string_lossy()))
|
||||
{
|
||||
return Ok(canon);
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
@@ -264,30 +280,19 @@ fn resolve_absolute(path: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
/// Is `path` (resolved) `root` or inside it, component by component? Exactly, on Windows too: what
|
||||
/// exists has its real case from [`resolve`], and a folder that doesn't exist yet may be a different
|
||||
/// one from the root where a parent folder is case sensitive.
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
root.components().all(|r| path.next() == Some(r))
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return false;
|
||||
}
|
||||
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
|
||||
let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered =
|
||||
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
@@ -381,6 +386,7 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A root and a path reached through links are compared after the links are followed.
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
@@ -428,20 +434,78 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that differs in case is another name until the file system says otherwise.
|
||||
#[test]
|
||||
fn names_are_compared_exactly() {
|
||||
let root = Path::new("/work/In");
|
||||
assert!(inside(Path::new("/work/In/new/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/IN/a.docx"), root));
|
||||
assert!(!inside(Path::new("/WORK/In/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/in\u{212A}/a.docx"), Path::new("/work/ink")), "the Kelvin sign folds to k");
|
||||
if cfg!(windows) {
|
||||
let root = Path::new(r"C:\work\In");
|
||||
assert!(inside(Path::new(r"c:\work\In\a.docx"), root), "a drive letter is one drive in either case");
|
||||
assert!(!inside(Path::new(r"C:\work\IN\a.docx"), root));
|
||||
}
|
||||
}
|
||||
|
||||
/// In a case-sensitive folder, `IN` beside the root `in` is another folder, there or not yet.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
fn a_case_sensitive_folder_keeps_a_differently_cased_name_out() {
|
||||
let base = std::env::temp_dir().join(format!("wc-file-access-case-sensitive-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let set = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output();
|
||||
if !set.as_ref().is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: a case-sensitive folder can't be made here: {set:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir(base.join("in")).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("in"))).unwrap().unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/new.docx")), Access::Write), Ok(()));
|
||||
let e = roots.check(&s(base.join("IN/new.docx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
std::fs::create_dir(base.join("IN")).unwrap();
|
||||
std::fs::write(base.join("IN/secret.docx"), "x").unwrap();
|
||||
let e = roots.check(&s(base.join("IN/secret.docx")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On Windows a path finds its real case on disk, and device names are refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_finds_the_real_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/A.SVG"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(&s(base.join("In/Sub/New.docx")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT/New.docx")), Access::Write), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT")), Access::Write), Ok(()), "the root itself, in another spelling");
|
||||
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
|
||||
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A symlink beside the write root that leads into it is not inside the root: writing would replace the link.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sibling_symlink_into_the_write_root_is_rejected() {
|
||||
let (base, roots) = folders("sibling-link");
|
||||
let link = base.join("evil");
|
||||
std::os::unix::fs::symlink(base.join("out"), &link).unwrap();
|
||||
let e = roots.check(&s(link), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Scopes nest, and a scope applies only on the thread that set it.
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
@@ -463,12 +527,13 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// What is a device name, with superscript digits and a name before a colon, and what isn't.
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL "] {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x"] {
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -509,7 +509,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
|
||||
|
||||
/// Largest document file opened by path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_DOCUMENT: u64 = 2 << 30;
|
||||
const MAX_DOCUMENT: u64 = 2u64 << 30;
|
||||
|
||||
/// The bytes of the document at `path`, read as `file.open` reads a path: inside the automation
|
||||
/// read root, and only a regular file of at most 2 GB. A named pipe would block the open and a
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user