mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-02 18:56:52 -06:00
Compare commits
350
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9dad9fca5f | ||
|
|
1bd422a454 | ||
|
|
0a7bf74427 | ||
|
|
f3d88f5da3 | ||
|
|
5991c5b7e4 | ||
|
|
7d0a1f897b | ||
|
|
f1c93ad7c7 | ||
|
|
c17448f4d5 | ||
|
|
902838c7b8 | ||
|
|
2f16864552 | ||
|
|
395eb4d8ff | ||
|
|
b8535745a0 | ||
|
|
e5bc372a0c | ||
|
|
16c803ecfd | ||
|
|
206ed0fcd4 | ||
|
|
7220765c02 | ||
|
|
257bdec953 | ||
|
|
ed757d0cdf | ||
|
|
1ab6d78010 | ||
|
|
7c6fbc0681 | ||
|
|
3afd70cf3d | ||
|
|
b741bbac9a | ||
|
|
fd948e2015 | ||
|
|
612e92e6c5 | ||
|
|
5ae937d8e3 | ||
|
|
c07395d712 | ||
|
|
1b9b8b1bf3 | ||
|
|
ea5d48b18c | ||
|
|
03b54b043f | ||
|
|
e2588d8d35 | ||
|
|
48e07fbcd1 | ||
|
|
28d2dac6fd | ||
|
|
481eb1e79b | ||
|
|
4b5ad59b01 | ||
|
|
f22123dbaf | ||
|
|
df475fac83 | ||
|
|
72e54545d8 | ||
|
|
209db57e2c | ||
|
|
cf8b64ffae | ||
|
|
aea7330f43 | ||
|
|
b8362fc62d | ||
|
|
c14183a0a0 | ||
|
|
cc438cb369 | ||
|
|
5a22d2d4ae | ||
|
|
940b64273c | ||
|
|
a1fa8b1a13 | ||
|
|
e8c3216cad | ||
|
|
8027b35f8d | ||
|
|
e862c6ad51 | ||
|
|
3035dda6d4 | ||
|
|
1a8e4ac2d3 | ||
|
|
c2f7c65e9c | ||
|
|
8d9eb6fc0f | ||
|
|
f722a2f80b | ||
|
|
678e813ec4 | ||
|
|
6b0c47d2a8 | ||
|
|
afba11d6e0 | ||
|
|
1f682738fd | ||
|
|
93abd12f9f | ||
|
|
836799463a | ||
|
|
647e726179 | ||
|
|
6b8f63e207 | ||
|
|
2b30b235d8 | ||
|
|
423c58523d | ||
|
|
e076e47529 | ||
|
|
f87e9cd6ba | ||
|
|
e70879e085 | ||
|
|
f416b3f1a5 | ||
|
|
9af6bdea33 | ||
|
|
4cf4eacc91 | ||
|
|
733a410095 | ||
|
|
20fc916072 | ||
|
|
64ec14c3df | ||
|
|
5c9f816ad2 | ||
|
|
eff3740ec5 | ||
|
|
c5375d8186 | ||
|
|
11871dc9a5 | ||
|
|
8e5200fc47 | ||
|
|
7a49244c7a | ||
|
|
c0b8362187 | ||
|
|
a65a49f9a2 | ||
|
|
05bfd76bcf | ||
|
|
ff5aff859b | ||
|
|
f6461d4f18 | ||
|
|
81d3713818 | ||
|
|
d41b7e38f4 | ||
|
|
6c53e35c16 | ||
|
|
b324cbab29 | ||
|
|
b065d1a70e | ||
|
|
bbf6ac60cb | ||
|
|
d66724fba0 | ||
|
|
3cc3ef1d51 | ||
|
|
878f3ef2ca | ||
|
|
cc2c37232a | ||
|
|
7cd6dcdbc2 | ||
|
|
866b188e2a | ||
|
|
b472bdef73 | ||
|
|
e01bf4a57b | ||
|
|
057a8b79b1 | ||
|
|
3a93ffab6d | ||
|
|
f72124cfdd | ||
|
|
3311690632 | ||
|
|
25f34eec75 | ||
|
|
b2a4699384 | ||
|
|
d23ae8609b | ||
|
|
80f01dabb8 | ||
|
|
e9da627bfe | ||
|
|
6c93357f0e | ||
|
|
7b180bcf1e | ||
|
|
32d96170e1 | ||
|
|
aa3e7b9d5f | ||
|
|
359999c32e | ||
|
|
15fc342b11 | ||
|
|
93f8cefacf | ||
|
|
012afe2dcf | ||
|
|
6c7d31aa6f | ||
|
|
830e629541 | ||
|
|
c6b037d6c0 | ||
|
|
b4eff8d494 | ||
|
|
79b3b88edd | ||
|
|
8b5bfa78bf | ||
|
|
313e14885f | ||
|
|
9a8786a3ab | ||
|
|
4b5a96163c | ||
|
|
5a68da541f | ||
|
|
3820b9b206 | ||
|
|
f7e2e88133 | ||
|
|
e874c67147 | ||
|
|
7dce30c8af | ||
|
|
b4efb2fef1 | ||
|
|
30b8f025d2 | ||
|
|
27efb34a95 | ||
|
|
61c69fceca | ||
|
|
605df8c165 | ||
|
|
199162f96a | ||
|
|
ea7322efac | ||
|
|
3e64bba9bb | ||
|
|
5d93167fe0 | ||
|
|
6659ce4adc | ||
|
|
43632f571c | ||
|
|
0e3f5f3ea6 | ||
|
|
3c8a1eeb2d | ||
|
|
3b7779df34 | ||
|
|
e7588ff931 | ||
|
|
ba1ed225c0 | ||
|
|
36e7ee7ade | ||
|
|
17c6d87f0d | ||
|
|
8d7ed624ec | ||
|
|
b4fffa91cc | ||
|
|
5ad1c48b3e | ||
|
|
ce54605a04 | ||
|
|
592d3cb902 | ||
|
|
fd81fadba7 | ||
|
|
17ae08d4b8 | ||
|
|
8edbfcdeef | ||
|
|
0f30f776bb | ||
|
|
19947b9170 | ||
|
|
1ec6f0bb58 | ||
|
|
3de53ecf4e | ||
|
|
faec3ecbde | ||
|
|
5945ca3cae | ||
|
|
a8f1edb45c | ||
|
|
a0d4edccd6 | ||
|
|
d0f25cd896 | ||
|
|
b743dbad0a | ||
|
|
45956f85bd | ||
|
|
1201692df6 | ||
|
|
2f33435bb8 | ||
|
|
a03307d6b0 | ||
|
|
8b4335903a | ||
|
|
929950acff | ||
|
|
4868d7947d | ||
|
|
0d31f95102 | ||
|
|
76ee611ed5 | ||
|
|
aa0a0b990a | ||
|
|
14111658d1 | ||
|
|
0c72c0a013 | ||
|
|
12545dd771 | ||
|
|
5e4243bf2a | ||
|
|
d80fb49267 | ||
|
|
93ce16e0f7 | ||
|
|
c70841a895 | ||
|
|
a27d6de7e1 | ||
|
|
bed86ba38e | ||
|
|
a16543415e | ||
|
|
1cf8870549 | ||
|
|
0b37a15d5d | ||
|
|
9c84f895cb | ||
|
|
cc2a5161c7 | ||
|
|
e7587b4b1b | ||
|
|
bb26821f2e | ||
|
|
b0a5ff0469 | ||
|
|
6e67ac4552 | ||
|
|
ebc9505a02 | ||
|
|
5fda6e6696 | ||
|
|
148987d098 | ||
|
|
eeac0d3322 | ||
|
|
cac0dd2ee0 | ||
|
|
5290f3bb62 | ||
|
|
ff781c42d2 | ||
|
|
262a821ec7 | ||
|
|
e802ec8f28 | ||
|
|
3e5c6ce405 | ||
|
|
3fe111cc9f | ||
|
|
8aa24886da | ||
|
|
2114b003ef | ||
|
|
c70411808d | ||
|
|
e129211603 | ||
|
|
91a52f278c | ||
|
|
80c5151ab3 | ||
|
|
b4b41e038d | ||
|
|
6637fb7bbf | ||
|
|
5e8c7cb7cb | ||
|
|
2c08518c6f | ||
|
|
4a4b37c255 | ||
|
|
676fe0ee9b | ||
|
|
16ec8d91ce | ||
|
|
6078524793 | ||
|
|
d729387c8c | ||
|
|
c7b21e5d02 | ||
|
|
273d2ed225 | ||
|
|
bdf3c54189 | ||
|
|
6a445b341a | ||
|
|
958dd78ceb | ||
|
|
0b7bdee856 | ||
|
|
8be58e3a21 | ||
|
|
8e7fca10b4 | ||
|
|
b83864e0f4 | ||
|
|
e39281dce7 | ||
|
|
60ec8580cd | ||
|
|
ac306cf704 | ||
|
|
0ac9cbfba9 | ||
|
|
488f75b6e0 | ||
|
|
d45c07368f | ||
|
|
dd3d3040ac | ||
|
|
ed0fe0d980 | ||
|
|
03da178335 | ||
|
|
8ee16cc876 | ||
|
|
b1958ac483 | ||
|
|
dfbeffd34a | ||
|
|
b8c2fa4962 | ||
|
|
7dbf9050e6 | ||
|
|
41f4118d0e | ||
|
|
273451b528 | ||
|
|
31aa5a1b00 | ||
|
|
0ef496019a | ||
|
|
514a95b80f | ||
|
|
741d74b3fa | ||
|
|
0837c9dac5 | ||
|
|
b92b7a40ad | ||
|
|
01b9ce4b81 | ||
|
|
90a6722453 | ||
|
|
b946229d38 | ||
|
|
5c9c343e46 | ||
|
|
9e8732bd85 | ||
|
|
c210ef5093 | ||
|
|
4c0b520a53 | ||
|
|
370489a59b | ||
|
|
783d2ce93e | ||
|
|
fd7461b295 | ||
|
|
b2964c2c1c | ||
|
|
6f7b6f2d87 | ||
|
|
b1e6d1fa22 | ||
|
|
0b1117c87f | ||
|
|
110852a379 | ||
|
|
17b26e39cc | ||
|
|
5653188ede | ||
|
|
37caf16978 | ||
|
|
a03571dea8 | ||
|
|
0345dd28f3 | ||
|
|
959bc54505 | ||
|
|
791e144fd7 | ||
|
|
6ce224d4b3 | ||
|
|
20b8ce57a8 | ||
|
|
40810c50de | ||
|
|
3d04c471a4 | ||
|
|
9f34d3790e | ||
|
|
69578bbc6f | ||
|
|
ee424da341 | ||
|
|
fe1cecbb90 | ||
|
|
c37ee263ce | ||
|
|
07e4b515fc | ||
|
|
f438ec2943 | ||
|
|
021269b675 | ||
|
|
b395c45437 | ||
|
|
68c5dfe8c7 | ||
|
|
1b8934c823 | ||
|
|
519ddb612b | ||
|
|
eac757af34 | ||
|
|
3c159e2331 | ||
|
|
f211d2914a | ||
|
|
2b99488c4b | ||
|
|
c15eb8077a | ||
|
|
d572fff4cb | ||
|
|
ad721fc2b5 | ||
|
|
1a86fd08fe | ||
|
|
0d4717cea6 | ||
|
|
60a150ab5b | ||
|
|
431251e139 | ||
|
|
5cac512cfa | ||
|
|
ace8f18c5a | ||
|
|
c7bb6f6da2 | ||
|
|
c2e4a05df1 | ||
|
|
77060f63ab | ||
|
|
cee47681a3 | ||
|
|
47039c163f | ||
|
|
b585ac4493 | ||
|
|
34b9e6aacc | ||
|
|
ce1f7ecb63 | ||
|
|
57427c7b98 | ||
|
|
dfb1341d72 | ||
|
|
32922ec9a4 | ||
|
|
7cfa807dc3 | ||
|
|
aec899bbee | ||
|
|
0f84914edc | ||
|
|
6b3555e831 | ||
|
|
0e96d0abd0 | ||
|
|
07544f5078 | ||
|
|
af4608d7f0 | ||
|
|
082d47c8a2 | ||
|
|
c70807b8a9 | ||
|
|
dd7b12f504 | ||
|
|
e525617d55 | ||
|
|
98bbdb506e | ||
|
|
b2c985ba06 | ||
|
|
0db3ce644a | ||
|
|
96eddcfe69 | ||
|
|
633f5bc212 | ||
|
|
85ad49db32 | ||
|
|
7c1792867d | ||
|
|
6e783bdc6e | ||
|
|
c2cb17cb36 | ||
|
|
aea58b38b8 | ||
|
|
ad4d2dfec0 | ||
|
|
c08be77357 | ||
|
|
a552c4bdda | ||
|
|
913d9fa5ab | ||
|
|
0d75ca3bf6 | ||
|
|
71d341fcfb | ||
|
|
3bf1a0a81c | ||
|
|
6e8820dc5d | ||
|
|
213b75ce02 | ||
|
|
8883429285 | ||
|
|
62bf70beb3 | ||
|
|
b0a2b71cbe | ||
|
|
1d890c0932 | ||
|
|
3d3e7ac5ef | ||
|
|
73f0701255 | ||
|
|
1f2510ddda | ||
|
|
734dedde28 |
+4
-1
@@ -2,7 +2,10 @@
|
||||
plan/
|
||||
/target
|
||||
/dist
|
||||
/corpus
|
||||
/corpus/*
|
||||
!/corpus/docx/
|
||||
/corpus/docx/*
|
||||
!/corpus/docx/README.md
|
||||
/log
|
||||
.DS_Store
|
||||
/.claude/
|
||||
|
||||
Generated
+165
-135
File diff suppressed because it is too large
Load Diff
+54
-54
@@ -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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
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-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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
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" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -85,28 +85,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
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-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
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" }
|
||||
# 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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
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" }
|
||||
|
||||
|
||||
@@ -188,3 +188,34 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
|
||||
for vector window controls. Its title-font features are disabled: no Cantarell
|
||||
font is embedded by this dependency and no font file is added to this repo.
|
||||
|
||||
sctk-adwaita's MIT licence:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Bartłomiej Maryńczak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
+21
-3
File diff suppressed because one or more lines are too long
@@ -36,9 +36,11 @@ USAGE:
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
Repeat --save OUT to write multiple outputs in order,
|
||||
after any outputs from --script.
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
@@ -632,6 +634,13 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let mut cli_outputs = Vec::new();
|
||||
for (i, arg) in rest.iter().enumerate() {
|
||||
if arg == "--save" {
|
||||
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
|
||||
cli_outputs.push(path.clone());
|
||||
}
|
||||
}
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
let password = password_from(&rest)?;
|
||||
@@ -680,7 +689,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
@@ -1048,6 +1057,7 @@ fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
wordcraft_engine::malloc_tuning::apply();
|
||||
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
|
||||
@@ -564,6 +564,64 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
|
||||
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
|
||||
let dir = script_dir("cli-saves");
|
||||
let input = dir.join("in.docx");
|
||||
let docx = dir.join("out.docx");
|
||||
let pdf = dir.join("out.pdf");
|
||||
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
|
||||
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
|
||||
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_script_and_cli_outputs() {
|
||||
let dir = script_dir("mixed-saves");
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
|
||||
let first = dir.join("cli.txt");
|
||||
let second = dir.join("cli.docx");
|
||||
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
|
||||
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
|
||||
assert!(path.is_file(), "{} was not written", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_a_missing_second_save_path_before_writing() {
|
||||
let dir = script_dir("missing-save");
|
||||
let first = dir.join("first.docx");
|
||||
let first_path = first.to_string_lossy();
|
||||
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
|
||||
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
|
||||
argv.extend(tail);
|
||||
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
|
||||
assert!(!first.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
|
||||
let dir = script_dir("preflight-saves");
|
||||
let first = dir.join("first.docx");
|
||||
let invalid = dir.join("missing/later.docx");
|
||||
let last = dir.join("missing-too/last.docx");
|
||||
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
|
||||
let first_path = first.to_string_lossy();
|
||||
let invalid_path = invalid.to_string_lossy();
|
||||
let last_path = last.to_string_lossy();
|
||||
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("script.docx"), "{err}");
|
||||
assert!(!first.exists());
|
||||
|
||||
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("later.docx"), "{err}");
|
||||
assert!(!first.exists() && !dir.join("script.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_bad_output_writes_no_output() {
|
||||
let dir = script_dir("badout");
|
||||
|
||||
@@ -3,6 +3,8 @@ mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod help;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! The CLI binary re-executes itself on Linux glibc with `MALLOC_TRIM_THRESHOLD_` fixed so freed
|
||||
//! page/render buffers are returned to the OS while respecting caller-supplied values.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use wordcraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR};
|
||||
|
||||
struct TempDirs(PathBuf);
|
||||
|
||||
impl TempDirs {
|
||||
fn new(tag: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let root = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-malloc-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => break dir,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", dir.display()),
|
||||
}
|
||||
};
|
||||
std::fs::create_dir_all(root.join("in")).unwrap();
|
||||
std::fs::create_dir_all(root.join("out")).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDirs {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn mcp_environ(tag: &str, set: Option<&str>) -> Vec<String> {
|
||||
let dirs = TempDirs::new(tag);
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] {
|
||||
cmd.env_remove(var);
|
||||
}
|
||||
if let Some(v) = set {
|
||||
cmd.env(TRIM_THRESHOLD_VAR, v);
|
||||
}
|
||||
let mut child = cmd
|
||||
.args(["mcp", "--automation-read-root", &s(&dirs.0.join("in")), "--automation-write-root", &s(&dirs.0.join("out"))])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"ping"}}"#).unwrap();
|
||||
let mut reply = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap();
|
||||
assert!(reply.contains(r#""id":1"#), "mcp answered after re-exec: {reply}");
|
||||
let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap();
|
||||
drop(stdin);
|
||||
assert!(child.wait().unwrap().success());
|
||||
environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_the_trim_threshold() {
|
||||
let env = mcp_environ("default", None);
|
||||
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_value_the_user_set() {
|
||||
let env = mcp_environ("explicit", Some("999999"));
|
||||
assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}");
|
||||
}
|
||||
@@ -110,7 +110,7 @@ impl Bridge {
|
||||
fn listen(&self, intake: IntakeSender) {
|
||||
self.host.listen(move |message| {
|
||||
if let Message::Open { name, data } = message {
|
||||
deliver_open(&intake, &name, &data);
|
||||
deliver_open(&intake, name.as_deref().unwrap_or("document"), &data);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -119,7 +119,7 @@ impl Bridge {
|
||||
/// The file an open message carries, queued for the next frame like a dropped file. A host's file
|
||||
/// is untrusted input: an oversized one is refused before it is copied into the app's memory (the
|
||||
/// data's own length, not the host's claim). The crate has cleaned the name (and cut it to 255
|
||||
/// characters); a blank one comes as `document` and becomes `Document.docx`.
|
||||
/// characters); a missing one comes as `None` and becomes `Document.docx`.
|
||||
fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
|
||||
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
|
||||
let FileData::Bytes(array) = data else {
|
||||
|
||||
@@ -13,14 +13,14 @@ pub fn open() -> (SharedSettings<Prefs>, craft::settings::LoadReport) {
|
||||
use std::time::Duration;
|
||||
|
||||
use craft::settings::{LegacyFile, LocalStorageFiles, Location, OpenOptions, SettingsStore};
|
||||
use wordcraft_ui_egui::prefs::legacy_ui_json;
|
||||
use wordcraft_ui_egui::prefs::legacy_ui_json_slots;
|
||||
|
||||
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
|
||||
const MAX_STORED: usize = 4 << 20;
|
||||
let options = OpenOptions::new(Location::Dir("wordcraft".into()))
|
||||
.files(Arc::new(LocalStorageFiles::new(MAX_STORED)))
|
||||
.debounce(Duration::ZERO)
|
||||
.legacy(vec![LegacyFile { path: "wordcraft.ui".into(), parse: legacy_ui_json }]);
|
||||
.legacy(vec![LegacyFile { paths: vec!["wordcraft.ui".into()], parse: legacy_ui_json_slots }]);
|
||||
let (store, report) = SettingsStore::open_with(options);
|
||||
(SharedSettings::new(store), report)
|
||||
}
|
||||
|
||||
@@ -60,8 +60,14 @@ winresource = "0.1"
|
||||
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
|
||||
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
|
||||
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
|
||||
# these versions and with this feature.
|
||||
|
||||
@@ -492,6 +492,9 @@ fn main() -> eframe::Result {
|
||||
let updates_unsafe = start_over_failed.is_some();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let updates_unsafe = false;
|
||||
// Before any thread or logger starts: re-exec on Linux glibc with MALLOC_TRIM_THRESHOLD_
|
||||
// fixed so large freed document/render buffers return to the OS.
|
||||
wordcraft_engine::malloc_tuning::apply();
|
||||
// First, so the panic hook (set once, by this call; the later one only gives it the crash-log
|
||||
// folder) and every start-up warning are recorded.
|
||||
let logger = logs::install(LogNames::new("wordcraft"));
|
||||
@@ -745,6 +748,15 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
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")) {
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings, Source};
|
||||
use craft::window::restore::Store;
|
||||
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
|
||||
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json_slots};
|
||||
|
||||
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
|
||||
const LEGACY_LIMIT: u64 = 8 << 20;
|
||||
@@ -41,7 +41,7 @@ fn open_in(dir: Option<PathBuf>, placement: &mut Store) -> (SharedSettings<Prefs
|
||||
None => OpenOptions::new(Location::Memory),
|
||||
};
|
||||
if let Some(dir) = &dir {
|
||||
options = options.legacy(vec![LegacyFile { path: dir.join("ui.json"), parse: legacy_ui_json }]);
|
||||
options = options.legacy(vec![LegacyFile { paths: vec![dir.join("ui.json")], parse: legacy_ui_json_slots }]);
|
||||
}
|
||||
let (store, report) = SettingsStore::<Prefs>::open_with(options);
|
||||
if let Source::Legacy(path) = &report.source {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Integration test for Linux Wayland client-side window decoration controls (#5814, #5375).
|
||||
//!
|
||||
//! Ensures that on Linux, client-side window controls use font-free Adwaita vector paths
|
||||
//! so the close button is rendered as a clean vector cross rather than a square fallback,
|
||||
//! and that sctk-adwaita has proper license attribution in NOTICE without bundling font files.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Strips an unquoted TOML `#` comment from a single line.
|
||||
fn strip_toml_comment(line: &str) -> &str {
|
||||
let mut in_double = false;
|
||||
let mut in_single = false;
|
||||
for (idx, ch) in line.char_indices() {
|
||||
match ch {
|
||||
'"' if !in_single => in_double = !in_double,
|
||||
'\'' if !in_double => in_single = !in_single,
|
||||
'#' if !in_double && !in_single => return &line[..idx],
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// Extracts the comment-stripped body of a TOML table section by exact `[header]`.
|
||||
fn toml_section(content: &str, header: &str) -> String {
|
||||
let mut in_section = false;
|
||||
let mut out = String::new();
|
||||
for raw_line in content.lines() {
|
||||
let line = strip_toml_comment(raw_line).trim();
|
||||
if line.starts_with('[') && line.ends_with(']') {
|
||||
if in_section {
|
||||
break;
|
||||
}
|
||||
in_section = line == header;
|
||||
continue;
|
||||
}
|
||||
if in_section && !line.is_empty() {
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
assert!(in_section, "expected target section {header} in apps/wordcraft/Cargo.toml");
|
||||
out
|
||||
}
|
||||
|
||||
/// Parses the `features = [...]` string array from the `winit = { ... }` dependency entry in a TOML section.
|
||||
fn winit_features(section: &str) -> Vec<&str> {
|
||||
let winit_start = section.find("winit").expect("target section must declare a winit dependency");
|
||||
let after_winit = §ion[winit_start..];
|
||||
let table_end = after_winit.find('}').expect("winit inline table must close with '}'");
|
||||
let winit_table = &after_winit[..=table_end];
|
||||
let features_start = winit_table.find("features").expect("winit dependency must declare features");
|
||||
let after_features = &winit_table[features_start..];
|
||||
let open_bracket = after_features.find('[').expect("winit features must open with '['");
|
||||
let after_open = &after_features[open_bracket + 1..];
|
||||
let close_bracket = after_open.find(']').expect("winit features must close with ']'");
|
||||
let array_body = &after_open[..close_bracket];
|
||||
array_body.split(',').map(|item| item.trim().trim_matches('"')).filter(|item| !item.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// Verifies that `apps/wordcraft/Cargo.toml` enables `wayland-csd-adwaita-notitle` for Linux.
|
||||
#[test]
|
||||
fn linux_manifest_enables_wayland_csd_adwaita_notitle() {
|
||||
let cargo_toml = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
|
||||
let content = std::fs::read_to_string(&cargo_toml).expect("read apps/wordcraft/Cargo.toml");
|
||||
|
||||
let linux_section = toml_section(&content, "[target.'cfg(target_os = \"linux\")'.dependencies]");
|
||||
let linux_features = winit_features(&linux_section);
|
||||
assert!(
|
||||
linux_features.contains(&"x11") && linux_features.contains(&"wayland-csd-adwaita-notitle"),
|
||||
"Linux winit dependency must enable x11 and wayland-csd-adwaita-notitle, got: {linux_features:?}"
|
||||
);
|
||||
|
||||
let other_unix_section = toml_section(&content, "[target.'cfg(all(unix, not(any(target_os = \"macos\", target_os = \"linux\"))))'.dependencies]");
|
||||
let other_unix_features = winit_features(&other_unix_section);
|
||||
assert!(
|
||||
other_unix_features.contains(&"x11") && !other_unix_features.contains(&"wayland-csd-adwaita-notitle"),
|
||||
"Non-Linux Unix winit dependency must enable x11 without wayland-csd-adwaita-notitle, got: {other_unix_features:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Verifies that `NOTICE` documents sctk-adwaita and its MIT licence.
|
||||
#[test]
|
||||
fn notice_documents_sctk_adwaita_attribution() {
|
||||
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
|
||||
let notice = std::fs::read_to_string(workspace_root.join("NOTICE")).expect("read NOTICE");
|
||||
assert!(notice.contains("Linux Wayland window decorations"), "NOTICE must include 'Linux Wayland window decorations'");
|
||||
assert!(notice.contains("sctk-adwaita"), "NOTICE must document sctk-adwaita");
|
||||
assert!(notice.contains("Bartłomiej Maryńczak"), "NOTICE must retain sctk-adwaita's author copyright");
|
||||
}
|
||||
|
||||
/// Parses `[[package]]` entries from `Cargo.lock` as `(name, version, dependencies)`.
|
||||
fn parse_lockfile_packages(lockfile: &str) -> Vec<(&str, &str, Vec<&str>)> {
|
||||
lockfile
|
||||
.split("[[package]]")
|
||||
.skip(1)
|
||||
.filter_map(|chunk| {
|
||||
let mut name = None;
|
||||
let mut version = None;
|
||||
let mut deps = Vec::new();
|
||||
let mut in_deps = false;
|
||||
for raw_line in chunk.lines() {
|
||||
let line = raw_line.trim();
|
||||
if in_deps {
|
||||
if line == "]" {
|
||||
in_deps = false;
|
||||
continue;
|
||||
}
|
||||
let dep = line.trim_end_matches(',').trim().trim_matches('"');
|
||||
if !dep.is_empty() {
|
||||
deps.push(dep);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("name = ") {
|
||||
name = Some(rest.trim_matches('"'));
|
||||
} else if let Some(rest) = line.strip_prefix("version = ") {
|
||||
version = Some(rest.trim_matches('"'));
|
||||
} else if line == "dependencies = [" {
|
||||
in_deps = true;
|
||||
}
|
||||
}
|
||||
Some((name?, version?, deps))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Verifies that WordCraft's resolved Linux `winit` -> `sctk-adwaita` dependency path in
|
||||
/// `Cargo.lock` does not pull in any title-font renderer crates.
|
||||
#[test]
|
||||
fn cargo_lock_contains_font_free_sctk_adwaita() {
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
|
||||
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
|
||||
let lockfile = std::fs::read_to_string(workspace_root.join("Cargo.lock")).expect("read Cargo.lock");
|
||||
let packages = parse_lockfile_packages(&lockfile);
|
||||
|
||||
let has_dep = |pkg_name: &str, target: &str| {
|
||||
packages.iter().any(|(name, _, deps)| *name == pkg_name && deps.iter().any(|spec| spec.split_whitespace().next() == Some(target)))
|
||||
};
|
||||
assert!(has_dep("winit", "sctk-adwaita"), "winit in Cargo.lock must depend on sctk-adwaita");
|
||||
|
||||
let mut queue = VecDeque::new();
|
||||
let mut visited = HashSet::new();
|
||||
for (idx, (name, _, _)) in packages.iter().enumerate() {
|
||||
if *name == "sctk-adwaita" && visited.insert(idx) {
|
||||
queue.push_back(idx);
|
||||
}
|
||||
}
|
||||
assert!(!queue.is_empty(), "Cargo.lock must include sctk-adwaita");
|
||||
|
||||
let forbidden = ["fontdue", "ab_glyph", "cosmic-text", "crossfont"];
|
||||
while let Some(idx) = queue.pop_front() {
|
||||
let (name, _, deps) = &packages[idx];
|
||||
assert!(!forbidden.contains(name), "sctk-adwaita's resolved dependency path must not include title-font renderer {name}");
|
||||
for spec in deps {
|
||||
let mut parts = spec.split_whitespace();
|
||||
let dep_name = parts.next().expect("dependency name");
|
||||
let dep_ver = parts.next();
|
||||
for (next_idx, (cand_name, cand_ver, _)) in packages.iter().enumerate() {
|
||||
if *cand_name == dep_name && dep_ver.is_none_or(|v| v == *cand_ver) && visited.insert(next_idx) {
|
||||
queue.push_back(next_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,5 +2,7 @@
|
||||
mod appimage_env;
|
||||
mod control_arg;
|
||||
mod help;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_decorations;
|
||||
#[cfg(unix)]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# DOCX corpus (local only)
|
||||
|
||||
This directory is where a local, real-world DOCX corpus can live for the opt-in
|
||||
`cargo xtask docx-corpus` harness. **The corpus is never committed.** `/corpus` is
|
||||
git-ignored; only this README is tracked. Never commit Word-produced files, documents
|
||||
you do not have the right to redistribute, or any proprietary template, theme, font
|
||||
or image. Word-produced documents are useful locally, including ones you made
|
||||
yourself, but they must stay untracked.
|
||||
|
||||
## Populate it
|
||||
|
||||
Put `.docx` files anywhere under this directory (subfolders are walked, symlinks are
|
||||
skipped):
|
||||
|
||||
```sh
|
||||
mkdir -p corpus/docx/mine
|
||||
cp ~/Documents/report.docx corpus/docx/mine/
|
||||
```
|
||||
|
||||
Useful sources for a local corpus:
|
||||
|
||||
- documents you wrote yourself, exported from Word, Google Docs, LibreOffice or Pages;
|
||||
- public-domain or openly licensed DOCX samples whose licence allows local testing;
|
||||
- synthetic files generated by WordCraft (`wordcraft-cli run --template sample --save …`);
|
||||
- deliberately broken files for the failure path (a text file renamed `.docx`, a
|
||||
truncated ZIP, a package missing `word/document.xml`).
|
||||
|
||||
Keep a note of where each file came from. If a corpus must be shared, share the
|
||||
manifest and the harness report, not the documents.
|
||||
|
||||
## Run it
|
||||
|
||||
```sh
|
||||
# The runner builds wordcraft-cli before every run (a no-op when it is current).
|
||||
cargo xtask docx-corpus --dir corpus/docx
|
||||
cargo xtask docx-corpus --dir corpus/docx --out target/docx-corpus/report.json
|
||||
cargo xtask docx-corpus --dir corpus/docx --all-pages
|
||||
cargo xtask docx-corpus --dir corpus/docx --timeout 120 --cli target/debug/wordcraft-cli
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
| Option | Meaning |
|
||||
|---|---|
|
||||
| `--dir <path>` | corpus directory (required) |
|
||||
| `--out <path>` | JSON report path (default `target/docx-corpus/report.json`); the Markdown summary is written beside it with an `.md` extension |
|
||||
| `--all-pages` | render every page instead of only page 1 (capped at 2,000 pages per file) |
|
||||
| `--timeout <secs>` | per-child-process timeout, default 60, maximum 3,600 |
|
||||
| `--cli <path>` | use a specific `wordcraft-cli` binary |
|
||||
| `-h`, `--help` | usage |
|
||||
|
||||
A missing or empty corpus directory is not an error: the command explains what is
|
||||
missing and exits successfully.
|
||||
|
||||
## What each file goes through
|
||||
|
||||
Every `.docx` is handled in child `wordcraft-cli` processes, each with the timeout
|
||||
above, so one hostile or hanging file cannot stop the run:
|
||||
|
||||
1. **Open + inspect** — `wordcraft-cli info` gives page and word counts; `wordcraft-cli text`
|
||||
gives the plain text baseline.
|
||||
2. **Render** — page 1 to PNG (`--all-pages` renders every page). Images go to
|
||||
`<report-stem>-artifacts/<index>-<file>/page-NNNN.png` beside the report.
|
||||
3. **Save** — `wordcraft-cli convert` writes a temporary `.docx` copy under the system
|
||||
temporary directory.
|
||||
4. **Reopen + compare** — the copy is opened again for page count and plain text. The
|
||||
temporary copy is then deleted.
|
||||
|
||||
The report records file name, bytes, open time, page count, word count, render time,
|
||||
round-trip time, rendered images, and every failure. Failures are classified as:
|
||||
|
||||
| Kind | Meaning |
|
||||
|---|---|
|
||||
| `open` | the file could not be opened or inspected (invalid package, encrypted, timeout, oversized, …) |
|
||||
| `render` | page rendering failed |
|
||||
| `save` | saving the temporary copy failed |
|
||||
| `reopen` | the saved copy could not be opened or its text read |
|
||||
| `text_mismatch` | reopened plain text differs from the original |
|
||||
| `page_count_delta` | reopened page count differs from the original |
|
||||
|
||||
The JSON report is deterministic for the same corpus and arguments apart from the
|
||||
timing fields: files are sorted by relative path, failure counts are always present,
|
||||
and there is no timestamp. The Markdown summary is a short human-readable table.
|
||||
|
||||
## Limits
|
||||
|
||||
- This harness measures open/render/save/reopen and text/page stability. It does **not**
|
||||
compare with Word's own rendering or page count, and it does not fix document bugs.
|
||||
A Word-vs-WordCraft visual comparison is a separate task.
|
||||
- PNG rendering is a smoke test that the page can be produced, not a fidelity score.
|
||||
- Files are treated as hostile: recursion depth, file count, file size, render pages and
|
||||
child output are capped, and symlinks are skipped. The caps are deliberately generous
|
||||
for normal documents; a file above them is reported as a failure rather than skipped
|
||||
silently.
|
||||
- The corpus and its reports stay local. `target/` is git-ignored too, so reports do not
|
||||
enter commits.
|
||||
+1
-1
@@ -1 +1 @@
|
||||
e56d26244bbac099bfd42e23fb12f78a4be418a7
|
||||
217f4130d7d3dbb21a160f23f6b0021918906cc0
|
||||
|
||||
@@ -21,26 +21,32 @@ pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
|
||||
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
|
||||
/// overrides the entire folder for isolated runs otherwise.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
settings_dir_with(CHOSEN.get(), |k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
fn settings_dir_with(chosen: Option<&PathBuf>, mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
if let Some(path) = chosen {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
if let Some(path) = env("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir()
|
||||
platform_settings_dir_for(env)
|
||||
}
|
||||
|
||||
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
|
||||
#[cfg(test)]
|
||||
fn platform_settings_dir() -> Option<PathBuf> {
|
||||
platform_settings_dir_for(|k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
fn platform_settings_dir_for(mut env: impl FnMut(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
env("APPDATA").map(|a| PathBuf::from(a).join("WordCraft"))
|
||||
} else {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("wordcraft"))
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("wordcraft"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,4 +115,26 @@ mod tests {
|
||||
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_dir_is_the_apps_folder() {
|
||||
let default_dir = settings_dir_with(None, |key| match key {
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("settings_dir should return Some when platform env var is set");
|
||||
let default_name = default_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
assert!(default_name == "wordcraft" || default_name == "WordCraft", "{}", default_dir.display());
|
||||
assert_eq!(settings_dir_with(None, |_| None), None);
|
||||
|
||||
let override_dir = settings_dir_with(None, |key| (key == "WORDCRAFT_PROFILE_DIR").then(|| "/tmp/profile".into()));
|
||||
assert_eq!(override_dir.as_deref(), Some(Path::new("/tmp/profile")));
|
||||
|
||||
let empty_override = settings_dir_with(None, |key| match key {
|
||||
"WORDCRAFT_PROFILE_DIR" => Some("".into()),
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some("/tmp/base".into()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(empty_override, Some(default_dir));
|
||||
}
|
||||
}
|
||||
|
||||
+52
-3
@@ -230,10 +230,26 @@ impl ChartAxis {
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters.
|
||||
/// characters. A trailing space stays when it is part of the code: the character after `_`,
|
||||
/// `*` or `\`, or text inside quotes.
|
||||
pub fn clean_fmt(s: &str) -> String {
|
||||
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
|
||||
let chars: Vec<char> = s.chars().take(MAX_FMT * 4).skip_while(|c| c.is_whitespace() || c.is_control()).take(MAX_FMT).collect();
|
||||
let mut keep = 0;
|
||||
let mut quoted = false;
|
||||
let mut operand = false;
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if !c.is_control() && (!c.is_whitespace() || operand || quoted) {
|
||||
keep = i + 1;
|
||||
}
|
||||
if operand {
|
||||
operand = false;
|
||||
} else if c == '"' {
|
||||
quoted = !quoted;
|
||||
} else if !quoted && matches!(c, '_' | '*' | '\\') {
|
||||
operand = true;
|
||||
}
|
||||
}
|
||||
chars[..keep].iter().map(|&c| if c.is_control() { ' ' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// A chart WordCraft can edit.
|
||||
@@ -512,4 +528,37 @@ mod tests {
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_keeps_a_trailing_space_that_is_an_operand() {
|
||||
// `_`, `*` and `\` take the next character, so a final space after one is part of the code.
|
||||
assert_eq!(clean_fmt("0_ "), "0_ ");
|
||||
assert_eq!(clean_fmt("#,##0_ "), "#,##0_ ");
|
||||
assert_eq!(clean_fmt("0* "), "0* ");
|
||||
assert_eq!(clean_fmt("0\\ "), "0\\ ");
|
||||
assert_eq!(clean_fmt("0_ \n "), "0_ ");
|
||||
assert_eq!(clean_fmt("0\"a "), "0\"a ", "a space inside quotes is text");
|
||||
// Other spaces at the ends, and control characters, still go.
|
||||
assert_eq!(clean_fmt(" 0.00 \t"), "0.00");
|
||||
assert_eq!(clean_fmt("0_\n"), "0_");
|
||||
assert_eq!(clean_fmt("0\"a\" "), "0\"a\"");
|
||||
assert_eq!(clean_fmt("\\_ "), "\\_", "an escaped `_` takes no operand");
|
||||
assert_eq!(clean_fmt("0\u{1}0"), "0 0");
|
||||
assert_eq!(clean_fmt("_\u{1}"), "_");
|
||||
assert_eq!(clean_fmt(" \n "), "");
|
||||
let long = format!("{}_ ", "0".repeat(MAX_FMT - 2));
|
||||
assert_eq!(clean_fmt(&long), long, "a code of exactly MAX_FMT characters keeps its operand");
|
||||
|
||||
// Axis and series formats both go through the cleaner.
|
||||
let mut a = ChartAxis { fmt: Some("0_ ".into()), ..Default::default() };
|
||||
a.sanitize();
|
||||
assert_eq!(a.fmt.as_deref(), Some("0_ "));
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], fmt: Some("#,##0_ ".into()), ..Default::default() }],
|
||||
categories: vec!["a".into()],
|
||||
..Default::default()
|
||||
};
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].fmt.as_deref(), Some("#,##0_ "));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -703,25 +703,44 @@ impl Document {
|
||||
}
|
||||
|
||||
/// A drawing id no shape uses yet (for gluing a connector to a shape that has none).
|
||||
///
|
||||
/// Returns one past the largest in-use shape id across the body, all secondary parts, and
|
||||
/// footnote/endnote separator stories (walking nested groups and tables); if `u32::MAX` is
|
||||
/// already in use, falls back via [`free_id`] to the smallest unused non-zero id (or `0` only
|
||||
/// if every non-zero `u32` id is taken).
|
||||
pub fn next_shape_id(&self) -> u32 {
|
||||
let mut max = 0u32;
|
||||
let mut largest: Option<u32> = None;
|
||||
let mut used: Vec<u32> = Vec::new();
|
||||
let mut record = |id: u32| {
|
||||
if id != 0 {
|
||||
largest = largest.max(Some(id));
|
||||
used.push(id);
|
||||
}
|
||||
};
|
||||
let mut see = |o: &InlineObject| match o {
|
||||
InlineObject::Shape { extra, .. } => max = max.max(extra.id),
|
||||
InlineObject::Shape { extra, .. } => record(extra.id),
|
||||
InlineObject::Group { children, .. } => {
|
||||
for c in children {
|
||||
if let InlineObject::Shape { extra, .. } = &c.obj {
|
||||
max = max.max(extra.id);
|
||||
let mut todo: Vec<&InlineObject> = children.iter().map(|c| &c.obj).collect();
|
||||
while let Some(obj) = todo.pop() {
|
||||
match obj {
|
||||
InlineObject::Shape { extra, .. } => record(extra.id),
|
||||
InlineObject::Group { children, .. } => todo.extend(children.iter().map(|c| &c.obj)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)) {
|
||||
let sep_stories = [&self.footnote_separators, &self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
|
||||
.flatten();
|
||||
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)).chain(sep_stories) {
|
||||
for b in blocks {
|
||||
edit::each_para(b, 0, &mut |p| p.objects.iter().for_each(&mut see));
|
||||
}
|
||||
}
|
||||
max.saturating_add(1).max(1)
|
||||
free_id(largest, used.into_iter(), 1).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Change every inline object in every story (paragraphs inside tables too), copying only
|
||||
@@ -798,7 +817,10 @@ impl Document {
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut Paragraph::normalize);
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
|
||||
p.normalize();
|
||||
p.reconcile_objects();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,6 +340,72 @@ impl Paragraph {
|
||||
self.runs = out;
|
||||
}
|
||||
|
||||
/// Make the objects match the U+FFFC markers one to one (files lie): drop surplus objects,
|
||||
/// and remove markers past the last object. Runs must already cover the text.
|
||||
///
|
||||
/// One scan finds the unmatched markers, one pass removes them and the runs and objects are
|
||||
/// fixed up once, so the cost is linear in the paragraph however many markers are unmatched.
|
||||
/// There is no cap on the markers: stopping early would leave markers without objects.
|
||||
pub fn reconcile_objects(&mut self) {
|
||||
let keep = self.objects.len();
|
||||
// Byte offsets of the unmatched markers (every marker after the first `keep`), ascending.
|
||||
let mut seen = 0usize;
|
||||
let mut drop: Vec<usize> = Vec::new();
|
||||
for (i, _) in self.text.match_indices(OBJ) {
|
||||
crate::work::steps(1);
|
||||
if seen >= keep {
|
||||
drop.push(i);
|
||||
}
|
||||
seen += 1;
|
||||
}
|
||||
if self.objects.len() > seen {
|
||||
self.objects.truncate(seen);
|
||||
self.touch();
|
||||
}
|
||||
if drop.is_empty() {
|
||||
return;
|
||||
}
|
||||
let w = OBJ.len_utf8();
|
||||
if self.text.len() == drop.len() * w {
|
||||
// Emptying: the mark keeps the formatting of what was deleted (as `delete` does).
|
||||
let revisions = (self.mark.ins, self.mark.del, self.mark.fmt_change.clone());
|
||||
let mut mark = self.props_of_char(0).clone();
|
||||
(mark.ins, mark.del, mark.fmt_change) = revisions;
|
||||
self.mark = mark;
|
||||
}
|
||||
// Shrink the runs: each removed marker takes `w` bytes off the run that holds it.
|
||||
let mut d = 0usize;
|
||||
let mut start = 0usize;
|
||||
for r in &mut self.runs {
|
||||
crate::work::steps(1);
|
||||
let re = start + r.len;
|
||||
let mut cut = 0usize;
|
||||
while let Some(&off) = drop.get(d) {
|
||||
crate::work::steps(1);
|
||||
if off >= re {
|
||||
break;
|
||||
}
|
||||
if off >= start {
|
||||
cut += w;
|
||||
}
|
||||
d += 1;
|
||||
}
|
||||
start = re;
|
||||
r.len -= cut.min(r.len);
|
||||
}
|
||||
let mut out = String::with_capacity(self.text.len() - drop.len() * w);
|
||||
// The pieces between markers; marker `k` sits before piece `k + 1` and stays if matched.
|
||||
for (k, piece) in self.text.split(OBJ).enumerate() {
|
||||
if k > 0 && k <= keep {
|
||||
out.push(OBJ);
|
||||
}
|
||||
out.push_str(piece);
|
||||
}
|
||||
self.text = out;
|
||||
self.normalize();
|
||||
self.touch();
|
||||
}
|
||||
|
||||
/// Delete `a..b` (bytes). Objects inside are removed.
|
||||
pub fn delete(&mut self, a: usize, b: usize) -> Result<()> {
|
||||
let (a, b) = (a.min(b), a.max(b));
|
||||
|
||||
@@ -291,25 +291,47 @@ impl InlineObject {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The text box stories this object shows: a text box's, or its group members'.
|
||||
/// The text box stories this object shows: a text box's, or its group members' (nested groups
|
||||
/// included, in member order).
|
||||
pub fn text_boxes(&self) -> Vec<u32> {
|
||||
match self {
|
||||
InlineObject::Shape { story: Some(id), .. } => vec![*id],
|
||||
InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(),
|
||||
InlineObject::Group { children, .. } => {
|
||||
let mut out = Vec::new();
|
||||
let mut todo: Vec<&InlineObject> = children.iter().rev().map(|c| &c.obj).collect();
|
||||
while let Some(obj) = todo.pop() {
|
||||
match obj {
|
||||
InlineObject::Shape { story: Some(id), .. } => out.push(*id),
|
||||
InlineObject::Group { children, .. } => {
|
||||
todo.extend(children.iter().rev().map(|c| &c.obj));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
/// The text box story slots of this object and its group members, to repoint.
|
||||
/// The text box story slots of this object and its group members (nested groups included, in
|
||||
/// member order), to repoint.
|
||||
pub fn text_box_slots(&mut self) -> Vec<&mut Option<u32>> {
|
||||
match self {
|
||||
InlineObject::Shape { story, .. } => vec![story],
|
||||
InlineObject::Group { children, .. } => children
|
||||
.iter_mut()
|
||||
.filter_map(|c| match &mut c.obj {
|
||||
InlineObject::Shape { story, .. } => Some(story),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
InlineObject::Group { children, .. } => {
|
||||
let mut out = Vec::new();
|
||||
let mut todo: Vec<&mut InlineObject> = children.iter_mut().rev().map(|c| &mut c.obj).collect();
|
||||
while let Some(obj) = todo.pop() {
|
||||
match obj {
|
||||
InlineObject::Shape { story, .. } => out.push(story),
|
||||
InlineObject::Group { children, .. } => {
|
||||
todo.extend(children.iter_mut().rev().map(|c| &mut c.obj));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,11 +42,27 @@ pub struct Revision {
|
||||
/// insertion or deletion.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub move_name: Option<String>,
|
||||
/// The change's UTC timestamp: from the file (`w16du:dateUtc`, where `date` is the local time
|
||||
/// Word writes in `w:date`), or the time WordCraft stamped the change with. `None` when the
|
||||
/// file doesn't give it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub date_utc: Option<String>,
|
||||
}
|
||||
|
||||
impl Revision {
|
||||
pub fn new(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>) -> Revision {
|
||||
Revision { kind, author: author.into(), date: date.into(), move_name: None }
|
||||
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None }
|
||||
}
|
||||
|
||||
/// A change made here: `date` is the local wall-clock time it was made at, as Word writes
|
||||
/// `w:date`, and `date_utc` the same instant in UTC.
|
||||
pub fn made_at(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>, utc: impl Into<String>) -> Revision {
|
||||
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: Some(utc.into()) }
|
||||
}
|
||||
|
||||
/// The instant changes are grouped by: the UTC time when it is known, else `date`.
|
||||
pub fn instant(&self) -> &str {
|
||||
self.date_utc.as_deref().unwrap_or(&self.date)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -440,6 +440,116 @@ fn prune_text_boxes_drops_only_unshown_ones() {
|
||||
assert_eq!(d.prune_text_boxes(), 0);
|
||||
}
|
||||
|
||||
/// A text-box shape (`story: Some(id)`) or plain shape (`story: None`) for nested-group tests.
|
||||
fn test_shape(story: Option<u32>) -> InlineObject {
|
||||
InlineObject::Shape {
|
||||
kind: para::ShapeKind::TextBox,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A group holding `children`.
|
||||
fn test_group(children: Vec<InlineObject>) -> InlineObject {
|
||||
InlineObject::Group {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
float: Default::default(),
|
||||
ch_w: 100.0,
|
||||
ch_h: 100.0,
|
||||
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
|
||||
canvas: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `obj` wrapped inside `levels` nested [`InlineObject::Group`]s.
|
||||
fn nested_group(levels: usize, obj: InlineObject) -> InlineObject {
|
||||
(0..levels).fold(obj, |inner, _| test_group(vec![inner]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_group_text_boxes_are_collected_and_slots_repointed_in_order() {
|
||||
let mut outer = test_group(vec![
|
||||
test_shape(Some(1)),
|
||||
test_shape(None),
|
||||
nested_group(1, test_shape(Some(2))), // depth 2 from outer
|
||||
test_group(vec![nested_group(1, test_shape(Some(3))), test_shape(Some(4))]), // depth 3 and depth 2
|
||||
nested_group(39, test_shape(Some(5))), // depth 40 from outer
|
||||
]);
|
||||
assert_eq!(outer.text_boxes(), vec![1, 2, 3, 4, 5]);
|
||||
let slots = outer.text_box_slots();
|
||||
assert_eq!(slots.len(), 6);
|
||||
for id in slots.into_iter().flatten() {
|
||||
*id += 100;
|
||||
}
|
||||
assert_eq!(outer.text_boxes(), vec![101, 102, 103, 104, 105]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_text_boxes_keeps_nested_group_boxes_and_drops_unreachable() {
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let depth2 = d.add_part(PartKind::TextBox, para_of("depth 2"));
|
||||
let depth3 = d.add_part(PartKind::TextBox, para_of("depth 3"));
|
||||
let deep = d.add_part(PartKind::TextBox, para_of("depth 40"));
|
||||
let linked_live = d.add_part(PartKind::TextBox, para_of("linked follower"));
|
||||
let orphan = d.add_part(PartKind::TextBox, para_of("unreachable"));
|
||||
let orphan_nested = d.add_part(PartKind::TextBox, para_of("inside unreachable"));
|
||||
|
||||
// Live link between two nested-group boxes and a dangling link to an unreachable box.
|
||||
d.parts.get_mut(&depth2).unwrap().body.next = Some(linked_live);
|
||||
d.parts.get_mut(&depth3).unwrap().body.next = Some(orphan);
|
||||
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(depth2))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(3, test_shape(Some(depth3))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(40, test_shape(Some(deep))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(linked_live))), &CharProps::default()).unwrap();
|
||||
let at_orphan = Pos { story: StoryRef::Part(orphan), path: Path::top(0), off: 0 };
|
||||
d.insert_object(&at_orphan, nested_group(2, test_shape(Some(orphan_nested))), &CharProps::default()).unwrap();
|
||||
|
||||
assert_eq!(d.prune_text_boxes(), 2);
|
||||
let kept: Vec<u32> = d.parts.keys().copied().collect();
|
||||
assert_eq!(kept, vec![depth2, depth3, deep, linked_live]);
|
||||
assert_eq!(d.plain_text(StoryRef::Part(depth2)), "depth 2");
|
||||
assert_eq!(d.plain_text(StoryRef::Part(depth3)), "depth 3");
|
||||
assert_eq!(d.plain_text(StoryRef::Part(deep)), "depth 40");
|
||||
assert_eq!(d.parts.get(&depth2).unwrap().body.next, Some(linked_live), "live chain link stays");
|
||||
assert_eq!(d.parts.get(&depth3).unwrap().body.next, None, "dangling chain link is cleared");
|
||||
assert_eq!(d.prune_text_boxes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_text_boxes_terminates_on_cyclic_nested_group_stories() {
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let a = d.add_part(PartKind::TextBox, para_of("a"));
|
||||
let b = d.add_part(PartKind::TextBox, para_of("b"));
|
||||
let dead_c = d.add_part(PartKind::TextBox, para_of("dead c"));
|
||||
let dead_d = d.add_part(PartKind::TextBox, para_of("dead d"));
|
||||
|
||||
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
|
||||
// Reachable cycle: body -> nested group -> a -> nested group -> b -> nested group -> (a, b).
|
||||
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(a))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(a), nested_group(2, test_shape(Some(b))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(b), nested_group(2, test_group(vec![test_shape(Some(a)), test_shape(Some(b))])), &CharProps::default()).unwrap();
|
||||
// Unreachable cycle: dead_c <-> dead_d through nested groups.
|
||||
d.insert_object(&at(dead_c), nested_group(2, test_shape(Some(dead_d))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(dead_d), nested_group(2, test_shape(Some(dead_c))), &CharProps::default()).unwrap();
|
||||
|
||||
assert_eq!(d.prune_text_boxes(), 2);
|
||||
let kept: Vec<u32> = d.parts.keys().copied().collect();
|
||||
assert_eq!(kept, vec![a, b]);
|
||||
assert_eq!(d.counted_stories(), vec![StoryRef::Body, StoryRef::Part(a), StoryRef::Part(b)]);
|
||||
}
|
||||
|
||||
/// `blocks` in the only cell of `levels` tables, each nested in the next.
|
||||
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
|
||||
(0..levels).fold(blocks, |inner, _| {
|
||||
@@ -818,3 +928,302 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
|
||||
assert!(!serde_json::to_string(&d).unwrap().contains("p0"));
|
||||
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_runs_reconciles_objects_with_markers() {
|
||||
let c = CharProps::default();
|
||||
let markers = |p: &Paragraph| p.text.chars().filter(|ch| *ch == '\u{FFFC}').count();
|
||||
let build = || {
|
||||
let mut d = Document::from_text("abc");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(1, fs("A"), &c).unwrap();
|
||||
p.insert_object(5, fs("B"), &c).unwrap();
|
||||
d
|
||||
};
|
||||
// More objects than markers (as a hand-edited .json can say): the surplus goes.
|
||||
let mut d = build();
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.push(fs("C"));
|
||||
d.normalize_runs();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!((markers(p), p.objects.len()), (2, 2));
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
|
||||
// More markers than objects: the unmatched marker goes, runs still cover the text.
|
||||
let mut d = build();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.text.push('\u{FFFC}');
|
||||
p.runs[0].len += 3;
|
||||
d.normalize_runs();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!((markers(p), p.objects.len()), (2, 2));
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
|
||||
// Deleting the first marker keeps B on the second.
|
||||
p.delete(1, 4).unwrap();
|
||||
assert_eq!(p.objects, vec![fs("B")]);
|
||||
// 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| {
|
||||
let mut p = Paragraph::default();
|
||||
p.objects = vec![fs("A")];
|
||||
p.text = format!("\u{FFFC}{}x", "\u{FFFC}".repeat(extra));
|
||||
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
|
||||
crate::work::count(|| {
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "\u{FFFC}x");
|
||||
std::hint::black_box(&p);
|
||||
})
|
||||
};
|
||||
let (s1, s8) = (reconcile(2_000), reconcile(16_000));
|
||||
assert!(s1 > 0, "no steps counted, so the walk this test watches no longer counts them (crate::work)");
|
||||
let ratio = s8 as f64 / s1 as f64;
|
||||
assert!(ratio <= 12.0, "8x the markers cost {ratio:.1}x the steps ({s1} -> {s8})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_drops_many_unmatched_markers_in_one_pass() {
|
||||
let c = CharProps::default();
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(0, fs("A"), &c).unwrap();
|
||||
p.insert_object(p.text.len(), fs("B"), &c).unwrap();
|
||||
let extra = 50_000;
|
||||
// "<A>x<B>" followed by many unmatched markers around more text, in one run.
|
||||
p.text = format!("\u{FFFC}x\u{FFFC}{}y{}z", "\u{FFFC}".repeat(extra), "\u{FFFC}".repeat(extra));
|
||||
p.runs = vec![Run { len: p.text.len(), props: c.clone() }];
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "\u{FFFC}x\u{FFFC}yz");
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")]);
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_keeps_every_matched_object() {
|
||||
let c = CharProps::default();
|
||||
let n = 100_050;
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.text = "\u{FFFC}".repeat(n);
|
||||
p.objects = (0..n).map(|_| fs("A")).collect();
|
||||
p.runs = vec![Run { len: p.text.len(), props: c }];
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.objects.len(), n);
|
||||
assert_eq!(p.text.matches('\u{FFFC}').count(), n);
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_keeps_run_props_across_several_runs() {
|
||||
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
|
||||
let italic = CharProps { italic: Some(true), ..CharProps::default() };
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects = vec![fs("A")];
|
||||
// Runs: plain "a<A>b<X>" | bold "<X><X>" (only unmatched, becomes empty) | italic "<X>c<X>" | plain "d".
|
||||
let x = "\u{FFFC}";
|
||||
let parts = [
|
||||
(format!("a\u{FFFC}b{x}"), plain.clone()),
|
||||
(format!("{x}{x}"), bold),
|
||||
(format!("{x}c{x}"), italic.clone()),
|
||||
("d".to_string(), plain.clone()),
|
||||
];
|
||||
p.text = parts.iter().map(|(t, _)| t.as_str()).collect();
|
||||
p.runs = parts.iter().map(|(t, c)| Run { len: t.len(), props: c.clone() }).collect();
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "a\u{FFFC}bcd");
|
||||
assert_eq!(p.objects, vec![fs("A")]);
|
||||
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
|
||||
// "a<A>b" plain (5 bytes: 1 + 3 + 1), "c" italic, "d" plain.
|
||||
assert_eq!(got, vec![(5, plain.clone()), (1, italic), (1, plain)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_marker_on_run_boundary_shrinks_the_right_run() {
|
||||
let (plain, bold) = (CharProps::default(), CharProps { bold: Some(true), ..CharProps::default() });
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
let x = "\u{FFFC}";
|
||||
// plain "ab" | bold "<X>cd" : the marker is the first byte of the second run.
|
||||
p.text = format!("ab{x}cd");
|
||||
p.runs = vec![Run { len: 2, props: plain.clone() }, Run { len: 2 + x.len(), props: bold.clone() }];
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "abcd");
|
||||
let got: Vec<(usize, CharProps)> = p.runs.iter().map(|r| (r.len, r.props.clone())).collect();
|
||||
assert_eq!(got, vec![(2, plain), (2, bold)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_objects_all_unmatched_markers_empties_the_paragraph() {
|
||||
let bold = CharProps { bold: Some(true), ..CharProps::default() };
|
||||
let mut d = Document::from_text("");
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.text = "\u{FFFC}".repeat(3);
|
||||
p.runs = vec![Run { len: p.text.len(), props: bold.clone() }];
|
||||
p.mark = CharProps { ins: Some(7), ..CharProps::default() };
|
||||
p.reconcile_objects();
|
||||
assert_eq!(p.text, "");
|
||||
assert!(p.objects.is_empty());
|
||||
assert!(p.runs.is_empty());
|
||||
// The mark takes the deleted formatting but keeps its own revision.
|
||||
assert_eq!(p.mark, CharProps { bold: Some(true), ins: Some(7), ..CharProps::default() });
|
||||
}
|
||||
|
||||
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
|
||||
InlineObject::Shape {
|
||||
kind: para::ShapeKind::Rectangle,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: connector::ShapeExtra { id, ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
fn group_of(children: Vec<InlineObject>) -> InlineObject {
|
||||
InlineObject::Group {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
float: Default::default(),
|
||||
ch_w: 100.0,
|
||||
ch_h: 100.0,
|
||||
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
|
||||
canvas: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nested_group_of(depth: usize, leaf: InlineObject) -> InlineObject {
|
||||
(0..depth).fold(leaf, |inner, _| group_of(vec![inner]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_accounts_for_shapes_in_nested_groups() {
|
||||
// Doubly-nested group carrying shape id 1: must not reissue id 1.
|
||||
let mut d = Document::from_text("body");
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(1, None)), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 2);
|
||||
|
||||
// Deeper nesting (5-level and 40-level groups) with mixed siblings.
|
||||
d.insert_object(
|
||||
&Pos::body(0, 0),
|
||||
nested_group_of(5, group_of(vec![shape_with_id(42, None), nested_group_of(35, shape_with_id(99, None))])),
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(d.next_shape_id(), 100);
|
||||
|
||||
// Nested group inside a secondary story (part).
|
||||
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
|
||||
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
|
||||
d.insert_object(&at_hdr, nested_group_of(3, shape_with_id(150, None)), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 151);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_preserves_flat_group_and_ungrouped_allocation() {
|
||||
let mut d = Document::from_text("body");
|
||||
assert_eq!(d.next_shape_id(), 1);
|
||||
|
||||
// Ungrouped shapes (including id 0).
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(0, None), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 1);
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(3, None), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(7, None), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 8);
|
||||
|
||||
// Flat (1-level) group.
|
||||
d.insert_object(&Pos::body(0, 0), group_of(vec![shape_with_id(12, None), shape_with_id(4, None)]), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), 13);
|
||||
|
||||
// At u32::MAX, overflow falls back to an unused non-zero id rather than reissuing u32::MAX.
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
|
||||
let id = d.next_shape_id();
|
||||
assert_ne!(id, 0);
|
||||
for used in [3, 4, 7, 12, u32::MAX] {
|
||||
assert_ne!(id, used);
|
||||
}
|
||||
assert_eq!(id, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_avoids_reissuing_u32_max_on_overflow() {
|
||||
// Non-overflow boundary: u32::MAX - 1 still advances to u32::MAX.
|
||||
let mut d = Document::from_text("body");
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(u32::MAX - 1, None), &CharProps::default()).unwrap();
|
||||
assert_eq!(d.next_shape_id(), u32::MAX);
|
||||
|
||||
// Once u32::MAX is in use inside a nested group, allocator must not reissue any in-use id.
|
||||
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
|
||||
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
|
||||
d.insert_object(&Pos::body(0, 0), shape_with_id(1, None), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at_hdr, nested_group_of(2, shape_with_id(2, None)), &CharProps::default()).unwrap();
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(3, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
|
||||
|
||||
let in_use = [1, 2, u32::MAX - 1, u32::MAX];
|
||||
let first = d.next_shape_id();
|
||||
assert_ne!(first, 0);
|
||||
assert!(!in_use.contains(&first), "reissued in-use shape id {first}");
|
||||
assert_eq!(first, 3);
|
||||
|
||||
// Using the returned id advances to the next unused id rather than repeating it.
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(first, None)), &CharProps::default()).unwrap();
|
||||
let second = d.next_shape_id();
|
||||
assert_ne!(second, 0);
|
||||
assert_ne!(second, first);
|
||||
assert!(!in_use.contains(&second), "reissued in-use shape id {second}");
|
||||
assert_eq!(second, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_terminates_on_cyclic_nested_group_stories() {
|
||||
// InlineObject::Group owns Vec<GroupChild> by value (and unsafe is forbidden), so a cyclic
|
||||
// in-memory Group tree cannot be constructed in safe Rust; mirror #8068 by constructing a
|
||||
// cyclic text-box story graph through nested groups instead.
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let mut d = Document::from_text("body");
|
||||
let a = d.add_part(PartKind::TextBox, para_of("a"));
|
||||
let b = d.add_part(PartKind::TextBox, para_of("b"));
|
||||
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
|
||||
|
||||
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(5, Some(a))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(a), nested_group_of(2, shape_with_id(10, Some(b))), &CharProps::default()).unwrap();
|
||||
d.insert_object(&at(b), nested_group_of(2, shape_with_id(25, Some(a))), &CharProps::default()).unwrap();
|
||||
|
||||
assert_eq!(d.next_shape_id(), 26);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_shape_id_accounts_for_shapes_in_note_separators() {
|
||||
let blocks_with = |obj: InlineObject| -> Blocks {
|
||||
let mut p = Paragraph::with_text("sep", CharProps::default());
|
||||
p.insert_object(0, obj, &CharProps::default()).unwrap();
|
||||
vec![para_block(p)]
|
||||
};
|
||||
|
||||
// A shape ID used only in a footnote separator story must not be reissued.
|
||||
let mut d = Document::from_text("body");
|
||||
d.footnote_separators.separator = Some(blocks_with(shape_with_id(1, None)));
|
||||
assert_eq!(d.next_shape_id(), 2);
|
||||
|
||||
// Every footnote and endnote separator slot is walked, including nested groups and tables.
|
||||
d.footnote_separators.continuation_separator = Some(blocks_with(nested_group_of(2, shape_with_id(2, None))));
|
||||
d.footnote_separators.continuation_notice = Some(nested_tables(1, blocks_with(shape_with_id(5, None))));
|
||||
assert_eq!(d.next_shape_id(), 6);
|
||||
|
||||
d.endnote_separators.separator = Some(blocks_with(shape_with_id(9, None)));
|
||||
assert_eq!(d.next_shape_id(), 10);
|
||||
|
||||
d.endnote_separators.continuation_separator = Some(blocks_with(nested_group_of(3, shape_with_id(14, None))));
|
||||
assert_eq!(d.next_shape_id(), 15);
|
||||
|
||||
// Overflow fallback also respects IDs held exclusively in note-separator stories.
|
||||
d.endnote_separators.continuation_notice = Some(blocks_with(nested_group_of(2, shape_with_id(u32::MAX, None))));
|
||||
let allocated = d.next_shape_id();
|
||||
assert_ne!(allocated, 0);
|
||||
for used in [1, 2, 5, 9, 14, u32::MAX] {
|
||||
assert_ne!(allocated, used);
|
||||
}
|
||||
assert_eq!(allocated, 3);
|
||||
}
|
||||
|
||||
@@ -316,7 +316,13 @@ fn styles_and_lists_round_trip() {
|
||||
#[test]
|
||||
fn tracked_style_definition_change_round_trips() {
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Format, author: "Ana".into(), date: "2026-10-17T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Format,
|
||||
author: "Ana".into(),
|
||||
date: "2026-10-17T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
std::sync::Arc::make_mut(&mut d.styles).upsert(Style {
|
||||
id: "Mine".into(),
|
||||
name: "Mine".into(),
|
||||
@@ -1005,8 +1011,20 @@ fn toc_field_skips_nested_stories() {
|
||||
#[test]
|
||||
fn tracked_changes_round_trip() {
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.settings.track_changes = true;
|
||||
let ins = CharProps { ins: Some(0), ..Default::default() };
|
||||
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
|
||||
@@ -1034,8 +1052,20 @@ fn tracked_changes_round_trip() {
|
||||
fn tracked_equations_round_trip() {
|
||||
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.settings.track_changes = true;
|
||||
let ins = CharProps { ins: Some(0), ..Default::default() };
|
||||
let del = CharProps { del: Some(1), ..Default::default() };
|
||||
@@ -1089,8 +1119,20 @@ fn tracked_equations_round_trip() {
|
||||
fn nested_omath_para_revisions_read() {
|
||||
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Ada".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Charles".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
|
||||
let base = wordcraft_docx::write(&d).unwrap();
|
||||
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
|
||||
@@ -1108,8 +1150,20 @@ fn tracked_paragraph_marks_round_trip() {
|
||||
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
|
||||
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
|
||||
split.mark.ins = Some(0);
|
||||
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
|
||||
@@ -1863,7 +1917,7 @@ fn kitchen_sink() -> Document {
|
||||
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
|
||||
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
|
||||
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.last_section.headers.default = Some(h);
|
||||
let mut blocks: Blocks = Vec::new();
|
||||
let mut p = para_runs(&[
|
||||
|
||||
@@ -41,7 +41,7 @@ fn sample() -> Document {
|
||||
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
|
||||
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
|
||||
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.last_section.headers.default = Some(head);
|
||||
|
||||
let mut p = Paragraph::new();
|
||||
|
||||
@@ -298,6 +298,8 @@ Review|Language|Translate|review.translate
|
||||
Review|Language|Language|review.language
|
||||
Review|Comments|New Comment|review.newComment
|
||||
Review|Comments|Delete|review.deleteComment
|
||||
Review|Comments|Delete All Comments in Document|review.deleteComment
|
||||
Review|Comments|Delete All Resolved Comments|review.deleteComment
|
||||
Review|Comments|Previous|review.previousComment
|
||||
Review|Comments|Next|review.nextComment
|
||||
Review|Comments|Show Comments|review.comments
|
||||
|
||||
@@ -210,14 +210,21 @@ pub fn new_revision(s: &mut Session, kind: RevisionKind) -> u32 {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|(i, r)| r.kind == kind && r.author == s.author && r.date == date && r.move_name.is_none() && held != Some(*i as u32))
|
||||
.find(|(i, r)| r.kind == kind && r.author == s.author && r.instant() == date && r.move_name.is_none() && held != Some(*i as u32))
|
||||
{
|
||||
return i as u32;
|
||||
}
|
||||
s.doc.revisions.push(Revision { kind, author: s.author.clone(), date, move_name: None });
|
||||
s.doc.revisions.push(made_revision(kind, s.author.clone(), date));
|
||||
(s.doc.revisions.len() - 1) as u32
|
||||
}
|
||||
|
||||
/// A revision record for a change made at `utc` (ISO 8601, UTC): dated in local wall-clock time,
|
||||
/// as Word writes `w:date`, with the UTC time beside it, so a save writes it as it is (#6851).
|
||||
pub fn made_revision(kind: RevisionKind, author: String, utc: String) -> Revision {
|
||||
let date = crate::io_ext::word_date(&utc, local_offset_secs).unwrap_or_else(|| utc.clone());
|
||||
Revision::made_at(kind, author, date, utc)
|
||||
}
|
||||
|
||||
/// Whether the paragraph at `path` is followed by another paragraph in the same container (so
|
||||
/// its paragraph mark can be removed by joining the two).
|
||||
pub fn has_next_para(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> bool {
|
||||
@@ -556,6 +563,10 @@ pub fn iso_from_unix_secs(secs: u64) -> String {
|
||||
|
||||
/// Seconds since the Unix epoch (UTC): the system clock, or the browser's on the web.
|
||||
pub fn now_unix() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(now) = TEST_NOW.with(std::cell::Cell::get) {
|
||||
return now;
|
||||
}
|
||||
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
|
||||
{
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
@@ -577,9 +588,23 @@ pub fn now_iso() -> String {
|
||||
/// 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 {
|
||||
#[cfg(test)]
|
||||
if let Some(zone) = TEST_ZONE.with(std::cell::Cell::get) {
|
||||
return zone(unix);
|
||||
}
|
||||
system_offset_secs(unix).clamp(-26 * 3600, 26 * 3600)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The clock [`now_unix`] reads on this thread in place of the system's, so a test can make
|
||||
/// edits at the instants it needs.
|
||||
pub static TEST_NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// The zone [`local_offset_secs`] gives on this thread in place of the system's. CI runs on
|
||||
/// UTC, where local time is UTC, so a test sets a zone that isn't to tell them apart.
|
||||
pub static TEST_ZONE: std::cell::Cell<Option<fn(u64) -> i64>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_offset_secs(unix: u64) -> i64 {
|
||||
use chrono::Offset;
|
||||
|
||||
@@ -362,10 +362,10 @@ fn copy_member(s: &mut Session, pos: &Pos, index: usize) -> CmdResult {
|
||||
if !copied {
|
||||
return Err(CmdError::Failed("the member vanished".into()));
|
||||
}
|
||||
s.clipboard_text = f.clipboard_text();
|
||||
s.clip_history.push(&f, &s.clipboard_text);
|
||||
s.clipboard = Some(f);
|
||||
Ok(super::edit::copy_result(s))
|
||||
let text = f.clipboard_text();
|
||||
let r = super::edit::copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Take member `index` out of the canvas at `pos`; the canvas stays selected.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Caret movement and selection.
|
||||
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::{Pos, StoryRef};
|
||||
use wordcraft_doc::math_edit::MathPos;
|
||||
use wordcraft_doc::para::OBJ;
|
||||
use wordcraft_doc::{InlineObject, Pos, StoryRef};
|
||||
use wordcraft_layout::ViewMode;
|
||||
|
||||
use super::{parse_pos, sel_result};
|
||||
@@ -119,9 +121,31 @@ 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)
|
||||
&& !s.math_left
|
||||
&& let Some(r) = into_equation(s, is_left)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
mv(s, v, if is_left { left } else { right })
|
||||
}
|
||||
|
||||
/// 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 { .. })) {
|
||||
return None;
|
||||
}
|
||||
s.sel = Selection::caret(Pos { off, ..f });
|
||||
s.goal_x = None;
|
||||
s.pending = None;
|
||||
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
|
||||
}
|
||||
|
||||
/// Left/Right in bidirectional text: one caret position to the left or right on the screen.
|
||||
/// Past the line's visual end the caret goes to the neighbouring line in reading order (the
|
||||
/// previous line when moving toward the paragraph's start edge).
|
||||
@@ -276,7 +300,11 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
|
||||
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
|
||||
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
|
||||
let to = if np == c.page {
|
||||
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
s.page_hint = np;
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
|
||||
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
|
||||
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
|
||||
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
|
||||
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added, or edited when its tag exists, and cited when no tag is given), "pages"?: string}"#),
|
||||
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
|
||||
let st = p::str(v, "style").unwrap_or("APA");
|
||||
let st = find_style(st).ok_or_else(|| {
|
||||
|
||||
@@ -37,22 +37,7 @@ fn auto_tag_base(src: &Source) -> String {
|
||||
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
|
||||
pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(a) = v.get("add") {
|
||||
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
// A new source's tag is made from its author and year; an edit keeps the tag it has.
|
||||
if src.tag.is_empty() {
|
||||
src.tag = auto_tag(&s.doc, &src);
|
||||
}
|
||||
// Edit Source keeps the source's place in the list and refreshes its citations.
|
||||
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
|
||||
Some(i) => {
|
||||
if let Some(x) = s.doc.sources.get_mut(i) {
|
||||
*x = src;
|
||||
}
|
||||
update_citations(s)?;
|
||||
}
|
||||
None => s.doc.sources.push(src),
|
||||
}
|
||||
s.touch();
|
||||
add_source(s, a)?;
|
||||
}
|
||||
if let Some(t) = p::str(v, "remove") {
|
||||
s.doc.sources.retain(|x| x.tag != t);
|
||||
@@ -63,6 +48,28 @@ pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
/// Adds a source, or edits the one with its tag, and returns that tag (#7443).
|
||||
fn add_source(s: &mut Session, a: &Value) -> Result<String, CmdError> {
|
||||
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
// A new source's tag is made from its author and year; an edit keeps the tag it has.
|
||||
if src.tag.is_empty() {
|
||||
src.tag = auto_tag(&s.doc, &src);
|
||||
}
|
||||
let tag = src.tag.clone();
|
||||
// Edit Source keeps the source's place in the list and refreshes its citations.
|
||||
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
|
||||
Some(i) => {
|
||||
if let Some(x) = s.doc.sources.get_mut(i) {
|
||||
*x = src;
|
||||
}
|
||||
update_citations(s)?;
|
||||
}
|
||||
None => s.doc.sources.push(src),
|
||||
}
|
||||
s.touch();
|
||||
Ok(tag)
|
||||
}
|
||||
|
||||
/// The largest bibliography sources file imported from disk.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SOURCES_FILE: u64 = 32 << 20;
|
||||
@@ -126,15 +133,16 @@ fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
|
||||
}
|
||||
|
||||
pub(super) fn citation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if v.get("source").is_some() {
|
||||
sources(s, &json!({"add": v.get("source")}))?;
|
||||
}
|
||||
let tag = match p::str(v, "tag") {
|
||||
Some(t) => t.to_string(),
|
||||
None => match v.get("source") {
|
||||
Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(),
|
||||
None => return Err(CmdError::Params("give `tag` or `source`".into())),
|
||||
},
|
||||
// The source just added or edited is the one cited when no `tag` is given, wherever it sits
|
||||
// in the list (#7443).
|
||||
let added = match v.get("source") {
|
||||
Some(a) => Some(add_source(s, a)?),
|
||||
None => None,
|
||||
};
|
||||
let tag = match (p::str(v, "tag"), added) {
|
||||
(Some(t), _) => t.to_string(),
|
||||
(None, Some(t)) => t,
|
||||
(None, None) => return Err(CmdError::Params("give `tag` or `source`".into())),
|
||||
};
|
||||
let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?;
|
||||
let pages = p::str(v, "pages").unwrap_or("").to_string();
|
||||
|
||||
@@ -597,6 +597,22 @@ fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
|
||||
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn citing_an_edited_source_that_is_not_last_cites_that_source() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.sources", &json!({"add": src_of("Alice, Ann", "2000")})).unwrap();
|
||||
s.run("references.sources", &json!({"add": src_of("Bob, Ben", "2001")})).unwrap();
|
||||
let mut edited = src_of("Alice Edited, Ann", "2000");
|
||||
edited["tag"] = json!("Ali00");
|
||||
let r = s.run("references.citation", &json!({"source": edited})).unwrap();
|
||||
assert_eq!(r["tag"], "Ali00");
|
||||
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
|
||||
assert_eq!(tags, ["Ali00", "Bob01"]);
|
||||
let f = fields(&s);
|
||||
assert_eq!(f[0].0, "CITATION Ali00");
|
||||
assert!(f[0].1.contains("Alice Edited") && f[0].1.contains("2000"), "{:?}", f[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
|
||||
@@ -244,10 +244,10 @@ fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
rows.push(row_text(s, &a, &b));
|
||||
blocks.push(Block::Para(para));
|
||||
}
|
||||
s.clipboard_text = rows.join("\n");
|
||||
let text = rows.join("\n");
|
||||
let media = s.doc.media_of_blocks(&blocks);
|
||||
s.clipboard = Some(Fragment { blocks, parts, media });
|
||||
Ok(super::edit::copy_result(s))
|
||||
let f = Fragment { blocks, parts, media };
|
||||
super::edit::copy_result(s, &f, &text)
|
||||
}
|
||||
|
||||
/// Delete each row's piece (bottom up, so earlier positions stay valid) and leave the caret at
|
||||
|
||||
@@ -279,6 +279,22 @@ fn content_base(s: &Session, r: &ControlRange) -> CharProps {
|
||||
content_props(&s.doc, &props)
|
||||
}
|
||||
|
||||
/// The formatting of what replaces a control's content: typed text, a list entry, a date or a
|
||||
/// check box's mark. In place of the placeholder, that is the control's own run properties
|
||||
/// (ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style: the
|
||||
/// showing placeholder's own character style is that style, whatever a producer called it (Word
|
||||
/// localizes only the id; another program may localize the name too). In place of a value, it is
|
||||
/// that value's formatting.
|
||||
fn replacement_props(s: &Session, r: &ControlRange) -> CharProps {
|
||||
if !r.control.showing_placeholder {
|
||||
return content_base(s, r);
|
||||
}
|
||||
match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, r) },
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Rules for typing and deleting
|
||||
|
||||
@@ -327,14 +343,8 @@ pub fn prepare_edit(s: &mut Session) -> Result<Option<CharProps>, CmdError> {
|
||||
if !r.control.showing_placeholder || !r.contains(&b) {
|
||||
return Ok(None);
|
||||
}
|
||||
// Text typed in place of the placeholder takes the control's own run properties (Word, and
|
||||
// ECMA-376 §17.5.2.27), else the content's formatting without the placeholder style. The
|
||||
// showing placeholder's own character style is that style, whatever a producer called it
|
||||
// (Word localizes only the id; another program may localize the name too).
|
||||
let props = match &r.control.run_props {
|
||||
Some(rp) => content_props(&s.doc, rp),
|
||||
None => CharProps { style: None, ..content_base(s, &r) },
|
||||
};
|
||||
// Text typed in place of the placeholder takes the control's own run properties, as in Word.
|
||||
let props = replacement_props(s, &r);
|
||||
s.sel = Selection { anchor: r.content_start(), focus: r.end.clone() };
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
c.showing_placeholder = false;
|
||||
@@ -666,7 +676,7 @@ fn toggle_check_box(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let now = p::bool(v, "value").unwrap_or(!checked);
|
||||
let (ch, font) = if now { (*checked_char, checked_font) } else { (*unchecked_char, unchecked_font) };
|
||||
let mut props = content_base(s, &r);
|
||||
let mut props = replacement_props(s, &r);
|
||||
if !font.is_empty() {
|
||||
props.font = Some(font.clone());
|
||||
}
|
||||
@@ -696,7 +706,7 @@ fn choose_item(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Err(CmdError::Params("give index, value or text".into()));
|
||||
};
|
||||
let Some(item) = item.cloned() else { return Err(CmdError::Params("no such entry".into())) };
|
||||
let props = content_base(s, &r);
|
||||
let props = replacement_props(s, &r);
|
||||
let end = set_content(s, &r, &item.display, &props)?;
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
if let ControlKind::ComboBox { last_value, .. } | ControlKind::DropDown { last_value, .. } = &mut c.kind {
|
||||
@@ -716,7 +726,7 @@ fn set_date(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let (y, m, d) = p::str(v, "date").and_then(parse_date).ok_or_else(|| CmdError::Params("date: YYYY-MM-DD".into()))?;
|
||||
let text = format_date_value(format, y, m, d);
|
||||
let props = content_base(s, &r);
|
||||
let props = replacement_props(s, &r);
|
||||
let end = set_content(s, &r, &text, &props)?;
|
||||
if let Some(c) = s.doc.control_mut(&r.start) {
|
||||
if let ControlKind::Date { full_date, .. } = &mut c.kind {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::{Border, BorderStyle, Borders, CharProps, LineSpacing, Rgb, TextColor};
|
||||
use wordcraft_doc::{Watermark, styles};
|
||||
use wordcraft_doc::{StyleKind, Watermark, styles};
|
||||
|
||||
use super::sel_result;
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
@@ -209,9 +209,16 @@ fn para_spacing(s: &mut Session, v: &Value) -> CmdResult {
|
||||
"double" => (0.0, 8.0, 2.0),
|
||||
_ => (0.0, 8.0, 1.15),
|
||||
};
|
||||
Arc::make_mut(&mut s.doc.styles).default_para.space_before = Some(before);
|
||||
Arc::make_mut(&mut s.doc.styles).default_para.space_after = Some(after);
|
||||
Arc::make_mut(&mut s.doc.styles).default_para.line_spacing = Some(LineSpacing::Multiple(line));
|
||||
let st = Arc::make_mut(&mut s.doc.styles);
|
||||
let apply = |p: &mut wordcraft_doc::props::ParaProps| {
|
||||
p.space_before = Some(before);
|
||||
p.space_after = Some(after);
|
||||
p.line_spacing = Some(LineSpacing::Multiple(line));
|
||||
};
|
||||
apply(&mut st.default_para);
|
||||
for style in st.styles.iter_mut().filter(|style| style.builtin && style.kind == StyleKind::Paragraph) {
|
||||
apply(&mut style.para);
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -287,7 +294,7 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
};
|
||||
let blocks: Vec<usize> = match p::str(v, "applyTo") {
|
||||
Some("document") => s.doc.sections().iter().map(|(end, _)| *end).collect(),
|
||||
Some("section") | None => vec![s.sel.focus.path.0.first().copied().unwrap_or(0) as usize],
|
||||
Some("section") | None => vec![super::page::section_end_of_focus(s)],
|
||||
Some(x) => return Err(CmdError::Params(format!("unknown `applyTo` `{x}`"))),
|
||||
};
|
||||
for block in blocks {
|
||||
@@ -295,3 +302,34 @@ fn page_borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::{Document, Style};
|
||||
|
||||
#[test]
|
||||
fn paragraph_spacing_preset_updates_builtin_styles_and_keeps_custom_styles() {
|
||||
let mut s = Session::new(Document::new());
|
||||
Arc::make_mut(&mut s.doc.styles).styles.push(Style {
|
||||
id: "CustomSpacing".into(),
|
||||
name: "Custom Spacing".into(),
|
||||
kind: StyleKind::Paragraph,
|
||||
builtin: false,
|
||||
para: wordcraft_doc::props::ParaProps { space_after: Some(24.0), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
s.run("design.paragraphSpacing", &json!({"value": "double"})).unwrap();
|
||||
|
||||
let normal = s.doc.styles.get("Normal").unwrap();
|
||||
assert_eq!(normal.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
|
||||
let heading = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_eq!((heading.para.space_before, heading.para.space_after), (Some(0.0), Some(8.0)));
|
||||
assert_eq!(heading.para.line_spacing, Some(LineSpacing::Multiple(2.0)));
|
||||
let custom = s.doc.styles.get("CustomSpacing").unwrap();
|
||||
assert_eq!(custom.para.space_after, Some(24.0));
|
||||
assert_eq!(custom.para.line_spacing, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,29 +208,28 @@ fn copy_with(s: &mut Session, whole: Option<&Path>) -> CmdResult {
|
||||
None if a == b => return Ok(json!({"text": ""})),
|
||||
None => s.doc.copy_range(&a, &b),
|
||||
};
|
||||
s.clipboard_text = f.clipboard_text();
|
||||
s.clip_history.push(&f, &s.clipboard_text);
|
||||
s.clipboard = Some(f);
|
||||
Ok(copy_result(s))
|
||||
let text = f.clipboard_text();
|
||||
let r = copy_result(s, &f, &text)?;
|
||||
s.clip_history.push(&f, &text);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// What Copy and Cut return: the clipboard's text, and the copy as HTML (equations as MathML,
|
||||
/// #816) and as RTF for the host to put on the system clipboard too, so other programs keep the
|
||||
/// formatting; and for a copy of one equation alone, its MathML (#1297).
|
||||
pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
|
||||
Some(f) => {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
(wordcraft_formats::html::export_fragment(&d), wordcraft_formats::rtf::export(&d))
|
||||
}
|
||||
None => (String::new(), String::new()),
|
||||
};
|
||||
let mut r = json!({"text": s.clipboard_text});
|
||||
for (k, v) in [("html", &s.clipboard_html), ("rtf", &s.clipboard_rtf)] {
|
||||
///
|
||||
/// The copy goes on the clipboard whole or not at all: a copy whose HTML or RTF cannot be made
|
||||
/// is refused, and the clipboard keeps what it held.
|
||||
pub(crate) fn copy_result(s: &mut Session, f: &Fragment, text: &str) -> CmdResult {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
let html = wordcraft_formats::html::export_fragment(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as HTML: {e}")))?;
|
||||
let rtf = wordcraft_formats::rtf::export(&d).map_err(|e| CmdError::Failed(format!("the copy cannot be exported as RTF: {e}")))?;
|
||||
let mut r = json!({"text": text});
|
||||
for (k, v) in [("html", &html), ("rtf", &rtf)] {
|
||||
if !v.is_empty() {
|
||||
r[k] = json!(v);
|
||||
}
|
||||
@@ -239,10 +238,16 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
// ("MathML" on Windows, `public.mathml.presentation` on macOS; #1297). Word looks for them
|
||||
// before anything else when it pastes; a copy with text around the equation doesn't offer
|
||||
// them, so pasting it keeps the text.
|
||||
if let Some((linear, display)) = s.clipboard.as_ref().and_then(|f| f.sole_equation()) {
|
||||
if let Some((linear, display)) = f.sole_equation() {
|
||||
r["mathml"] = json!(wordcraft_formats::mathml::linear_to_mathml(linear, display));
|
||||
}
|
||||
r
|
||||
// The copy is on the clipboard now: its text, its fragment and its HTML and RTF flavours,
|
||||
// all at once.
|
||||
s.clipboard_text = text.to_string();
|
||||
s.clipboard = Some(f.clone());
|
||||
s.clipboard_html = html;
|
||||
s.clipboard_rtf = rtf;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
|
||||
|
||||
@@ -261,6 +261,11 @@ fn insert_nodes_as_equation(s: &mut Session, nodes: Arg, v: &Value) -> CmdResult
|
||||
/// Starts editing the equation at the caret, materializing lazy nodes and clamping the requested
|
||||
/// position, and returns the equation and caret.
|
||||
fn edit(s: &mut Session, v: &Value) -> CmdResult {
|
||||
edit_at(s, v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()))
|
||||
}
|
||||
|
||||
/// [`edit`] at `pos` in the equation, or at its end without one.
|
||||
pub(super) fn edit_at(s: &mut Session, pos: Option<MathPos>) -> CmdResult {
|
||||
let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?;
|
||||
let nodes = match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) {
|
||||
Some(InlineObject::Equation { math, linear, .. }) => {
|
||||
@@ -272,8 +277,7 @@ fn edit(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
_ => return Err(CmdError::Failed("no equation there".into())),
|
||||
};
|
||||
let pos =
|
||||
v.get("pos").and_then(|p| serde_json::from_value::<MathPos>(p.clone()).ok()).unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
|
||||
let pos = pos.unwrap_or_else(|| MathPos::new(Vec::new(), me::units(&nodes)));
|
||||
let Some(session) = crate::next_math_session() else {
|
||||
return Err(CmdError::Failed("no equation editing session available".into()));
|
||||
};
|
||||
|
||||
@@ -59,6 +59,74 @@ fn structures_symbols_and_navigation() {
|
||||
assert!(s.math.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_and_right_step_into_an_equation_next_to_the_caret() {
|
||||
let mut s = session();
|
||||
s.run("document.setText", &json!({"text": "ab\ncd"})).unwrap();
|
||||
let p0 = s.doc.start_of(s.sel.focus.story);
|
||||
let p1 = Pos { path: s.doc.next_para(p0.story, &p0.path).unwrap(), ..p0.clone() };
|
||||
// An equation between "a" and "b", and another one between "c" and "d".
|
||||
for p in [&p0, &p1] {
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p.clone() }})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "x+y", "edit": false})).unwrap();
|
||||
}
|
||||
let after = 1 + OBJ.len_utf8();
|
||||
let editing = |s: &Session| s.math.as_ref().map(|m| (m.at.path.clone(), m.at.off, m.pos.clone()));
|
||||
|
||||
// Right from "a|" enters the equation at its start.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
|
||||
// Leaving it to the right, the next Right goes on to the text, not back in.
|
||||
for _ in 0..10 {
|
||||
if s.math.is_none() {
|
||||
break;
|
||||
}
|
||||
s.run("equation.move", &json!({"dir": "right"})).unwrap();
|
||||
}
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after));
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + 1));
|
||||
|
||||
// Left from just after the equation in the second paragraph enters it at its end.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
|
||||
s.run("caret.left", &json!({})).unwrap();
|
||||
let end = MathPos::new(Vec::new(), me::units(&nodes_of(&s, &Pos { off: 1, ..p1.clone() }).unwrap()));
|
||||
assert_eq!(editing(&s), Some((p1.path.clone(), 1, end)));
|
||||
for _ in 0..10 {
|
||||
if s.math.is_none() {
|
||||
break;
|
||||
}
|
||||
s.run("equation.move", &json!({"dir": "left"})).unwrap();
|
||||
}
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
|
||||
s.run("caret.left", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 0));
|
||||
|
||||
// Shift+Right selects over the equation, as before.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
|
||||
s.run("caret.right", &json!({"extend": true})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.anchor.off, s.sel.focus.off), (true, 1, after));
|
||||
|
||||
// caret.left/right sent while editing (the arrow keys go to equation.move instead) leave
|
||||
// the equation and move on, as before, rather than opening the equation they land next to.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: after, ..p0.clone() }})).unwrap();
|
||||
s.run("equation.edit", &json!({})).unwrap();
|
||||
s.run("caret.left", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, 1));
|
||||
// With two equations side by side, Right from the first goes on past the second.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: after, ..p1.clone() }})).unwrap();
|
||||
s.run("insert.equation", &json!({"linear": "z", "edit": false})).unwrap();
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p1.clone() }})).unwrap();
|
||||
s.run("equation.edit", &json!({})).unwrap();
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!((s.math.is_none(), s.sel.focus.off), (true, after + OBJ.len_utf8()));
|
||||
// That holds only for the command that left the equation: the next Right opens one again.
|
||||
s.run("caret.set", &json!({"pos": Pos { off: 1, ..p0.clone() }})).unwrap();
|
||||
s.run("caret.right", &json!({})).unwrap();
|
||||
assert_eq!(editing(&s), Some((p0.path.clone(), 1, MathPos::default())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbering_conversion_and_display() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -53,11 +53,11 @@ impl Recorder<'_> {
|
||||
if let Some(r) = self.rid {
|
||||
return r;
|
||||
}
|
||||
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.date == self.date);
|
||||
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.instant() == self.date);
|
||||
let r = match found {
|
||||
Some(i) => i as u32,
|
||||
None => {
|
||||
self.revisions.push(Revision { kind: RevisionKind::Format, author: self.author.clone(), date: self.date.clone(), move_name: None });
|
||||
self.revisions.push(crate::cmd::made_revision(RevisionKind::Format, self.author.clone(), self.date.clone()));
|
||||
self.revisions.len().saturating_sub(1) as u32
|
||||
}
|
||||
};
|
||||
|
||||
@@ -27,6 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#"{"type"?: "indented|runIn", "columns"?: 1-4, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "headings"?: bool (letter headings)} (replaces an existing index's settings)"#,
|
||||
),
|
||||
CommandSpec::new("references.updateIndex", "Update Index", "References › Index", |s, _| {
|
||||
check_index_reachable(s)?;
|
||||
super::citations::update_generated(s)?;
|
||||
sel_result(s)
|
||||
}),
|
||||
@@ -135,8 +136,67 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// while Different First Page is off) don't count. Only an index in the main text is rebuilt.
|
||||
fn has_index(s: &Session, main: bool) -> bool {
|
||||
s.doc.shown_stories().into_iter().any(|story| {
|
||||
s.doc
|
||||
.para_paths(story)
|
||||
.iter()
|
||||
.filter(|path| (story == StoryRef::Body && path.depth() == 0) == main)
|
||||
.filter_map(|path| s.doc.para(story, path))
|
||||
.any(|p| {
|
||||
p.objects.iter().any(|o| {
|
||||
matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Refuses Insert and Update Index when the document has an index they can't rebuild, even beside
|
||||
/// one in the main text, rather than adding a second index or reporting an update that left it
|
||||
/// unchanged.
|
||||
fn check_index_reachable(s: &Session) -> Result<(), CmdError> {
|
||||
if has_index(s, false) {
|
||||
return Err(CmdError::Failed(
|
||||
"the index is in a table, text box, header or footer, where it can't be updated; move it into the main text, then use Update Index"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
// A range-field index after text in its paragraph is not rebuilt either: Update Index only
|
||||
// takes one that starts its paragraph.
|
||||
if range_index_after_text(s) {
|
||||
return Err(CmdError::Failed(
|
||||
"the index follows text in its paragraph, where it can't be updated; put it at the start of its own paragraph in the main text".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a main-text range-field INDEX has text before it in its paragraph.
|
||||
fn range_index_after_text(s: &Session) -> bool {
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).any(|p| {
|
||||
p.objects_with_offsets().any(|(off, o)| {
|
||||
matches!(o, InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
|
||||
&& !p.text.get(..off).is_some_and(|t| t.chars().all(|c| c.is_whitespace() || c == wordcraft_doc::para::OBJ))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let instr = index_instr(v);
|
||||
check_index_reachable(s)?;
|
||||
// An index Word wrote as a range field is first made a plain field in its own paragraph, as
|
||||
// Update Index makes it, so it takes the new settings rather than a second index being added
|
||||
// beside it (#8034).
|
||||
if index_field(s).is_none() && has_index(s, true) {
|
||||
super::citations::update_generated(s)?;
|
||||
if index_field(s).is_none() {
|
||||
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
|
||||
}
|
||||
}
|
||||
match index_field(s) {
|
||||
Some((i, _)) => {
|
||||
// Settings for the index that is there: a new field code, then rebuild it.
|
||||
@@ -484,4 +544,157 @@ mod tests {
|
||||
let (i, _) = index_field(&s).unwrap();
|
||||
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
|
||||
}
|
||||
|
||||
/// #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.
|
||||
#[test]
|
||||
fn an_index_outside_the_main_text_is_refused_not_doubled() {
|
||||
let indexes = |s: &Session| {
|
||||
std::iter::once(StoryRef::Body)
|
||||
.chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)))
|
||||
.flat_map(|story| s.doc.para_paths(story).into_iter().filter_map(move |path| s.doc.para(story, &path).cloned()))
|
||||
.flat_map(|p| p.objects)
|
||||
.filter(|o| matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX"))
|
||||
.count()
|
||||
};
|
||||
for in_box in [false, true] {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text(
|
||||
"Kilns are hot.
|
||||
End.",
|
||||
));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let at = if in_box {
|
||||
s.run("insert.textBox", &json!({"text": "Box"})).unwrap();
|
||||
let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap();
|
||||
Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 }
|
||||
} else {
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
|
||||
Pos { story: StoryRef::Body, path: cell, off: 0 }
|
||||
};
|
||||
// A range field, as a Word file holds its index.
|
||||
let p = s.doc.para_mut(at.story, &at.path).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let r = s.run("references.index", &json!({"columns": 2}));
|
||||
assert!(r.is_err(), "Insert Index with the index in a {}: {r:?}", if in_box { "text box" } else { "table" });
|
||||
assert_eq!(indexes(&s), 1, "INDEX fields after Insert Index");
|
||||
assert!(s.run("references.updateIndex", &json!({})).is_err(), "Update Index reports the index it can't rebuild");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3670: an index in a table is refused even when the main text also has one, so the update
|
||||
/// can't report success and leave the table's index as it was.
|
||||
#[test]
|
||||
fn an_index_in_a_table_is_refused_beside_one_in_the_main_text() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({})).unwrap();
|
||||
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
|
||||
let p = s.doc.para_mut(StoryRef::Body, &cell).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default()).unwrap();
|
||||
assert!(s.run("references.index", &json!({"columns": 2})).is_err());
|
||||
assert!(s.run("references.updateIndex", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// #3670: only the headers a page shows count. An INDEX in a first-page header is out of
|
||||
/// reach while Different First Page is on, and doesn't block Insert Index while it is off.
|
||||
#[test]
|
||||
fn an_index_in_a_header_blocks_insert_only_while_the_header_is_shown() {
|
||||
let with_header_index = |first: bool, title_page: bool| {
|
||||
let mut d = wordcraft_doc::Document::from_text("Kilns are hot.");
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![std::sync::Arc::new(wordcraft_doc::Block::Para(p))]);
|
||||
if first {
|
||||
d.last_section.headers.first = Some(id);
|
||||
} else {
|
||||
d.last_section.headers.default = Some(id);
|
||||
}
|
||||
d.last_section.title_page = title_page;
|
||||
let mut s = Session::new(d);
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s
|
||||
};
|
||||
let body_has_index = |s: &Session| index_field(s).is_some();
|
||||
// Linked (default) header: shown, so Insert Index is refused.
|
||||
let mut s = with_header_index(false, false);
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
assert!(!body_has_index(&s));
|
||||
// First-page header with Different First Page off: hidden, so the body gets its index.
|
||||
let mut s = with_header_index(true, false);
|
||||
s.run("references.index", &json!({})).unwrap();
|
||||
assert!(body_has_index(&s));
|
||||
// The same header with Different First Page on is shown again.
|
||||
let mut s = with_header_index(true, true);
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
assert!(!body_has_index(&s));
|
||||
}
|
||||
|
||||
/// An index Word wrote as a range field in the main text takes Insert Index's settings and is
|
||||
/// rebuilt, rather than a second index being added at the caret (#8034).
|
||||
#[test]
|
||||
fn insert_index_gives_a_range_field_index_in_the_main_text_its_settings() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
let at = s.doc.body.len();
|
||||
let mut para = wordcraft_doc::para::Paragraph::new();
|
||||
para.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("references.index", &json!({"columns": 2})).unwrap();
|
||||
let instrs: Vec<String> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX" => {
|
||||
Some(instr.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(instrs.len(), 1, "one index, not a second beside it: {instrs:?}");
|
||||
assert!(FieldCode::parse(&instrs[0]).arg('c').is_some(), "the index took the new columns setting: {instrs:?}");
|
||||
let text: String =
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
|
||||
"
|
||||
",
|
||||
);
|
||||
assert!(text.contains("Kilns are hot."), "the text before the index survives: {text:?}");
|
||||
assert!(text.contains("Kilns, 1"), "Update Index generated an entry: {text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_field_index_after_text_is_refused_not_reported_updated() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
|
||||
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
|
||||
s.run("references.markEntry", &json!({})).unwrap();
|
||||
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
let end = p.len();
|
||||
p.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
|
||||
p.insert_object(end, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
|
||||
.unwrap();
|
||||
assert!(s.run("references.updateIndex", &json!({})).is_err());
|
||||
assert!(s.run("references.index", &json!({})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ pub use items::{
|
||||
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
|
||||
use links::{bookmark, delete_bookmark, link, link_targets};
|
||||
pub use links::{bookmark_name_ok, bookmark_range, bookmark_span};
|
||||
pub use objects::{base64_decode, base64_encode};
|
||||
pub use objects::{MAX_TABLE_ROWS, base64_decode, base64_encode};
|
||||
use objects::{icon, shape, table, text_box};
|
||||
pub(crate) use objects::{image_ext, picture};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::{
|
||||
/// 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).
|
||||
pub(super) fn hf_part(s: &mut Session, header: bool) -> u32 {
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let block = crate::cmd::page::section_end_of_focus(s);
|
||||
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();
|
||||
@@ -98,15 +98,12 @@ pub(super) fn edit_hf(s: &mut Session, v: &Value, header: bool) -> CmdResult {
|
||||
let shown = match page {
|
||||
Some(page) => shown_hf(s, page, header)?,
|
||||
None => {
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let set = s
|
||||
.doc
|
||||
.sections()
|
||||
.into_iter()
|
||||
.find(|(end, _)| block <= *end)
|
||||
.or_else(|| s.doc.sections().pop())
|
||||
.map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
|
||||
set.flatten().filter(|id| s.doc.parts.contains_key(id))
|
||||
// The caret's section's own, else the one it is linked to from a section before it, as
|
||||
// layout shows it (#3639): editing that one keeps the link.
|
||||
let section = crate::cmd::page::hf_section_of_focus(s);
|
||||
let sections = s.doc.sections();
|
||||
let set = sections.iter().take(section + 1).rev().find_map(|(_, sp)| if header { sp.headers.default } else { sp.footers.default });
|
||||
set.filter(|id| s.doc.parts.contains_key(id))
|
||||
}
|
||||
};
|
||||
let Some(id) = shown else {
|
||||
|
||||
@@ -311,7 +311,7 @@ pub fn format_date_parts_in(fmt: &str, lang: Option<&str>, y: i64, m: usize, d:
|
||||
('m', _) => out.push_str(&mm.to_string()),
|
||||
('s', 2..) => out.push_str(&format!("{ss:02}")),
|
||||
('s', _) => out.push_str(&ss.to_string()),
|
||||
('a' | 'A', _) => out.push_str(if hh < 12 { "AM" } else { "PM" }),
|
||||
// Bare `a`/`A` is literal; AM/PM is the `am/pm` token (#3488).
|
||||
_ => {
|
||||
for _ in 0..n {
|
||||
out.push(c);
|
||||
|
||||
@@ -23,8 +23,13 @@ fn insert_block_at_caret(s: &mut Session, block: Block) -> Result<Path, CmdError
|
||||
Ok(insert_at)
|
||||
}
|
||||
|
||||
/// Most rows an inserted table has. The table model holds more, but an inserted table starts
|
||||
/// small: the command that inserts one clamps to this, so the others read it rather than
|
||||
/// repeating the number.
|
||||
pub const MAX_TABLE_ROWS: usize = 1_000;
|
||||
|
||||
pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, 1000) as usize;
|
||||
let rows = p::u64(v, "rows").unwrap_or(2).clamp(1, MAX_TABLE_ROWS as u64) as usize;
|
||||
let cols = p::u64(v, "cols").unwrap_or(2).clamp(1, 63) as usize;
|
||||
let width = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
|
||||
let mut t = Table::new(rows, cols, width);
|
||||
|
||||
@@ -358,6 +358,8 @@ fn date_pictures_keep_quoted_text() {
|
||||
// Two quotes outside quoted text are one too (an apostrophe), not an empty quoted text.
|
||||
assert_eq!(format_date_parts("yyyy '' MM", 2026, 10, 21, (0, 0, 0), 0), "2026 ' 10");
|
||||
assert_eq!(format_date_parts("d''MM", 2026, 10, 21, (0, 0, 0), 0), "21'10");
|
||||
// Bare `a` is literal, not AM/PM (#3488).
|
||||
assert_eq!(format_date_parts("yyyy a", 2026, 10, 21, (14, 30, 0), 0), "2026 a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,7 +27,7 @@ pub use merge::{merge_range, refresh};
|
||||
#[cfg(test)]
|
||||
use merge::{mergefield_name, placeholder};
|
||||
use recipients::recipients;
|
||||
pub use recipients::{RECIPIENT_EXTENSIONS, is_spreadsheet_name, parse_csv};
|
||||
pub use recipients::{CsvLimits, MAX_CELLS, MAX_FIELDS, MAX_TEXT_BYTES, RECIPIENT_EXTENSIONS, RECIPIENT_LIMITS, is_spreadsheet_name, parse_csv};
|
||||
|
||||
/// The mail-merge data source and preview state (lives in the session, not the document).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
|
||||
@@ -19,22 +19,32 @@ fn csv_separator(text: &str) -> char {
|
||||
[',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(',')
|
||||
}
|
||||
|
||||
/// Ends the current row: kept when it has any non-empty field, otherwise dropped.
|
||||
fn push_csv_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>) {
|
||||
if row.iter().any(|x| !x.is_empty()) {
|
||||
rows.push(std::mem::take(row));
|
||||
} else {
|
||||
row.clear();
|
||||
}
|
||||
/// What a CSV may hold while it is read: the parser refuses a list that is over these, so a
|
||||
/// hostile file is never built and then cut.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CsvLimits {
|
||||
/// Most columns in a record.
|
||||
pub fields: usize,
|
||||
/// Most cells in the list: its records times its widest record.
|
||||
pub cells: usize,
|
||||
/// Most bytes of cell text in all.
|
||||
pub text: usize,
|
||||
}
|
||||
|
||||
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
|
||||
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
|
||||
///
|
||||
/// The limits are kept while the list is read, not after it: a record wider than
|
||||
/// `limits.fields`, a list of more than `limits.cells` cells, or more than `limits.text` bytes
|
||||
/// of cell text is refused, rather than built and then cut.
|
||||
pub fn parse_csv(text: &str, limits: &CsvLimits) -> Result<Vec<Vec<String>>, CmdError> {
|
||||
let sep = csv_separator(text);
|
||||
let mut rows = Vec::new();
|
||||
let mut row = Vec::new();
|
||||
let mut cell = String::new();
|
||||
let mut q = false;
|
||||
// The widest record read so far, and the bytes of cell text read so far.
|
||||
let mut widest = 0usize;
|
||||
let mut text_bytes = 0usize;
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if q {
|
||||
@@ -51,29 +61,75 @@ pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
|
||||
} else if c == '"' {
|
||||
q = true;
|
||||
} else if c == sep {
|
||||
row.push(std::mem::take(&mut cell));
|
||||
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
|
||||
} else if c == '\n' || c == '\r' {
|
||||
if c == '\r' && chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
row.push(std::mem::take(&mut cell));
|
||||
push_csv_row(&mut rows, &mut row);
|
||||
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
|
||||
end_row(&mut rows, &mut row, &mut widest, limits)?;
|
||||
} else {
|
||||
cell.push(c);
|
||||
}
|
||||
// The text read so far: the finished cells and the one being read.
|
||||
if text_bytes.saturating_add(cell.len()) > limits.text {
|
||||
return Err(CmdError::Failed(format!("the CSV can't have more than {} of text", text_size(limits.text))));
|
||||
}
|
||||
if rows.len() > 100_000 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
row.push(cell);
|
||||
push_csv_row(&mut rows, &mut row);
|
||||
rows
|
||||
// The last cell, when the file doesn't end with a line break.
|
||||
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
|
||||
end_row(&mut rows, &mut row, &mut widest, limits)?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// A finished cell joins the record: the record's width stays inside the limit.
|
||||
fn end_cell(row: &mut Vec<String>, cell: &mut String, text_bytes: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
|
||||
*text_bytes = text_bytes.saturating_add(cell.len());
|
||||
row.push(std::mem::take(cell));
|
||||
if row.len() > limits.fields {
|
||||
return Err(CmdError::Failed(format!("the CSV can't have more than {} columns", limits.fields)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A finished record joins the list (an empty one is dropped). The list costs its records times
|
||||
/// its widest record — a recipient list pads every record to the header's width — so a list
|
||||
/// over the limit is refused here, while it is read.
|
||||
fn end_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>, widest: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
|
||||
if row.iter().any(|x| !x.is_empty()) {
|
||||
*widest = (*widest).max(row.len());
|
||||
rows.push(std::mem::take(row));
|
||||
} else {
|
||||
row.clear();
|
||||
}
|
||||
if rows.len().saturating_mul(*widest) > limits.cells {
|
||||
return Err(CmdError::Failed(format!("the CSV can't have more than {} cells (its records times its widest record)", limits.cells)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A byte budget, said the way a reader says it.
|
||||
fn text_size(bytes: usize) -> String {
|
||||
if bytes >= 1 << 20 { format!("{} MB", bytes >> 20) } else { format!("{bytes} bytes") }
|
||||
}
|
||||
|
||||
/// Most records and fields a recipient list keeps.
|
||||
const MAX_RECORDS: usize = 100_000;
|
||||
|
||||
const MAX_FIELDS: usize = 1_000;
|
||||
pub const MAX_FIELDS: usize = 1_000;
|
||||
|
||||
/// Most cells a recipient list keeps: its records times its fields. A recipient list pads every
|
||||
/// record to the header's width, so this is what a list costs, not how many values it says.
|
||||
pub const MAX_CELLS: usize = 2_000_000;
|
||||
|
||||
/// Most bytes of cell text a recipient list keeps. The table path keeps the same budget.
|
||||
pub const MAX_TEXT_BYTES: usize = 64 << 20;
|
||||
|
||||
/// The limits a recipient list keeps.
|
||||
pub const RECIPIENT_LIMITS: CsvLimits = CsvLimits { fields: MAX_FIELDS, cells: MAX_CELLS, text: MAX_TEXT_BYTES };
|
||||
|
||||
pub(super) fn cell(x: &Value) -> String {
|
||||
match x {
|
||||
@@ -117,12 +173,12 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
|
||||
|
||||
/// Skip unquoted blank prefix lines only when a text recipient list has a header.
|
||||
/// Headerless lists and the shared CSV reader keep whitespace records.
|
||||
fn recipient_csv(text: &str, headers: bool) -> Vec<Vec<String>> {
|
||||
fn recipient_csv(text: &str, headers: bool) -> Result<Vec<Vec<String>>, CmdError> {
|
||||
let prefix = text
|
||||
.split_inclusive(['\n', '\r'])
|
||||
.take_while(|line| headers && line.trim().is_empty())
|
||||
.fold(0_usize, |bytes, line| bytes.saturating_add(line.len()));
|
||||
parse_csv(text.get(prefix..).unwrap_or_default())
|
||||
parse_csv(text.get(prefix..).unwrap_or_default(), &RECIPIENT_LIMITS)
|
||||
}
|
||||
|
||||
pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -131,7 +187,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
table_from_rows(v.get("fields").and_then(Value::as_array), arr)?
|
||||
} else {
|
||||
let all = if let Some(c) = p::str(v, "csv") {
|
||||
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))
|
||||
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))?
|
||||
} else {
|
||||
let (bytes, ext) = if let Some(d) = p::str(v, "data") {
|
||||
let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?;
|
||||
@@ -188,7 +244,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sheet = json!(chosen);
|
||||
rows
|
||||
} else {
|
||||
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))
|
||||
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))?
|
||||
}
|
||||
};
|
||||
header_split(all, p::bool(v, "headers").unwrap_or(true))?
|
||||
|
||||
@@ -2,9 +2,54 @@ use super::*;
|
||||
|
||||
#[test]
|
||||
fn csv_parsing() {
|
||||
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n");
|
||||
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n", &RECIPIENT_LIMITS).unwrap();
|
||||
assert_eq!(r, vec![vec!["Name", "City"], vec!["Smith, Ann", "Paris"], vec!["Bo", "Oslo \"N\""]]);
|
||||
assert_eq!(parse_csv("a;b\n1;2")[1], vec!["1", "2"]);
|
||||
assert_eq!(parse_csv("a;b\n1;2", &RECIPIENT_LIMITS).unwrap()[1], vec!["1", "2"]);
|
||||
}
|
||||
|
||||
/// The parser keeps its limits while it reads the list, so a hostile list is refused
|
||||
/// instead of being built and then cut.
|
||||
#[test]
|
||||
fn csv_parsing_refuses_a_list_over_its_limits() {
|
||||
// A record wider than the limit.
|
||||
let e = parse_csv("a,b,c,d,e", &CsvLimits { fields: 4, cells: 100, text: 1_000 }).unwrap_err();
|
||||
assert!(e.to_string().contains("4 columns"), "{e}");
|
||||
// More cells than the list keeps.
|
||||
let e = parse_csv("a,b\nc,d\ne,f\ng,h\ni,j\nk,l", &CsvLimits { fields: 10, cells: 10, text: 1_000 }).unwrap_err();
|
||||
assert!(e.to_string().contains("10 cells"), "{e}");
|
||||
// More text than the list keeps.
|
||||
let e = parse_csv("abcdefghij", &CsvLimits { fields: 10, cells: 100, text: 8 }).unwrap_err();
|
||||
assert!(e.to_string().contains("of text"), "{e}");
|
||||
// A list inside the limits still parses.
|
||||
let limits = CsvLimits { fields: 4, cells: 10, text: 1_000 };
|
||||
assert_eq!(parse_csv("a,b\nc,d", &limits).unwrap(), vec![vec!["a", "b"], vec!["c", "d"]]);
|
||||
}
|
||||
|
||||
/// A recipient list over its limits is refused, not built.
|
||||
#[test]
|
||||
fn a_recipient_list_over_its_limits_is_refused() {
|
||||
// A record wider than the list's fields.
|
||||
let wide = format!("{}\nvalue", "f,".repeat(MAX_FIELDS + 1));
|
||||
let e = parse_csv(&wide, &RECIPIENT_LIMITS).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_FIELDS} columns")), "{e}");
|
||||
|
||||
// A record of exactly the limit's width is kept.
|
||||
let exact = format!("{}\nvalue", "f,".repeat(MAX_FIELDS - 1));
|
||||
assert_eq!(parse_csv(&exact, &RECIPIENT_LIMITS).unwrap()[0].len(), MAX_FIELDS);
|
||||
|
||||
// A wide header over many records: the list would cost more cells than it keeps, and
|
||||
// every record is padded to the header's width.
|
||||
let mut csv = format!("{}\n", (0..MAX_FIELDS).map(|i| format!("f{i}")).collect::<Vec<_>>().join(","));
|
||||
for _ in 0..=MAX_CELLS / MAX_FIELDS {
|
||||
csv.push_str("value\n");
|
||||
}
|
||||
let e = parse_csv(&csv, &RECIPIENT_LIMITS).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_CELLS} cells")), "{e}");
|
||||
|
||||
// The command refuses it too, with a message of its own.
|
||||
let mut s = Session::new(Document::new());
|
||||
let e = s.run("mailings.recipients", &json!({"csv": wide})).unwrap_err();
|
||||
assert!(e.to_string().contains("columns"), "{e}");
|
||||
}
|
||||
|
||||
/// #4001: finishing a merge opens a new document, with a new undo history. It is not an
|
||||
@@ -56,13 +101,16 @@ fn csv_delimiter_reads_complete_header_record() {
|
||||
let quoted = header.replace('"', "\"\"");
|
||||
let text = format!("\"{quoted}\"{sep}City{sep}{sep}\r\nAda{sep}Paris{sep}{sep}\nBo{sep}Oslo{sep}{sep}");
|
||||
assert_eq!(
|
||||
parse_csv(&text),
|
||||
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
|
||||
vec![vec![header.as_str(), "City", "", ""], vec!["Ada", "Paris", "", ""], vec!["Bo", "Oslo", "", ""]],
|
||||
"separator {sep:?}, embedded newline {newline:?}"
|
||||
);
|
||||
// A multiline field after an ordinary column must not end detection either.
|
||||
let text = format!("ID{sep}\"{quoted}\"{sep}City\n1{sep}Ada{sep}Paris\n2{sep}Bo{sep}Oslo");
|
||||
assert_eq!(parse_csv(&text), vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]);
|
||||
assert_eq!(
|
||||
parse_csv(&text, &RECIPIENT_LIMITS).unwrap(),
|
||||
vec![vec!["ID", header.as_str(), "City"], vec!["1", "Ada", "Paris"], vec!["2", "Bo", "Oslo"]]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +122,7 @@ fn csv_delimiter_reads_multiline_headers_after_blank_lines() {
|
||||
let header = format!("Given{newline}Family");
|
||||
for prefix in ["\n\r\n", "\r", "\r\r"] {
|
||||
let text = format!("{prefix}\"{header}\"{sep}City\rAda{sep}Paris");
|
||||
assert_eq!(parse_csv(&text), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
|
||||
assert_eq!(parse_csv(&text, &RECIPIENT_LIMITS).unwrap(), vec![vec![header.as_str(), "City"], vec!["Ada", "Paris"]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,34 +147,41 @@ fn recipient_csv_blank_prefix_keeps_columns_without_dropping_literal_records() {
|
||||
let rows = s.merge.rows.clone();
|
||||
assert!(s.run("mailings.recipients", &json!({"csv": " \t\r\n \r"})).is_err());
|
||||
assert_eq!(s.merge.rows, rows, "an empty headered list must not replace existing recipients");
|
||||
assert_eq!(parse_csv(" \nName,Email\nAda,ada@example.com")[0], vec![" "], "the shared CSV reader keeps literal whitespace rows");
|
||||
assert_eq!(
|
||||
parse_csv(" \nName,Email\nAda,ada@example.com", &RECIPIENT_LIMITS).unwrap()[0],
|
||||
vec![" "],
|
||||
"the shared CSV reader keeps literal whitespace rows"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_keeps_record_boundaries_and_ties() {
|
||||
// Later records cannot choose the header's delimiter.
|
||||
assert_eq!(parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]);
|
||||
assert_eq!(
|
||||
parse_csv("Name;City\rAda;Paris,,,,\rBo;Oslo", &RECIPIENT_LIMITS).unwrap(),
|
||||
vec![vec!["Name", "City"], vec!["Ada", "Paris,,,,"], vec!["Bo", "Oslo"]]
|
||||
);
|
||||
// Existing ties prefer tab, then semicolon, then comma.
|
||||
assert_eq!(parse_csv("A,B;C\n1,2;3"), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
|
||||
assert_eq!(parse_csv("A;B\tC\n1;2\t3"), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
|
||||
assert_eq!(parse_csv("Name\nAda,Paris;Oslo"), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
|
||||
assert!(parse_csv("").is_empty());
|
||||
assert_eq!(parse_csv("\nName\nAda"), vec![vec!["Name"], vec!["Ada"]]);
|
||||
assert_eq!(parse_csv("A,B;C\n1,2;3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A,B", "C"], vec!["1,2", "3"]]);
|
||||
assert_eq!(parse_csv("A;B\tC\n1;2\t3", &RECIPIENT_LIMITS).unwrap(), vec![vec!["A;B", "C"], vec!["1;2", "3"]]);
|
||||
assert_eq!(parse_csv("Name\nAda,Paris;Oslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada,Paris;Oslo"]]);
|
||||
assert!(parse_csv("", &RECIPIENT_LIMITS).unwrap().is_empty());
|
||||
assert_eq!(parse_csv("\nName\nAda", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name"], vec!["Ada"]]);
|
||||
// The reader remains permissive about an unterminated quoted cell.
|
||||
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo"), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
|
||||
assert_eq!(parse_csv("Name,City\nAda,\"Paris\nOslo", &RECIPIENT_LIMITS).unwrap(), vec![vec!["Name", "City"], vec!["Ada", "Paris\nOslo"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_ignores_quoted_text() {
|
||||
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n");
|
||||
let r = parse_csv("\"Name, first, last\";City\nAnn;Paris\n", &RECIPIENT_LIMITS).unwrap();
|
||||
assert_eq!(r, vec![vec!["Name, first, last", "City"], vec!["Ann", "Paris"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_skips_leading_blank_lines() {
|
||||
let want = vec![vec!["Name", "Email"], vec!["Ann", "ann@x.org"]];
|
||||
assert_eq!(parse_csv("\nName,Email\nAnn,ann@x.org\n"), want);
|
||||
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;ann@x.org"), want);
|
||||
assert_eq!(parse_csv("\nName,Email\nAnn,ann@x.org\n", &RECIPIENT_LIMITS).unwrap(), want);
|
||||
assert_eq!(parse_csv("\r\n\r\nName;Email\r\nAnn;ann@x.org", &RECIPIENT_LIMITS).unwrap(), want);
|
||||
}
|
||||
|
||||
/// Field types ignore case (ECMA-376 Part 1, 17.16.1), and `MERGEFIELDX` is another field.
|
||||
|
||||
@@ -103,7 +103,7 @@ fn exact_text(s: &Session) -> Option<String> {
|
||||
return res.clone();
|
||||
}
|
||||
let kept = [s.md_file.latest.as_deref(), s.md_file.saved.as_deref()];
|
||||
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).same_content(&s.doc)).map(str::to_string);
|
||||
let res = kept.into_iter().flatten().find(|text| parse(&s.doc, text).is_ok_and(|d| d.same_content(&s.doc))).map(str::to_string);
|
||||
*s.md_file.cached_exact.borrow_mut() = Some((s.rev(), res.clone()));
|
||||
res
|
||||
}
|
||||
@@ -216,15 +216,16 @@ fn enter(s: &mut Session) -> Result<(), CmdError> {
|
||||
// The file's own text when it still says what the document holds, so nothing is lost.
|
||||
let (text, loses_content, block_lines) = match exact_text(s) {
|
||||
Some(text) => {
|
||||
let (_, lines) = parse_with_lines(&s.doc, &text);
|
||||
let (_, lines) = parse_with_lines(&s.doc, &text)?;
|
||||
(text, false, lines)
|
||||
}
|
||||
None => {
|
||||
let text = wordcraft_formats::markdown::export(&s.doc);
|
||||
let text = wordcraft_formats::markdown::export(&s.doc)
|
||||
.map_err(|e| CmdError::Failed(format!("the document cannot be written as Markdown: {e}")))?;
|
||||
if text.len() > MAX_SOURCE_BYTES {
|
||||
return Err(CmdError::Failed(too_long()));
|
||||
}
|
||||
let (doc, lines) = parse_with_lines(&s.doc, &text);
|
||||
let (doc, lines) = parse_with_lines(&s.doc, &text)?;
|
||||
let loses_content = !doc.same_content(&s.doc);
|
||||
(text, loses_content, lines)
|
||||
}
|
||||
@@ -289,7 +290,19 @@ pub fn apply(s: &mut Session) {
|
||||
}
|
||||
(src.text.clone(), src.entry_text.clone(), src.entry_doc.clone(), src.has_step, src.entry_lines.clone())
|
||||
};
|
||||
let (doc, lines) = if text == *entry_text { ((*entry_doc).clone(), entry_lines) } else { parse_with_lines(&s.doc, &text) };
|
||||
let (doc, lines) = if text == *entry_text {
|
||||
((*entry_doc).clone(), entry_lines)
|
||||
} else {
|
||||
// The text cannot be read as Markdown: the document stays as it is, rather than
|
||||
// becoming an empty one.
|
||||
match parse_with_lines(&s.doc, &text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
s.status = e.to_string();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
let step = if !has_step {
|
||||
s.checkpoint(LABEL);
|
||||
Some(s.undo_mark())
|
||||
@@ -313,19 +326,20 @@ pub fn apply(s: &mut Session) {
|
||||
|
||||
/// `text` as a document and block lines, with what isn't in Markdown from `current`: its page, settings,
|
||||
/// properties and language, as opening the file gave it.
|
||||
fn parse_with_lines(current: &Document, text: &str) -> (Document, Vec<usize>) {
|
||||
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, ¤t.last_section);
|
||||
fn parse_with_lines(current: &Document, text: &str) -> Result<(Document, Vec<usize>), CmdError> {
|
||||
let (mut doc, lines) = wordcraft_formats::markdown::import_on_with_lines(text, ¤t.last_section)
|
||||
.map_err(|e| CmdError::Failed(format!("the Markdown cannot be read: {e}")))?;
|
||||
doc.ensure_nonempty();
|
||||
doc.settings = current.settings.clone();
|
||||
doc.core = current.core.clone();
|
||||
Arc::make_mut(&mut doc.styles).default_chr.lang = current.styles.default_chr.lang.clone();
|
||||
(doc, lines)
|
||||
Ok((doc, lines))
|
||||
}
|
||||
|
||||
/// `text` as a document, with what isn't in Markdown from `current`: its page, settings,
|
||||
/// properties and language, as opening the file gave it.
|
||||
fn parse(current: &Document, text: &str) -> Document {
|
||||
parse_with_lines(current, text).0
|
||||
fn parse(current: &Document, text: &str) -> Result<Document, CmdError> {
|
||||
parse_with_lines(current, text).map(|(doc, _)| doc)
|
||||
}
|
||||
|
||||
/// The byte offset where `line` starts, or the end of a text with fewer lines.
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
|
||||
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
|
||||
return Ok(false);
|
||||
}
|
||||
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
|
||||
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, s.author.clone(), now_iso()));
|
||||
let rid = (s.doc.revisions.len() - 1) as u32;
|
||||
let at = track_delete_as(s, &a, &b, rid)?.at;
|
||||
s.sel = Selection::caret(at);
|
||||
@@ -75,13 +75,13 @@ pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
|
||||
return None;
|
||||
}
|
||||
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
|
||||
let date = src.date.clone();
|
||||
let (date, date_utc) = (src.date.clone(), src.date_utc.clone());
|
||||
let taken: BTreeSet<&str> = s.doc.revisions.iter().filter_map(|r| r.move_name.as_deref()).collect();
|
||||
let name = (1..).map(|n: u64| format!("move{n}")).find(|n| !taken.contains(n.as_str()))?;
|
||||
if let Some(r) = s.doc.revisions.get_mut(m.rev as usize) {
|
||||
r.move_name = Some(name.clone());
|
||||
}
|
||||
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name) });
|
||||
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name), date_utc });
|
||||
Some((s.doc.revisions.len() - 1) as u32)
|
||||
}
|
||||
|
||||
@@ -278,4 +278,23 @@ mod tests {
|
||||
assert_eq!(texts(&s), ["First one.", "Second one.", "Third one."]);
|
||||
assert!(kinds(&mut s).is_empty());
|
||||
}
|
||||
|
||||
/// A command that fails between a tracked cut and its paste changed nothing, so the move
|
||||
/// the cut recorded is still there: the paste is a move, as it was before the command.
|
||||
#[test]
|
||||
fn a_failed_command_between_a_tracked_cut_and_its_paste_leaves_the_move() {
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("document.setText", &json!({"text": "First one.\nSecond one.\nThird one."})).unwrap();
|
||||
s.run("file.setAuthor", &json!({"name": "Ana"})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 2, "off": 0}})).unwrap();
|
||||
s.run("edit.cut", &json!({})).unwrap();
|
||||
// A command that fails: there is no such character style.
|
||||
assert!(s.run("format.charStyle", &json!({"style": "NoSuchStyle"})).is_err());
|
||||
s.run("caret.set", &json!({"pos": {"block": 0, "off": 0}})).unwrap();
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
let k = kinds(&mut s);
|
||||
assert!(k.iter().any(|(k, m)| k == "moveTo" && m == "move1"), "{k:?}");
|
||||
assert!(k.iter().any(|(k, m)| k == "moveFrom" && m == "move1"), "{k:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ pub use picture::{OriginalSize, PictureLook, cropped_original_size, fit_size, or
|
||||
use picture::{clear_background, grown, picture_style};
|
||||
#[cfg(test)]
|
||||
pub(crate) use select::all_objects;
|
||||
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};
|
||||
|
||||
@@ -176,7 +176,7 @@ pub fn min_size(o: &InlineObject) -> f32 {
|
||||
}
|
||||
|
||||
/// Select the object whose character is at `pos`.
|
||||
pub(super) fn select_object(s: &mut Session, pos: &Pos) {
|
||||
pub(crate) fn select_object(s: &mut Session, pos: &Pos) {
|
||||
s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos.clone() } };
|
||||
}
|
||||
|
||||
|
||||
@@ -250,6 +250,26 @@ pub fn section_index_of_focus(s: &Session) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
/// The caret's section, for the header and footer commands. In a header or footer it is the
|
||||
/// section of the caret's page when that page shows it: a section linked to the previous one
|
||||
/// shows that section's header, so the header alone names the earlier section (#3639).
|
||||
pub fn hf_section_of_focus(s: &mut Session) -> usize {
|
||||
let wordcraft_doc::StoryRef::Part(id) = s.sel.focus.story else { return section_index_of_focus(s) };
|
||||
let layout = s.layout();
|
||||
match layout.pages.get(s.page_hint) {
|
||||
Some(pg) if pg.header_story == Some(id) || pg.footer_story == Some(id) => pg.section,
|
||||
_ => section_of_part(s, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last body block of the caret's section ([`hf_section_of_focus`]), the block
|
||||
/// [`wordcraft_doc::Document::section_mut`] takes. In a header or footer the caret's block index
|
||||
/// counts that story's paragraphs, not the body's, so it would name another section (#3639).
|
||||
pub fn section_end_of_focus(s: &mut Session) -> usize {
|
||||
let i = hf_section_of_focus(s);
|
||||
s.doc.sections().get(i).map(|(end, _)| *end).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn sect(s: &Session) -> SectionProps {
|
||||
let i = section_index_of_focus(s);
|
||||
s.doc.sections().get(i).map(|(_, x)| (*x).clone()).unwrap_or_default()
|
||||
|
||||
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#"{"color": "RRGGBB" | null, "paragraph"?: bool} (text selected inside one paragraph is shaded itself, as in Word; `paragraph: true` shades the paragraphs instead, as Borders and Shading › Apply to: Paragraph)"#,
|
||||
),
|
||||
CommandSpec::new("para.borders", "Borders", "Home › Paragraph", borders).params(
|
||||
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind`"#,
|
||||
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind` (with whole table cells selected, `kind` borders the cells as a block instead of their paragraphs)"#,
|
||||
),
|
||||
CommandSpec::new("para.sort", "Sort", "Home › Paragraph", sort).params(r#"{"descending"?: bool}"#),
|
||||
CommandSpec::new("para.keepNext", "Keep with Next", "Home › Paragraph › Line and Page Breaks", |s, v| tog(s, v, |p| p.keep_next, |p, b| p.keep_next = Some(b)))
|
||||
|
||||
@@ -102,6 +102,10 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// A paragraph with a bottom border, like Word's Horizontal Line.
|
||||
return fmt(s, &|p| p.borders = Some(Borders { bottom: Some(Border { width: 1.5, ..b }), ..Default::default() }));
|
||||
}
|
||||
// Whole table cells selected: the border goes on the cells, not their paragraphs (#7874).
|
||||
if let Some(range) = s.cell_range().cloned() {
|
||||
return crate::cmd::table::cell_block_borders(s, &range, kind, b);
|
||||
}
|
||||
fmt(s, &|p| {
|
||||
let mut cur = p.borders.unwrap_or_default();
|
||||
match kind {
|
||||
|
||||
@@ -187,7 +187,7 @@ fn paste_special(s: &mut Session, v: &Value) -> CmdResult {
|
||||
return Ok(r);
|
||||
}
|
||||
"formatted" => s.clipboard.clone().ok_or_else(|| CmdError::Failed("the clipboard is empty".into()))?,
|
||||
"html" => adopt(s, import_html(&src)),
|
||||
"html" => adopt(s, import_html(&src).map_err(|e| CmdError::Failed(format!("bad HTML: {e}")))?),
|
||||
_ => adopt(s, wordcraft_formats::rtf::import(src.as_bytes()).map_err(|e| CmdError::Failed(format!("bad RTF: {e}")))?),
|
||||
};
|
||||
insert(s, frag)?;
|
||||
@@ -204,8 +204,8 @@ const BLOCKQUOTE_INDENT: f32 = 36.0;
|
||||
/// (#1270): it pastes as a Normal paragraph indented by the page's `blockquote` margins, else half
|
||||
/// an inch each side, rather than in the (centred, italic) Quote style. Opening an .html file keeps
|
||||
/// `<blockquote>` as Quote, so HTML round-trips.
|
||||
fn import_html(html: &str) -> Document {
|
||||
let mut doc = wordcraft_formats::html::import(html_fragment(html));
|
||||
fn import_html(html: &str) -> Result<Document, String> {
|
||||
let mut doc = wordcraft_formats::html::import(html_fragment(html))?;
|
||||
let (left, right) = blockquote_margins(html);
|
||||
for b in &mut doc.body {
|
||||
each_para(Arc::make_mut(b), 0, &mut |p| {
|
||||
@@ -217,7 +217,7 @@ fn import_html(html: &str) -> Document {
|
||||
}
|
||||
});
|
||||
}
|
||||
doc
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// The left and right margins (points) the payload's `<style>` sheets give `blockquote` — LibreOffice
|
||||
@@ -294,7 +294,7 @@ fn has_content(d: &Document) -> bool {
|
||||
/// [`MAX_PASTE_BYTES`], or it holds nothing to paste (the caller pastes the text then).
|
||||
pub fn rich_fragment(s: &mut Session, v: &Value) -> Option<Fragment> {
|
||||
let fits = |k: &str| p::str(v, k).filter(|t| !t.trim().is_empty() && t.len() <= MAX_PASTE_BYTES);
|
||||
let doc = fits("html").map(import_html);
|
||||
let doc = fits("html").and_then(|html| import_html(html).ok());
|
||||
let doc = match doc.filter(has_content) {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
|
||||
@@ -560,6 +560,73 @@ fn caption_for_an_object_in_a_cell_stays_in_the_cell() {
|
||||
assert_eq!(texts.get(1).map(String::as_str), Some("Figure 1"), "{texts:?}");
|
||||
}
|
||||
|
||||
/// A TOC inserted before a heading leaves the caret at the heading's first character, past the
|
||||
/// `_Toc` bookmark its entry links to: Delete then deletes that character, and the entry still
|
||||
/// finds its heading (Delete at offset zero took the bookmark).
|
||||
#[test]
|
||||
fn the_caret_after_a_toc_sits_past_the_headings_bookmark() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns\nBody text."));
|
||||
s.run("para.style", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(0), off: 0 });
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap();
|
||||
assert_eq!(heading.plain_text(), "Kilns");
|
||||
let marks = |p: &Paragraph| p.objects.iter().filter(|o| matches!(o, InlineObject::BookmarkStart { .. })).count();
|
||||
assert_eq!(marks(&heading), 1, "the heading has its bookmark");
|
||||
s.run("text.delete", &json!({})).unwrap();
|
||||
let heading = s.doc.para_at(&s.sel.focus).cloned().unwrap();
|
||||
assert_eq!(heading.plain_text(), "ilns", "Delete took the first character");
|
||||
assert_eq!(marks(&heading), 1, "the bookmark stays");
|
||||
}
|
||||
|
||||
/// Inserting a table of contents (Word itself warns when there's no heading yet, but still
|
||||
/// creates an empty one) must leave the caret in a fresh paragraph just after it, like Word
|
||||
/// does — not inside the table's own title, where typing the rest of the document (and later
|
||||
/// updating the table) would splice stray text into unrelated paragraphs and blank the title.
|
||||
#[test]
|
||||
fn a_toc_inserted_before_any_headings_exist_leaves_the_caret_after_it() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("references.toc", &json!({"levels": 2})).unwrap();
|
||||
assert_eq!(s.sel.focus.path, Path::top(1), "the caret must land right after the table, not inside it");
|
||||
s.run("text.insert", &json!({"text": "\r"})).unwrap();
|
||||
s.run("para.style", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Kilns\r"})).unwrap();
|
||||
s.run("para.style", &json!({"style": "Normal"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Body text."})).unwrap();
|
||||
s.run("references.updateToc", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
s.doc.plain_text(StoryRef::Body).matches("Contents").count(),
|
||||
1,
|
||||
"the title stays where it was, it doesn't vanish and reappear elsewhere"
|
||||
);
|
||||
assert!(s.doc.plain_text(StoryRef::Body).contains("Body text."), "typed body content survives untouched");
|
||||
let heading = s.doc.body.iter().filter_map(|b| b.as_para()).find(|p| p.props.style.as_deref() == Some("Heading1"));
|
||||
assert_eq!(heading.map(|p| p.plain_text()), Some("Kilns".to_string()));
|
||||
}
|
||||
|
||||
/// A settings-based replacement of a table whose last entry is directly followed by a table
|
||||
/// (nothing paragraph-shaped in between) must still land the caret in a real paragraph: the
|
||||
/// block "after" the table isn't always a paragraph just because it exists.
|
||||
#[test]
|
||||
fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_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 (_, 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(_)), "test setup: a table must directly follow the table's entries");
|
||||
// Replacing the table's settings must still land the caret in a fresh paragraph right
|
||||
// after the table, not snap back into the table's own entries (a bogus position pointing
|
||||
// at the table gets silently corrected by `clamp_selection` to the nearest *preceding*
|
||||
// paragraph, so a weaker "is this some paragraph" check wouldn't catch the regression).
|
||||
s.run("references.toc", &json!({"levels": 3})).unwrap();
|
||||
let (_, new_end) = toc_range(&s).unwrap();
|
||||
assert_eq!(s.sel.focus.path, Path::top(new_end + 1), "the caret must land right after the table, not snap back into the table");
|
||||
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
|
||||
}
|
||||
|
||||
/// A fresh scratch directory for the file-name tests below.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
|
||||
|
||||
@@ -412,6 +412,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// its paragraph ending the title's section, and the new entries follow in their columns.
|
||||
Some((start, _)) if title_above_break(s, start).is_some() => {
|
||||
replace_toc_above_break(s, v, start, &tabs)?;
|
||||
caret_after_toc(s)?;
|
||||
return sel_result(s);
|
||||
}
|
||||
Some((start, end)) => {
|
||||
@@ -444,10 +445,43 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(i), Block::Para(head))?;
|
||||
let leader = leader(p::str(v, "tabLeader").unwrap_or("dot"));
|
||||
regenerate_toc(s, Some(leader), &tabs)?;
|
||||
s.clamp_selection();
|
||||
caret_after_toc(s)?;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Like Word, the caret lands in the paragraph right after the table, ready to keep typing — not
|
||||
/// inside the table's own title or entries, where typing (or Enter) would corrupt them. When a
|
||||
/// table (or nothing) follows, a paragraph is added there first, and the entries are rebuilt so
|
||||
/// their page numbers count it.
|
||||
fn caret_after_toc(s: &mut Session) -> Result<(), CmdError> {
|
||||
if let Some((_, end)) = toc_range(s) {
|
||||
let after = end + 1;
|
||||
if !s.doc.body.get(after).is_some_and(|b| b.as_para().is_some()) {
|
||||
s.doc.insert_block(StoryRef::Body, &Path::top(after), Block::Para(Paragraph::new()))?;
|
||||
// Rebuilt as they now are (their leader and tabs), only the page numbers can change.
|
||||
let tabs = cached_toc_tabs(s);
|
||||
regenerate_toc(s, None, &tabs)?;
|
||||
}
|
||||
if let Some((_, end)) = toc_range(s) {
|
||||
// Past the markers the paragraph starts with (a heading's `_Toc` bookmark, which its
|
||||
// entry links to): Delete there takes the first character, not the bookmark.
|
||||
let off = s.doc.body.get(end + 1).and_then(|b| b.as_para()).map_or(0, |p| {
|
||||
let mut off = 0;
|
||||
for (at, o) in p.objects_with_offsets() {
|
||||
if at != off || !o.is_marker() {
|
||||
break;
|
||||
}
|
||||
off += OBJ.len_utf8();
|
||||
}
|
||||
off
|
||||
});
|
||||
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(end + 1), off });
|
||||
}
|
||||
}
|
||||
s.clamp_selection();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces a TOC whose title sits above the section break its field's paragraph ends
|
||||
/// (`title_above_break`): the field takes `v`'s settings, the title `v`'s `title` if one is given
|
||||
/// (otherwise it is kept, as Word's Insert Table of Contents keeps it), and the entries are rebuilt.
|
||||
|
||||
@@ -33,7 +33,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
|
||||
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
|
||||
.when(comments_change),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
|
||||
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
|
||||
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (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()))?;
|
||||
|
||||
@@ -267,11 +267,564 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
resolve_loose_blocks(blocks, accept)?;
|
||||
}
|
||||
}
|
||||
s.doc.revisions.clear();
|
||||
// Keep revision entries still referenced by surviving stories or metadata (e.g., Ruby or
|
||||
// content-control run properties) and compact/remap the table; clear it directly when none
|
||||
// survive.
|
||||
retain_referenced_revisions(&mut s.doc);
|
||||
s.clamp_selection();
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn lookup_rev(idx: u32, remap: &[Option<u32>]) -> Option<u32> {
|
||||
remap.get(idx as usize).copied().flatten()
|
||||
}
|
||||
|
||||
fn remap_opt_rev(slot: &mut Option<u32>, remap: &[Option<u32>]) -> bool {
|
||||
let Some(old) = *slot else { return false };
|
||||
let next = lookup_rev(old, remap);
|
||||
if next != *slot {
|
||||
*slot = next;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn step_prop_change<'a, T>(
|
||||
slot: &'a mut Option<Box<wordcraft_doc::props::PropChange<T>>>,
|
||||
remap: &[Option<u32>],
|
||||
changed: &mut bool,
|
||||
) -> Option<&'a mut T> {
|
||||
let old = slot.as_ref()?.rev;
|
||||
let Some(new) = lookup_rev(old, remap) else {
|
||||
*slot = None;
|
||||
*changed = true;
|
||||
return None;
|
||||
};
|
||||
let ch = slot.as_deref_mut()?;
|
||||
if ch.rev != new {
|
||||
ch.rev = new;
|
||||
*changed = true;
|
||||
}
|
||||
Some(&mut ch.old)
|
||||
}
|
||||
|
||||
fn collect_char(mut c: &wordcraft_doc::CharProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(i) = c.ins {
|
||||
f(i);
|
||||
}
|
||||
if let Some(i) = c.del {
|
||||
f(i);
|
||||
}
|
||||
let Some(ch) = c.fmt_change.as_deref() else { break };
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
c = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_char(mut c: &mut wordcraft_doc::CharProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
changed |= remap_opt_rev(&mut c.ins, remap);
|
||||
changed |= remap_opt_rev(&mut c.del, remap);
|
||||
let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) else { break };
|
||||
c = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_para_props(mut p: &wordcraft_doc::ParaProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(nc) = p.num_change.as_deref() {
|
||||
f(nc.rev);
|
||||
}
|
||||
let Some(ch) = p.fmt_change.as_deref() else { break };
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
p = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_para_props(mut p: &mut wordcraft_doc::ParaProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
if let Some(old) = p.num_change.as_deref().map(|nc| nc.rev) {
|
||||
match lookup_rev(old, remap) {
|
||||
Some(new) => {
|
||||
if let Some(nc) = p.num_change.as_deref_mut()
|
||||
&& nc.rev != new
|
||||
{
|
||||
nc.rev = new;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
p.num_change = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(old) = step_prop_change(&mut p.fmt_change, remap, &mut changed) else { break };
|
||||
p = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_section(mut s: &wordcraft_doc::SectionProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
while let Some(ch) = s.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
s = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_section(mut s: &mut wordcraft_doc::SectionProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
while let Some(old) = step_prop_change(&mut s.fmt_change, remap, &mut changed) {
|
||||
s = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_table_props(mut t: &wordcraft_doc::props::TableProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
while let Some(ch) = t.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
t = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_table_props(mut t: &mut wordcraft_doc::props::TableProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
while let Some(old) = step_prop_change(&mut t.fmt_change, remap, &mut changed) {
|
||||
t = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_row_props(mut r: &wordcraft_doc::props::RowProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
loop {
|
||||
if let Some(ex) = r.exceptions.as_deref() {
|
||||
collect_table_props(ex, f);
|
||||
}
|
||||
let Some(ch) = r.fmt_change.as_deref() else { break };
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
r = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_row_props(mut r: &mut wordcraft_doc::props::RowProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
loop {
|
||||
if let Some(ex) = r.exceptions.as_deref_mut() {
|
||||
changed |= remap_table_props(ex, remap);
|
||||
}
|
||||
let Some(old) = step_prop_change(&mut r.fmt_change, remap, &mut changed) else { break };
|
||||
r = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_cell_props(mut c: &wordcraft_doc::props::CellProps, f: &mut impl FnMut(u32) -> bool) {
|
||||
while let Some(ch) = c.fmt_change.as_deref() {
|
||||
if !f(ch.rev) {
|
||||
break;
|
||||
}
|
||||
c = &ch.old;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_cell_props(mut c: &mut wordcraft_doc::props::CellProps, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
while let Some(old) = step_prop_change(&mut c.fmt_change, remap, &mut changed) {
|
||||
c = old;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_leaf_object(obj: &InlineObject, f: &mut impl FnMut(u32) -> bool) {
|
||||
match obj {
|
||||
InlineObject::Ruby { props, .. } => collect_char(props, f),
|
||||
InlineObject::ControlStart { control } => {
|
||||
if let Some(rp) = &control.run_props {
|
||||
collect_char(rp, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_object(obj: &InlineObject, f: &mut impl FnMut(u32) -> bool) {
|
||||
let InlineObject::Group { children, .. } = obj else {
|
||||
collect_leaf_object(obj, f);
|
||||
return;
|
||||
};
|
||||
let mut stack = Vec::new();
|
||||
let mut cur = children.as_slice();
|
||||
loop {
|
||||
for ch in cur {
|
||||
match &ch.obj {
|
||||
InlineObject::Group { children: inner, .. } => {
|
||||
if !inner.is_empty() {
|
||||
stack.push(inner.as_slice());
|
||||
}
|
||||
}
|
||||
other => collect_leaf_object(other, f),
|
||||
}
|
||||
}
|
||||
let Some(next) = stack.pop() else { break };
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_leaf_object(obj: &mut InlineObject, remap: &[Option<u32>]) -> bool {
|
||||
match obj {
|
||||
InlineObject::Ruby { props, .. } => remap_char(props, remap),
|
||||
InlineObject::ControlStart { control } => control.run_props.as_mut().is_some_and(|rp| remap_char(rp, remap)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_object(obj: &mut InlineObject, remap: &[Option<u32>]) -> bool {
|
||||
let InlineObject::Group { children, .. } = obj else {
|
||||
return remap_leaf_object(obj, remap);
|
||||
};
|
||||
let mut changed = false;
|
||||
let mut stack = Vec::new();
|
||||
let mut cur = children.as_mut_slice();
|
||||
loop {
|
||||
for ch in cur {
|
||||
match &mut ch.obj {
|
||||
InlineObject::Group { children: inner, .. } => {
|
||||
if !inner.is_empty() {
|
||||
stack.push(inner.as_mut_slice());
|
||||
}
|
||||
}
|
||||
other => changed |= remap_leaf_object(other, remap),
|
||||
}
|
||||
}
|
||||
let Some(next) = stack.pop() else { break };
|
||||
cur = next;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_controls(wrap: &wordcraft_doc::ControlWrap, f: &mut impl FnMut(u32) -> bool) {
|
||||
for c in &wrap.open {
|
||||
if let Some(rp) = &c.run_props {
|
||||
collect_char(rp, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_controls(wrap: &mut wordcraft_doc::ControlWrap, remap: &[Option<u32>]) -> bool {
|
||||
let mut changed = false;
|
||||
for c in &mut wrap.open {
|
||||
if let Some(rp) = &mut c.run_props {
|
||||
changed |= remap_char(rp, remap);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn collect_para(p: &Paragraph, f: &mut impl FnMut(u32) -> bool) {
|
||||
collect_para_props(&p.props, f);
|
||||
for r in &p.runs {
|
||||
collect_char(&r.props, f);
|
||||
}
|
||||
collect_char(&p.mark, f);
|
||||
if let Some(sec) = p.section.as_deref() {
|
||||
collect_section(sec, f);
|
||||
}
|
||||
for obj in &p.objects {
|
||||
collect_object(obj, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_table(table: &wordcraft_doc::table::Table, f: &mut impl FnMut(u32) -> bool) {
|
||||
let mut stack = Vec::new();
|
||||
let mut cur = table;
|
||||
loop {
|
||||
collect_table_props(&cur.props, f);
|
||||
collect_controls(&cur.controls, f);
|
||||
for row in &cur.rows {
|
||||
collect_row_props(&row.props, f);
|
||||
collect_controls(&row.controls, f);
|
||||
for cell in &row.cells {
|
||||
collect_cell_props(&cell.props, f);
|
||||
collect_controls(&cell.controls, f);
|
||||
for b in &cell.blocks {
|
||||
match b.as_ref() {
|
||||
wordcraft_doc::Block::Para(p) => collect_para(p, f),
|
||||
wordcraft_doc::Block::Table(nested) => stack.push(nested),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(next) = stack.pop() else { break };
|
||||
cur = next;
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_block(block: &wordcraft_doc::Block, f: &mut impl FnMut(u32) -> bool) {
|
||||
match block {
|
||||
wordcraft_doc::Block::Para(p) => collect_para(p, f),
|
||||
wordcraft_doc::Block::Table(t) => collect_table(t, f),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_blocks(blocks: &wordcraft_doc::Blocks, f: &mut impl FnMut(u32) -> bool) {
|
||||
for b in blocks {
|
||||
collect_block(b, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn block_needs_rewrite(block: &wordcraft_doc::Block, remap: &[Option<u32>]) -> bool {
|
||||
let mut needs = false;
|
||||
collect_block(block, &mut |idx| {
|
||||
let next = lookup_rev(idx, remap);
|
||||
if next != Some(idx) {
|
||||
needs = true;
|
||||
}
|
||||
next.is_some()
|
||||
});
|
||||
needs
|
||||
}
|
||||
|
||||
fn remap_blocks(blocks: &mut wordcraft_doc::Blocks, remap: &[Option<u32>]) {
|
||||
let mut stack: Vec<&mut std::sync::Arc<wordcraft_doc::Block>> = blocks.iter_mut().collect();
|
||||
while let Some(arc_b) = stack.pop() {
|
||||
if !block_needs_rewrite(arc_b, remap) {
|
||||
continue;
|
||||
}
|
||||
match std::sync::Arc::make_mut(arc_b) {
|
||||
wordcraft_doc::Block::Para(p) => {
|
||||
let mut changed = remap_para_props(&mut p.props, remap);
|
||||
for r in &mut p.runs {
|
||||
changed |= remap_char(&mut r.props, remap);
|
||||
}
|
||||
changed |= remap_char(&mut p.mark, remap);
|
||||
if let Some(sec) = p.section.as_deref_mut() {
|
||||
changed |= remap_section(sec, remap);
|
||||
}
|
||||
for obj in &mut p.objects {
|
||||
changed |= remap_object(obj, remap);
|
||||
}
|
||||
if changed {
|
||||
p.touch();
|
||||
}
|
||||
}
|
||||
wordcraft_doc::Block::Table(t) => {
|
||||
remap_table_props(&mut t.props, remap);
|
||||
remap_controls(&mut t.controls, remap);
|
||||
for row in &mut t.rows {
|
||||
remap_row_props(&mut row.props, remap);
|
||||
remap_controls(&mut row.controls, remap);
|
||||
for cell in &mut row.cells {
|
||||
remap_cell_props(&mut cell.props, remap);
|
||||
remap_controls(&mut cell.controls, remap);
|
||||
stack.extend(cell.blocks.iter_mut());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_styles(styles: &wordcraft_doc::styles::StyleSheet, f: &mut impl FnMut(u32) -> bool) {
|
||||
collect_char(&styles.default_chr, f);
|
||||
collect_para_props(&styles.default_para, f);
|
||||
for st in &styles.styles {
|
||||
collect_para_props(&st.para, f);
|
||||
collect_char(&st.chr, f);
|
||||
if let Some(ch) = st.para_change.as_deref()
|
||||
&& f(ch.rev)
|
||||
{
|
||||
collect_para_props(&ch.old, f);
|
||||
}
|
||||
if let Some(ch) = st.chr_change.as_deref()
|
||||
&& f(ch.rev)
|
||||
{
|
||||
collect_char(&ch.old, f);
|
||||
}
|
||||
if let Some(tbl) = &st.table {
|
||||
for c in [&tbl.header_chr, &tbl.band_chr, &tbl.first_col_chr, &tbl.total_chr, &tbl.last_col_chr, &tbl.col_band_chr] {
|
||||
collect_char(c, f);
|
||||
}
|
||||
for pf in tbl.regions.values() {
|
||||
collect_char(&pf.chr, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_styles(styles: &mut std::sync::Arc<wordcraft_doc::styles::StyleSheet>, remap: &[Option<u32>]) {
|
||||
let mut needs = false;
|
||||
collect_styles(styles, &mut |idx| {
|
||||
let next = lookup_rev(idx, remap);
|
||||
if next != Some(idx) {
|
||||
needs = true;
|
||||
}
|
||||
next.is_some()
|
||||
});
|
||||
if !needs {
|
||||
return;
|
||||
}
|
||||
let styles = std::sync::Arc::make_mut(styles);
|
||||
remap_char(&mut styles.default_chr, remap);
|
||||
remap_para_props(&mut styles.default_para, remap);
|
||||
for st in &mut styles.styles {
|
||||
remap_para_props(&mut st.para, remap);
|
||||
remap_char(&mut st.chr, remap);
|
||||
let mut dummy = false;
|
||||
if let Some(old) = step_prop_change(&mut st.para_change, remap, &mut dummy) {
|
||||
remap_para_props(old, remap);
|
||||
}
|
||||
if let Some(old) = step_prop_change(&mut st.chr_change, remap, &mut dummy) {
|
||||
remap_char(old, remap);
|
||||
}
|
||||
if let Some(tbl) = &mut st.table {
|
||||
for c in
|
||||
[&mut tbl.header_chr, &mut tbl.band_chr, &mut tbl.first_col_chr, &mut tbl.total_chr, &mut tbl.last_col_chr, &mut tbl.col_band_chr]
|
||||
{
|
||||
remap_char(c, remap);
|
||||
}
|
||||
for pf in tbl.regions.values_mut() {
|
||||
remap_char(&mut pf.chr, remap);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_numbering(numbering: &wordcraft_doc::numbering::Numbering, f: &mut impl FnMut(u32) -> bool) {
|
||||
for abs in &numbering.abstracts {
|
||||
for lvl in &abs.levels {
|
||||
collect_char(&lvl.chr, f);
|
||||
}
|
||||
}
|
||||
for num in &numbering.nums {
|
||||
for (_, lvl) in &num.level_overrides {
|
||||
collect_char(&lvl.chr, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remap_numbering(numbering: &mut std::sync::Arc<wordcraft_doc::numbering::Numbering>, remap: &[Option<u32>]) {
|
||||
let mut needs = false;
|
||||
collect_numbering(numbering, &mut |idx| {
|
||||
let next = lookup_rev(idx, remap);
|
||||
if next != Some(idx) {
|
||||
needs = true;
|
||||
}
|
||||
next.is_some()
|
||||
});
|
||||
if !needs {
|
||||
return;
|
||||
}
|
||||
let numbering = std::sync::Arc::make_mut(numbering);
|
||||
for abs in &mut numbering.abstracts {
|
||||
for lvl in &mut abs.levels {
|
||||
remap_char(&mut lvl.chr, remap);
|
||||
}
|
||||
}
|
||||
for num in &mut numbering.nums {
|
||||
for (_, lvl) in &mut num.level_overrides {
|
||||
remap_char(&mut lvl.chr, remap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_doc_revisions(doc: &wordcraft_doc::Document, f: &mut impl FnMut(u32) -> bool) {
|
||||
collect_blocks(&doc.body, f);
|
||||
collect_section(&doc.last_section, f);
|
||||
for part in doc.parts.values() {
|
||||
collect_blocks(&part.blocks, f);
|
||||
}
|
||||
for sep in [&doc.footnote_separators, &doc.endnote_separators] {
|
||||
for blocks in [&sep.separator, &sep.continuation_separator, &sep.continuation_notice].into_iter().flatten() {
|
||||
collect_blocks(blocks, f);
|
||||
}
|
||||
}
|
||||
for bb in &doc.glossary {
|
||||
collect_blocks(&bb.blocks, f);
|
||||
}
|
||||
collect_styles(&doc.styles, f);
|
||||
collect_numbering(&doc.numbering, f);
|
||||
}
|
||||
|
||||
fn rewrite_doc_revisions(doc: &mut wordcraft_doc::Document, remap: &[Option<u32>]) {
|
||||
remap_blocks(&mut doc.body, remap);
|
||||
remap_section(&mut doc.last_section, remap);
|
||||
for part in doc.parts.values_mut() {
|
||||
remap_blocks(&mut part.blocks, remap);
|
||||
}
|
||||
for sep in [&mut doc.footnote_separators, &mut doc.endnote_separators] {
|
||||
for blocks in [&mut sep.separator, &mut sep.continuation_separator, &mut sep.continuation_notice].into_iter().flatten() {
|
||||
remap_blocks(blocks, remap);
|
||||
}
|
||||
}
|
||||
for bb in &mut doc.glossary {
|
||||
remap_blocks(&mut bb.blocks, remap);
|
||||
}
|
||||
remap_styles(&mut doc.styles, remap);
|
||||
remap_numbering(&mut doc.numbering, remap);
|
||||
}
|
||||
|
||||
/// Retain only revision entries still referenced by `doc`, compacting `doc.revisions` and remapping
|
||||
/// surviving references (or clearing invalid out-of-bounds ones). On the common path with no
|
||||
/// surviving references, the walk avoids heap allocation for paragraphs, non-nested tables, and
|
||||
/// non-nested inline objects (an iterative stack allocates only for tables inside tables or groups
|
||||
/// inside groups), `BTreeSet::new()` never allocates, and `doc.revisions.clear()` runs directly
|
||||
/// without allocating `remap`/`kept` or running the rewrite pass.
|
||||
fn retain_referenced_revisions(doc: &mut wordcraft_doc::Document) {
|
||||
let old_len = doc.revisions.len();
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
let mut has_invalid = false;
|
||||
// The callback returns whether the visited index is valid; PropChange walkers stop descending
|
||||
// into `ch.old` when an outer `ch.rev` is out of bounds because `step_prop_change` discards the
|
||||
// whole outer PropChange (including any nested indices buried inside it). That keeps the table
|
||||
// at its exact fixed point in a single pass.
|
||||
collect_doc_revisions(doc, &mut |idx| {
|
||||
if (idx as usize) < old_len {
|
||||
used.insert(idx);
|
||||
true
|
||||
} else {
|
||||
has_invalid = true;
|
||||
false
|
||||
}
|
||||
});
|
||||
if used.is_empty() && !has_invalid {
|
||||
doc.revisions.clear();
|
||||
return;
|
||||
}
|
||||
if !has_invalid && used.len() == old_len {
|
||||
return;
|
||||
}
|
||||
let mut remap = vec![None; old_len];
|
||||
let mut kept = Vec::with_capacity(used.len());
|
||||
let mut needs_rewrite = has_invalid;
|
||||
for old in used {
|
||||
let new = kept.len() as u32;
|
||||
remap[old as usize] = Some(new);
|
||||
if new != old {
|
||||
needs_rewrite = true;
|
||||
}
|
||||
kept.push(doc.revisions[old as usize].clone());
|
||||
}
|
||||
doc.revisions = kept;
|
||||
if needs_rewrite {
|
||||
rewrite_doc_revisions(doc, &remap);
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept or Reject All; with `stopTracking`, Track Changes is turned off as well.
|
||||
pub(super) fn resolve_all_then(s: &mut Session, v: &Value, accept: bool) -> CmdResult {
|
||||
let out = resolve_all(s, accept)?;
|
||||
@@ -608,10 +1161,11 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
|
||||
list.iter()
|
||||
.map(|c| {
|
||||
let rev = c.rev.and_then(|r| s.doc.revisions.get(r as usize));
|
||||
// The date in UTC when it is known; a file's `w:date` without it is as read.
|
||||
let mut v = json!({
|
||||
"kind": c.kind, "start": pos_json(&c.a), "end": pos_json(&c.b),
|
||||
"text": s.doc.copy_range(&c.a, &c.b).plain_text(),
|
||||
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.date.clone()),
|
||||
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.instant().to_string()),
|
||||
});
|
||||
if c.kind == "format" {
|
||||
v["description"] = json!(fmt_revisions::describe(&c.props));
|
||||
|
||||
@@ -163,17 +163,17 @@ fn remove_anchors(s: &mut Session, ids: &BTreeSet<u32>) -> Result<(), CmdError>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The comment and every reply below it, replies to replies included (#1345). A parent cycle
|
||||
/// from a hostile file ends the walk instead of looping.
|
||||
fn thread_of(s: &Session, id: u32) -> Vec<u32> {
|
||||
/// The comments and every reply below them, replies to replies included (#1345), each once. A
|
||||
/// parent cycle from a hostile file ends the walk instead of looping.
|
||||
fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
|
||||
let mut children: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
|
||||
for (k, c) in &s.doc.comments {
|
||||
if let Some(parent) = c.parent {
|
||||
children.entry(parent).or_default().push(*k);
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::from([id]);
|
||||
let mut ids = vec![id];
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut ids: Vec<u32> = roots.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
let mut i = 0;
|
||||
while let Some(&at) = ids.get(i) {
|
||||
for k in children.get(&at).into_iter().flatten() {
|
||||
@@ -188,11 +188,15 @@ fn thread_of(s: &Session, id: u32) -> Vec<u32> {
|
||||
|
||||
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
|
||||
validate_comment_id(v)?;
|
||||
let ids: Vec<u32> = if p::bool(v, "all").unwrap_or(false) {
|
||||
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
|
||||
// Delete All Resolved Comments (#7818): each resolved comment goes with its replies.
|
||||
let resolved: Vec<u32> = s.doc.comments.iter().filter(|(_, c)| c.resolved).map(|(k, _)| *k).collect();
|
||||
threads_of(s, resolved)
|
||||
} else if p::bool(v, "all").unwrap_or(false) {
|
||||
s.doc.comments.keys().copied().collect()
|
||||
} else {
|
||||
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("no comment here".into()))?;
|
||||
thread_of(s, id)
|
||||
threads_of(s, [id])
|
||||
};
|
||||
remove_anchors(s, &ids.iter().copied().collect())?;
|
||||
for id in &ids {
|
||||
|
||||
@@ -549,6 +549,135 @@ fn selected(s: &Session) -> (usize, usize) {
|
||||
(a.off, b.off)
|
||||
}
|
||||
|
||||
/// Two edits an hour apart in the repeated hour as daylight saving time ends are two changes,
|
||||
/// though both were made at 01:30 local time: each keeps its UTC time (#6851). Rejecting one at
|
||||
/// the caret leaves the other pending. Saved as DOCX or Word XML, both are dated 01:30, as Word
|
||||
/// dates them, with their UTC times beside it (`w16du:dateUtc`), so they reopen as two changes,
|
||||
/// and a second save writes them as read.
|
||||
#[test]
|
||||
fn edits_in_the_repeated_hour_stay_separate_changes() {
|
||||
use crate::cmd::{TEST_NOW, TEST_ZONE};
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
TEST_NOW.with(|c| c.set(None));
|
||||
TEST_ZONE.with(|z| z.set(None));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
TEST_ZONE.with(|z| z.set(Some(crate::io_ext::tests::new_york)));
|
||||
|
||||
let mut s = Session::new(Document::new());
|
||||
s.view.proofing = false;
|
||||
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
// 1 November 2026, 01:30 EDT (05:30 UTC) and then 01:30 EST (06:30 UTC).
|
||||
for (now, text) in [(1_793_511_000, " One"), (1_793_514_600, " Two")] {
|
||||
TEST_NOW.with(|c| c.set(Some(now)));
|
||||
s.run("text.insert", &json!({"text": text})).unwrap();
|
||||
}
|
||||
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10), ("insert".into(), 10, 14)]);
|
||||
let utc = ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"];
|
||||
let instants = |d: &Document| d.revisions.iter().map(|r| r.instant().to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(instants(&s.doc), utc);
|
||||
let listed = s.run("review.changes", &json!({})).unwrap();
|
||||
assert_eq!(listed.as_array().map(|l| l.iter().map(|c| c["date"].clone()).collect::<Vec<_>>()), Some(vec![json!(utc[0]), json!(utc[1])]));
|
||||
|
||||
let local = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
|
||||
for name in ["repeated.docx", "repeated.xml"] {
|
||||
let bytes = crate::io::save_bytes(name, &s.doc).unwrap();
|
||||
let read = |bytes: &[u8]| if name.ends_with(".xml") { wordcraft_docx::read_xml(bytes) } else { wordcraft_docx::read(bytes) }.unwrap();
|
||||
let written = read(&bytes);
|
||||
assert_eq!(local(&written), ["2026-11-01T01:30:00Z"; 2], "{name}");
|
||||
assert_eq!(instants(&written), utc, "{name}");
|
||||
|
||||
let mut opened = Session::new(crate::io::open_bytes(name, &bytes).unwrap());
|
||||
opened.view.proofing = false;
|
||||
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10), ("insert".into(), 10, 14)], "{name}");
|
||||
// Saved again, the changes are written as read: their local time doesn't move.
|
||||
let again = read(&crate::io::save_bytes(name, &opened.doc).unwrap());
|
||||
assert_eq!((local(&again), instants(&again)), (local(&written), instants(&written)), "{name}");
|
||||
|
||||
opened.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
|
||||
opened.run("review.reject", &json!({})).unwrap();
|
||||
assert_eq!(opened.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One", "{name}");
|
||||
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10)], "{name}: the earlier insertion is still pending");
|
||||
}
|
||||
assert_eq!(instants(&s.doc), utc, "saving leaves the session's changes as they were");
|
||||
|
||||
s.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
|
||||
s.run("review.reject", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One");
|
||||
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10)], "the earlier insertion is still pending");
|
||||
}
|
||||
|
||||
/// A change made at 08:33 UTC at UTC+8 is dated 16:33 in a Word file, as Word dates it, and 08:33
|
||||
/// UTC in an OpenDocument file, whose `dc:date` is an instant (#6851).
|
||||
#[test]
|
||||
fn a_new_change_is_dated_in_utc_in_opendocument() {
|
||||
use crate::cmd::{TEST_NOW, TEST_ZONE};
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
TEST_NOW.with(|c| c.set(None));
|
||||
TEST_ZONE.with(|z| z.set(None));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
|
||||
TEST_NOW.with(|c| c.set(Some(1_794_818_004)));
|
||||
|
||||
let mut s = Session::new(Document::new());
|
||||
s.view.proofing = false;
|
||||
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.insert", &json!({"text": " One"})).unwrap();
|
||||
let utc = "2026-11-16T08:33:24Z";
|
||||
let dates = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
|
||||
for (name, date) in [("new.odt", utc), ("new.fodt", utc), ("new.docx", "2026-11-16T16:33:24Z"), ("new.xml", "2026-11-16T16:33:24Z")] {
|
||||
let opened = crate::io::open_bytes(name, &crate::io::save_bytes(name, &s.doc).unwrap()).unwrap();
|
||||
assert_eq!(dates(&opened), [date], "{name}");
|
||||
assert!(opened.revisions.iter().all(|r| r.instant() == utc), "{name}: {:?}", opened.revisions);
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracked change read from a file keeps its `w:date` and `w16du:dateUtc` as read through open
|
||||
/// and save in another zone (#6851): one without a UTC time (an older Word, another program), whose
|
||||
/// zone WordCraft doesn't guess, and one written in UTC, where the two are the same.
|
||||
#[test]
|
||||
fn a_file_date_is_written_as_read() {
|
||||
use crate::cmd::TEST_ZONE;
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
TEST_ZONE.with(|z| z.set(None));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
|
||||
|
||||
let date = "2026-11-16T08:33:24Z";
|
||||
for utc in [None, Some(date)] {
|
||||
let mut doc = Document::from_text("Draft.");
|
||||
let mut rev = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date);
|
||||
rev.date_utc = utc.map(String::from);
|
||||
doc.revisions.push(rev);
|
||||
doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
|
||||
let dates = |d: &Document| d.revisions.iter().map(|r| (r.date.clone(), r.date_utc.clone())).collect::<Vec<_>>();
|
||||
let want = vec![(date.to_string(), utc.map(String::from))];
|
||||
for name in ["file.docx", "file.xml"] {
|
||||
let bytes = crate::io::save_bytes(name, &doc).unwrap();
|
||||
let opened = crate::io::open_bytes(name, &bytes).unwrap();
|
||||
assert_eq!(dates(&opened), want, "{name} {utc:?}: opened");
|
||||
let saved = crate::io::save_bytes(name, &opened).unwrap();
|
||||
let again = if name.ends_with(".xml") { wordcraft_docx::read_xml(&saved) } else { wordcraft_docx::read(&saved) }.unwrap();
|
||||
assert_eq!(dates(&again), want, "{name} {utc:?}: saved again");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept and Move to Next, Reject and Move to Next: the change at the caret is resolved and
|
||||
/// the next one is selected; without `next` the caret stays where the change was.
|
||||
#[test]
|
||||
@@ -796,6 +925,77 @@ fn deleting_a_comment_in_a_parent_cycle_ends() {
|
||||
assert!(s.doc.comments.is_empty());
|
||||
}
|
||||
|
||||
/// Comments on "one", "two" and "three" with a reply on the first; the ids, in that order.
|
||||
fn three_commented_words(s: &mut Session) -> [u64; 4] {
|
||||
s.view.proofing = false;
|
||||
s.run("document.setText", &json!({"text": "one two three"})).unwrap();
|
||||
let on = |s: &mut Session, word: &str| {
|
||||
s.run("select.text", &json!({"text": word})).unwrap();
|
||||
s.run("review.newComment", &json!({"text": word})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let (one, two, three) = (on(s, "one"), on(s, "two"), on(s, "three"));
|
||||
let reply = s.run("review.reply", &json!({"id": one, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
|
||||
[one, reply, two, three]
|
||||
}
|
||||
|
||||
/// #7818: Review › Delete › Delete All Resolved Comments deletes each resolved comment with its
|
||||
/// replies and their text, and keeps the open ones with their anchors; Undo brings them back.
|
||||
#[test]
|
||||
fn delete_all_resolved_comments_keeps_the_open_ones() {
|
||||
let mut s = Session::new(Document::new());
|
||||
let [one, reply, two, three] = three_commented_words(&mut s);
|
||||
for id in [one, three] {
|
||||
s.run("review.resolveComment", &json!({"id": id, "value": true})).unwrap();
|
||||
}
|
||||
let part = |s: &Session, id: u64| s.doc.comments[&(id as u32)].part;
|
||||
let kept_part = part(&s, two);
|
||||
let gone_parts: Vec<u32> = [one, reply, three].iter().map(|id| part(&s, *id)).collect();
|
||||
// The caret sits in the open comment, which Delete alone would take.
|
||||
s.run("select.text", &json!({"text": "two"})).unwrap();
|
||||
let depth = s.undo_depth();
|
||||
|
||||
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
|
||||
|
||||
let mut deleted: Vec<u64> = out["deleted"].as_array().unwrap().iter().filter_map(|v| v.as_u64()).collect();
|
||||
let mut want = vec![one, reply, three];
|
||||
deleted.sort_unstable();
|
||||
want.sort_unstable();
|
||||
assert_eq!(deleted, want, "the resolved comments and the reply below one of them");
|
||||
assert_eq!(s.doc.comments.keys().map(|k| u64::from(*k)).collect::<Vec<_>>(), vec![two], "the open comment stays");
|
||||
assert!(s.doc.parts.contains_key(&kept_part));
|
||||
assert!(gone_parts.iter().all(|p| !s.doc.parts.contains_key(p)), "the deleted comments' text parts are gone");
|
||||
assert_eq!(anchors(&s), vec![(wordcraft_doc::StoryRef::Body, two as u32); 2], "only the open comment's anchors are left");
|
||||
assert_eq!(s.undo_depth(), depth + 1, "one undo step");
|
||||
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.comments.len(), 4);
|
||||
assert_eq!(anchors(&s).len(), 6);
|
||||
}
|
||||
|
||||
/// #7818: with nothing resolved, Delete All Resolved Comments leaves every comment.
|
||||
#[test]
|
||||
fn delete_all_resolved_comments_without_resolved_ones_keeps_all() {
|
||||
let mut s = Session::new(Document::new());
|
||||
three_commented_words(&mut s);
|
||||
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
|
||||
assert_eq!(out["deleted"], json!([]));
|
||||
assert_eq!(s.doc.comments.len(), 4);
|
||||
assert_eq!(anchors(&s).len(), 6);
|
||||
}
|
||||
|
||||
/// #7818: Review › Delete › Delete All Comments in Document deletes every comment, reply and
|
||||
/// anchor, resolved or not.
|
||||
#[test]
|
||||
fn delete_all_comments_in_document_deletes_every_comment() {
|
||||
let mut s = Session::new(Document::new());
|
||||
let [one, ..] = three_commented_words(&mut s);
|
||||
s.run("review.resolveComment", &json!({"id": one, "value": true})).unwrap();
|
||||
s.run("review.deleteComment", &json!({"all": true})).unwrap();
|
||||
assert!(s.doc.comments.is_empty());
|
||||
assert!(s.doc.parts.is_empty(), "no comment text is left: {:?}", s.doc.parts.keys());
|
||||
assert!(anchors(&s).is_empty());
|
||||
}
|
||||
|
||||
/// A very long reply chain (as a hostile file could hold) is deleted in one pass over the
|
||||
/// comments, not one pass per reply: 50,000 replies would otherwise freeze the app.
|
||||
#[test]
|
||||
@@ -1048,7 +1248,7 @@ fn rtf_tracked_changes_accept_and_reject_after_opening_and_round_trip() {
|
||||
let rtf: &[u8] = br"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\*\revtbl {Unknown;}{Alice;}{Bob;}}
|
||||
\pard Keep {\revised\revauth1\revdttm-1480361314 added }text{\deleted\revauthdel2\revdttmdel-2016341499 gone} end{\revised\revauth1\revdttm-1480361314\deleted\revauthdel2\revdttmdel-2016341499 both}.\par}";
|
||||
let opened = wordcraft_formats::rtf::import(rtf).unwrap();
|
||||
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).as_bytes()).unwrap();
|
||||
let again = wordcraft_formats::rtf::import(wordcraft_formats::rtf::export(&opened).unwrap().as_bytes()).unwrap();
|
||||
for doc in [opened, again] {
|
||||
for (cmd, want) in [("review.acceptAll", "Keep added text end."), ("review.rejectAll", "Keep text gone end.")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
@@ -1206,3 +1406,533 @@ fn preexisting_table_with_redlined_cell_content_preserves_table_shell() {
|
||||
assert!(s_rt.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect every revision reference `(location, idx, expected_kind)` surviving anywhere in `doc`
|
||||
/// and assert that each resolves to an existing entry in `doc.revisions` of the expected kind.
|
||||
fn assert_all_revision_refs_valid(doc: &Document, label: &str) -> usize {
|
||||
use wordcraft_doc::{
|
||||
Block, Blocks, CharProps, InlineObject, ParaProps, RevisionKind, SectionProps,
|
||||
props::{CellProps, RowProps, TableProps},
|
||||
};
|
||||
|
||||
fn check_idx(doc: &Document, label: &str, loc: &str, idx: u32, expected: RevisionKind, count: &mut usize) {
|
||||
*count += 1;
|
||||
let rev = doc.revisions.get(idx as usize).unwrap_or_else(|| {
|
||||
panic!("{label}: dangling revision index {idx} at {loc} (revisions.len() == {})", doc.revisions.len());
|
||||
});
|
||||
assert_eq!(rev.kind, expected, "{label}: revision index {idx} at {loc} has kind {:?}, expected {expected:?}", rev.kind);
|
||||
}
|
||||
|
||||
fn walk_char(doc: &Document, label: &str, loc: &str, c: &CharProps, count: &mut usize) {
|
||||
if let Some(i) = c.ins {
|
||||
check_idx(doc, label, &format!("{loc}.ins"), i, RevisionKind::Insert, count);
|
||||
}
|
||||
if let Some(i) = c.del {
|
||||
check_idx(doc, label, &format!("{loc}.del"), i, RevisionKind::Delete, count);
|
||||
}
|
||||
if let Some(ch) = &c.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_char(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_para_props(doc: &Document, label: &str, loc: &str, p: &ParaProps, count: &mut usize) {
|
||||
if let Some(nc) = &p.num_change {
|
||||
check_idx(doc, label, &format!("{loc}.num_change"), nc.rev, RevisionKind::Format, count);
|
||||
}
|
||||
if let Some(ch) = &p.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_para_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_section(doc: &Document, label: &str, loc: &str, s: &SectionProps, count: &mut usize) {
|
||||
if let Some(ch) = &s.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_section(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_table_props(doc: &Document, label: &str, loc: &str, t: &TableProps, count: &mut usize) {
|
||||
if let Some(ch) = &t.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_table_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_row_props(doc: &Document, label: &str, loc: &str, r: &RowProps, count: &mut usize) {
|
||||
if let Some(ex) = r.exceptions.as_deref() {
|
||||
walk_table_props(doc, label, &format!("{loc}.exceptions"), ex, count);
|
||||
}
|
||||
if let Some(ch) = &r.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_row_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_cell_props(doc: &Document, label: &str, loc: &str, c: &CellProps, count: &mut usize) {
|
||||
if let Some(ch) = &c.fmt_change {
|
||||
check_idx(doc, label, &format!("{loc}.fmt_change"), ch.rev, RevisionKind::Format, count);
|
||||
walk_cell_props(doc, label, &format!("{loc}.fmt_change.old"), &ch.old, count);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_object(doc: &Document, label: &str, loc: &str, obj: &InlineObject, count: &mut usize) {
|
||||
match obj {
|
||||
InlineObject::Ruby { props, .. } => walk_char(doc, label, &format!("{loc}.ruby.props"), props, count),
|
||||
InlineObject::ControlStart { control } => {
|
||||
if let Some(rp) = &control.run_props {
|
||||
walk_char(doc, label, &format!("{loc}.control.run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
InlineObject::Group { children, .. } => {
|
||||
for (i, ch) in children.iter().enumerate() {
|
||||
walk_object(doc, label, &format!("{loc}.group[{i}]"), &ch.obj, count);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_blocks(doc: &Document, label: &str, loc: &str, blocks: &Blocks, count: &mut usize) {
|
||||
for (bi, b) in blocks.iter().enumerate() {
|
||||
match &**b {
|
||||
Block::Para(p) => {
|
||||
let ploc = format!("{loc}[{bi}]");
|
||||
walk_para_props(doc, label, &format!("{ploc}.props"), &p.props, count);
|
||||
for (ri, r) in p.runs.iter().enumerate() {
|
||||
walk_char(doc, label, &format!("{ploc}.runs[{ri}]"), &r.props, count);
|
||||
}
|
||||
walk_char(doc, label, &format!("{ploc}.mark"), &p.mark, count);
|
||||
if let Some(sec) = p.section.as_deref() {
|
||||
walk_section(doc, label, &format!("{ploc}.section"), sec, count);
|
||||
}
|
||||
for (oi, obj) in p.objects.iter().enumerate() {
|
||||
walk_object(doc, label, &format!("{ploc}.objects[{oi}]"), obj, count);
|
||||
}
|
||||
}
|
||||
Block::Table(t) => {
|
||||
let tloc = format!("{loc}[{bi}]");
|
||||
walk_table_props(doc, label, &format!("{tloc}.props"), &t.props, count);
|
||||
for (ci, ctl) in t.controls.open.iter().enumerate() {
|
||||
if let Some(rp) = &ctl.run_props {
|
||||
walk_char(doc, label, &format!("{tloc}.controls[{ci}].run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
for (ri, row) in t.rows.iter().enumerate() {
|
||||
walk_row_props(doc, label, &format!("{tloc}.rows[{ri}].props"), &row.props, count);
|
||||
for (ci, ctl) in row.controls.open.iter().enumerate() {
|
||||
if let Some(rp) = &ctl.run_props {
|
||||
walk_char(doc, label, &format!("{tloc}.rows[{ri}].controls[{ci}].run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
for (ci, cell) in row.cells.iter().enumerate() {
|
||||
walk_cell_props(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].props"), &cell.props, count);
|
||||
for (ki, ctl) in cell.controls.open.iter().enumerate() {
|
||||
if let Some(rp) = &ctl.run_props {
|
||||
walk_char(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].controls[{ki}].run_props"), rp, count);
|
||||
}
|
||||
}
|
||||
walk_blocks(doc, label, &format!("{tloc}.rows[{ri}].cells[{ci}].blocks"), &cell.blocks, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut count = 0;
|
||||
walk_blocks(doc, label, "body", &doc.body, &mut count);
|
||||
walk_section(doc, label, "last_section", &doc.last_section, &mut count);
|
||||
for (id, part) in &doc.parts {
|
||||
walk_blocks(doc, label, &format!("part({:?}#{id})", part.kind), &part.blocks, &mut count);
|
||||
}
|
||||
for (sname, sep) in [("footnote_separators", &doc.footnote_separators), ("endnote_separators", &doc.endnote_separators)] {
|
||||
for (fname, blocks) in [
|
||||
("separator", &sep.separator),
|
||||
("continuation_separator", &sep.continuation_separator),
|
||||
("continuation_notice", &sep.continuation_notice),
|
||||
] {
|
||||
if let Some(bl) = blocks {
|
||||
walk_blocks(doc, label, &format!("{sname}.{fname}"), bl, &mut count);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (gi, bb) in doc.glossary.iter().enumerate() {
|
||||
walk_blocks(doc, label, &format!("glossary[{gi}]"), &bb.blocks, &mut count);
|
||||
}
|
||||
walk_char(doc, label, "styles.default_chr", &doc.styles.default_chr, &mut count);
|
||||
walk_para_props(doc, label, "styles.default_para", &doc.styles.default_para, &mut count);
|
||||
for st in &doc.styles.styles {
|
||||
walk_para_props(doc, label, &format!("styles[{}].para", st.id), &st.para, &mut count);
|
||||
walk_char(doc, label, &format!("styles[{}].chr", st.id), &st.chr, &mut count);
|
||||
if let Some(ch) = &st.para_change {
|
||||
check_idx(doc, label, &format!("styles[{}].para_change", st.id), ch.rev, RevisionKind::Format, &mut count);
|
||||
walk_para_props(doc, label, &format!("styles[{}].para_change.old", st.id), &ch.old, &mut count);
|
||||
}
|
||||
if let Some(ch) = &st.chr_change {
|
||||
check_idx(doc, label, &format!("styles[{}].chr_change", st.id), ch.rev, RevisionKind::Format, &mut count);
|
||||
walk_char(doc, label, &format!("styles[{}].chr_change.old", st.id), &ch.old, &mut count);
|
||||
}
|
||||
if let Some(tbl) = &st.table {
|
||||
for (k, c) in [
|
||||
("header_chr", &tbl.header_chr),
|
||||
("band_chr", &tbl.band_chr),
|
||||
("first_col_chr", &tbl.first_col_chr),
|
||||
("total_chr", &tbl.total_chr),
|
||||
("last_col_chr", &tbl.last_col_chr),
|
||||
("col_band_chr", &tbl.col_band_chr),
|
||||
] {
|
||||
walk_char(doc, label, &format!("styles[{}].table.{k}", st.id), c, &mut count);
|
||||
}
|
||||
for (rk, pf) in &tbl.regions {
|
||||
walk_char(doc, label, &format!("styles[{}].table.regions[{rk:?}].chr", st.id), &pf.chr, &mut count);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ai, abs) in doc.numbering.abstracts.iter().enumerate() {
|
||||
for (li, lvl) in abs.levels.iter().enumerate() {
|
||||
walk_char(doc, label, &format!("numbering.abstracts[{ai}].levels[{li}].chr"), &lvl.chr, &mut count);
|
||||
}
|
||||
}
|
||||
for (ni, num) in doc.numbering.nums.iter().enumerate() {
|
||||
for (li, (_, lvl)) in num.level_overrides.iter().enumerate() {
|
||||
walk_char(doc, label, &format!("numbering.nums[{ni}].level_overrides[{li}].chr"), &lvl.chr, &mut count);
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// #8129: Accept All / Reject All must not invalidate revision references that survive in
|
||||
/// preserved annotation properties (e.g., a Ruby guide in a header story carrying a Format record
|
||||
/// into the document's own revision table).
|
||||
#[test]
|
||||
fn accept_and_reject_all_keep_surviving_header_ruby_revision_valid() {
|
||||
use wordcraft_doc::{
|
||||
CharProps, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para::RubyAlign, para_block, props::PropChange,
|
||||
};
|
||||
|
||||
let mut orig = Document::from_text("Original body text.");
|
||||
// Populate indices 0..=4 so the header Ruby guide owns Format revision at index 4.
|
||||
for i in 0..4 {
|
||||
orig.revisions.push(Revision::new(RevisionKind::Insert, format!("Prior {i}"), "2026-11-28T00:00:00Z"));
|
||||
}
|
||||
orig.revisions.push(Revision::new(RevisionKind::Format, "HeaderOwner", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut header_para = Paragraph::new();
|
||||
let ruby = InlineObject::Ruby {
|
||||
base: "漢字".into(),
|
||||
ruby: "かんじ".into(),
|
||||
align: RubyAlign::Center,
|
||||
size: 6.0,
|
||||
raise: 10.0,
|
||||
base_size: 12.0,
|
||||
lang: "ja-JP".into(),
|
||||
props: Box::new(CharProps { bold: Some(true), fmt_change: PropChange::boxed(4, CharProps::default()), ..Default::default() }),
|
||||
};
|
||||
header_para.insert_object(0, ruby, &CharProps::default()).unwrap();
|
||||
let header_id = orig.add_part(PartKind::Header, vec![para_block(header_para)]);
|
||||
orig.last_section.headers.default = Some(header_id);
|
||||
|
||||
// Body-only edit compared against `orig`: compare preserves the header and its index-4 record.
|
||||
let mut compared = Session::new(orig);
|
||||
compared.run("review.compare", &json!({"text": "Revised body text.", "author": "Reviewer"})).unwrap();
|
||||
assert!(assert_all_revision_refs_valid(&compared.doc, "after compare") >= 3);
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "Revised body text."), ("review.rejectAll", "Original body text.")] {
|
||||
let mut s = Session::new(compared.doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
|
||||
let surviving = assert_all_revision_refs_valid(&s.doc, cmd);
|
||||
assert_eq!(surviving, 1, "{cmd}: header Ruby revision reference survives");
|
||||
let header = s.doc.parts.get(&header_id).expect("header preserved");
|
||||
let hp = header.blocks[0].as_para().expect("header paragraph");
|
||||
let InlineObject::Ruby { props, .. } = &hp.objects[0] else { panic!("expected Ruby") };
|
||||
let rev_idx = props.fmt_change.as_ref().expect("Ruby fmt_change preserved").rev;
|
||||
let rev = &s.doc.revisions[rev_idx as usize];
|
||||
assert_eq!(rev.kind, RevisionKind::Format);
|
||||
assert_eq!(rev.author, "HeaderOwner");
|
||||
assert_eq!(rev.date, "2026-11-29T00:00:00Z");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8129: Surviving revision references across footer, footnote, comment, and text-box stories
|
||||
/// (including shared indices and ContentControl run_props) remain valid and compacted after both
|
||||
/// Accept All and Reject All, and repeated resolution is idempotent.
|
||||
#[test]
|
||||
fn accept_and_reject_all_keep_surviving_refs_across_other_stories() {
|
||||
use wordcraft_doc::{
|
||||
CharProps, Comment, ContentControl, ControlKind, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef,
|
||||
para::{NoteKind, RubyAlign, ShapeKind},
|
||||
para_block,
|
||||
props::PropChange,
|
||||
};
|
||||
|
||||
let make_ruby = |rev: u32| InlineObject::Ruby {
|
||||
base: "漢".into(),
|
||||
ruby: "かん".into(),
|
||||
align: RubyAlign::Center,
|
||||
size: 6.0,
|
||||
raise: 10.0,
|
||||
base_size: 12.0,
|
||||
lang: "ja-JP".into(),
|
||||
props: Box::new(CharProps { bold: Some(true), fmt_change: PropChange::boxed(rev, CharProps::default()), ..Default::default() }),
|
||||
};
|
||||
|
||||
let mut doc = Document::from_text("");
|
||||
// Indices 0..=7; only 2 (Footer/TextBox) and 5 (Footnote/Comment) survive resolution.
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Unused0", "2026-11-20T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Unused1", "2026-11-21T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Format, "FooterOwner", "2026-11-22T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Unused3", "2026-11-23T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Unused4", "2026-11-24T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Format, "FootnoteOwner", "2026-11-25T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut footer_para = Paragraph::new();
|
||||
footer_para.insert_object(0, make_ruby(2), &CharProps::default()).unwrap();
|
||||
let footer_id = doc.add_part(PartKind::Footer, vec![para_block(footer_para)]);
|
||||
doc.last_section.footers.default = Some(footer_id);
|
||||
|
||||
let mut footnote_para = Paragraph::new();
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.run_props = Some(CharProps { italic: Some(true), fmt_change: PropChange::boxed(5, CharProps::default()), ..Default::default() });
|
||||
footnote_para.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &CharProps::default()).unwrap();
|
||||
footnote_para.insert_object(footnote_para.len(), InlineObject::ControlEnd, &CharProps::default()).unwrap();
|
||||
let footnote_id = doc.add_part(PartKind::Footnote, vec![para_block(footnote_para)]);
|
||||
|
||||
let mut textbox_para = Paragraph::new();
|
||||
textbox_para.insert_object(0, make_ruby(2), &CharProps::default()).unwrap();
|
||||
let textbox_id = doc.add_part(PartKind::TextBox, vec![para_block(textbox_para)]);
|
||||
|
||||
let mut comment_para = Paragraph::new();
|
||||
comment_para.insert_object(0, make_ruby(5), &CharProps::default()).unwrap();
|
||||
let comment_id = doc.add_part(PartKind::Comment, vec![para_block(comment_para)]);
|
||||
doc.comments.insert(1, Comment { author: "Alice".into(), part: comment_id, ..Default::default() });
|
||||
|
||||
let body_p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_p.insert_text(body_p.len(), "Revised", &CharProps { ins: Some(6), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), "Original", &CharProps { del: Some(7), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), " body.", &CharProps::default()).unwrap();
|
||||
body_p
|
||||
.insert_object(
|
||||
body_p.len(),
|
||||
InlineObject::NoteRef { kind: NoteKind::Footnote, id: footnote_id, custom: String::new() },
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
body_p
|
||||
.insert_object(
|
||||
body_p.len(),
|
||||
InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w: 72.0,
|
||||
h: 36.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story: Some(textbox_id),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
},
|
||||
&CharProps::default(),
|
||||
)
|
||||
.unwrap();
|
||||
body_p.insert_object(0, InlineObject::CommentStart { id: 1 }, &CharProps::default()).unwrap();
|
||||
body_p.insert_object(body_p.len(), InlineObject::CommentEnd { id: 1 }, &CharProps::default()).unwrap();
|
||||
assert_eq!(assert_all_revision_refs_valid(&doc, "before resolution"), 6);
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "Revised body."), ("review.rejectAll", "Original body.")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, cmd), 4, "{cmd}: 4 surviving references");
|
||||
assert_eq!(s.doc.revisions.len(), 2, "{cmd}: compacted to 2 distinct referenced revisions");
|
||||
|
||||
let InlineObject::Ruby { props: footer_props, .. } = &s.doc.parts[&footer_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected footer Ruby");
|
||||
};
|
||||
let InlineObject::ControlStart { control: fn_ctl } = &s.doc.parts[&footnote_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected footnote ControlStart");
|
||||
};
|
||||
let InlineObject::Ruby { props: tb_props, .. } = &s.doc.parts[&textbox_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected textbox Ruby");
|
||||
};
|
||||
let InlineObject::Ruby { props: cm_props, .. } = &s.doc.parts[&comment_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected comment Ruby");
|
||||
};
|
||||
|
||||
let footer_rev = footer_props.fmt_change.as_ref().unwrap().rev;
|
||||
let tb_rev = tb_props.fmt_change.as_ref().unwrap().rev;
|
||||
let fn_rev = fn_ctl.run_props.as_ref().unwrap().fmt_change.as_ref().unwrap().rev;
|
||||
let cm_rev = cm_props.fmt_change.as_ref().unwrap().rev;
|
||||
|
||||
assert_eq!(footer_rev, tb_rev, "{cmd}: shared index preserved across footer and textbox");
|
||||
assert_eq!(fn_rev, cm_rev, "{cmd}: shared index preserved across footnote and comment");
|
||||
assert_eq!(s.doc.revisions[footer_rev as usize].author, "FooterOwner");
|
||||
assert_eq!(s.doc.revisions[fn_rev as usize].author, "FootnoteOwner");
|
||||
|
||||
// Second pass must be idempotent.
|
||||
let after_first = s.doc.clone();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc, after_first, "{cmd}: second pass must be a no-op");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8129: Common path — when Accept All or Reject All leaves no surviving revision references
|
||||
/// anywhere in the document, the revision table is cleared completely as before.
|
||||
#[test]
|
||||
fn accept_and_reject_all_clear_revision_table_when_no_refs_survive() {
|
||||
use wordcraft_doc::{CharProps, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para_block};
|
||||
|
||||
let mut doc = Document::from_text("Body ");
|
||||
doc.revisions.push(Revision::new(RevisionKind::Insert, "Alice", "2026-11-29T00:00:00Z"));
|
||||
doc.revisions.push(Revision::new(RevisionKind::Delete, "Bob", "2026-11-29T00:00:00Z"));
|
||||
let body_p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_p.insert_text(body_p.len(), "new", &CharProps { ins: Some(0), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), "old", &CharProps { del: Some(1), ..Default::default() }).unwrap();
|
||||
|
||||
let mut header_p = Paragraph::with_text("Hdr ", CharProps::default());
|
||||
header_p.insert_text(header_p.len(), "ins", &CharProps { ins: Some(0), ..Default::default() }).unwrap();
|
||||
let header_id = doc.add_part(PartKind::Header, vec![para_block(header_p)]);
|
||||
doc.last_section.headers.default = Some(header_id);
|
||||
|
||||
for (cmd, want_body, want_hdr) in [("review.acceptAll", "Body new", "Hdr ins"), ("review.rejectAll", "Body old", "Hdr ")] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd}: body endpoint");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(header_id)), want_hdr, "{cmd}: header endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, cmd), 0);
|
||||
assert!(s.doc.revisions.is_empty(), "{cmd}: revision table cleared when no references survive");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8129: Malformed input — an out-of-bounds outer `PropChange` burying a valid inner revision
|
||||
/// index must reach its fixed point in a single Accept All / Reject All pass: the buried record
|
||||
/// is discarded along with its invalid outer change, the table contains only records still
|
||||
/// referenced, and a second resolution pass leaves the document identical.
|
||||
#[test]
|
||||
fn accept_and_reject_all_reach_fixed_point_with_buried_rev_in_invalid_outer_change() {
|
||||
use wordcraft_doc::{
|
||||
CharProps, InlineObject, Paragraph, PartKind, Revision, RevisionKind, StoryRef, para::RubyAlign, para_block, props::PropChange,
|
||||
};
|
||||
|
||||
let make_ruby = |props: CharProps| InlineObject::Ruby {
|
||||
base: "漢".into(),
|
||||
ruby: "かん".into(),
|
||||
align: RubyAlign::Center,
|
||||
size: 6.0,
|
||||
raise: 10.0,
|
||||
base_size: 12.0,
|
||||
lang: "ja-JP".into(),
|
||||
props: Box::new(props),
|
||||
};
|
||||
|
||||
// Case 1: Only surviving reference carrier is malformed (invalid outer rev 99 burying valid
|
||||
// inner rev 0). One pass must clear both the malformed PropChange and the revision table.
|
||||
let mut sole_doc = Document::from_text("");
|
||||
sole_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInner", "2026-11-28T00:00:00Z"));
|
||||
sole_doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
sole_doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut hdr_para = Paragraph::new();
|
||||
let buried_props = CharProps {
|
||||
bold: Some(true),
|
||||
fmt_change: PropChange::boxed(99, CharProps { fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
hdr_para.insert_object(0, make_ruby(buried_props), &CharProps::default()).unwrap();
|
||||
let hdr_id = sole_doc.add_part(PartKind::Header, vec![para_block(hdr_para)]);
|
||||
sole_doc.last_section.headers.default = Some(hdr_id);
|
||||
|
||||
let body_p = sole_doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_p.insert_text(body_p.len(), "New", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
|
||||
body_p.insert_text(body_p.len(), "Old", &CharProps { del: Some(2), ..Default::default() }).unwrap();
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "New"), ("review.rejectAll", "Old")] {
|
||||
let mut s = Session::new(sole_doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd} sole: body endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, &format!("{cmd} sole")), 0);
|
||||
assert!(s.doc.revisions.is_empty(), "{cmd} sole: buried revision must not linger after pass 1");
|
||||
let InlineObject::Ruby { props, .. } = &s.doc.parts[&hdr_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected Ruby");
|
||||
};
|
||||
assert!(props.fmt_change.is_none(), "{cmd} sole: invalid outer fmt_change discarded");
|
||||
|
||||
let after_first = s.doc.clone();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc, after_first, "{cmd} sole: second pass must be a no-op");
|
||||
}
|
||||
|
||||
// Case 2: Mixed malformed and valid surviving carriers, including a valid -> invalid -> valid
|
||||
// chain. After one pass, only the genuinely surviving records remain and pass 2 is a no-op.
|
||||
let mut mixed_doc = Document::from_text("");
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInOuter", "2026-11-20T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "KeptOuter", "2026-11-21T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "BuriedInMid", "2026-11-22T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Format, "KeptOther", "2026-11-23T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Insert, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
mixed_doc.revisions.push(Revision::new(RevisionKind::Delete, "Reviewer", "2026-11-29T00:00:00Z"));
|
||||
|
||||
let mut hdr_mixed = Paragraph::new();
|
||||
// Ruby 0: invalid outer (99) burying valid rev 0.
|
||||
let outer_invalid = CharProps {
|
||||
fmt_change: PropChange::boxed(99, CharProps { ins: Some(0), fmt_change: PropChange::boxed(0, CharProps::default()), ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
// Ruby 1: valid outer (1) containing invalid middle (88) burying valid rev 2.
|
||||
let nested_invalid = CharProps {
|
||||
fmt_change: PropChange::boxed(
|
||||
1,
|
||||
CharProps {
|
||||
fmt_change: PropChange::boxed(88, CharProps { fmt_change: PropChange::boxed(2, CharProps::default()), ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
hdr_mixed.insert_object(0, make_ruby(outer_invalid), &CharProps::default()).unwrap();
|
||||
hdr_mixed.insert_object(hdr_mixed.len(), make_ruby(nested_invalid), &CharProps::default()).unwrap();
|
||||
let hdr_mixed_id = mixed_doc.add_part(PartKind::Header, vec![para_block(hdr_mixed)]);
|
||||
mixed_doc.last_section.headers.default = Some(hdr_mixed_id);
|
||||
|
||||
let mut ftr_mixed = Paragraph::new();
|
||||
let valid_other = CharProps { fmt_change: PropChange::boxed(3, CharProps::default()), ..Default::default() };
|
||||
ftr_mixed.insert_object(0, make_ruby(valid_other), &CharProps::default()).unwrap();
|
||||
let ftr_mixed_id = mixed_doc.add_part(PartKind::Footer, vec![para_block(ftr_mixed)]);
|
||||
mixed_doc.last_section.footers.default = Some(ftr_mixed_id);
|
||||
|
||||
let body_m = mixed_doc.para_mut(StoryRef::Body, &wordcraft_doc::Path(vec![0])).unwrap();
|
||||
body_m.insert_text(body_m.len(), "New", &CharProps { ins: Some(4), ..Default::default() }).unwrap();
|
||||
body_m.insert_text(body_m.len(), "Old", &CharProps { del: Some(5), ..Default::default() }).unwrap();
|
||||
|
||||
for (cmd, want_body) in [("review.acceptAll", "New"), ("review.rejectAll", "Old")] {
|
||||
let mut s = Session::new(mixed_doc.clone());
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want_body, "{cmd} mixed: body endpoint");
|
||||
assert_eq!(assert_all_revision_refs_valid(&s.doc, &format!("{cmd} mixed")), 2);
|
||||
let authors: Vec<&str> = s.doc.revisions.iter().map(|r| r.author.as_str()).collect();
|
||||
assert_eq!(authors, vec!["KeptOuter", "KeptOther"], "{cmd} mixed: only genuinely referenced records retained");
|
||||
|
||||
let hdr_objs = &s.doc.parts[&hdr_mixed_id].blocks[0].as_para().unwrap().objects;
|
||||
let InlineObject::Ruby { props: p0, .. } = &hdr_objs[0] else { panic!("expected Ruby 0") };
|
||||
let InlineObject::Ruby { props: p1, .. } = &hdr_objs[1] else { panic!("expected Ruby 1") };
|
||||
let InlineObject::Ruby { props: pf, .. } = &s.doc.parts[&ftr_mixed_id].blocks[0].as_para().unwrap().objects[0] else {
|
||||
panic!("expected footer Ruby");
|
||||
};
|
||||
assert!(p0.fmt_change.is_none(), "{cmd} mixed: invalid outer discarded");
|
||||
let p1_outer = p1.fmt_change.as_ref().expect("valid outer retained");
|
||||
assert_eq!(s.doc.revisions[p1_outer.rev as usize].author, "KeptOuter");
|
||||
assert!(p1_outer.old.fmt_change.is_none(), "{cmd} mixed: invalid middle and buried inner discarded");
|
||||
let pf_outer = pf.fmt_change.as_ref().expect("valid footer ref retained");
|
||||
assert_eq!(s.doc.revisions[pf_outer.rev as usize].author, "KeptOther");
|
||||
|
||||
let after_first = s.doc.clone();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc, after_first, "{cmd} mixed: second pass must be a no-op");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ use clear::{cell_prefix, guard_delete, text_spans};
|
||||
use convert::{formula, from_text, quick_table, sort_table, to_text};
|
||||
pub use convert::{text_table_cells, text_table_lines};
|
||||
use layout::{autofit, borders, fix_caret, properties, set_column_widths};
|
||||
pub(crate) use layout::{sync_cell_widths, text_direction, touch_cells};
|
||||
pub(crate) use layout::{cell_block_borders, sync_cell_widths, text_direction, touch_cells};
|
||||
pub(crate) use select::{extend_selection, grow_select_all, select_cell_first, select_range};
|
||||
use select::{select_cells, select_column};
|
||||
pub use structure::split_targets;
|
||||
|
||||
@@ -279,3 +279,185 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Home › Paragraph › Borders with whole cells selected (the table, rows, columns or a block of
|
||||
/// cells): the border goes on the cells as one block, as in Word, not on the paragraphs in them
|
||||
/// (#7874). `all` borders every cell, `outside` the block's edges, `inside` the lines between its
|
||||
/// cells, `none` clears every side, and one side toggles along that edge of the block. Other kinds
|
||||
/// change nothing.
|
||||
pub(crate) fn cell_block_borders(s: &mut Session, range: &crate::CellRange, kind: &str, b: Border) -> CmdResult {
|
||||
let nil = Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 };
|
||||
let b = Border { space: 0.0, ..b };
|
||||
let one_side = ["top", "left", "bottom", "right"].iter().position(|k| *k == kind);
|
||||
if one_side.is_none() && !matches!(kind, "all" | "none" | "outside" | "inside") {
|
||||
return sel_result(s);
|
||||
}
|
||||
let t = s.doc.table(range.story, &range.table).ok_or_else(|| CmdError::Disabled("the selection isn't in a table".into()))?;
|
||||
let (g0, g1) = range.cols;
|
||||
let picked = with_merge_runs(t, range.cells(t));
|
||||
// The selected cells' grid columns, row by row from the block's first row.
|
||||
let r0 = picked.iter().map(|&(r, _)| r).min().unwrap_or(range.rows.0);
|
||||
let mut spans: Vec<Vec<(usize, usize)>> = Vec::new();
|
||||
for &(r, c) in &picked {
|
||||
let i = r.saturating_sub(r0);
|
||||
if spans.len() <= i {
|
||||
spans.resize_with(i + 1, Vec::new);
|
||||
}
|
||||
spans[i].push(super::grid_cols(t, r, c));
|
||||
}
|
||||
// Whether a selected cell in row `r` covers any of grid columns `a..=z`.
|
||||
let picked_in = |r: Option<usize>, (a, z): (usize, usize)| {
|
||||
r.and_then(|r| r.checked_sub(r0)).and_then(|i| spans.get(i)).is_some_and(|row| row.iter().any(|&(sa, sz)| sa <= z && sz >= a))
|
||||
};
|
||||
// Each selected cell, and which of its sides (top, left, bottom, right) are on the block's edge:
|
||||
// above and below, where no selected cell lies across that side (a row that skips the selected
|
||||
// grid columns with `w:gridBefore` leaves a gap in the block). A row's first and last cells are
|
||||
// on it too when the row skips grid columns (`w:gridBefore`, `w:gridAfter`): the layout draws
|
||||
// those as the table's outer edge.
|
||||
let cells: Vec<(usize, usize, [bool; 4])> = picked
|
||||
.iter()
|
||||
.map(|&(r, c)| {
|
||||
let (a, z) = super::grid_cols(t, r, c);
|
||||
let last = t.rows.get(r).map_or(0, |row| row.cells.len().saturating_sub(1));
|
||||
(r, c, [!picked_in(r.checked_sub(1), (a, z)), a <= g0 || c == 0, !picked_in(Some(r + 1), (a, z)), z >= g1 || c >= last])
|
||||
})
|
||||
.collect();
|
||||
// Whether cell (`r`, `c`) draws a line on side `i`, its own or one the table or its style gives it.
|
||||
let resolved = wordcraft_layout::CellBorders::new(&s.doc, t);
|
||||
let draws = |r: usize, c: usize, i: usize| side(&resolved.of(r, c), i).is_some_and(|x| x.is_visible());
|
||||
// One side is taken off when a line already shows all along that edge, drawn by the cells
|
||||
// there or by cells beyond them that span the whole side, as the button toggles.
|
||||
let shown = one_side.is_some_and(|i| {
|
||||
cells.iter().filter(|(_, _, edge)| edge[i]).all(|&(r, c, _)| {
|
||||
if draws(r, c, i) {
|
||||
return true;
|
||||
}
|
||||
let across = beside(t, r, c, i, (g0, g1));
|
||||
if matches!(i, 1 | 3) {
|
||||
// The cell beside it in the row has the same height.
|
||||
return !across.is_empty() && across.into_iter().all(|(nr, nc)| draws(nr, nc, (i + 2) % 4));
|
||||
}
|
||||
// Above or below: the cells drawing the facing line must cover the side's grid
|
||||
// columns within the block, so a row that skips columns there leaves it uncovered.
|
||||
let (a, z) = super::grid_cols(t, r, c);
|
||||
let drawing = across.into_iter().filter(|&(nr, nc)| draws(nr, nc, (i + 2) % 4)).map(|(nr, nc)| super::grid_cols(t, nr, nc));
|
||||
covers(drawing.collect(), (a.max(g0), z.min(g1)))
|
||||
})
|
||||
});
|
||||
// The sides to set: (row, cell, side, border).
|
||||
let mut writes: Vec<(usize, usize, usize, Border)> = Vec::new();
|
||||
for (r, c, edge) in cells {
|
||||
for (i, on_edge) in edge.into_iter().enumerate() {
|
||||
let new = match kind {
|
||||
"all" => Some(b),
|
||||
"none" => Some(nil),
|
||||
"outside" if on_edge => Some(b),
|
||||
"inside" if !on_edge => Some(b),
|
||||
_ if one_side == Some(i) && on_edge => Some(if shown { nil } else { b }),
|
||||
_ => None,
|
||||
};
|
||||
let Some(new) = new else { continue };
|
||||
writes.push((r, c, i, new));
|
||||
// Each cell draws its own sides, so a line on the block's edge is also the facing
|
||||
// side of the cell beyond it: that gets the same border, or No Border would leave
|
||||
// the neighbour's line showing.
|
||||
if on_edge {
|
||||
writes.extend(beside(t, r, c, i, (g0, g1)).into_iter().map(|(nr, nc)| (nr, nc, (i + 2) % 4, new)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let t = s.doc.table_mut(range.story, &range.table)?;
|
||||
for (r, c, i, new) in writes {
|
||||
let Some(cl) = t.rows.get_mut(r).and_then(|row| row.cells.get_mut(c)) else { continue };
|
||||
let mut cur = cl.props.borders.unwrap_or_default();
|
||||
*side_mut(&mut cur, i) = Some(new);
|
||||
cl.props.borders = Some(cur);
|
||||
}
|
||||
touch_cells(s, &range.table)?;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Whether the grid column spans `parts` (first, last) cover every column of `a..=z`.
|
||||
fn covers(mut parts: Vec<(usize, usize)>, (a, z): (usize, usize)) -> bool {
|
||||
parts.sort_unstable();
|
||||
let mut next = a;
|
||||
for (pa, pz) in parts {
|
||||
if pa > next {
|
||||
break;
|
||||
}
|
||||
next = next.max(pz + 1);
|
||||
}
|
||||
next > z
|
||||
}
|
||||
|
||||
/// `cells` with the rest of each vertically merged cell's run: the merged cell is one cell over
|
||||
/// its rows, though selecting it from its first row takes in only that row.
|
||||
fn with_merge_runs(t: &Table, mut cells: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
|
||||
// The cell starting at grid column `g` of row `r`, when there is one.
|
||||
let at = |r: usize, g: usize| t.cell_at_grid(r, g).filter(|&c| t.grid_col(r, c) == g);
|
||||
let continues =
|
||||
|r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.props.vmerge == wordcraft_doc::props::VMerge::Continue);
|
||||
let mut seen: std::collections::HashSet<(usize, usize)> = cells.iter().copied().collect();
|
||||
let mut i = 0;
|
||||
while let Some(&(r, c)) = cells.get(i) {
|
||||
i += 1;
|
||||
let g = t.grid_col(r, c);
|
||||
let below = at(r + 1, g).filter(|&nc| continues(r + 1, nc)).map(|nc| (r + 1, nc));
|
||||
let above = r.checked_sub(1).filter(|_| continues(r, c)).and_then(|pr| at(pr, g).map(|pc| (pr, pc)));
|
||||
for next in [below, above].into_iter().flatten() {
|
||||
if seen.insert(next) {
|
||||
cells.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
cells
|
||||
}
|
||||
|
||||
/// The cells across side `i` (top, left, bottom, right) of cell (`r`, `c`) whose facing edge lies
|
||||
/// wholly on that line. Above and below, only cells within grid columns `cols` (the selected
|
||||
/// block's), so a wider cell's edge beyond the block keeps its line.
|
||||
fn beside(t: &Table, r: usize, c: usize, i: usize, (g0, g1): (usize, usize)) -> Vec<(usize, usize)> {
|
||||
let Some(row) = t.rows.get(r) else { return Vec::new() };
|
||||
match i {
|
||||
1 => c.checked_sub(1).map(|p| vec![(r, p)]).unwrap_or_default(),
|
||||
3 => {
|
||||
if c + 1 < row.cells.len() {
|
||||
vec![(r, c + 1)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let nr = if i == 0 { r.checked_sub(1) } else { Some(r + 1) };
|
||||
let Some((nr, next)) = nr.and_then(|nr| t.rows.get(nr).map(|x| (nr, x))) else { return Vec::new() };
|
||||
let (a, z) = super::grid_cols(t, r, c);
|
||||
(0..next.cells.len())
|
||||
.filter(|&nc| {
|
||||
let (na, nz) = super::grid_cols(t, nr, nc);
|
||||
na <= z && nz >= a && na >= g0 && nz <= g1
|
||||
})
|
||||
.map(|nc| (nr, nc))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `i` of `b`: top, left, bottom, right.
|
||||
fn side(b: &Borders, i: usize) -> Option<Border> {
|
||||
match i {
|
||||
0 => b.top,
|
||||
1 => b.left,
|
||||
2 => b.bottom,
|
||||
_ => b.right,
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `i` of `b` to set: top, left, bottom, right.
|
||||
fn side_mut(b: &mut Borders, i: usize) -> &mut Option<Border> {
|
||||
match i {
|
||||
0 => &mut b.top,
|
||||
1 => &mut b.left,
|
||||
2 => &mut b.bottom,
|
||||
_ => &mut b.right,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(crate) use autoformat::smart_quote;
|
||||
use delete::{backspace, delete, delete_sentence_back, delete_word_back, delete_word_fwd};
|
||||
pub use enter_tab::MAX_TYPED_PARAGRAPHS;
|
||||
use enter_tab::{back_tab, new_paragraph, tab};
|
||||
use unicode::{ins_char, insert_code, toggle_unicode};
|
||||
use unicode::{ins_char, insert_break, insert_code, toggle_unicode};
|
||||
pub use unicode::{oem_code_page, system_code_pages, system_oem_code_page};
|
||||
|
||||
/// The text-entry commands: typing, Enter, breaks, Tab, deleting and typed symbols.
|
||||
@@ -26,9 +26,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("text.insert", "Type Text", "Editing", insert).params(r#"{"text": string, "raw"?: bool, "paragraphs"?: bool} (paragraphs: each line a paragraph, one undo step, at most 10000 lines)"#),
|
||||
CommandSpec::new("text.newParagraph", "New Paragraph", "Editing", new_paragraph).key("Enter"),
|
||||
CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| ins_char(s, '\n')).key("Shift+Enter"),
|
||||
CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| ins_char(s, PAGE_BREAK)).key("Mod+Enter"),
|
||||
CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| ins_char(s, COLUMN_BREAK)).key("Mod+Shift+Enter"),
|
||||
CommandSpec::new("text.lineBreak", "Line Break", "Editing", |s, _| insert_break(s, '\n')).key("Shift+Enter"),
|
||||
CommandSpec::new("text.pageBreak", "Page Break", "Insert › Pages", |s, _| insert_break(s, PAGE_BREAK)).key("Mod+Enter"),
|
||||
CommandSpec::new("text.columnBreak", "Column Break", "Layout › Breaks", |s, _| insert_break(s, COLUMN_BREAK)).key("Mod+Shift+Enter"),
|
||||
CommandSpec::new("text.tab", "Tab", "Editing", tab).key("Tab"),
|
||||
CommandSpec::new("text.backTab", "Shift+Tab", "Editing", back_tab).key("Shift+Tab"),
|
||||
// A tab character even in a table cell, where Tab moves to the next cell (#3137); ⌥Tab on macOS.
|
||||
|
||||
@@ -58,8 +58,9 @@ fn sample_text(s: &Session) -> Option<String> {
|
||||
|
||||
/// `text.newParagraph`: Enter, unless the selection is in a control that takes no paragraph break.
|
||||
pub(super) fn new_paragraph(s: &mut Session, _: &Value) -> CmdResult {
|
||||
// Enter in a one-line plain text control (or a check box or list) does nothing, as in Word.
|
||||
if crate::cmd::controls::refuses_paragraph(s) {
|
||||
// Enter in a one-line plain text control (or a check box or list), or on a selected picture or
|
||||
// shape, does nothing, as in Word (#4126).
|
||||
if crate::cmd::controls::refuses_paragraph(s) || crate::cmd::objects::object_selection(s).is_some() {
|
||||
return sel_result(s);
|
||||
}
|
||||
enter(s, true)?;
|
||||
|
||||
@@ -110,3 +110,17 @@ pub(super) fn ins_char(s: &mut Session, c: char) -> CmdResult {
|
||||
type_text(s, c.encode_utf8(&mut b))?;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// A line, page or column break. On a selected picture or shape, Word puts the break in front of
|
||||
/// it and keeps it selected, rather than replacing it (#4126).
|
||||
pub(super) fn insert_break(s: &mut Session, c: char) -> CmdResult {
|
||||
let Some(at) = crate::cmd::objects::object_selection(s).map(|(p, _)| p) else { return ins_char(s, c) };
|
||||
s.sel = Selection::caret(at.clone());
|
||||
ins_char(s, c)?;
|
||||
// The break goes in front of the object, or of the content control around it.
|
||||
let at = Pos { off: at.off + c.len_utf8(), ..at };
|
||||
if s.doc.para_at(&at).and_then(|p| p.object_at(at.off)).is_some_and(|o| o.is_drawing()) {
|
||||
crate::cmd::objects::select_object(s, &at);
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
use super::{Arc, CmdError, CmdResult, Document, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p, sel_result};
|
||||
use crate::cmd::insert::MAX_TABLE_ROWS;
|
||||
use crate::cmd::mailings::{CsvLimits, MAX_TEXT_BYTES};
|
||||
use wordcraft_doc::CharProps;
|
||||
use wordcraft_doc::table::MAX_COLS;
|
||||
|
||||
const TABLE_LIMITS: CsvLimits = CsvLimits { fields: MAX_COLS, cells: MAX_TABLE_ROWS * MAX_COLS, text: MAX_TEXT_BYTES };
|
||||
|
||||
/// Options › Language › Set as default: only the saved default proofing language (what future
|
||||
/// blank documents are written in), as Word's Set as Preferred. A setting, like `file.options`: the
|
||||
@@ -458,7 +463,14 @@ pub(super) fn customize_ribbon(s: &mut Session, v: &Value) -> CmdResult {
|
||||
pub(super) fn spreadsheet_rows(v: &Value) -> Result<Vec<Vec<String>>, CmdError> {
|
||||
// The CSV fallback is for an absent `values`; an explicit null is a malformed argument.
|
||||
let Some(values) = v.get("values") else {
|
||||
return Ok(crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6")));
|
||||
let rows = crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6"), &TABLE_LIMITS)
|
||||
.map_err(|e| CmdError::Failed(format!("{e}; a table holds at most {MAX_TABLE_ROWS} rows of {MAX_COLS} columns")))?;
|
||||
// A table holds so many rows: a longer list would lose its records quietly, because
|
||||
// the table the command inserts is shorter than the list.
|
||||
if rows.len() > MAX_TABLE_ROWS {
|
||||
return Err(CmdError::Failed(format!("a table holds at most {MAX_TABLE_ROWS} rows")));
|
||||
}
|
||||
return Ok(rows);
|
||||
};
|
||||
let list = values.as_array().ok_or_else(|| CmdError::Params("`values` must be an array of rows".into()))?;
|
||||
if list.is_empty() || list.len() > 1000 {
|
||||
|
||||
@@ -116,9 +116,9 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
std::mem::take(&mut revised.body)
|
||||
};
|
||||
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Insert, author: author.clone(), date: date.clone(), move_name: None });
|
||||
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Insert, author.clone(), date.clone()));
|
||||
let ins = (s.doc.revisions.len() - 1) as u32;
|
||||
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Delete, author: author.clone(), date: date.clone(), move_name: None });
|
||||
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, author.clone(), date.clone()));
|
||||
let del = (s.doc.revisions.len() - 1) as u32;
|
||||
let mut char_fallbacks = 0usize;
|
||||
let mut table_fallbacks = 0usize;
|
||||
@@ -443,7 +443,11 @@ fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx:
|
||||
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
|
||||
_ => {
|
||||
if let Some(x) = a {
|
||||
out.push(Arc::new(mark_block(x, &|c| c.del = Some(ctx.del))));
|
||||
out.push(Arc::new(mark_block(x, &|c| {
|
||||
// An existing deletion is another author's: keep their revision
|
||||
// stamp instead of re-attributing the paragraph to this compare.
|
||||
c.del.get_or_insert(ctx.del);
|
||||
})));
|
||||
}
|
||||
if let Some(x) = b {
|
||||
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
|
||||
@@ -1437,10 +1441,10 @@ fn diff_table(
|
||||
|
||||
/// Find or create the formatting revision entry for `author` and `date`.
|
||||
fn format_revision(doc: &mut Document, author: &str, date: &str) -> u32 {
|
||||
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.date == date) {
|
||||
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.instant() == date) {
|
||||
return u32::try_from(i).unwrap_or(u32::MAX);
|
||||
}
|
||||
doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Format, author: author.to_string(), date: date.to_string(), move_name: None });
|
||||
doc.revisions.push(crate::cmd::made_revision(RevisionKind::Format, author.to_string(), date.to_string()));
|
||||
u32::try_from(doc.revisions.len().saturating_sub(1)).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
@@ -1613,8 +1617,17 @@ fn block_text(b: &Block, depth: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a copy of `b` with all text runs and paragraph marks across all nested table cells
|
||||
/// updated by `f` iteratively, without recursion or depth truncation.
|
||||
/// A copy of the block with every run (in tables, every cell's) changed by `f`, and a paragraph's
|
||||
/// mark along with them, so a whole inserted or deleted paragraph carries the revision even when
|
||||
/// the paragraph is empty (`format` returns early for a length-0 range). Walks nested tables
|
||||
/// iteratively, without recursion or depth truncation.
|
||||
///
|
||||
/// 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 {
|
||||
let mut out = b.clone();
|
||||
let mut todo = vec![&mut out];
|
||||
|
||||
@@ -237,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"csv"?: string, "values"?: [[cell, …], …] (rows of equal length, at most 1000 rows × 63 columns; wins over csv), "header"?: bool (first row repeats on each page), "style"?: table style name (default GridTable1Light)}"#),
|
||||
CommandSpec::new("layout.linkToPrevious", "Link to Previous", "Header & Footer › Navigation", |s, v| {
|
||||
let header = p::bool(v, "footer").map(|f| !f).unwrap_or(true);
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let block = crate::cmd::page::section_end_of_focus(s);
|
||||
let sect = s.doc.section_mut(block);
|
||||
if header {
|
||||
sect.headers = Default::default();
|
||||
@@ -252,7 +252,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("hf.previous", "Previous Section", "Header & Footer › Navigation", |s, _| hf_nav(s, -1)).pure(),
|
||||
CommandSpec::new("hf.position", "Header/Footer Position", "Header & Footer › Position", |s, v| {
|
||||
let (h, f) = (p::f32(v, "header"), p::f32(v, "footer"));
|
||||
let block = s.sel.focus.path.0.first().copied().unwrap_or(0) as usize;
|
||||
let block = crate::cmd::page::section_end_of_focus(s);
|
||||
let sect = s.doc.section_mut(block);
|
||||
if let Some(h) = h {
|
||||
sect.header = h.clamp(0.0, 300.0);
|
||||
|
||||
@@ -11,6 +11,196 @@ fn compare_marks_changes() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "The dog sat.\nKeep this.\nNew line here.");
|
||||
}
|
||||
|
||||
/// Top-level body blocks that are empty paragraphs.
|
||||
fn empty_paras(s: &Session) -> usize {
|
||||
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_a_whole_paragraph_and_its_mark() {
|
||||
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "NEW");
|
||||
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
|
||||
|
||||
// A whole deleted paragraph carries the deletion on its mark.
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
|
||||
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_marks_an_empty_paragraphs_mark() {
|
||||
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
|
||||
let mut s = Session::new(Document::from_text("A\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
|
||||
|
||||
// An empty deleted paragraph is stamped on its mark too.
|
||||
let mut s = Session::new(Document::from_text("A\n\nB"));
|
||||
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let empty = s.doc.body[1].as_para().unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_keeps_another_authors_deletion_stamp() {
|
||||
// A paragraph the original already carries as a tracked deletion by another author: Compare
|
||||
// must keep that author's revision on its runs and on its paragraph mark, not re-attribute
|
||||
// the block to its own deletion revision.
|
||||
let mut doc = Document::from_text("A\nOLD\nB");
|
||||
doc.revisions.push(wordcraft_doc::Revision::new(RevisionKind::Delete, "Alice", ""));
|
||||
let p = doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
for r in &mut p.runs {
|
||||
r.props.del = Some(0);
|
||||
}
|
||||
p.mark.del = Some(0);
|
||||
let mut s = Session::new(doc);
|
||||
s.run("review.compare", &json!({"text": "A\nB", "author": "Bob"})).unwrap();
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.runs.iter().all(|r| r.props.del == Some(0)), "the runs' deletion was re-stamped: {:?}", mid.runs);
|
||||
assert_eq!(mid.mark.del, Some(0), "the paragraph mark's deletion was re-stamped");
|
||||
assert_eq!(s.doc.revisions.first().map(|r| (r.kind, r.author.as_str())), Some((RevisionKind::Delete, "Alice")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_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.
|
||||
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");
|
||||
}
|
||||
|
||||
#[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.
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style() {
|
||||
// Pins the fixed behaviour for rejecting an inserted paragraph that carries a section
|
||||
// break. This was a known limitation recorded on `mark_block` (compare.rs): `resolve`'s
|
||||
// `remove_empty_para` refused paragraphs carrying a section, so once the inserted
|
||||
// paragraph's text was rejected the empty paragraph was joined into the next one, which
|
||||
// took its properties ("Body" came back Normal instead of its original Heading 1). Fixed
|
||||
// on main by #5734 (issue #5667): `resolve_para` now removes the section break first, so
|
||||
// the empty paragraph goes whole and the following paragraph keeps its own properties.
|
||||
// After Reject All the original is restored exactly.
|
||||
let mut original = Document::from_text("Intro\nBody");
|
||||
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
|
||||
let mut s = Session::new(original);
|
||||
|
||||
let mut rev = Document::from_text("Intro\nAppendix\nBody");
|
||||
{
|
||||
let p = rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
p.props.style = Some("Normal".into());
|
||||
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
|
||||
}
|
||||
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-section-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
s.run("review.rejectAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Intro\nBody");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
let body = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(body.plain_text(), "Body");
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
|
||||
// The Accept-side mirror of `compare_pins_rejecting_an_inserted_section_keeps_the_next_paragraphs_style`:
|
||||
// compare deletes a paragraph that carries a section break whole (original `A`, `OLD`
|
||||
// with a section break, `B`; revised `A`, `B`). Accept All goes through the same #5734
|
||||
// branch in `resolve_para` as the reject case: the section break is removed first, so
|
||||
// the emptied paragraph goes whole instead of being joined into the next one. After
|
||||
// Accept All the revised text stands exactly and `B` keeps its own properties.
|
||||
let mut original = Document::from_text("A\nOLD\nB");
|
||||
{
|
||||
let p = original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap();
|
||||
p.props.style = Some("Normal".into());
|
||||
p.section = Some(Box::new(wordcraft_doc::section::SectionProps::default()));
|
||||
}
|
||||
original.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap().props.style = Some("Heading1".into());
|
||||
let mut s = Session::new(original);
|
||||
|
||||
let mut rev = Document::from_text("A\nB");
|
||||
rev.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(1)).unwrap().props.style = Some("Heading1".into());
|
||||
let path = std::env::temp_dir().join(format!("wc-compare-section-accept-{}.docx", std::process::id()));
|
||||
crate::io::save_path(&path, &rev).unwrap();
|
||||
s.run("review.compare", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(s.doc.body.len(), 3);
|
||||
let mid = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(mid.plain_text(), "OLD");
|
||||
assert!(mid.mark.del.is_some(), "the deleted sectioned paragraph's mark is not marked deleted");
|
||||
s.run("review.acceptAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
assert_eq!(empty_paras(&s), 0, "accepting the deleted sectioned paragraph left it behind");
|
||||
let body = s.doc.body[1].as_para().unwrap();
|
||||
assert_eq!(body.plain_text(), "B");
|
||||
assert_eq!(body.props.style.as_deref(), Some("Heading1"), "the following paragraph keeps its own properties (fixed on main by #5734)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_options_ignore_case_and_white_space() {
|
||||
let original = "The Cat sat.\nTwo spaces here.";
|
||||
@@ -1661,10 +1851,32 @@ fn spreadsheet_rejects_hostile_values() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CSV too wide or too long for a table is refused, not cut.
|
||||
#[test]
|
||||
fn insert_spreadsheet_refuses_a_csv_a_table_cannot_hold() {
|
||||
use crate::cmd::insert::MAX_TABLE_ROWS;
|
||||
use wordcraft_doc::table::MAX_COLS;
|
||||
let mut s = Session::new(Document::new());
|
||||
// Wider than a table's columns.
|
||||
let wide = format!("{}\nvalue", "c,".repeat(MAX_COLS));
|
||||
let e = s.run("insert.spreadsheet", &json!({"csv": wide})).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_COLS} columns")), "{e}");
|
||||
// Longer than a table's rows: the records above the limit would be lost quietly.
|
||||
let long = format!("value\n{}", "value\n".repeat(MAX_TABLE_ROWS));
|
||||
let e = s.run("insert.spreadsheet", &json!({"csv": long})).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_TABLE_ROWS} rows")), "{e}");
|
||||
// A table's own width and length are fine.
|
||||
let ok = format!("{}\nvalue", "c,".repeat(MAX_COLS - 1));
|
||||
s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap();
|
||||
let ok = "value\n".repeat(MAX_TABLE_ROWS);
|
||||
s.run("insert.spreadsheet", &json!({"csv": ok})).unwrap();
|
||||
}
|
||||
|
||||
/// The inspector's removals delete straight from the document, so they aren't tracked: on a
|
||||
/// document that tracks changes the text would go with no revision to show for it, and the
|
||||
/// revision trail would be broken behind the user's back. The removal is refused instead,
|
||||
/// and the document is left as it was.
|
||||
|
||||
#[test]
|
||||
fn inspect_removals_are_refused_while_the_document_tracks_changes() {
|
||||
let mut s = Session::new(Document::from_text("Visible text.\nHidden text."));
|
||||
@@ -2775,6 +2987,7 @@ fn compare_strips_source_revisions_from_adopted_notes() {
|
||||
author: "Other".into(),
|
||||
date: "2026-01-01T00:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
for part in rev.doc.parts.values_mut() {
|
||||
if part.kind == wordcraft_doc::PartKind::Footnote
|
||||
|
||||
@@ -284,14 +284,17 @@ fn import_chunk(c: &wordcraft_docx::AltChunk) -> Option<Document> {
|
||||
|| matches!(ext.as_str(), "mht" | "mhtml")
|
||||
|| mht::is_mht(b)
|
||||
{
|
||||
mht::import(b)
|
||||
mht::import(b).map_err(|e| log::warn!("altChunk {}: the MHT cannot be read: {e}", c.part)).ok()?
|
||||
} else if ct.contains("rtf") || ext == "rtf" || b.starts_with(b"{\\rtf") {
|
||||
rtf::import(b).ok()?
|
||||
rtf::import(b).map_err(|e| log::warn!("altChunk {}: the RTF cannot be read: {e}", c.part)).ok()?
|
||||
} else if ct.contains("html") || matches!(ext.as_str(), "html" | "htm" | "xhtml") {
|
||||
html::import_page(&html::decode_as(b, charset), &|_| None)
|
||||
.map_err(|e| log::warn!("altChunk {}: the HTML cannot be read: {e}", c.part))
|
||||
.ok()?
|
||||
} else if ct == "text/plain" || ext == "txt" {
|
||||
txt::import(b)
|
||||
} else {
|
||||
log::warn!("altChunk {}: its type ({ct}) is not one WordCraft reads", c.part);
|
||||
return None;
|
||||
};
|
||||
// shortcut: pictures fit the chunk's default page, not the section it lands in; fit them there if wide pictures in chunks overflow narrow sections.
|
||||
@@ -496,7 +499,7 @@ pub fn open_path_in(path: &std::path::Path, password: Option<&str>, region: &wor
|
||||
// Pictures referenced by a relative path load from beside the HTML file.
|
||||
let images = LocalImages::new(path.parent().unwrap_or(std::path::Path::new("")));
|
||||
let html = wordcraft_formats::html::decode(&bytes);
|
||||
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), ®ion_page(region));
|
||||
let mut doc = wordcraft_formats::html::import_on(&html, &|src| images.load(src), ®ion_page(region))?;
|
||||
fit_pictures(&mut doc);
|
||||
opened(&mut doc);
|
||||
return Ok((doc, false));
|
||||
|
||||
@@ -98,6 +98,15 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// A UTC date and time (a `Z` or an offset) as Word writes `w:date`: the wall-clock time in the
|
||||
/// zone `zone` gives for an instant (seconds east of UTC), with a `Z` Word writes but doesn't
|
||||
/// mean. Word read the UTC dates WordCraft wrote as local time, shifted by the user's offset from
|
||||
/// UTC (#6851). None for anything else (no zone or no time of day, before 1970, unreadable).
|
||||
pub(crate) fn word_date(date: &str, zone: impl Fn(u64) -> i64) -> Option<String> {
|
||||
let utc = u64::try_from(chrono::DateTime::parse_from_rfc3339(date.trim()).ok()?.timestamp()).ok()?;
|
||||
Some(crate::cmd::iso_from_unix_secs(utc.checked_add_signed(zone(utc))?))
|
||||
}
|
||||
|
||||
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
|
||||
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
|
||||
/// `file.strictReport`'s page check and a downloaded page image.
|
||||
@@ -134,9 +143,45 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// New York in 2026: daylight saving time from 8 March 07:00 UTC to 1 November 06:00 UTC.
|
||||
pub(crate) fn new_york(t: u64) -> i64 {
|
||||
if (1_772_953_200..1_793_512_800).contains(&t) { -4 * 3600 } else { -5 * 3600 }
|
||||
}
|
||||
|
||||
/// Word dates `w:date` in local wall-clock time with a `Z`; the change keeps UTC (#6851).
|
||||
#[test]
|
||||
fn word_dates_tracked_changes_in_local_time() {
|
||||
let plus8 = |_| 8 * 3600;
|
||||
// The issue's edit: 08:33:24 UTC at UTC+8, which Word showed as 8:33 AM.
|
||||
assert_eq!(word_date("2026-11-16T08:33:24Z", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
|
||||
// A date naming its offset is that instant, whatever the zone.
|
||||
assert_eq!(word_date("2026-11-16T16:33:24+08:00", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
|
||||
// West of UTC, the date can go back a day.
|
||||
assert_eq!(word_date("2026-01-01T03:00:00Z", new_york).as_deref(), Some("2025-12-31T22:00:00Z"));
|
||||
|
||||
// The repeated hour: 05:30 and 06:30 UTC are both 01:30 in New York; `dateUtc` keeps them
|
||||
// apart. Either side of a change of offset takes the offset at that instant.
|
||||
assert_eq!(word_date("2026-11-01T05:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
|
||||
assert_eq!(word_date("2026-11-01T06:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
|
||||
assert_eq!(word_date("2026-11-01T04:30:00Z", new_york).as_deref(), Some("2026-11-01T00:30:00Z"));
|
||||
assert_eq!(word_date("2026-11-01T07:30:00Z", new_york).as_deref(), Some("2026-11-01T02:30:00Z"));
|
||||
assert_eq!(word_date("2026-03-08T06:30:00Z", new_york).as_deref(), Some("2026-03-08T01:30:00Z"));
|
||||
assert_eq!(word_date("2026-03-08T07:30:00Z", new_york).as_deref(), Some("2026-03-08T03:30:00Z"));
|
||||
|
||||
// Anything else is left as it is: no zone, no time of day, before 1970, not a date.
|
||||
for date in ["", "2026-11-16T08:33:24", "2026-11-16", "1969-12-31T23:00:00Z", "yesterday", "2026-13-01T00:00:00Z"] {
|
||||
assert_eq!(word_date(date, plus8), None, "{date:?}");
|
||||
}
|
||||
// A hostile zone or a far date doesn't overflow.
|
||||
for zone in [i64::MAX, i64::MIN] {
|
||||
let _ = word_date("2026-11-16T08:33:24Z", |_| zone);
|
||||
}
|
||||
assert!(word_date("9999-12-31T23:59:59Z", plus8).is_some());
|
||||
}
|
||||
|
||||
/// A page image is the printed page: headers and footers draw at full strength (#6267).
|
||||
#[test]
|
||||
fn a_page_image_draws_headers_at_full_strength() {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod io;
|
||||
mod io_ext;
|
||||
pub mod keymap;
|
||||
pub(crate) mod locale;
|
||||
pub mod malloc_tuning;
|
||||
pub mod math_gallery;
|
||||
pub mod packs;
|
||||
pub(crate) mod prefs;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! glibc malloc tuning for native binaries (adapted from Storytold's `photocraft` #8743).
|
||||
//!
|
||||
//! With glibc's defaults, transient large buffers (page render targets, autofit tables, decoded
|
||||
//! images) raise glibc's dynamic `mmap` and `trim` thresholds (up to 32 MiB on 64-bit), so later
|
||||
//! heap allocations stay in glibc arenas instead of returning freed pages to the OS. Fixing
|
||||
//! `MALLOC_TRIM_THRESHOLD_` at 128 KiB (`131072`) disables dynamic threshold growth so freed
|
||||
//! pages above 128 KiB are returned cleanly while preserving multi-arena allocation throughput.
|
||||
//!
|
||||
//! Because glibc reads its malloc environment variables once at process start and mutating the
|
||||
//! process environment in Rust requires `unsafe` (forbidden workspace-wide) and happens after glibc
|
||||
//! initialization, [`apply`] re-executes the current executable via `exec` when no malloc tuning
|
||||
//! variable is already set (keeping PID, argv, `argv[0]`, and environment). Setting any `MALLOC_*`
|
||||
//! variable or `glibc.malloc.*` tunable opts out.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// The glibc environment variable [`apply`] sets.
|
||||
pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_";
|
||||
|
||||
/// Fixed trim threshold (128 KiB, glibc's initial default) to disable dynamic threshold escalation.
|
||||
pub const TRIM_THRESHOLD: &str = "131072";
|
||||
|
||||
/// glibc malloc variables that indicate callers or wrappers already configured malloc tuning.
|
||||
const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"];
|
||||
|
||||
/// Whether startup should re-execute with [`TRIM_THRESHOLD_VAR`] set, given an environment reader:
|
||||
/// true only when no malloc variable or `glibc.malloc.*` tunable is present.
|
||||
pub fn needs_restart(var: impl Fn(&str) -> Option<OsString>) -> bool {
|
||||
if MALLOC_VARS.iter().any(|v| var(v).is_some()) {
|
||||
return false;
|
||||
}
|
||||
!var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc."))
|
||||
}
|
||||
|
||||
/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] is true.
|
||||
///
|
||||
/// Must be called early in `main()` before worker threads start or logs/crash hooks initialize.
|
||||
/// Returns immediately if tuning variables are already present or if `exec` fails.
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
pub fn apply() {
|
||||
use std::io::Write;
|
||||
use std::os::unix::process::CommandExt;
|
||||
|
||||
if !needs_restart(|k| std::env::var_os(k)) {
|
||||
return;
|
||||
}
|
||||
let Ok(exe) = std::env::current_exe() else { return };
|
||||
let mut args = std::env::args_os();
|
||||
let mut cmd = std::process::Command::new(exe);
|
||||
if let Some(argv0) = args.next() {
|
||||
cmd.arg0(argv0);
|
||||
}
|
||||
// `exec` replaces the current process in place and only returns on error.
|
||||
let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec();
|
||||
let _ = writeln!(std::io::stderr(), "wordcraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err})");
|
||||
}
|
||||
|
||||
/// No-op on platforms without Linux glibc.
|
||||
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
|
||||
pub fn apply() {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restarts_only_without_malloc_tuning() {
|
||||
assert!(needs_restart(env(&[])));
|
||||
assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")])));
|
||||
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "re-executed process stops");
|
||||
assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any explicit value opts out");
|
||||
assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")])));
|
||||
assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")])));
|
||||
assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")])));
|
||||
}
|
||||
}
|
||||
@@ -230,6 +230,9 @@ pub struct Session {
|
||||
pub editing_lang: Option<String>,
|
||||
/// Editing inside an equation: which one and the caret in it.
|
||||
pub math: Option<MathEdit>,
|
||||
/// The running command left the equation being edited before it ran (see [`Session::run`]),
|
||||
/// so Left/Right don't open the equation the caret now sits next to (#4138).
|
||||
pub(crate) math_left: bool,
|
||||
/// Equations are typed in LaTeX rather than the linear format.
|
||||
pub math_latex: bool,
|
||||
/// Text typed into equations is normal (non-math) text.
|
||||
|
||||
@@ -280,6 +280,7 @@ impl Session {
|
||||
findings: _,
|
||||
ribbon: _,
|
||||
editing_lang: _,
|
||||
math_left: _,
|
||||
math_latex: _,
|
||||
math_normal_text: _,
|
||||
last_highlight: _,
|
||||
|
||||
@@ -80,8 +80,12 @@ impl Session {
|
||||
};
|
||||
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
|
||||
let [newest, _] = std::mem::take(&mut self.layout);
|
||||
// Only preserve the alternate layout slot for the current document revision (e.g. Print vs
|
||||
// Web/Draft toggling); a superseded revision can never hit `fits()` again and would keep an
|
||||
// obsolete DocLayout live in memory.
|
||||
let prev = newest.filter(|e| e.0 == rev);
|
||||
self.layout =
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), newest];
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
|
||||
l
|
||||
}
|
||||
|
||||
@@ -275,3 +279,31 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
drop(first);
|
||||
|
||||
// Switching view mode at the same revision keeps the prior layout in `layout[1]`.
|
||||
session.view.mode = ViewMode::Draft;
|
||||
let same_rev_other_mode = session.layout();
|
||||
assert!(first_weak.upgrade().is_some(), "same-revision alternate view mode stays cached");
|
||||
|
||||
let draft_weak = Arc::downgrade(&same_rev_other_mode);
|
||||
drop(same_rev_other_mode);
|
||||
|
||||
// Advancing `rev` makes earlier layouts unreachable: building the new layout must drop them.
|
||||
session.run("text.insert", &serde_json::json!({"text": "hello"})).expect("insert");
|
||||
let after_edit = session.layout();
|
||||
assert!(draft_weak.upgrade().is_none(), "superseded revision layout must be dropped");
|
||||
assert!(first_weak.upgrade().is_none(), "older revision layout must not remain live");
|
||||
drop(after_edit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +157,7 @@ impl Session {
|
||||
merge,
|
||||
ui_requests: Vec::new(),
|
||||
math,
|
||||
math_left: false,
|
||||
math_latex: false,
|
||||
math_normal_text: false,
|
||||
also_selected,
|
||||
|
||||
@@ -27,16 +27,20 @@ struct ElsewhereContext {
|
||||
blocks_before: Option<std::collections::BTreeMap<String, Fragment>>,
|
||||
default_language_before: Option<String>,
|
||||
pending_application_change_before: bool,
|
||||
/// The tracked move the command would have dropped, put back when it fails.
|
||||
move_before: Option<crate::cmd::moves::PendingMove>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn leave_math_for_command(&mut self, id: &str) {
|
||||
self.math_left = false;
|
||||
if self.math.is_some()
|
||||
&& (id.starts_with("text.") || id.starts_with("caret.") || id.starts_with("select.") || id.starts_with("edit.paste"))
|
||||
&& let Some(m) = self.math.take()
|
||||
{
|
||||
let off = m.at.off + wordcraft_doc::para::OBJ.len_utf8();
|
||||
self.sel = Selection::caret(Pos { off, ..m.at });
|
||||
self.math_left = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,7 +215,9 @@ impl Session {
|
||||
} else if spec.id.starts_with("caret.") {
|
||||
self.typing_open = false;
|
||||
}
|
||||
// Only the paste right after a tracked cut makes it a move.
|
||||
// Only the paste right after a tracked cut makes it a move. A command that fails
|
||||
// changed nothing, so the move it would have dropped is put back (below).
|
||||
let move_before = self.pending_move.clone();
|
||||
if (spec.mutates || matches!(id, "edit.undo" | "edit.undoTo" | "edit.redo")) && !matches!(id, "edit.cut" | "edit.paste" | "edit.pasteSpecial")
|
||||
{
|
||||
self.pending_move = None;
|
||||
@@ -237,7 +243,7 @@ impl Session {
|
||||
};
|
||||
if self.document_id != home || (result.is_err() && self.order.iter().any(|d| *d >= mark)) {
|
||||
return self.finish_elsewhere(
|
||||
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before },
|
||||
ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before },
|
||||
result,
|
||||
);
|
||||
}
|
||||
@@ -302,6 +308,9 @@ impl Session {
|
||||
self.join_anchor = false;
|
||||
}
|
||||
}
|
||||
// The command failed, so the tracked move it would have dropped is still there:
|
||||
// the paste after it is a move, as it was before the command.
|
||||
self.pending_move = move_before;
|
||||
if let Some(dirty) = dirty_before {
|
||||
self.dirty = dirty;
|
||||
}
|
||||
@@ -480,7 +489,8 @@ impl Session {
|
||||
/// as it was (opening a document is no edit to undo there). Failed: the documents the command opened close again and the first document is
|
||||
/// active and as it was.
|
||||
fn finish_elsewhere(&mut self, context: ElsewhereContext, result: Result<Value, CmdError>) -> Result<Value, CmdError> {
|
||||
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before } = context;
|
||||
let ElsewhereContext { home, mark, before_doc, blocks_before, default_language_before, pending_application_change_before, move_before } =
|
||||
context;
|
||||
// Another document is a state change the input method has to see, never an IME edit.
|
||||
self.ime_edit_outcome = ImeEditOutcome::default();
|
||||
match &result {
|
||||
@@ -512,6 +522,9 @@ impl Session {
|
||||
self.undo_evicted = ev;
|
||||
self.column = c;
|
||||
}
|
||||
// The command failed, so the tracked move it would have dropped is still
|
||||
// there: the paste after it is a move, as it was before the command.
|
||||
self.pending_move = move_before;
|
||||
}
|
||||
if let Some(b) = blocks_before {
|
||||
self.building_blocks = b;
|
||||
|
||||
@@ -162,6 +162,7 @@ impl Session {
|
||||
editing_lang: _,
|
||||
// Equation editing mode, like `view`: not part of the document or its history.
|
||||
math: _,
|
||||
math_left: _,
|
||||
math_latex: _,
|
||||
math_normal_text: _,
|
||||
// The save password, like the file path: not an edit to the document.
|
||||
|
||||
+247
-2
@@ -17,6 +17,7 @@ mod find_apostrophes;
|
||||
mod fit_one_page;
|
||||
mod font_sizes;
|
||||
mod fonts;
|
||||
mod home_borders_cells;
|
||||
mod ime_noop;
|
||||
mod page_number_formats_in_lists;
|
||||
mod para_tools;
|
||||
@@ -4092,6 +4093,74 @@ fn layout_size_when_focus_is_in_header_updates_correct_section() {
|
||||
assert_eq!((s0.page_w, s0.page_h), (612.0, 792.0));
|
||||
}
|
||||
|
||||
/// #3639: with the caret in section 2's header, the header and footer commands change section 2.
|
||||
/// The caret's block index counts the header's paragraphs, and block 0 of the body is in section 1.
|
||||
#[test]
|
||||
fn header_and_footer_commands_change_the_section_of_the_header_the_caret_is_in() {
|
||||
use wordcraft_doc::{Block, Paragraph, PartKind, StoryRef};
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "section 1"}));
|
||||
run(&mut s, "layout.break", json!({"kind": "nextPage"}));
|
||||
run(&mut s, "text.insert", json!({"text": "section 2"}));
|
||||
assert_eq!(s.doc.sections().len(), 2);
|
||||
let header = |s: &mut Session, text: &str| {
|
||||
s.doc.add_part(PartKind::Header, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text(text, Default::default())))])
|
||||
};
|
||||
let (h1, h2) = (header(&mut s, "H1"), header(&mut s, "H2"));
|
||||
let f1 = s.doc.add_part(PartKind::Footer, vec![std::sync::Arc::new(Block::Para(Paragraph::with_text("F1", Default::default())))]);
|
||||
s.doc.section_mut(0).headers.default = Some(h1);
|
||||
s.doc.section_mut(0).footers.default = Some(f1);
|
||||
s.doc.last_section.headers.default = Some(h2);
|
||||
let first = s.doc.sections()[0].1.clone();
|
||||
let in_h2 = |s: &mut Session| s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h2)));
|
||||
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "hf.position", json!({"header": 50}));
|
||||
assert_eq!(s.doc.last_section.header, 50.0);
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "design.pageBorders", json!({"kind": "box"}));
|
||||
assert!(s.doc.last_section.page_borders.is_some());
|
||||
// Section 2 has no footer of its own and shows section 1's: Edit Footer opens that one and
|
||||
// keeps the link.
|
||||
in_h2(&mut s);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f1);
|
||||
assert_eq!(s.doc.last_section.footers.default, None, "section 2 stays linked");
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "insert.footer", json!({"text": "F2"}));
|
||||
let f2 = s.doc.last_section.footers.default.expect("section 2 has the new footer");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(f2)), "F2");
|
||||
in_h2(&mut s);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f2, "Edit Footer opens section 2's footer");
|
||||
in_h2(&mut s);
|
||||
run(&mut s, "layout.linkToPrevious", json!({}));
|
||||
assert_eq!(s.doc.last_section.headers.default, None, "section 2 is linked to section 1");
|
||||
|
||||
assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(h1)), "H1");
|
||||
|
||||
// Section 2 now shows section 1's header and has its own footer. With the caret in that
|
||||
// header on section 2's page, the commands change section 2, not section 1 that owns it.
|
||||
let page2 = s.layout().pages.iter().position(|pg| pg.section == 1).expect("section 2 has a page");
|
||||
assert_eq!(s.layout().pages[page2].header_story, Some(h1));
|
||||
let in_h1 = |s: &mut Session, page: usize| {
|
||||
s.sel = crate::Selection::caret(s.doc.start_of(StoryRef::Part(h1)));
|
||||
s.page_hint = page;
|
||||
};
|
||||
in_h1(&mut s, page2);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f2, "Edit Footer opens the footer section 2 shows");
|
||||
in_h1(&mut s, page2);
|
||||
run(&mut s, "hf.position", json!({"header": 40}));
|
||||
assert_eq!(s.doc.last_section.header, 40.0);
|
||||
assert_eq!(*s.doc.sections()[0].1, first, "section 1 is untouched");
|
||||
// On section 1's own page the same header is section 1's.
|
||||
in_h1(&mut s, 0);
|
||||
assert_eq!(run(&mut s, "insert.editFooter", json!({}))["story"], f1);
|
||||
in_h1(&mut s, 0);
|
||||
run(&mut s, "hf.position", json!({"header": 30}));
|
||||
assert_eq!(s.doc.sections()[0].1.header, 30.0);
|
||||
assert_eq!(s.doc.last_section.header, 40.0);
|
||||
}
|
||||
|
||||
/// #1433: the smallest page there can be (0.1" wide, no margins, set straight through Page
|
||||
/// Setup's section) still lays out and exports text, a table and two columns.
|
||||
#[test]
|
||||
@@ -5407,6 +5476,22 @@ fn replacing_a_toc_keeps_its_title_above_the_section_break() {
|
||||
assert_eq!(toc_layout(&s), before, "{}", text(&s));
|
||||
}
|
||||
|
||||
/// Replacing Word's TOC whose title sits above a section break leaves the caret after the table,
|
||||
/// as a plain replacement does: with the caret in the title, typing went into the title.
|
||||
#[test]
|
||||
fn replacing_a_toc_above_a_section_break_leaves_the_caret_after_it() {
|
||||
let mut s = word_toc_above_a_section_break("TOCHeading");
|
||||
s.sel = crate::Selection::caret(Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 2 });
|
||||
run(&mut s, "references.toc", json!({"levels": 1}));
|
||||
// Past the last entry, not in the title or the entries.
|
||||
let last_entry = s.doc.body.iter().rposition(|b| b.as_para().is_some_and(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC"))));
|
||||
assert!(last_entry.is_some_and(|e| s.sel.focus.path.last() > e), "{:?}: {}", s.sel.focus, text(&s));
|
||||
run(&mut s, "text.insert", json!({"text": "typed"}));
|
||||
let (paras, _) = toc_layout(&s);
|
||||
assert_eq!(paras.first().map(|(_, _, t)| t.as_str()), Some("Contents"), "the title is untouched: {paras:?}");
|
||||
assert!(paras.iter().any(|(st, _, t)| t == "typed" && !st.starts_with("TOC")), "{paras:?}");
|
||||
}
|
||||
|
||||
/// #4041: removing Word's TOC whose title sits above a section break takes the title, the blank
|
||||
/// paragraph ending its section and that break with the entries, as Word's Remove Table of
|
||||
/// Contents does (observed in Word for Mac): the empty paragraph after the table, ending the
|
||||
@@ -7323,7 +7408,7 @@ fn scratch_dir(name: &str) -> std::path::PathBuf {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
pub(crate) fn tiny_png() -> Vec<u8> {
|
||||
wordcraft_geom::picture::encode_format(
|
||||
&image::DynamicImage::from(image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 30, 30, 255])).clone()),
|
||||
image::ImageFormat::Png,
|
||||
@@ -9649,6 +9734,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
|
||||
assert_eq!(text(&s), "Q");
|
||||
}
|
||||
|
||||
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
|
||||
#[test]
|
||||
fn change_case_follows_turkic_language_mapping() {
|
||||
// 1. Turkish (tr-TR): all 5 modes
|
||||
// Capitalize Each Word (title)
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Işık");
|
||||
|
||||
// UPPERCASE
|
||||
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
|
||||
assert_eq!(text(&s), "İSTANBUL IŞIK");
|
||||
|
||||
// lowercase
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(text(&s), "istanbul ışık");
|
||||
|
||||
// sentence case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
|
||||
assert_eq!(text(&s), "İstanbul. Işık.");
|
||||
|
||||
// toggle case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
|
||||
assert_eq!(text(&s), "iSTANBUL ıŞIK");
|
||||
|
||||
// 2. Azerbaijani (az-AZ)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 3. Crimean Tatar (crh)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 4. English control (en-US): unchanged Unicode default
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "Istanbul");
|
||||
|
||||
// 5. Mixed-language selection: Turkish run followed by English run
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Istanbul");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_sentence_ignores_decimal_points() {
|
||||
// #3485: Sentence case should not capitalize after decimal points.
|
||||
@@ -9721,6 +9877,9 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
|
||||
#[test]
|
||||
fn markup_pdf_takes_the_track_changes_option_colours() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
|
||||
// A fixed creation date: without one each PDF is stamped with the current time, and the
|
||||
// exports compared below differ when a clock second ticks over between them.
|
||||
s.doc.core.created = "2026-01-01T00:00:00Z".into();
|
||||
s.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
|
||||
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
|
||||
@@ -15256,6 +15415,32 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
for i in 0..80 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
|
||||
}
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 2, "expected a multi-page document, got {pages}");
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let start = s.sel.focus.clone();
|
||||
// Advance page by page until the last page, then one more PageDown must reach the end.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
}
|
||||
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
|
||||
// Step back page by page until page 0, then one more PageUp must reach the start.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
}
|
||||
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -15446,7 +15631,7 @@ fn sectioned_revision(delete: bool) -> Session {
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": 2, "off": 0}}));
|
||||
run(&mut s, "para.style", json!({"style": "Heading1"}));
|
||||
let kind = if delete { RevisionKind::Delete } else { RevisionKind::Insert };
|
||||
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
s.doc.last_section.margin_left = 72.0;
|
||||
let mut sect = s.doc.last_section.clone();
|
||||
sect.margin_left = 144.0;
|
||||
@@ -15651,3 +15836,63 @@ fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
|
||||
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
|
||||
assert_eq!(c.bold, Some(true));
|
||||
}
|
||||
|
||||
/// #8068: A text box reachable only inside nested shape groups survives mutating Session commands
|
||||
/// (which call `prune_text_boxes`) and copy/paste adoption, while an unreachable box is pruned.
|
||||
#[test]
|
||||
fn nested_group_text_box_survives_mutating_session_commands() {
|
||||
use wordcraft_doc::para::{GroupChild, InlineObject, ShapeKind};
|
||||
use wordcraft_doc::{CharProps, Document, Paragraph, PartKind, Path, para_block};
|
||||
|
||||
let mut d = Document::from_text("body");
|
||||
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
|
||||
let nested_tb = d.add_part(PartKind::TextBox, para_of("nested group box"));
|
||||
let orphan_tb = d.add_part(PartKind::TextBox, para_of("orphan box"));
|
||||
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: 50.0,
|
||||
h: 20.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story: Some(nested_tb),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
let group = |obj: InlineObject| InlineObject::Group {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
float: Default::default(),
|
||||
ch_w: 100.0,
|
||||
ch_h: 100.0,
|
||||
children: vec![GroupChild { x: 0.0, y: 0.0, obj }],
|
||||
canvas: None,
|
||||
};
|
||||
d.insert_object(&Pos::body(0, 0), group(group(shape)), &CharProps::default()).unwrap();
|
||||
|
||||
let mut s = Session::new(d);
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": " edited"}));
|
||||
|
||||
assert!(s.doc.parts.contains_key(&nested_tb), "nested group text box must survive prune");
|
||||
assert!(!s.doc.parts.contains_key(&orphan_tb), "unreachable text box must still be pruned");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(nested_tb)), "nested group box");
|
||||
let objs = &s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects;
|
||||
assert_eq!(objs.len(), 1);
|
||||
assert_eq!(objs[0].text_boxes(), vec![nested_tb]);
|
||||
|
||||
// Copy/paste adopts the nested-group text box into a fresh story via text_box_slots() and survives prune.
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
let ids: Vec<u32> = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects.iter().flat_map(InlineObject::text_boxes).collect();
|
||||
assert_eq!(ids.len(), 2, "original and pasted nested groups each hold a text box");
|
||||
assert_ne!(ids[0], ids[1], "pasted nested group box gets its own story id");
|
||||
for id in ids {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,41 @@ fn assert_fixture_font(s: &mut Session) {
|
||||
assert!(runs > 0, "the font check must inspect laid-out body text");
|
||||
}
|
||||
|
||||
/// A document that just spills onto a second page: the most lines `make` can put on one page,
|
||||
/// then space before the last paragraph until it moves to page 2 ([`spill_last_paragraph`]).
|
||||
/// The fixtures are set in the bundled [`FIXTURE_FONT`], but a fixed line count still depends on
|
||||
/// that font's exact metrics and the page setup, so the tests find the spill point instead.
|
||||
fn just_spilling(make: impl Fn(usize) -> Session) -> Session {
|
||||
let mut lines = 10;
|
||||
while make(lines + 1).layout().pages.len() < 2 {
|
||||
lines += 1;
|
||||
assert!(lines < 120, "{lines} lines still fit on one page");
|
||||
}
|
||||
let mut s = make(lines);
|
||||
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page");
|
||||
spill_last_paragraph(&mut s);
|
||||
s
|
||||
}
|
||||
|
||||
/// Adds space before the last paragraph, half a point at a time, until it moves to page 2. The
|
||||
/// document then overflows by less than half a point, which any font reduction it is fitted with
|
||||
/// brings back.
|
||||
fn spill_last_paragraph(s: &mut Session) {
|
||||
let mut before = match s.doc.body.last().map(|b| &**b) {
|
||||
Some(wordcraft_doc::Block::Para(p)) => p.props.space_before.unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
};
|
||||
while s.layout().pages.len() < 2 {
|
||||
before += 0.5;
|
||||
assert!(before <= 200.0, "space before the last paragraph never moved it to page 2");
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = s.doc.body.last_mut().map(std::sync::Arc::make_mut) {
|
||||
p.props.space_before = Some(before);
|
||||
}
|
||||
s.touch();
|
||||
s.relayout();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_fails_on_single_page() {
|
||||
let mut s = create_multiline_doc(5);
|
||||
@@ -144,15 +179,20 @@ fn fit_one_page_respects_max_delta() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_respects_step_pt() {
|
||||
let mut s = create_multiline_doc(27);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
let at_11_4 = |lines: usize| {
|
||||
let mut s = create_multiline_doc(lines);
|
||||
for b in &mut s.doc.body {
|
||||
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
p.mark.size = Some(11.4);
|
||||
for r in &mut p.runs {
|
||||
r.props.size = Some(11.4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.touch();
|
||||
s
|
||||
};
|
||||
let mut s = just_spilling(at_11_4);
|
||||
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -162,7 +202,7 @@ fn fit_one_page_respects_step_pt() {
|
||||
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
|
||||
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
|
||||
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, fine-grained steps (0.1..0.4) succeed (11.4 -> 11.0 pt).
|
||||
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
|
||||
s.doc = doc_backup;
|
||||
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
|
||||
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
|
||||
@@ -877,7 +917,7 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
|
||||
|
||||
#[test]
|
||||
fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
let mut s = create_multiline_doc(26);
|
||||
let mut s = just_spilling(create_multiline_doc);
|
||||
assert_eq!(s.layout().pages.len(), 2);
|
||||
assert_fixture_font(&mut s);
|
||||
|
||||
@@ -894,12 +934,10 @@ fn fit_one_page_preserves_budget_across_document_serialization() {
|
||||
assert_eq!(reopened_doc.fit_state.as_ref().map(|f| f.cum_delta), Some(0.5));
|
||||
assert!(reopened_doc.custom_props.is_empty(), "custom_props must remain empty");
|
||||
|
||||
// Reopen into a new session with additional spill
|
||||
// Reopen into a new session with additional spill: the last paragraph moves to page 2 again
|
||||
let mut s2 = Session::new(reopened_doc);
|
||||
let extra_p = wordcraft_doc::Paragraph::with_text("Extra overflow paragraph.", CharProps::default());
|
||||
s2.doc.body.push(wordcraft_doc::para_block(extra_p));
|
||||
s2.touch();
|
||||
s2.relayout();
|
||||
assert_eq!(s2.layout().pages.len(), 1);
|
||||
spill_last_paragraph(&mut s2);
|
||||
|
||||
// Second fit on reopened document preserves previous 0.5 delta, allowing only remaining 0.5 pt up to 1.0 cap
|
||||
let res2 = s2.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
//! #7874: Home › Paragraph › Borders with whole table cells selected borders the cells as a
|
||||
//! block, as Word does, instead of each paragraph in them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::props::{Border, Borders};
|
||||
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
|
||||
|
||||
use crate::{Selection, Session};
|
||||
|
||||
/// A document of a 3 x 3 table with text in every cell, the caret in the first cell.
|
||||
fn doc() -> Session {
|
||||
let mut t = Table::new(3, 3, 300.0);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = Cell::with_text(&format!("c{r}{c}")).blocks;
|
||||
}
|
||||
}
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
|
||||
let mut s = Session::new(d);
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
|
||||
s
|
||||
}
|
||||
|
||||
fn table(s: &Session) -> &Table {
|
||||
s.doc.body.iter().find_map(|b| b.as_table()).unwrap()
|
||||
}
|
||||
|
||||
fn cell_borders(s: &Session, r: usize, c: usize) -> Borders {
|
||||
table(s).rows[r].cells[c].props.borders.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Which sides of cell (`r`, `c`) the layout draws a line on, the table style's lines included:
|
||||
/// top, left, bottom, right.
|
||||
fn drawn(s: &Session, r: usize, c: usize) -> [bool; 4] {
|
||||
let b = wordcraft_layout::cell_borders(&s.doc, table(s), r, c);
|
||||
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
|
||||
}
|
||||
|
||||
/// Which sides of cell (`r`, `c`) show a line: top, left, bottom, right.
|
||||
fn shown(s: &Session, r: usize, c: usize) -> [bool; 4] {
|
||||
let b = cell_borders(s, r, c);
|
||||
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
|
||||
}
|
||||
|
||||
/// Whether any paragraph in the table has borders of its own.
|
||||
fn para_borders(s: &Session) -> bool {
|
||||
table(s).rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).any(|p| p.props.borders.is_some())
|
||||
}
|
||||
|
||||
fn borders(s: &mut Session, kind: &str) {
|
||||
s.run("para.borders", &json!({"kind": kind})).unwrap();
|
||||
}
|
||||
|
||||
/// Select whole cells: rows `rows` and grid columns `cols` of the table.
|
||||
fn select(s: &mut Session, rows: (usize, usize), cols: (usize, usize)) {
|
||||
crate::cmd::table::select_range(s, StoryRef::Body, &Path(vec![0]), rows, cols).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_borders_on_a_selected_table_borders_every_cell() {
|
||||
let mut s = doc();
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "all");
|
||||
for r in 0..3 {
|
||||
for c in 0..3 {
|
||||
assert_eq!(shown(&s, r, c), [true; 4], "cell ({r}, {c}) has a line on every side");
|
||||
}
|
||||
}
|
||||
assert!(!para_borders(&s), "the paragraphs in the cells get no borders of their own");
|
||||
// The line is the one asked for, with no paragraph spacing.
|
||||
let top = cell_borders(&s, 1, 1).top.unwrap();
|
||||
assert_eq!((top.width, top.space), (0.5, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_and_inside_borders_follow_the_selected_block() {
|
||||
let mut s = doc();
|
||||
// The top-left 2 x 2 cells.
|
||||
select(&mut s, (0, 1), (0, 1));
|
||||
borders(&mut s, "outside");
|
||||
assert_eq!(shown(&s, 0, 0), [true, true, false, false]);
|
||||
assert_eq!(shown(&s, 0, 1), [true, false, false, true]);
|
||||
assert_eq!(shown(&s, 1, 0), [false, true, true, false]);
|
||||
assert_eq!(shown(&s, 1, 1), [false, false, true, true]);
|
||||
assert_eq!(table(&s).rows[2].cells[2].props.borders, None, "a cell outside the selection is left alone");
|
||||
// The cells beyond the block share its edge lines: their facing sides get the same line.
|
||||
assert_eq!(shown(&s, 0, 2), [false, true, false, false]);
|
||||
assert_eq!(shown(&s, 2, 0), [true, false, false, false]);
|
||||
borders(&mut s, "inside");
|
||||
assert_eq!(shown(&s, 0, 0), [true; 4]);
|
||||
assert_eq!(shown(&s, 1, 1), [true; 4]);
|
||||
assert_eq!(shown(&s, 0, 2), [false, true, false, false], "Inside leaves the cells beyond the block alone");
|
||||
assert!(!para_borders(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_border_on_a_row_clears_the_lines_it_shares_with_the_rows_around_it() {
|
||||
let mut s = doc();
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "all");
|
||||
select(&mut s, (1, 1), (0, 2));
|
||||
borders(&mut s, "none");
|
||||
for c in 0..3 {
|
||||
// Each cell draws its own sides, so the rows above and below must not keep the lines.
|
||||
assert_eq!(shown(&s, 0, c), [true, true, false, true], "the row above keeps its other lines, cell (0, {c})");
|
||||
assert_eq!(shown(&s, 1, c), [false; 4], "cell (1, {c})");
|
||||
assert_eq!(shown(&s, 2, c), [false, true, true, true], "the row below keeps its other lines, cell (2, {c})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_that_skips_grid_columns_has_its_first_cell_on_the_outside() {
|
||||
let mut s = doc();
|
||||
// The middle row starts at grid column 1 (`w:gridBefore`): two cells.
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[1].cells.remove(0);
|
||||
tb.rows[1].props.grid_before = 1;
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "outside");
|
||||
assert_eq!(shown(&s, 1, 0), [false, true, false, false], "the row's first cell is on the table's left edge");
|
||||
assert_eq!(shown(&s, 1, 1), [false, false, false, true]);
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "inside");
|
||||
assert_eq!(shown(&s, 1, 0), [true, false, true, true], "Inside leaves the row's outer edge without a line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_side_toggles_along_the_block_edge_and_no_border_clears_the_cells() {
|
||||
let mut s = doc();
|
||||
// The middle row, with no line on it or around it.
|
||||
select(&mut s, (1, 1), (0, 2));
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "bottom");
|
||||
for c in 0..3 {
|
||||
assert_eq!(shown(&s, 1, c), [false, false, true, false], "cell (1, {c})");
|
||||
}
|
||||
borders(&mut s, "bottom");
|
||||
for c in 0..3 {
|
||||
assert_eq!(shown(&s, 1, c), [false; 4], "the second press takes the bottom line off cell (1, {c})");
|
||||
}
|
||||
borders(&mut s, "all");
|
||||
borders(&mut s, "none");
|
||||
let nil = |x: Option<Border>| x.is_some_and(|x| !x.is_visible());
|
||||
for c in 0..3 {
|
||||
let b = cell_borders(&s, 1, c);
|
||||
assert!(
|
||||
nil(b.top) && nil(b.left) && nil(b.bottom) && nil(b.right),
|
||||
"No Border writes no line on every side of cell (1, {c}), over the table's own borders"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_in_a_cell_still_borders_its_paragraph() {
|
||||
let mut s = doc();
|
||||
borders(&mut s, "all");
|
||||
assert!(para_borders(&s), "without whole cells selected, the paragraph is bordered as before");
|
||||
assert_eq!(table(&s).rows[0].cells[0].props.borders, None);
|
||||
}
|
||||
|
||||
/// A line the table's style draws counts as shown: the first press of one side takes it off,
|
||||
/// from the cells along the edge and the ones beyond it, and the second puts it back.
|
||||
#[test]
|
||||
fn one_side_takes_off_a_line_the_table_style_draws() {
|
||||
let mut s = doc();
|
||||
assert!(table(&s).rows[1].cells.iter().all(|c| c.props.borders.is_none()), "no cell has borders of its own");
|
||||
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "Table Grid draws the middle row's bottom line");
|
||||
select(&mut s, (1, 1), (0, 2));
|
||||
borders(&mut s, "bottom");
|
||||
for c in 0..3 {
|
||||
assert!(!drawn(&s, 1, c)[2] && !drawn(&s, 2, c)[0], "the first press takes the line off cell (1, {c})");
|
||||
assert!(drawn(&s, 1, c)[0], "the other sides keep the style's lines, cell (1, {c})");
|
||||
}
|
||||
borders(&mut s, "bottom");
|
||||
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "the second press puts it back");
|
||||
}
|
||||
|
||||
/// A column whose middle row skips it (`w:gridBefore`) is two blocks of cells: the cells above
|
||||
/// and below the gap face it with an outer edge, not an inside one.
|
||||
#[test]
|
||||
fn a_column_with_a_skipped_middle_cell_has_outer_edges_at_the_gap() {
|
||||
let mut s = doc();
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[1].cells.remove(0);
|
||||
tb.rows[1].props.grid_before = 1;
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "none");
|
||||
// The first grid column: cells (0, 0) and (2, 0); the middle row has no cell there.
|
||||
select(&mut s, (0, 2), (0, 0));
|
||||
borders(&mut s, "outside");
|
||||
assert_eq!(shown(&s, 0, 0), [true; 4], "Outside draws the bottom of the cell above the gap");
|
||||
assert_eq!(shown(&s, 2, 0), [true; 4], "and the top of the cell below it");
|
||||
borders(&mut s, "none");
|
||||
borders(&mut s, "inside");
|
||||
assert_eq!(shown(&s, 0, 0), [false; 4], "Inside has no line between cells that don't meet");
|
||||
assert_eq!(shown(&s, 2, 0), [false; 4]);
|
||||
}
|
||||
|
||||
/// A line drawn along only part of an edge isn't shown along it: the press completes it. Here
|
||||
/// the selected cell spans the three cells below it, and only the first of them draws its top.
|
||||
#[test]
|
||||
fn one_side_completes_a_line_drawn_along_part_of_the_edge() {
|
||||
let mut s = doc();
|
||||
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
|
||||
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[0].cells.truncate(1);
|
||||
tb.rows[0].cells[0].props.span = 3;
|
||||
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
|
||||
for (c, cell) in tb.rows[1].cells.iter_mut().enumerate() {
|
||||
cell.props.borders = Some(Borders { top: Some(if c == 0 { line } else { nil }), ..Default::default() });
|
||||
}
|
||||
select(&mut s, (0, 0), (0, 2));
|
||||
borders(&mut s, "bottom");
|
||||
assert!(drawn(&s, 0, 0)[2], "the line goes all along the selected cell's bottom");
|
||||
assert!((0..3).all(|c| drawn(&s, 1, c)[0]), "and along the tops of the cells below");
|
||||
}
|
||||
|
||||
/// A cell merged over two rows is one cell: selected from its first row, No Border clears its
|
||||
/// outline in the second row too.
|
||||
#[test]
|
||||
fn no_border_clears_all_of_a_vertically_merged_cell() {
|
||||
use wordcraft_doc::props::VMerge;
|
||||
let mut s = doc();
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[0].cells[1].props.vmerge = VMerge::Restart;
|
||||
tb.rows[1].cells[1].props.vmerge = VMerge::Continue;
|
||||
s.run("table.selectTable", &json!({})).unwrap();
|
||||
borders(&mut s, "all");
|
||||
// The merged cell, as selecting it from its first row selects it.
|
||||
select(&mut s, (0, 0), (1, 1));
|
||||
borders(&mut s, "none");
|
||||
assert_eq!(shown(&s, 0, 1), [false; 4]);
|
||||
assert_eq!(shown(&s, 1, 1), [false; 4], "the merged cell's second row keeps no line");
|
||||
assert!(shown(&s, 1, 0)[1] && shown(&s, 2, 1)[2], "the cells around it keep their other lines");
|
||||
}
|
||||
|
||||
/// The cells below draw a line along only part of the edge when their row skips the rest of its
|
||||
/// columns (`w:gridAfter`): the press completes it.
|
||||
#[test]
|
||||
fn one_side_completes_a_line_over_a_row_that_skips_columns() {
|
||||
let mut s = doc();
|
||||
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
|
||||
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
|
||||
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
tb.rows[0].cells.truncate(1);
|
||||
tb.rows[0].cells[0].props.span = 3;
|
||||
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
|
||||
tb.rows[1].cells.truncate(1);
|
||||
tb.rows[1].props.grid_after = 2;
|
||||
tb.rows[1].cells[0].props.borders = Some(Borders { top: Some(line), ..Default::default() });
|
||||
select(&mut s, (0, 0), (0, 2));
|
||||
borders(&mut s, "bottom");
|
||||
assert!(drawn(&s, 0, 0)[2], "the selected cell's bottom gets the line all along it");
|
||||
}
|
||||
@@ -429,6 +429,7 @@ fn tracked_separator_session(slot: Slot) -> Session {
|
||||
author: "Alice".into(),
|
||||
date: String::new(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let props = wordcraft_doc::CharProps { ins: Some(0), ..Default::default() };
|
||||
let p = wordcraft_doc::Paragraph::with_text("SEP", props);
|
||||
|
||||
@@ -2362,6 +2362,102 @@ fn shift_right_at_the_end_of_a_cell_selects_the_cell_first() {
|
||||
assert_eq!(shift_right(&mut s), Some(((1, 1), (0, 0))));
|
||||
}
|
||||
|
||||
/// Left or Right as the canvas sends it: while an equation is edited the arrows move inside it
|
||||
/// (`equation.move`, as ui-egui's `equation_key` does); otherwise they run the command bound to the
|
||||
/// key, with Shift extending the selection.
|
||||
fn arrow(s: &mut Session, key: &str) {
|
||||
if s.math.is_some() {
|
||||
run(s, "equation.move", json!({"dir": if key == "Left" { "left" } else { "right" }}));
|
||||
return;
|
||||
}
|
||||
let (key, extend) = key.strip_prefix("Shift+").map_or((key, false), |k| (k, true));
|
||||
let id = s.registry.by_shortcut(key).map(|c| c.id).unwrap_or_else(|| panic!("nothing bound to {key}"));
|
||||
run(s, id, if extend { json!({"extend": true}) } else { json!({}) });
|
||||
}
|
||||
|
||||
/// The equation being edited and the caret in it.
|
||||
fn editing(s: &Session) -> Option<(Pos, wordcraft_doc::math_edit::MathPos)> {
|
||||
s.math.as_ref().map(|m| (m.at.clone(), m.pos.clone()))
|
||||
}
|
||||
|
||||
/// Presses `key` until the caret is out of the equation (at most 10 times).
|
||||
fn arrow_out(s: &mut Session, key: &str) {
|
||||
for _ in 0..10 {
|
||||
if s.math.is_none() {
|
||||
return;
|
||||
}
|
||||
arrow(s, key);
|
||||
}
|
||||
panic!("{key} didn't leave the equation");
|
||||
}
|
||||
|
||||
/// "a", an equation `x+y`, "b"; or with `n` equations side by side.
|
||||
fn equations_between_a_and_b(n: usize) -> Session {
|
||||
let mut s = typed("ab");
|
||||
for _ in 0..n {
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_and_right_keys_step_into_and_out_of_an_equation() {
|
||||
use wordcraft_doc::math_edit::{MathPos, units};
|
||||
let e = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y")));
|
||||
let mut s = equations_between_a_and_b(1);
|
||||
// Right from "a|" opens the equation at its start; leaving it past its end puts the caret
|
||||
// after it, so the next Right goes on over "b".
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!(editing(&s), Some((Pos::body(0, 1), MathPos::default())));
|
||||
arrow_out(&mut s, "Right");
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1 + e));
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 2 + e)));
|
||||
// Left over "b", then into the equation at its end; out past its start, then on over "a".
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 1 + e)));
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!(editing(&s), Some((Pos::body(0, 1), end)));
|
||||
arrow_out(&mut s, "Left");
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1));
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!((editing(&s), s.sel.focus.clone()), (None, Pos::body(0, 0)));
|
||||
// Shift+Right selects over the equation as one character, as before.
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
arrow(&mut s, "Shift+Right");
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1 + e)));
|
||||
// With text selected, Left and Right only collapse the selection, even when its moving end is
|
||||
// next to the equation.
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
|
||||
arrow(&mut s, "Shift+Right");
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
|
||||
let e = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let mut s = equations_between_a_and_b(2);
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 1)}));
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1)), "into the first one");
|
||||
arrow_out(&mut s, "Right");
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1 + e), "between the two equations");
|
||||
arrow(&mut s, "Right");
|
||||
assert_eq!(editing(&s), Some((Pos::body(0, 1 + e), wordcraft_doc::math_edit::MathPos::default())), "into the second one");
|
||||
arrow_out(&mut s, "Right");
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1 + e)), "Left goes back into the second one");
|
||||
arrow_out(&mut s, "Left");
|
||||
arrow(&mut s, "Left");
|
||||
assert_eq!(editing(&s).map(|(at, _)| at), Some(Pos::body(0, 1)), "then into the first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_initial_capitals_are_corrected() {
|
||||
let s = typed("the WOrd and THe end, not IDs or CDs. TV is fine ");
|
||||
@@ -3320,13 +3416,22 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "İNgilizce ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
|
||||
// #3503: two initial capitals and caps-lock with a stray İ in English.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "Wİrd ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "wİRD ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
|
||||
}
|
||||
|
||||
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
|
||||
/// each run's own language; other languages keep the Unicode default.
|
||||
#[test]
|
||||
fn change_case_follows_turkic_case_mapping() {
|
||||
for tag in ["tr-TR", "az-AZ"] {
|
||||
for tag in ["tr-TR", "az-AZ", "crh"] {
|
||||
for (mode, input, want) in [
|
||||
("upper", "istanbul", "İSTANBUL"),
|
||||
("lower", "IŞIK", "ışık"),
|
||||
@@ -3539,6 +3644,77 @@ fn typing_over_backward_selection_keeps_its_font() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `One`, a picture (floating with Square wrapping when `floating`), `Two`; the picture selected,
|
||||
/// right to left when floating.
|
||||
fn picture_between_paragraphs(floating: bool) -> Session {
|
||||
let mut s = s();
|
||||
typ(&mut s, "One\n");
|
||||
run(&mut s, "insert.picture", json!({"data": crate::cmd::insert::base64_encode(&crate::tests::tiny_png()), "width": 50}));
|
||||
typ(&mut s, "\nTwo");
|
||||
let pic = Pos::body(1, 0);
|
||||
let end = Pos { off: pic.off + wordcraft_doc::para::OBJ.len_utf8(), ..pic.clone() };
|
||||
run(&mut s, "select.range", json!({"anchor": pic, "focus": end}));
|
||||
if floating {
|
||||
run(&mut s, "arrange.wrap", json!({"wrap": "square"}));
|
||||
s.sel = crate::Selection { anchor: s.sel.focus.clone(), focus: s.sel.anchor.clone() };
|
||||
}
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_some_and(|(_, o)| o.is_floating() == floating));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_on_a_selected_picture_does_nothing() {
|
||||
// Word for Mac: with a picture selected, inline or floating, Enter (any number of times)
|
||||
// leaves it alone (#4126).
|
||||
for floating in [false, true] {
|
||||
let mut s = picture_between_paragraphs(floating);
|
||||
let (doc, sel) = (s.doc.clone(), s.sel.clone());
|
||||
typ(&mut s, "\n\n\n");
|
||||
assert_eq!(s.doc, doc, "the picture and the paragraphs stay as they were (floating: {floating})");
|
||||
assert_eq!(s.sel, sel, "the picture stays selected (floating: {floating})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_break_on_a_selected_picture_goes_in_front_of_it() {
|
||||
// Word for Mac: Shift+Enter or a page break on a selected picture puts the break in front of
|
||||
// it (an inline picture moves down a line or to the next page; a floating one's anchor does)
|
||||
// and keeps it selected (#4126). A column break is treated the same way.
|
||||
use wordcraft_doc::para::{COLUMN_BREAK, OBJ, PAGE_BREAK};
|
||||
for (id, c) in [("text.lineBreak", '\n'), ("text.pageBreak", PAGE_BREAK), ("text.columnBreak", COLUMN_BREAK)] {
|
||||
for floating in [false, true] {
|
||||
let mut s = picture_between_paragraphs(floating);
|
||||
let (doc, sel) = (s.doc.clone(), s.sel.clone());
|
||||
let (at, before) = crate::cmd::objects::object_selection(&s).map(|(p, o)| (p, o.clone())).unwrap();
|
||||
run(&mut s, id, json!({}));
|
||||
run(&mut s, id, json!({}));
|
||||
let text: Vec<_> = paras(&s).into_iter().map(|p| p.0).collect();
|
||||
assert_eq!(text, ["One".to_string(), format!("{c}{c}{OBJ}"), "Two".to_string()], "{id}, floating: {floating}");
|
||||
let (pos, o) = crate::cmd::objects::object_selection(&s).expect("the picture stays selected");
|
||||
assert_eq!((pos.off, o), (at.off + 2 * c.len_utf8(), &before), "{id}, floating: {floating}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((&s.doc, &s.sel), (&doc, &sel), "{id}, floating: {floating}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_break_on_a_picture_in_a_picture_control_keeps_the_picture_selected() {
|
||||
// The break goes in front of the control, and the picture (not the control's start) stays
|
||||
// selected (#4126).
|
||||
let mut s = picture_between_paragraphs(false);
|
||||
run(&mut s, "developer.picture", json!({}));
|
||||
let obj = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let pic = Pos::body(1, obj);
|
||||
run(&mut s, "select.range", json!({"anchor": pic, "focus": Pos { off: obj * 2, ..pic.clone() }}));
|
||||
let before = crate::cmd::objects::object_selection(&s).map(|(_, o)| o.clone()).expect("the picture is selected");
|
||||
run(&mut s, "text.lineBreak", json!({}));
|
||||
assert!(paras(&s)[1].0.starts_with('\n'), "{:?}", paras(&s)[1].0);
|
||||
let (_, o) = crate::cmd::objects::object_selection(&s).expect("the picture stays selected");
|
||||
assert_eq!(o, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_arrow_moves_through_a_ligature_one_letter_at_a_time() {
|
||||
// A font that draws "ffi" as one glyph (bundled, so the test doesn't depend on the installed
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! A value chosen in a content control in place of its placeholder (a list entry, a date, a check
|
||||
//! box's mark) takes the control's own run properties (`w:sdtPr/w:rPr`, ECMA-376 Part 1
|
||||
//! §17.5.2.27), as typed text does (#3116). Packages are hand-written: the controls WordCraft
|
||||
//! inserts carry no run properties.
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::props::CharProps;
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_engine::io::{open_bytes, save_bytes};
|
||||
|
||||
const W: &str =
|
||||
r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml""#;
|
||||
const RELS: &str = r#"xmlns="http://schemas.openxmlformats.org/package/2006/relationships""#;
|
||||
const TYPE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
|
||||
/// Opens a package with `body` and a grey Placeholder Text character style.
|
||||
fn open(body: &str) -> wordcraft_doc::Document {
|
||||
let styles = r#"<w:style w:type="character" w:styleId="PlaceholderText"><w:name w:val="Placeholder Text"/><w:rPr><w:color w:val="808080"/></w:rPr></w:style>"#;
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for (name, value) in [
|
||||
(
|
||||
"_rels/.rels",
|
||||
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/officeDocument" Target="word/document.xml"/></Relationships>"#),
|
||||
),
|
||||
(
|
||||
"word/_rels/document.xml.rels",
|
||||
format!(r#"<Relationships {RELS}><Relationship Id="rId1" Type="{TYPE}/styles" Target="styles.xml"/></Relationships>"#),
|
||||
),
|
||||
("word/document.xml", format!(r#"<w:document {W}><w:body>{body}</w:body></w:document>"#)),
|
||||
("word/styles.xml", format!(r#"<w:styles {W}>{styles}</w:styles>"#)),
|
||||
] {
|
||||
zip.add(name, value.as_bytes(), craft_zip::Compression::Deflated).unwrap();
|
||||
}
|
||||
open_bytes("form.docx", &zip.finish().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// A paragraph holding a control of `kind` (its `w:sdtPr` type element) tagged `tag`. Its
|
||||
/// placeholder is grey and boxed; its run properties ask for blue Source Serif 4 at 14 pt.
|
||||
fn control(tag: &str, kind: &str) -> String {
|
||||
let own = r#"<w:rPr><w:rFonts w:ascii="Source Serif 4" w:hAnsi="Source Serif 4"/><w:color w:val="1F4E79"/><w:sz w:val="28"/></w:rPr>"#;
|
||||
let shown =
|
||||
r#"<w:rPr><w:rStyle w:val="PlaceholderText"/><w:color w:val="808080"/><w:bdr w:val="single" w:sz="4" w:space="0" w:color="808080"/></w:rPr>"#;
|
||||
format!(
|
||||
r#"<w:p><w:sdt><w:sdtPr>{own}<w:tag w:val="{tag}"/><w:showingPlcHdr/>{kind}</w:sdtPr><w:sdtContent><w:r>{shown}<w:t>Choose</w:t></w:r></w:sdtContent></w:sdt></w:p>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// The formatting of the control's first character, and the control's own run properties.
|
||||
fn formatting(d: &wordcraft_doc::Document, tag: &str) -> (CharProps, CharProps) {
|
||||
let r = d.control_ranges(StoryRef::Body).into_iter().find(|r| r.control.tag == tag).unwrap();
|
||||
let at = r.content_start();
|
||||
(d.para_at(&at).unwrap().props_of_char(at.off).clone(), r.control.run_props.clone().unwrap())
|
||||
}
|
||||
|
||||
/// What shows of a run's formatting here: colour, font, size and box.
|
||||
fn look(p: &CharProps) -> impl PartialEq + std::fmt::Debug {
|
||||
(p.color, p.font.clone(), p.size, p.border)
|
||||
}
|
||||
|
||||
/// A list entry, a date or a check box's mark chosen in place of the placeholder takes the
|
||||
/// control's run properties, as typed text does; it kept the placeholder's grey and box. A saved
|
||||
/// file keeps the value's formatting.
|
||||
#[test]
|
||||
fn choosing_over_a_placeholder_takes_the_controls_formatting() {
|
||||
let entries = r#"<w:listItem w:displayText="Small" w:value="S"/><w:listItem w:displayText="Large" w:value="L"/>"#;
|
||||
let choices = [
|
||||
("size", format!("<w:dropDownList>{entries}</w:dropDownList>"), "developer.chooseItem", json!({"control": "size", "index": 1})),
|
||||
(
|
||||
"due",
|
||||
r#"<w:date><w:dateFormat w:val="d MMMM yyyy"/></w:date>"#.into(),
|
||||
"developer.setDate",
|
||||
json!({"control": "due", "date": "2026-12-01"}),
|
||||
),
|
||||
("ok", r#"<w14:checkbox><w14:checked w14:val="0"/></w14:checkbox>"#.into(), "developer.toggleCheckBox", json!({"control": "ok"})),
|
||||
];
|
||||
let body: String = choices.iter().map(|(tag, kind, ..)| control(tag, kind)).collect();
|
||||
let mut s = Session::new(open(&body));
|
||||
for (tag, _, command, params) in &choices {
|
||||
let (placeholder, own) = formatting(&s.doc, tag);
|
||||
assert_ne!(look(&placeholder), look(&own), "{tag}: the placeholder is formatted apart from its control");
|
||||
s.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}"));
|
||||
assert_eq!(look(&formatting(&s.doc, tag).0), look(&own), "{tag}: {command} gives the control's run properties");
|
||||
}
|
||||
let saved = open_bytes("form.docx", &save_bytes("form.docx", &s.doc).unwrap()).unwrap();
|
||||
for (tag, ..) in &choices {
|
||||
let (value, own) = formatting(&saved, tag);
|
||||
assert_eq!(look(&value), look(&own), "{tag}: the saved value keeps the control's run properties");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod comment_ids;
|
||||
mod content_controls;
|
||||
mod date_fields;
|
||||
mod macro_packages;
|
||||
mod odt_charts;
|
||||
|
||||
@@ -63,6 +63,8 @@ pub struct FontDb {
|
||||
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
run_style_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock<Vec<CatalogEntry>>,
|
||||
/// Fonts the user added at run time, and the folder they are stored in (#582).
|
||||
@@ -133,6 +135,8 @@ impl FontDb {
|
||||
diagram_search_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
run_style_hook: Mutex::new(None),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
user: RwLock::new(user::UserFonts::default()),
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::face::{FALLBACK_FAMILY, FontFace};
|
||||
use super::fallback_data::{
|
||||
BALLOT_BOXES, DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block,
|
||||
fallback_order,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
|
||||
use super::fallback_data::{
|
||||
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
|
||||
};
|
||||
use super::{Arc, FontDb};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{HashMap, Ordering};
|
||||
@@ -28,7 +29,11 @@ impl FontDb {
|
||||
_ => "Italic",
|
||||
};
|
||||
let styled = self.face(&base.family, style);
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, &[c]) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
base
|
||||
})
|
||||
}
|
||||
|
||||
/// The fallback search, cached per (character, excluded face) until loaded faces or font
|
||||
@@ -70,6 +75,9 @@ impl FontDb {
|
||||
if let Some(face) = self.circle_fallback(c, exclude) {
|
||||
return (Some(face), self.read_faces().len());
|
||||
}
|
||||
if let Some((face, n)) = self.ballot_box_fallback(c, exclude) {
|
||||
return (Some(face), n);
|
||||
}
|
||||
let (found, n) = self.loaded_fallback(c, exclude);
|
||||
if found.is_some() {
|
||||
return (found, n);
|
||||
@@ -97,6 +105,38 @@ impl FontDb {
|
||||
find()
|
||||
}
|
||||
|
||||
/// A ballot box (☐ ☑ ☒, a check box's symbols) the face lacks: the first of the symbol faces
|
||||
/// ([`crate::word::SYMBOL`], in that order) that has all three, so a check box looks the same
|
||||
/// ticked and unticked (#7863). The UI fallback has ☐, drawn with a drop shadow, and ☑ but no
|
||||
/// ☒, which put a box's two states in different fonts. `None` when no listed face has all
|
||||
/// three: the ordinary fallback then. With the face, the number of loaded faces before the
|
||||
/// search: a face loaded during it (by it, or by another thread for a family it had passed)
|
||||
/// leaves that number behind, so the answer isn't cached for the new face list.
|
||||
fn ballot_box_fallback(&self, c: char, exclude: u32) -> Option<(Arc<FontFace>, usize)> {
|
||||
if !BALLOT_BOXES.contains(&c) {
|
||||
return None;
|
||||
}
|
||||
let n = self.read_faces().len();
|
||||
let all = |f: &Arc<FontFace>| f.id != exclude && BALLOT_BOXES.iter().all(|b| f.covers(*b));
|
||||
for family in crate::word::SYMBOL {
|
||||
if let Some(face) = self.find(family, "Regular").filter(all) {
|
||||
return Some((face, n));
|
||||
}
|
||||
// An installed family is loaded only when its files map all three.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let enabled = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled;
|
||||
if enabled && !self.is_loaded(family) && BALLOT_BOXES.iter().all(|b| self.family_maps(family, *b)) {
|
||||
self.load_cataloged(family);
|
||||
if let Some(face) = self.find(family, "Regular").filter(all) {
|
||||
return Some((face, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// [`Self::search_fallback`] when no loaded face covers `c`: load a system font that does,
|
||||
/// one search at a time.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -199,8 +239,13 @@ impl FontDb {
|
||||
|
||||
/// The face for a run, and the number of loaded faces the search last chose from.
|
||||
fn search_run(&self, chars: &[char], exclude: u32, bold: bool, italic: bool) -> (Option<Arc<FontFace>>, usize) {
|
||||
// A run of ballot boxes draws in their one face, as each of them alone does (#7863).
|
||||
let ballot = chars.first().filter(|_| chars.iter().all(|c| BALLOT_BOXES.contains(c))).and_then(|c| self.ballot_box_fallback(*c, exclude));
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let (mut base, mut checked) = self.loaded_covering(chars, exclude);
|
||||
let (mut base, mut checked) = match ballot {
|
||||
Some((face, n)) => (Some(face), n),
|
||||
None => self.loaded_covering(chars, exclude),
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if base.is_none() {
|
||||
// A character no loaded face covers: load a system font for it, then retry (the run's
|
||||
@@ -235,12 +280,16 @@ impl FontDb {
|
||||
(true, false) => "Bold",
|
||||
_ => "Italic",
|
||||
};
|
||||
let before_style = self.read_faces().len();
|
||||
// The count stays the one `base` was chosen from. `base` is loaded, so the style lookup
|
||||
// only picks among the family's loaded faces and loads nothing: a later count could only
|
||||
// take in a face another thread loaded meanwhile, and cache this answer for faces it never
|
||||
// saw (#7863).
|
||||
let styled = self.face(&base.family, style);
|
||||
if before_style == checked {
|
||||
checked = self.read_faces().len();
|
||||
#[cfg(test)]
|
||||
if let Some(hook) = self.run_style_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
|
||||
hook(self);
|
||||
}
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && styled_covers(&styled, &base, chars) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
base
|
||||
@@ -557,3 +606,11 @@ impl FontDb {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Can `styled`, a bold or italic face of `base`'s family, draw `chars` in its place? It must map
|
||||
/// them all, and all three ballot boxes when they are ballot boxes and `base` has all three, so a
|
||||
/// check box's states stay in one face in bold or italic text too (#7863).
|
||||
fn styled_covers(styled: &FontFace, base: &FontFace, chars: &[char]) -> bool {
|
||||
let boxes = chars.iter().all(|c| BALLOT_BOXES.contains(c)) && BALLOT_BOXES.iter().all(|b| base.covers(*b));
|
||||
chars.iter().chain(BALLOT_BOXES.iter().filter(|_| boxes)).all(|c| styled.covers(*c))
|
||||
}
|
||||
|
||||
@@ -242,6 +242,9 @@ pub const RTL_FALLBACKS: &[&str] = &[
|
||||
pub const RTL_FALLBACKS: &[&str] =
|
||||
&["Noto Naskh Arabic", "Noto Sans Arabic", "Noto Sans Hebrew", "Vazirmatn", "Segoe UI", "Arial", "Tahoma", "DejaVu Sans"];
|
||||
|
||||
/// The ballot boxes ☐ ☑ ☒: a check box's unchecked symbol and its two usual checked ones.
|
||||
pub(super) const BALLOT_BOXES: [char; 3] = ['\u{2610}', '\u{2611}', '\u{2612}'];
|
||||
|
||||
/// Families tried (when installed) for characters the loaded fonts lack: CJK, symbols, emoji.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) const SYSTEM_FALLBACKS: &[&str] = &[
|
||||
|
||||
@@ -866,6 +866,130 @@ fn circle_checks_face_coverage() {
|
||||
assert_eq!(db.fallback_for('●', primary.id()).unwrap().family, FALLBACK_FAMILY);
|
||||
}
|
||||
|
||||
/// A bundled Source Sans 3 Regular named `family` that maps ☒ (U+2612) too: its ☐–☑ cmap group
|
||||
/// runs on one character further (the next group starts at U+2615, so the groups stay sorted).
|
||||
fn with_every_ballot_box(family: &str) -> Vec<u8> {
|
||||
let mut data = named_face("SourceSans3-Regular.ttf", family);
|
||||
let (from, to) = ([0x2610_u32, 0x2611].map(u32::to_be_bytes).concat(), [0x2610_u32, 0x2612].map(u32::to_be_bytes).concat());
|
||||
let mut patched = 0;
|
||||
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
|
||||
data[at..at + to.len()].copy_from_slice(&to);
|
||||
patched += 1;
|
||||
}
|
||||
assert!(patched > 0);
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_draws_every_state_in_one_face() {
|
||||
// #7863: with the check box's font missing, ☐ and ☑ came from the UI fallback, which has no
|
||||
// ☒, and ☒ from another face, so ticking a box changed how it looked.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
assert!(!primary.covers('☐'), "the requested face lacks the boxes");
|
||||
// A listed symbol face with ☐ and ☑ only, then a later one with all three.
|
||||
db.add_document_fonts(vec![
|
||||
(named_face("SourceSerif4-Regular.ttf", "Apple Symbols"), "Apple Symbols".to_string()),
|
||||
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
]);
|
||||
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").id()).collect();
|
||||
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
|
||||
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), false, false).expect("a face has them");
|
||||
assert_eq!(run.id(), faces[0], "a run of them takes the same face");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_check_box_draws_every_state_in_one_face() {
|
||||
// The listed family's Regular face has all three boxes and its Bold face only ☐ and ☑: bold ☐
|
||||
// and ☑ took the Bold face, and ☒ the Regular one.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.add_document_fonts(vec![
|
||||
(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
(named_face("SourceSans3-Bold.ttf", "DejaVu Sans"), "DejaVu Sans".to_string()),
|
||||
]);
|
||||
let faces: Vec<u32> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").id()).collect();
|
||||
assert!(faces.iter().all(|f| *f == faces[0]), "one face for every state: {faces:?}");
|
||||
let run = db.fallback_for_run(&['☐', '☑'], primary.id(), true, false).expect("a face has them");
|
||||
assert_eq!(run.id(), faces[0], "a bold run of them takes the same face");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ballot_boxes_load_an_installed_symbol_face() {
|
||||
let dir = font_dir("ballot-boxes");
|
||||
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("DejaVu Sans")).unwrap();
|
||||
// An earlier listed family with only two of the boxes: never loaded for them.
|
||||
std::fs::write(dir.join("TwoBoxes-Regular.ttf"), named_face("SourceSerif4-Regular.ttf", "Apple Symbols")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.set_system_fallback(false);
|
||||
assert!(db.fallback_for('☐', primary.id()).is_some());
|
||||
assert!(!db.is_loaded("DejaVu Sans"), "nothing is loaded with the system fallback off");
|
||||
db.set_system_fallback(true);
|
||||
let found = db.fallback_for('☐', primary.id()).unwrap();
|
||||
assert_eq!(found.family, "DejaVu Sans", "the installed face with all three");
|
||||
assert_eq!(db.fallback_for('☒', primary.id()).unwrap().id(), found.id());
|
||||
assert!(!db.is_loaded("Apple Symbols"), "a listed family without all three is not loaded");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_check_box_keeps_one_face_when_a_symbol_face_loads_during_its_search() {
|
||||
// A search for ☐ passed Apple Symbols, not loaded yet, and was loading the installed Segoe UI
|
||||
// Symbol when another thread loaded Apple Symbols. Its answer was remembered for the face count
|
||||
// after both loads, so ☐ kept Segoe UI Symbol while ☑ and ☒ took Apple Symbols, the first
|
||||
// listed face with all three.
|
||||
let dir = font_dir("ballot-box-race");
|
||||
std::fs::write(dir.join("Symbols-Regular.ttf"), with_every_ballot_box("Segoe UI Symbol")).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
let reads = || db.coverage.lock().unwrap().reads;
|
||||
let unread = reads();
|
||||
let loading = db.loading.lock().unwrap();
|
||||
std::thread::scope(|s| {
|
||||
let search = s.spawn(|| db.fallback_for('☐', primary.id()));
|
||||
// Past Apple Symbols, the search reads the installed file's character map, then waits for
|
||||
// `loading` to load the file. (A search that finishes without reading it ends the wait too.)
|
||||
while reads() == unread && !search.is_finished() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Another thread loads Apple Symbols meanwhile, as a font load adds faces (`loading` is
|
||||
// held here).
|
||||
db.add_fonts(vec![(with_every_ballot_box("Apple Symbols"), None)]);
|
||||
drop(loading);
|
||||
assert!(search.join().unwrap().is_some());
|
||||
});
|
||||
let faces: Vec<String> = ['☐', '☑', '☒'].iter().map(|c| db.fallback_for(*c, primary.id()).expect("a face has it").family.clone()).collect();
|
||||
assert_eq!(faces, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_run_of_check_boxes_keeps_one_face_when_a_symbol_face_loads_during_its_style_lookup() {
|
||||
// A bold run of boxes chose DejaVu Sans, the first listed face loaded with all three, and
|
||||
// looked up its bold face while another thread loaded Apple Symbols, listed earlier. The run's
|
||||
// answer was remembered for the face count after that load, so the run kept DejaVu Sans while
|
||||
// each box alone took Apple Symbols.
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
let primary = db.face("Inter", "Regular");
|
||||
db.add_document_fonts(vec![(with_every_ballot_box("DejaVu Sans"), "DejaVu Sans".to_string())]);
|
||||
let apple = with_every_ballot_box("Apple Symbols");
|
||||
*db.run_style_hook.lock().unwrap() = Some(Box::new(move |db| {
|
||||
// A font load adds faces and leaves the generation as it is.
|
||||
db.add_fonts(vec![(apple, None)]);
|
||||
}));
|
||||
let run = ['☐', '☑', '☒'];
|
||||
assert!(db.fallback_for_run(&run, primary.id(), true, false).is_some());
|
||||
assert!(db.run_style_hook.lock().unwrap().is_none(), "Apple Symbols loaded during the run's style lookup");
|
||||
let boxes: Vec<String> = run.iter().map(|c| db.fallback_styled(*c, primary.id(), true, false).expect("a face has it").family.clone()).collect();
|
||||
assert_eq!(boxes, ["Apple Symbols"; 3], "the first listed face with all three, for every state");
|
||||
let again = db.fallback_for_run(&run, primary.id(), true, false).expect("a face has them");
|
||||
assert_eq!(again.family, "Apple Symbols", "the run takes the face each box takes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_postscript_names() {
|
||||
let dir = font_dir("postscript");
|
||||
|
||||
@@ -40,6 +40,11 @@ pub fn has_named_substitutes(family: &str) -> bool {
|
||||
|
||||
const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"];
|
||||
|
||||
/// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
|
||||
/// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
|
||||
/// A check box's ballot boxes take their face from this list too (`FontDb::fallback_for`, #7863).
|
||||
pub(crate) const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
|
||||
|
||||
/// Serif faces known by name with no open clone of their own (lowercase): they take the generic
|
||||
/// serif list, but as fonts we know, not by a guess from the name ([`has_own_substitutes`]).
|
||||
const KNOWN_SERIFS: &[&str] = &[
|
||||
@@ -75,9 +80,6 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
|
||||
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
|
||||
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
|
||||
// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
|
||||
// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
|
||||
const SYMBOL: &[&str] = &["Apple Symbols", "Segoe UI Symbol", "DejaVu Sans", "Noto Sans Symbols", "Noto Sans Symbols 2", "Source Sans 3"];
|
||||
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
|
||||
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
|
||||
// headings and screens. Open fonts with full Persian coverage first.
|
||||
|
||||
+14
-24
@@ -4,38 +4,28 @@ use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_html::doc::{ImageLoader, PAGE_FONT, css_len_pt, decode, decode_as, decode_entity, esc, export_flow, parse, parse_with, unescape};
|
||||
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
use crate::{from_shared, shared_section, to_shared};
|
||||
|
||||
pub fn import(html: &str) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import(html))
|
||||
}
|
||||
|
||||
pub fn import(html: &str) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import(html)).unwrap_or_default()
|
||||
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_page(html, images))
|
||||
}
|
||||
|
||||
pub fn import_page(html: &str, images: ImageLoader<'_>) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_page(html, images)).unwrap_or_default()
|
||||
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_with(html, images))
|
||||
}
|
||||
|
||||
pub fn import_with(html: &str, images: ImageLoader<'_>) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_with(html, images)).unwrap_or_default()
|
||||
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_html::doc::import_on(html, images, &shared_section(page)?))
|
||||
}
|
||||
|
||||
pub fn import_on(html: &str, images: ImageLoader<'_>, page: &SectionProps) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_html::doc::import_on(html, images, &shared_section(page))).unwrap_or_default()
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_html::doc::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_html::doc::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn export_fragment(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_html::doc::export_fragment(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
pub fn export_fragment(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_html::doc::export_fragment(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
@@ -4,23 +4,22 @@ use wordcraft_doc::{Document, SectionProps};
|
||||
|
||||
pub use craft_latex::{escape_text, latex_to_linear, linear_to_latex};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_latex::import(bytes)).unwrap_or_default()
|
||||
use crate::{from_shared, to_shared};
|
||||
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
from_shared(craft_latex::import(bytes))
|
||||
}
|
||||
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
let mut d = import(bytes);
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let mut d = import(bytes)?;
|
||||
d.last_section = page.clone();
|
||||
d
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> craft_flow::Flow {
|
||||
craft_latex::parse(text)
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_latex::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_latex::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
+39
-15
@@ -28,6 +28,27 @@ use wordcraft_doc::Document;
|
||||
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
|
||||
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
|
||||
|
||||
/// The document as the shared model the format crates read and write.
|
||||
///
|
||||
/// A conversion that fails is an error, never an empty document or an empty file: the caller
|
||||
/// says so instead of writing a file with nothing in it.
|
||||
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
|
||||
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The shared model as the app's document model. A conversion that fails is an error, never
|
||||
/// an empty document.
|
||||
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
|
||||
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The page a file that gives no page size starts on, as the shared model.
|
||||
pub(crate) fn shared_section(page: &wordcraft_doc::SectionProps) -> Result<craft_wordmodel::SectionProps, String> {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
Ok(to_shared(&d)?.last_section)
|
||||
}
|
||||
|
||||
/// Extensions this crate handles.
|
||||
pub const EXTENSIONS: &[&str] =
|
||||
&["txt", "text", "md", "markdown", "html", "htm", "xhtml", "mht", "mhtml", "rtf", "odt", "ott", "fodt", "tex", "latex", "ltx"];
|
||||
@@ -35,15 +56,15 @@ pub const EXTENSIONS: &[&str] =
|
||||
/// Import `bytes` in the format named by `ext` (no dot, any case). `None` = not our format.
|
||||
pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let r = match ext.as_str() {
|
||||
let r: Result<Document, String> = match ext.as_str() {
|
||||
"txt" | "text" => Ok(txt::import(bytes)),
|
||||
"md" | "markdown" => Ok(markdown::import(&txt::decode(bytes))),
|
||||
"html" | "htm" | "xhtml" => Ok(html::import_page(&html::decode(bytes), &|_| None)),
|
||||
"mht" | "mhtml" => Ok(mht::import(bytes)),
|
||||
"md" | "markdown" => markdown::import(&txt::decode(bytes)),
|
||||
"html" | "htm" | "xhtml" => html::import_page(&html::decode(bytes), &|_| None),
|
||||
"mht" | "mhtml" => mht::import(bytes),
|
||||
"rtf" => rtf::import(bytes),
|
||||
"odt" | "ott" => odt::import(bytes),
|
||||
"fodt" => odt::import_flat(bytes),
|
||||
"tex" | "latex" | "ltx" => Ok(latex::import(bytes)),
|
||||
"tex" | "latex" | "ltx" => latex::import(bytes),
|
||||
_ => return None,
|
||||
};
|
||||
Some(r.map(|mut d| {
|
||||
@@ -57,33 +78,36 @@ pub fn import(ext: &str, bytes: &[u8]) -> Option<Result<Document, String>> {
|
||||
/// formats keep the page their file gives.
|
||||
pub fn import_on(ext: &str, bytes: &[u8], page: &wordcraft_doc::SectionProps) -> Option<Result<Document, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let mut doc = match ext.as_str() {
|
||||
let mut doc: Result<Document, String> = match ext.as_str() {
|
||||
"odt" | "ott" => return Some(odt::import_on(bytes, page)),
|
||||
"fodt" => return Some(odt::import_flat_on(bytes, page)),
|
||||
"txt" | "text" => txt::import_on(bytes, page),
|
||||
"txt" | "text" => Ok(txt::import_on(bytes, page)),
|
||||
"md" | "markdown" => markdown::import_on(&txt::decode(bytes), page),
|
||||
"html" | "htm" | "xhtml" => html::import_on(&html::decode(bytes), &|_| None, page),
|
||||
"mht" | "mhtml" => mht::import_on(bytes, page),
|
||||
_ => return import(&ext, bytes),
|
||||
};
|
||||
doc.ensure_nonempty();
|
||||
Some(Ok(doc))
|
||||
if let Ok(d) = doc.as_mut() {
|
||||
d.ensure_nonempty();
|
||||
}
|
||||
Some(doc)
|
||||
}
|
||||
|
||||
/// Export `doc` in the format named by `ext`. `None` = not our format.
|
||||
pub fn export(ext: &str, doc: &Document) -> Option<Result<Vec<u8>, String>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
let out: Result<Vec<u8>, String> = match ext.as_str() {
|
||||
"txt" | "text" => Ok(txt::export(doc)),
|
||||
"md" | "markdown" => Ok(markdown::export(doc).into_bytes()),
|
||||
"html" | "htm" | "xhtml" => Ok(html::export(doc).into_bytes()),
|
||||
"rtf" => Ok(rtf::export(doc).into_bytes()),
|
||||
"md" | "markdown" => markdown::export(doc).map(String::into_bytes),
|
||||
"html" | "htm" | "xhtml" => html::export(doc).map(String::into_bytes),
|
||||
"rtf" => rtf::export(doc).map(String::into_bytes),
|
||||
"odt" => odt::export(doc),
|
||||
"ott" => odt::export_template(doc),
|
||||
"fodt" => odt::export_flat(doc),
|
||||
"tex" | "latex" | "ltx" => Ok(latex::export(doc).into_bytes()),
|
||||
"tex" | "latex" | "ltx" => latex::export(doc).map(String::into_bytes),
|
||||
_ => return None,
|
||||
})
|
||||
};
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// How [`export_with`] writes a copy.
|
||||
|
||||
@@ -4,23 +4,19 @@ use wordcraft_doc::{Block, Document, SectionProps};
|
||||
|
||||
pub use craft_markdown::{Refs, escape, parse, parse_inlines};
|
||||
|
||||
fn shared_section(page: &SectionProps) -> craft_wordmodel::SectionProps {
|
||||
let mut d = Document::new();
|
||||
d.last_section = page.clone();
|
||||
wordcraft_docx::to_shared_model(&d).map(|s| s.last_section).unwrap_or_default()
|
||||
use crate::{from_shared, shared_section, to_shared};
|
||||
|
||||
pub fn import(text: &str) -> Result<Document, String> {
|
||||
from_shared(craft_markdown::import(text))
|
||||
}
|
||||
|
||||
pub fn import(text: &str) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_markdown::import(text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn import_on(text: &str, page: &SectionProps) -> Document {
|
||||
wordcraft_docx::from_shared_model(craft_markdown::import_on(text, &shared_section(page))).unwrap_or_default()
|
||||
pub fn import_on(text: &str, page: &SectionProps) -> Result<Document, String> {
|
||||
from_shared(craft_markdown::import_on(text, &shared_section(page)?))
|
||||
}
|
||||
|
||||
/// [`import_on`] returning the document and the 0-based starting line of each top-level block.
|
||||
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<usize>) {
|
||||
let doc = import_on(text, page);
|
||||
pub fn import_on_with_lines(text: &str, page: &SectionProps) -> Result<(Document, Vec<usize>), String> {
|
||||
let doc = import_on(text, page)?;
|
||||
let src_lines: Vec<&str> = text.strip_prefix('\u{FEFF}').unwrap_or(text).lines().collect();
|
||||
let mut out = Vec::with_capacity(doc.body.len());
|
||||
let mut cursor = 0usize;
|
||||
@@ -57,12 +53,9 @@ pub fn import_on_with_lines(text: &str, page: &SectionProps) -> (Document, Vec<u
|
||||
}
|
||||
out.push(found.min(src_lines.len()));
|
||||
}
|
||||
(doc, out)
|
||||
Ok((doc, out))
|
||||
}
|
||||
|
||||
pub fn export(doc: &Document) -> String {
|
||||
match wordcraft_docx::to_shared_model(doc) {
|
||||
Ok(shared) => craft_markdown::export(&shared),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
pub fn export(doc: &Document) -> Result<String, String> {
|
||||
Ok(craft_markdown::export(&to_shared(doc)?))
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn is_mht(bytes: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
/// Import an MHT file.
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
pub fn import(bytes: &[u8]) -> Result<Document, String> {
|
||||
import_on(bytes, &SectionProps::default())
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ fn part_bytes(part: &Part) -> &[u8] {
|
||||
}
|
||||
|
||||
/// [`import`] onto `page`.
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result<Document, String> {
|
||||
let msg = craft_mime::parse(bytes, &craft_mime::Limits::DEFAULT);
|
||||
let mut leaves = Vec::new();
|
||||
collect_leaves(&msg.root, &mut leaves);
|
||||
@@ -46,7 +46,7 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Document {
|
||||
.or_else(|| leaves.iter().copied().find(|p| matches!(p.declared_media_type(), Some("text/html" | "application/xhtml+xml"))));
|
||||
let Some(root) = root else {
|
||||
let text = leaves.iter().copied().find(|p| p.declared_media_type().unwrap_or("text/plain") == "text/plain").map(part_bytes).unwrap_or(&[]);
|
||||
return crate::txt::import_on(text, page);
|
||||
return Ok(crate::txt::import_on(text, page));
|
||||
};
|
||||
let html = crate::html::decode_as(part_bytes(root), root.content_type.get("charset"));
|
||||
let base = root.content_location().unwrap_or("");
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user