mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 22:59:18 +00:00
Compare commits
193
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c658b7a3ba | ||
|
|
d89f035219 | ||
|
|
860d728dfd | ||
|
|
0282a6124f | ||
|
|
3bb8a438b0 | ||
|
|
f333552fe5 | ||
|
|
63dbe61cda | ||
|
|
722ee1b60d | ||
|
|
53e426820a | ||
|
|
e77669a552 | ||
|
|
55ee6bfcb8 | ||
|
|
b6adce3262 | ||
|
|
68c94e9a2b | ||
|
|
ae713e05a8 | ||
|
|
b8ba467e54 | ||
|
|
71a3072fec | ||
|
|
25af5ed462 | ||
|
|
8a24807722 | ||
|
|
a269d3e13d | ||
|
|
b5d21f1ba9 | ||
|
|
8bda45fefa | ||
|
|
ba31d08b3f | ||
|
|
b6ced6363b | ||
|
|
bcaba5a37c | ||
|
|
e927cd7e8e | ||
|
|
f5930f52ca | ||
|
|
3c22bd688c | ||
|
|
777aae19e5 | ||
|
|
cc1f3231a7 | ||
|
|
d81b0b503e | ||
|
|
7460b7f916 | ||
|
|
538597a7ea | ||
|
|
58a3e6cf5b | ||
|
|
53c9e64e98 | ||
|
|
3ee43d57d2 | ||
|
|
6c3c3d181e | ||
|
|
5b4302828e | ||
|
|
08e21b1abc | ||
|
|
a188a76506 | ||
|
|
e219a5a9c3 | ||
|
|
7810b05973 | ||
|
|
89f0d39e7f | ||
|
|
946a626f5c | ||
|
|
9769b941c4 | ||
|
|
769a799620 | ||
|
|
0de7b3a5aa | ||
|
|
9f813636cf | ||
|
|
7e70097130 | ||
|
|
4cb1d22b0e | ||
|
|
d9b3a8eb9c | ||
|
|
3c73997925 | ||
|
|
d7748aa732 | ||
|
|
f5a9d415b8 | ||
|
|
a5b4b22ebf | ||
|
|
4f7d01edac | ||
|
|
5aa1a78082 | ||
|
|
9986d9b4cd | ||
|
|
dd017d865d | ||
|
|
393103ffdd | ||
|
|
c7661b2b0e | ||
|
|
20dd292da4 | ||
|
|
988cfaa5f1 | ||
|
|
0bd4878a34 | ||
|
|
737a19bbb0 | ||
|
|
c5f0865fa7 | ||
|
|
319838ab02 | ||
|
|
21b1ceb1c1 | ||
|
|
845df1cd48 | ||
|
|
0c9e6054d9 | ||
|
|
8f6a40d3f4 | ||
|
|
9ce63943af | ||
|
|
74ffe933cf | ||
|
|
306040b646 | ||
|
|
65960089a8 | ||
|
|
ec4922027f | ||
|
|
cb919da767 | ||
|
|
aadcc80cab | ||
|
|
6bf2ef18bb | ||
|
|
3b929eac31 | ||
|
|
a895098132 | ||
|
|
82887db8bb | ||
|
|
ac99969305 | ||
|
|
76b74dec50 | ||
|
|
2daca588a4 | ||
|
|
ae4f2dbf48 | ||
|
|
591a5ace12 | ||
|
|
f6d1207be2 | ||
|
|
77aab09d31 | ||
|
|
ee9a8153d3 | ||
|
|
5ad1be0472 | ||
|
|
ae876e0cdc | ||
|
|
f0b95f73fb | ||
|
|
4c8296a5b1 | ||
|
|
9b1ef01485 | ||
|
|
a46514f5df | ||
|
|
6af5d8c650 | ||
|
|
1e91f5cc1e | ||
|
|
bd9529b083 | ||
|
|
a7396929c7 | ||
|
|
42df428b01 | ||
|
|
fbb26d0b85 | ||
|
|
84a8675092 | ||
|
|
bfa3d12bfa | ||
|
|
e92a4d45f8 | ||
|
|
f4431d6b63 | ||
|
|
5203e2e7dc | ||
|
|
bdae1b73ae | ||
|
|
bdb955d2c6 | ||
|
|
d78467b616 | ||
|
|
069a69a5eb | ||
|
|
50f4b803a6 | ||
|
|
b81f67dfab | ||
|
|
ddcaffe387 | ||
|
|
11f830907d | ||
|
|
3512da9553 | ||
|
|
9a349bf372 | ||
|
|
16b7706a4d | ||
|
|
ffdc0c2332 | ||
|
|
d813e02661 | ||
|
|
b2c183fc8b | ||
|
|
f900ac06c2 | ||
|
|
4bc5b97c31 | ||
|
|
3f70941206 | ||
|
|
f1583c3417 | ||
|
|
f4f182b900 | ||
|
|
f966ceaa25 | ||
|
|
9b9dc5b103 | ||
|
|
2c70194a5b | ||
|
|
57bdc13e28 | ||
|
|
f302f189a6 | ||
|
|
a12799387d | ||
|
|
c3696df3d9 | ||
|
|
b6022a338c | ||
|
|
1e4c3d52de | ||
|
|
3c1ea66dd9 | ||
|
|
55992a696b | ||
|
|
eaec70d125 | ||
|
|
b4db8a407c | ||
|
|
4094828264 | ||
|
|
6f7afc6a5d | ||
|
|
c634f6c83e | ||
|
|
6cc86be260 | ||
|
|
f5d1d992a2 | ||
|
|
f550268bab | ||
|
|
b3c7338b3c | ||
|
|
31b7bd6a63 | ||
|
|
48fca374b3 | ||
|
|
5833546550 | ||
|
|
ead0870d33 | ||
|
|
6db58aa0c0 | ||
|
|
eff8661a58 | ||
|
|
acf8e9950d | ||
|
|
8a58d674b7 | ||
|
|
ef81c547af | ||
|
|
3d53abc13a | ||
|
|
2ee73a0d33 | ||
|
|
b4f129911d | ||
|
|
3ecce1f442 | ||
|
|
5d43bb5414 | ||
|
|
63f5623990 | ||
|
|
a830b61074 | ||
|
|
f0933342d4 | ||
|
|
b6a4fd1266 | ||
|
|
0a29a6d73a | ||
|
|
a29663bd95 | ||
|
|
a7e02482fe | ||
|
|
6e55462d5a | ||
|
|
6f6bf92576 | ||
|
|
b66f579e7b | ||
|
|
7df90b72cf | ||
|
|
117c098553 | ||
|
|
154982988a | ||
|
|
cf6d23c918 | ||
|
|
80eef0e4ac | ||
|
|
5e097aa288 | ||
|
|
417cc45a1c | ||
|
|
ff7d032da6 | ||
|
|
0aaef7a5bd | ||
|
|
be5fe3d36f | ||
|
|
f053740960 | ||
|
|
7581392111 | ||
|
|
04e8e61e82 | ||
|
|
bf95e83642 | ||
|
|
bec88fd149 | ||
|
|
1b34471bc8 | ||
|
|
44badab540 | ||
|
|
e209b4f6fd | ||
|
|
68de4560b5 | ||
|
|
b1c6aafc33 | ||
|
|
45299ba839 | ||
|
|
78ea592cf4 | ||
|
|
c1a20368dc | ||
|
|
32d4d32292 |
Generated
+97
-98
@@ -1173,7 +1173,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1224,7 +1224,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1236,7 +1236,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1244,7 +1244,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1269,12 +1269,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-keymap",
|
||||
"craft-theme",
|
||||
"craft-tracked",
|
||||
@@ -1288,7 +1287,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1306,12 +1305,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1319,7 +1318,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1328,12 +1327,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1341,7 +1340,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1361,7 +1360,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
@@ -1377,7 +1376,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1387,7 +1386,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1395,7 +1394,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1421,7 +1420,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
@@ -1438,7 +1437,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1446,7 +1445,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1466,7 +1465,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1485,7 +1484,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
@@ -1497,7 +1496,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
@@ -1507,7 +1506,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1517,7 +1516,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1532,7 +1531,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1551,7 +1550,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1560,7 +1559,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1583,7 +1582,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-subset"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"harfbuzz-subset-sys",
|
||||
@@ -1596,7 +1595,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-font-subset",
|
||||
]
|
||||
@@ -1604,7 +1603,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gpu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"egui-wgpu",
|
||||
"log",
|
||||
@@ -1616,7 +1615,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1629,7 +1628,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1642,7 +1641,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.1",
|
||||
@@ -1672,7 +1671,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1699,7 +1698,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1717,7 +1716,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1725,7 +1724,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1740,7 +1739,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
@@ -1751,7 +1750,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
@@ -1761,7 +1760,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"roxmltree",
|
||||
@@ -1771,7 +1770,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp-server"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1779,7 +1778,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1797,7 +1796,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
@@ -1809,7 +1808,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1820,7 +1819,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
@@ -1831,7 +1830,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1840,7 +1839,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1866,7 +1865,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
@@ -1877,7 +1876,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1894,7 +1893,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1905,7 +1904,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1921,7 +1920,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"serde",
|
||||
@@ -1931,7 +1930,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-channel",
|
||||
@@ -1969,7 +1968,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1993,7 +1992,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -2004,7 +2003,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -2017,7 +2016,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2036,7 +2035,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -2049,7 +2048,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2066,17 +2065,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
@@ -2093,7 +2092,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2105,7 +2104,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2129,7 +2128,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2144,7 +2143,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2159,7 +2158,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2169,7 +2168,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2178,7 +2177,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2193,12 +2192,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2212,7 +2211,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2229,7 +2228,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2267,7 +2266,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2278,7 +2277,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2296,7 +2295,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2317,7 +2316,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2338,7 +2337,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-test-kit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2349,7 +2348,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2368,7 +2367,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2400,7 +2399,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2411,7 +2410,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-platform",
|
||||
@@ -2423,7 +2422,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2431,7 +2430,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2463,7 +2462,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -2477,7 +2476,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -2490,7 +2489,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -2502,7 +2501,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2512,7 +2511,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -3905,7 +3904,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3914,7 +3913,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3932,7 +3931,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3950,12 +3949,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4684,7 +4683,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4823,7 +4822,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
@@ -10094,4 +10093,4 @@ source = "git+https://github.com/storytold/egui.git?rev=399fc6e0ea65059e37de680f
|
||||
[[patch.unused]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=18499ec3a61f6d7a7d8a70951fa9765e5cf9853c#18499ec3a61f6d7a7d8a70951fa9765e5cf9853c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ad10c35ae545f0fb816364381a1a8154012b2359#ad10c35ae545f0fb816364381a1a8154012b2359"
|
||||
|
||||
+39
-39
@@ -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 = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -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 = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -174,14 +174,14 @@ 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 = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
|
||||
@@ -16,6 +16,7 @@ workspace = true
|
||||
[dependencies]
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-engine = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-render = { workspace = true }
|
||||
wordcraft-mcp = { workspace = true }
|
||||
wordcraft-zotero = { workspace = true }
|
||||
|
||||
@@ -616,6 +616,10 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
}
|
||||
let password = password_from(rest)?;
|
||||
let mut s = open(&i, password.as_deref())?;
|
||||
// A refused strict export prints only its report, so its note waits for the export to succeed.
|
||||
if !strict {
|
||||
report_missing_metric_fonts();
|
||||
}
|
||||
if rest.iter().any(|a| a == "--update-fields") {
|
||||
update_fields(&mut s)?;
|
||||
}
|
||||
@@ -631,8 +635,11 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
|
||||
if let Err(e) = r {
|
||||
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
eprintln!("wrote {o}");
|
||||
Ok(())
|
||||
if strict {
|
||||
report_missing_metric_fonts();
|
||||
}
|
||||
// The confirmation is a result, so it goes to stdout with the others (#7070).
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))
|
||||
}
|
||||
|
||||
fn load_run_script(rest: &[String], script_path: Option<&Path>) -> Result<Option<script::Script>, Failure> {
|
||||
@@ -656,6 +663,16 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
|
||||
(from_file, from_template)
|
||||
}
|
||||
|
||||
fn report_missing_metric_fonts() {
|
||||
for (word, used) in wordcraft_fonts::word::missing_metric_fonts() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"note: {word} and its metric-compatible twins aren't installed; the primary family is {used}, so lines and pages may not match Word's; uncovered characters may use glyph fallback"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show a successful command's result, or its warning when results aren't printed.
|
||||
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
|
||||
if print {
|
||||
@@ -817,7 +834,11 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
eprintln!("wrote {out}");
|
||||
// A reader that hung up only loses the confirmation; the remaining saves still run.
|
||||
match write_stdout(|w| writeln!(w, "wrote {out}")) {
|
||||
Ok(()) | Err(Failure::StdoutClosed) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -887,7 +908,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
eprintln!("{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = arg_value(&rest, "--save") {
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
eprintln!("wrote {o}");
|
||||
write_stdout(|w| writeln!(w, "wrote {o}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Removes the temporary test folder when the test finishes or panics.
|
||||
struct TempRoot(PathBuf);
|
||||
|
||||
impl TempRoot {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_saves_home_relative_paths_and_can_clear_the_override() {
|
||||
let root = TempRoot(std::env::temp_dir().join(format!("wc-custom-dictionary-{}", std::process::id())));
|
||||
let home = root.0.join("home");
|
||||
let profile = root.0.join("profile");
|
||||
for folder in [&home, &profile] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
std::fs::write(folder.join("custom.dic"), "wordcraftdictionary\n").unwrap();
|
||||
}
|
||||
let (preferred, fallback) = if cfg!(windows) { (&profile, &home) } else { (&home, &profile) };
|
||||
let options = |home: Option<&Path>, profile: Option<&Path>, paths: &[&str]| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(home) = home {
|
||||
cli.env("HOME", home);
|
||||
}
|
||||
if let Some(profile) = profile {
|
||||
cli.env("USERPROFILE", profile);
|
||||
}
|
||||
cli.args(["run", "--print"]);
|
||||
for path in paths {
|
||||
cli.args(["--cmd", &format!("file.options={}", json!({"customDictionary": path})), "--cmd", "file.options"]);
|
||||
}
|
||||
cli.output().unwrap()
|
||||
};
|
||||
let assert_saved = |home, profile, paths: &[&str], expected: &[Option<&Path>]| {
|
||||
let report = options(home, profile, paths);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), expected.len() * 2, "{out}");
|
||||
for (pair, expected) in reads.as_chunks::<2>().0.iter().zip(expected) {
|
||||
for read in pair {
|
||||
assert_eq!(read["customDictionary"].as_str().map(Path::new), *expected, "{out}");
|
||||
}
|
||||
}
|
||||
};
|
||||
let assert_refused = |home, profile, path, reason: &str| {
|
||||
let report = options(home, profile, &[path]);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
|
||||
let dic = preferred.join("custom.dic");
|
||||
let absolute = dic.to_str().unwrap();
|
||||
assert_saved(Some(&home), Some(&profile), &["~/custom.dic"], &[Some(&dic)]);
|
||||
assert_saved(None, None, &[absolute, "auto", absolute, ""], &[Some(&dic), None, Some(&dic), None]);
|
||||
let empty = Path::new("");
|
||||
let (empty_home, empty_profile) = if cfg!(windows) { (fallback.as_path(), empty) } else { (empty, fallback.as_path()) };
|
||||
assert_saved(Some(empty_home), Some(empty_profile), &["~/custom.dic"], &[Some(&fallback.join("custom.dic"))]);
|
||||
assert_refused(None, None, "~/custom.dic", "cannot expand");
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(&home), Some(&profile), &[r"~\custom.dic"], &[Some(&dic)]);
|
||||
assert_refused(None, None, r"~\custom.dic", "cannot expand");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\C:\custom.dic", "relative to the home folder");
|
||||
assert_refused(Some(&home), Some(&profile), r"~\\custom.dic", "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(&home), Some(&profile), r"~\custom.dic", "isn't a full path");
|
||||
}
|
||||
root.remove().unwrap();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn folder_options_save_home_relative_paths_and_validate_before_reading() {
|
||||
let profile = std::env::temp_dir().join(format!("wc-folder-options-profile-{}", std::process::id()));
|
||||
let templates = profile.join("Templates").join("Personal");
|
||||
let dictionaries = profile.join("Dictionaries");
|
||||
std::fs::create_dir_all(&templates).unwrap();
|
||||
std::fs::create_dir_all(&dictionaries).unwrap();
|
||||
let options = |profile: Option<&Path>, params: Value| {
|
||||
let mut cli = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"));
|
||||
cli.env_remove("HOME").env_remove("USERPROFILE");
|
||||
if let Some(profile) = profile {
|
||||
cli.env(if cfg!(windows) { "USERPROFILE" } else { "HOME" }, profile);
|
||||
}
|
||||
cli.args(["run", "--print", "--cmd", &format!("file.options={params}"), "--cmd", "file.options"]).output().unwrap()
|
||||
};
|
||||
let assert_saved = |profile, params| {
|
||||
let report = options(profile, params);
|
||||
assert!(report.status.success(), "{}", String::from_utf8_lossy(&report.stderr));
|
||||
let out = String::from_utf8(report.stdout).unwrap();
|
||||
let reads: Vec<Value> =
|
||||
out.lines().filter_map(|line| line.strip_prefix("file.options: ")).map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(reads.len(), 2, "{out}");
|
||||
for read in reads {
|
||||
assert_eq!(Path::new(read["userTemplatesFolder"].as_str().unwrap()), templates);
|
||||
assert_eq!(Path::new(read["dictionariesFolder"].as_str().unwrap()), dictionaries);
|
||||
}
|
||||
};
|
||||
assert_saved(Some(profile.as_path()), json!({"userTemplatesFolder": "~/Templates/Personal", "dictionariesFolder": "~/Dictionaries"}));
|
||||
assert_saved(None, json!({"userTemplatesFolder": templates, "dictionariesFolder": dictionaries}));
|
||||
|
||||
let win_params = json!({"userTemplatesFolder": r"~\Templates/Personal", "dictionariesFolder": r"~\Dictionaries"});
|
||||
let assert_refused = |profile, params, reason: &str| {
|
||||
let report = options(profile, params);
|
||||
let error = String::from_utf8_lossy(&report.stderr);
|
||||
assert!(!report.status.success() && error.contains(reason), "{error}");
|
||||
};
|
||||
if cfg!(windows) {
|
||||
assert_saved(Some(profile.as_path()), win_params.clone());
|
||||
assert_refused(None, win_params, "cannot expand");
|
||||
assert_refused(Some(profile.as_path()), json!({"userTemplatesFolder": r"~\C:\Templates"}), "relative to the home folder");
|
||||
} else {
|
||||
assert_refused(Some(profile.as_path()), win_params, "isn't a full path");
|
||||
}
|
||||
assert_refused(None, json!({"dictionariesFolder": "~/Dictionaries"}), "cannot expand");
|
||||
assert_refused(None, json!({"userTemplatesFolder": r"\\unreachable.invalid\share"}), "can't be a network folder");
|
||||
std::fs::remove_dir_all(profile).unwrap();
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod custom_dictionary;
|
||||
mod folder_options;
|
||||
mod help;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
@@ -12,3 +14,4 @@ mod picture_then_typing;
|
||||
mod reproducible_pdf;
|
||||
mod strict;
|
||||
mod text_tracked;
|
||||
mod wrote_on_stdout;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! A write's `wrote <path>` confirmation is a result, so it goes to stdout, where a script that
|
||||
//! captures the output finds it; stderr keeps errors and diagnostics (#7070).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("wc-cli-wrote-{name}-{}", std::process::id()));
|
||||
// A failed run leaves its directory behind (cleanup runs only after the assertions), and a
|
||||
// later process can reuse the PID: start clean so a stale file cannot pass a check.
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The confirmation is on stdout and not on stderr, and the file is there.
|
||||
fn assert_wrote_on_stdout(run: &Output, out: &Path) {
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
assert!(out.is_file(), "{} was not written", out.display());
|
||||
let line = format!("wrote {}", out.display());
|
||||
assert!(stdout.lines().any(|l| l == line), "stdout lacks `{line}`: {stdout:?}");
|
||||
assert!(!stderr.contains("wrote "), "the confirmation is on stderr too: {stderr:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_confirms_the_write_on_stdout() {
|
||||
let d = dir("convert");
|
||||
let (input, out) = (d.join("in.txt"), d.join("out.docx"));
|
||||
std::fs::write(&input, "Hello").unwrap();
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("convert").arg(&input).arg(&out).output().unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_confirms_each_save_on_stdout() {
|
||||
let d = dir("run");
|
||||
let out = d.join("out.docx");
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.args(["run", "--template", "blank", "--cmd", r#"text.insert={"text":"x"}"#, "--save"])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_wrote_on_stdout(&run, &out);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A reader that has already hung up does not stop the job: every save still runs, though its
|
||||
/// confirmation has nowhere to go. A PNG is written only in the confirming loop, so it shows a
|
||||
/// save that was skipped.
|
||||
#[test]
|
||||
fn run_keeps_saving_after_stdout_closes() {
|
||||
let d = dir("closed");
|
||||
let job = d.join("job.json");
|
||||
std::fs::write(
|
||||
&job,
|
||||
r#"{"template": "blank", "commands": [{"command": "text.insert", "params": {"text": "x"}}], "save": ["first.docx", "second.png"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (reader, writer) = std::io::pipe().unwrap();
|
||||
drop(reader);
|
||||
let run = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(["run", "--script"]).arg(&job).stdout(writer).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(run.status.success(), "status {:?}, stderr: {stderr}", run.status);
|
||||
for out in ["first.docx", "second.png"] {
|
||||
assert!(d.join(out).is_file(), "{out} was not written; stderr: {stderr}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -206,6 +206,10 @@ display_name = "entropybeater"
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
|
||||
@@ -813,8 +813,14 @@ impl Document {
|
||||
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
|
||||
/// JSON, whose run lengths may overflow, fall short or split a character.
|
||||
pub fn normalize_runs(&mut self) {
|
||||
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
|
||||
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
|
||||
let separators = [&mut self.footnote_separators, &mut self.endnote_separators]
|
||||
.into_iter()
|
||||
.flat_map(|s| [&mut s.separator, &mut s.continuation_separator, &mut s.continuation_notice])
|
||||
.flatten();
|
||||
let stories = std::iter::once(&mut self.body)
|
||||
.chain(self.parts.values_mut().map(|part| &mut part.blocks))
|
||||
.chain(separators)
|
||||
.chain(self.glossary.iter_mut().map(|entry| &mut entry.blocks));
|
||||
for blocks in stories {
|
||||
for b in blocks.iter_mut() {
|
||||
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
|
||||
|
||||
@@ -773,6 +773,10 @@ pub struct SectionProps {
|
||||
pub page_w: f32,
|
||||
pub page_h: f32,
|
||||
pub landscape: bool,
|
||||
/// Top and bottom margins, points. Negative is Word's exact margin (`w:pgMar` `w:top` /
|
||||
/// `w:bottom` below zero, ECMA-376 §17.6.11; DOC `dyaTop` / `dyaBottom`): the text starts
|
||||
/// (ends) at the absolute value from the page edge even when the header (footer) is taller,
|
||||
/// and overlaps it.
|
||||
pub margin_top: f32,
|
||||
pub margin_bottom: f32,
|
||||
pub margin_left: f32,
|
||||
@@ -912,17 +916,21 @@ impl SectionProps {
|
||||
pub fn text_width(&self) -> f32 {
|
||||
(self.page_w - self.margin_left - self.margin_right - self.gutter).max(18.0)
|
||||
}
|
||||
/// Height of the text area between the margins, points (a negative, exact margin counts at
|
||||
/// its size).
|
||||
pub fn text_height(&self) -> f32 {
|
||||
(self.page_h - self.margin_top - self.margin_bottom).max(18.0)
|
||||
(self.page_h - self.margin_top.abs() - self.margin_bottom.abs()).max(18.0)
|
||||
}
|
||||
/// Swap to landscape/portrait (keeps margins relative to the paper as Word does: rotates them).
|
||||
/// An exact (negative) top or bottom turns into a side at its size, as in Word: only the top
|
||||
/// and bottom can be exact.
|
||||
pub fn set_landscape(&mut self, on: bool) {
|
||||
if on == self.landscape {
|
||||
return;
|
||||
}
|
||||
self.landscape = on;
|
||||
std::mem::swap(&mut self.page_w, &mut self.page_h);
|
||||
let (t, b, l, r) = (self.margin_top, self.margin_bottom, self.margin_left, self.margin_right);
|
||||
let (t, b, l, r) = (self.margin_top.abs(), self.margin_bottom.abs(), self.margin_left, self.margin_right);
|
||||
if on {
|
||||
self.margin_top = l;
|
||||
self.margin_bottom = r;
|
||||
|
||||
@@ -959,6 +959,25 @@ fn normalize_runs_reconciles_objects_with_markers() {
|
||||
// Deleting the first marker keeps B on the second.
|
||||
p.delete(1, 4).unwrap();
|
||||
assert_eq!(p.objects, vec![fs("B")]);
|
||||
|
||||
let mut d = build();
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.objects.push(fs("Surplus"));
|
||||
p.runs[0].len = 1;
|
||||
d.footnote_separators.continuation_notice = Some(d.body.clone());
|
||||
d.endnote_separators.separator = Some(d.body.clone());
|
||||
d.glossary.push(BuildingBlock { name: "Quick Parts example".into(), blocks: d.body.clone(), ..Default::default() });
|
||||
d.normalize_runs();
|
||||
for (name, blocks) in [
|
||||
("footnote continuation notice", d.footnote_separators.continuation_notice.as_ref().unwrap()),
|
||||
("endnote separator", d.endnote_separators.separator.as_ref().unwrap()),
|
||||
("Quick Parts entry", &d.glossary[0].blocks),
|
||||
] {
|
||||
edit::each_para(&blocks[0], 0, &mut |p| {
|
||||
assert_eq!(p.objects, vec![fs("A"), fs("B")], "{name} drops the surplus object");
|
||||
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len(), "{name} repairs its runs");
|
||||
});
|
||||
}
|
||||
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
|
||||
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
|
||||
let reconcile = |extra: usize| {
|
||||
|
||||
@@ -861,14 +861,19 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
let n: usize = found.iter().map(Vec::len).sum();
|
||||
let saved_sel = s.sel.clone();
|
||||
let orig_story_matched = found.iter().any(|r| r[0].a.story == saved_sel.focus.story);
|
||||
// The main text comes last, so under Track Changes the caret ends where it did before;
|
||||
// when the original story had no match, restore the selection so it stays there.
|
||||
let orig_story = saved_sel.focus.story;
|
||||
let mut orig_story_sel = None;
|
||||
// The main text comes last, so under Track Changes keep the selection from the caret's own
|
||||
// story (or restore the saved selection if that story had no match, #9063 / #9186).
|
||||
for results in found.into_iter().rev() {
|
||||
let is_orig = results[0].a.story == orig_story;
|
||||
replace_found(s, results)?;
|
||||
if s.doc.settings.track_changes && is_orig {
|
||||
orig_story_sel = Some(s.sel.clone());
|
||||
}
|
||||
}
|
||||
if s.doc.settings.track_changes && !orig_story_matched {
|
||||
s.sel = saved_sel;
|
||||
if s.doc.settings.track_changes {
|
||||
s.sel = orig_story_sel.unwrap_or(saved_sel);
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
|
||||
@@ -956,14 +956,16 @@ pub fn state(s: &Session) -> Value {
|
||||
(*cached_state(s)).clone()
|
||||
}
|
||||
|
||||
/// The common East Asian family shown by the font controls. If a slot has no face, keep
|
||||
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
|
||||
/// The common East Asian family shown by the font controls. A theme slot without a face uses
|
||||
/// the run's ordinary font, as layout does. Resolve each theme slot once per selection.
|
||||
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
|
||||
let mut themes = HashMap::new();
|
||||
let mut fonts = runs.iter().map(|run| {
|
||||
run.font_ea_theme
|
||||
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
|
||||
.or(run.font_ea.as_deref())
|
||||
let mut fonts = runs.iter().map(|run| match run.font_ea_theme {
|
||||
Some(slot) => {
|
||||
let face = *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run));
|
||||
Some(face.unwrap_or(&run.font))
|
||||
}
|
||||
None => run.font_ea.as_deref(),
|
||||
});
|
||||
let first = fonts.next().flatten()?;
|
||||
fonts.all(|font| font == Some(first)).then_some(first)
|
||||
|
||||
@@ -33,7 +33,9 @@ pub(crate) use select::select_object;
|
||||
pub(crate) use select::{edit_obj, has_shape_or_canvas};
|
||||
#[cfg(test)]
|
||||
use select::{has_group, holds_ink, obj_size, with_obj};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
|
||||
pub use select::{
|
||||
has_picture_format_target, min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use shape::can_link;
|
||||
pub(crate) use shape::set_text_body;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::select::{edit_obj, has_picture, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
@@ -190,7 +190,7 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
|
||||
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
|
||||
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
|
||||
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
|
||||
if picks.len() < 2 {
|
||||
if picks.is_empty() || (picks.len() == 1 && has_picture(s).is_none()) {
|
||||
return run(s);
|
||||
}
|
||||
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
|
||||
|
||||
@@ -7,6 +7,16 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether commands that already format multiple pictures have a target. A secondary
|
||||
/// picture counts when objects were explicitly picked, even if the primary object is a shape.
|
||||
pub fn has_picture_format_target(s: &Session) -> bool {
|
||||
has_picture(s).is_none() || (!s.also_selected.is_empty() && !target_objects(s, |o| matches!(o, InlineObject::Image { .. })).is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn has_any_picture(s: &Session) -> Option<&'static str> {
|
||||
(!has_picture_format_target(s)).then_some("select a picture first")
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a picture, shape, or active text box is selected.
|
||||
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
|
||||
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
|
||||
|
||||
@@ -4,9 +4,9 @@ use super::picture::{
|
||||
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
|
||||
};
|
||||
use super::select::{
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
|
||||
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
|
||||
with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_picture, has_any_shape, has_floating, has_group, has_movable, has_object,
|
||||
has_picture, has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box,
|
||||
target_objects, with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
};
|
||||
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
|
||||
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
@@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"percent": 0..100}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"tolerance"?: 0..255}"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
|
||||
@@ -164,8 +164,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"maxPixels"?: n}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_any_picture),
|
||||
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
|
||||
let bytes = if let Some(d) = p::str(v, "data") {
|
||||
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
|
||||
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
@@ -220,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_picture),
|
||||
.when(has_any_picture),
|
||||
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
|
||||
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
|
||||
// picture's pixels are never rewritten. A flip mirrors what is on the page, so a
|
||||
|
||||
@@ -432,6 +432,59 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
|
||||
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_border_uses_picked_pictures_even_when_a_shape_is_primary() {
|
||||
for (picked, expected) in
|
||||
[(&[2, 0][..], [true, false]), (&[2, 0, 1][..], [true, true]), (&[0, 2, 1][..], [true, true]), (&[2][..], [false, false])]
|
||||
{
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
for w in [20, 24] {
|
||||
let data = super::super::insert::base64_encode(&png(w, 10));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
}
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
for index in picked {
|
||||
s.run("select.addObject", &json!({"index": index})).unwrap();
|
||||
}
|
||||
let selection = s.sel.clone();
|
||||
let extras = s.also_selected.clone();
|
||||
let undo = s.undo_depth();
|
||||
let shape = |s: &Session| {
|
||||
let (_, object) = all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).unwrap();
|
||||
serde_json::to_value(object).unwrap()
|
||||
};
|
||||
let shape_before = shape(&s);
|
||||
let borders = |s: &Session| {
|
||||
all_objects(s)
|
||||
.into_iter()
|
||||
.filter_map(|(_, o)| match o {
|
||||
InlineObject::Image { media, .. } => Some(s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let result = s.run("picture.border", &json!({"width": 3}));
|
||||
if expected == [false, false] {
|
||||
assert!(result.is_err(), "a shape alone cannot take a picture border");
|
||||
assert_eq!(s.undo_depth(), undo);
|
||||
} else {
|
||||
result.unwrap();
|
||||
assert_eq!(s.undo_depth(), undo + 1);
|
||||
}
|
||||
assert_eq!(s.sel, selection);
|
||||
assert_eq!(s.also_selected, extras);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
assert_eq!(borders(&s), expected);
|
||||
if expected != [false, false] {
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(borders(&s), [false, false]);
|
||||
assert_eq!(shape(&s), shape_before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #8832: a picture command on several selected pictures changes each, in one undo step.
|
||||
#[test]
|
||||
fn picture_border_applies_to_every_selected_picture() {
|
||||
@@ -2267,3 +2320,55 @@ fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
|
||||
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
|
||||
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_format_commands_stay_enabled_when_shape_is_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then one picture added.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.border", &json!({"color": "FF0000", "width": 3})).unwrap();
|
||||
assert!(matches!(
|
||||
&all_objects(&s)[1].1,
|
||||
InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.border.is_some())
|
||||
));
|
||||
|
||||
// Shape clicked first, then two pictures added.
|
||||
s.run("select.addObject", &json!({"index": 2})).unwrap();
|
||||
s.run("picture.style", &json!({"style": "rounded"})).unwrap();
|
||||
let objs = all_objects(&s);
|
||||
for idx in [1, 2] {
|
||||
assert!(
|
||||
matches!(&objs[idx].1, InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.style.as_deref() == Some("rounded"))),
|
||||
"picture {idx} should get rounded style"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_object_picture_commands_need_the_picture_selected_first() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
|
||||
// Shape clicked first, then the picture added: Crop, Change Picture and Alt Text would act on the shape.
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
for (cmd, args) in [("picture.crop", json!({"left": 0.1})), ("picture.altText", json!({"text": "x"})), ("picture.change", json!({"data": data}))]
|
||||
{
|
||||
assert!(matches!(s.run(cmd, &args), Err(CmdError::Disabled(_))), "{cmd}");
|
||||
}
|
||||
|
||||
// Picture first: enabled.
|
||||
s.run("select.objects", &json!({"index": 1})).unwrap();
|
||||
s.run("picture.crop", &json!({"left": 0.1})).unwrap();
|
||||
}
|
||||
|
||||
@@ -301,19 +301,25 @@ fn home_from(home: Option<std::ffi::OsString>, userprofile: Option<std::ffi::OsS
|
||||
set(first).or_else(|| set(second))
|
||||
}
|
||||
|
||||
/// The path a folder setting names: `~/…` under the home folder, or the path as given. With no
|
||||
/// home folder to expand under, `~/` is refused rather than left as a relative path.
|
||||
/// Expand a file or folder path under the home folder with the saved settings' platform-specific prefix.
|
||||
fn expand_home(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<std::path::PathBuf, CmdError> {
|
||||
match (f.strip_prefix("~/"), home) {
|
||||
(Some(rest), Some(h)) => Ok(h.join(rest)),
|
||||
(Some(_), None) => Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
|
||||
(None, _) => Ok(std::path::PathBuf::from(f)),
|
||||
let prefix = if cfg!(windows) && f.starts_with("~\\") { "~\\" } else { "~/" };
|
||||
let Some(rest) = f.strip_prefix(prefix) else { return Ok(std::path::PathBuf::from(f)) };
|
||||
let Some(home) = home else {
|
||||
return Err(CmdError::Params(format!("`{key}`: cannot expand `{prefix}` because HOME or USERPROFILE is not set")));
|
||||
};
|
||||
// A Windows drive, device or root in the suffix would replace the home path on join.
|
||||
if prefix == "~\\"
|
||||
&& matches!(std::path::Path::new(rest).components().next(), Some(std::path::Component::Prefix(_) | std::path::Component::RootDir))
|
||||
{
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} must be relative to the home folder")));
|
||||
}
|
||||
Ok(home.join(rest))
|
||||
}
|
||||
|
||||
/// A folder setting (`dictionariesFolder`, `userTemplatesFolder`): `auto` (or nothing) forgets
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/`. With
|
||||
/// `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// it; otherwise an existing folder, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
/// With `local_only`, a network folder is refused before anything looks at it (#2852): even checking
|
||||
/// that it exists would make Windows authenticate to that host.
|
||||
fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
@@ -339,8 +345,12 @@ fn folder_setting(key: &str, f: &str, local_only: bool) -> Result<Option<String>
|
||||
}
|
||||
|
||||
/// A file setting (`customDictionary`): `auto` (or nothing) forgets it; otherwise an existing
|
||||
/// file, given as an absolute path or one starting with `~/`.
|
||||
/// file, given as an absolute path or one starting with `~/` (`~\` also works on Windows).
|
||||
fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
file_setting_in(key, f, home_dir().as_deref())
|
||||
}
|
||||
|
||||
fn file_setting_in(key: &str, f: &str, home: Option<&std::path::Path>) -> Result<Option<String>, CmdError> {
|
||||
let f = f.trim();
|
||||
if f.is_empty() || f.eq_ignore_ascii_case("auto") {
|
||||
return Ok(None);
|
||||
@@ -348,15 +358,7 @@ fn file_setting(key: &str, f: &str) -> Result<Option<String>, CmdError> {
|
||||
if f.chars().count() > MAX_FOLDER_CHARS || f.chars().any(char::is_control) {
|
||||
return Err(CmdError::Params(format!("`{key}` isn't a file path")));
|
||||
}
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
|
||||
let path = if let Some(rest) = f.strip_prefix("~/") {
|
||||
match home {
|
||||
Some(h) => h.join(rest),
|
||||
None => return Err(CmdError::Params(format!("`{key}`: cannot expand `~/` because HOME or USERPROFILE is not set"))),
|
||||
}
|
||||
} else {
|
||||
std::path::PathBuf::from(f)
|
||||
};
|
||||
let path = expand_home(key, f, home)?;
|
||||
if !path.is_absolute() {
|
||||
return Err(CmdError::Params(format!("`{key}`: {f:?} isn't a full path")));
|
||||
}
|
||||
@@ -378,9 +380,10 @@ pub fn use_dictionaries_folder(folder: Option<&str>) {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{expand_home, home_from};
|
||||
use super::{expand_home, file_setting_in, home_from};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn os(s: &str) -> Option<OsString> {
|
||||
Some(OsString::from(s))
|
||||
@@ -416,4 +419,48 @@ mod tests {
|
||||
let err = expand_home("dictionariesFolder", "~/dic", None).unwrap_err();
|
||||
assert!(format!("{err:?}").contains("cannot expand"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_expands_tilde_with_the_same_platform_prefix() {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
struct TempHome(PathBuf);
|
||||
impl TempHome {
|
||||
fn remove(self) -> std::io::Result<()> {
|
||||
let res = std::fs::remove_dir_all(&self.0);
|
||||
std::mem::forget(self);
|
||||
res
|
||||
}
|
||||
}
|
||||
impl Drop for TempHome {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
let dir = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let candidate = std::env::temp_dir().join(format!("wc-options-home-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break TempHome(candidate),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("temp dir {}: {e}", candidate.display()),
|
||||
}
|
||||
};
|
||||
let dic = dir.0.join("custom.dic");
|
||||
std::fs::write(&dic, "wordcraftdictionary\n").unwrap();
|
||||
let expected = dic.to_string_lossy().into_owned();
|
||||
|
||||
assert_eq!(file_setting_in("customDictionary", "~/custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let missing_home = file_setting_in("customDictionary", "~/custom.dic", None).unwrap_err();
|
||||
assert!(format!("{missing_home:?}").contains("cannot expand"), "{missing_home:?}");
|
||||
if cfg!(windows) {
|
||||
assert_eq!(file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
let drive = file_setting_in("customDictionary", r"~\C:\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{drive:?}").contains("relative to the home folder"), "{drive:?}");
|
||||
} else {
|
||||
let backslash = file_setting_in("customDictionary", r"~\custom.dic", Some(&dir.0)).unwrap_err();
|
||||
assert!(format!("{backslash:?}").contains("isn't a full path"), "{backslash:?}");
|
||||
}
|
||||
dir.remove().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,20 +520,22 @@ fn margins(s: &mut Session, v: &Value) -> CmdResult {
|
||||
None => return Err(CmdError::Params(format!("unknown preset `{x}`"))),
|
||||
},
|
||||
None => {
|
||||
// A negative margin given counts as zero; one left out keeps its value, so an exact
|
||||
// (negative) top or bottom from the file stays exact when another side changes, as
|
||||
// in Word.
|
||||
let c = sect(s);
|
||||
let given = |k: &str| p::f32(v, k).map(|m| m.max(0.0));
|
||||
(
|
||||
p::f32(v, "top").unwrap_or(c.margin_top),
|
||||
p::f32(v, "bottom").unwrap_or(c.margin_bottom),
|
||||
p::f32(v, "left").unwrap_or(c.margin_left),
|
||||
p::f32(v, "right").unwrap_or(c.margin_right),
|
||||
given("top").unwrap_or(c.margin_top),
|
||||
given("bottom").unwrap_or(c.margin_bottom),
|
||||
given("left").unwrap_or(c.margin_left.max(0.0)),
|
||||
given("right").unwrap_or(c.margin_right.max(0.0)),
|
||||
)
|
||||
}
|
||||
};
|
||||
// Negative margins count as zero before the fit check, so one can't offset another.
|
||||
let (t, b, l, r) = (t.max(0.0), b.max(0.0), l.max(0.0), r.max(0.0));
|
||||
let gutter = p::f32(v, "gutter").map(|g| g.max(0.0));
|
||||
let cur = sect(s);
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t, b, l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
if !margins_fit((cur.page_w, cur.page_h), (t.abs(), b.abs(), l, r), gutter.unwrap_or(cur.gutter)) {
|
||||
return Err(CmdError::Params("margins leave no room for text".into()));
|
||||
}
|
||||
// A preset picks mirrored or not, as does `mirror` (Page Setup's Multiple pages); plain numbers
|
||||
@@ -588,7 +590,7 @@ fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
sections
|
||||
.iter()
|
||||
.find(|(e, _)| *e == block)
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), x.gutter))
|
||||
.is_none_or(|(_, x)| margins_fit(oriented(x), (x.margin_top.abs(), x.margin_bottom.abs(), x.margin_left, x.margin_right), x.gutter))
|
||||
};
|
||||
if !selected_section_ends(s).into_iter().all(fits) {
|
||||
return Err(CmdError::Params(MARGINS_DONT_FIT.into()));
|
||||
|
||||
@@ -433,3 +433,26 @@ fn page_number_format_keeps_or_clears_the_start() {
|
||||
assert_eq!(back["pageNumFormat"], "decimal");
|
||||
assert_eq!(back["pageNumStart"], 1);
|
||||
}
|
||||
|
||||
/// An exact (negative) top or bottom margin survives Margins and Orientation: changing another
|
||||
/// margin keeps it exact, and turning the page moves its size, as a plain margin, to the side it
|
||||
/// goes to.
|
||||
#[test]
|
||||
fn exact_margins_survive_margins_and_orientation() {
|
||||
let mut s = doc();
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.doc.last_section.margin_bottom = -40.0;
|
||||
s.run("layout.margins", &json!({"left": 80.0})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0));
|
||||
// A negative margin given still counts as zero.
|
||||
s.run("layout.margins", &json!({"top": -30.0})).unwrap();
|
||||
assert_eq!((s.doc.last_section.margin_top, s.doc.last_section.margin_bottom), (0.0, -40.0));
|
||||
s.doc.last_section.margin_top = -60.0;
|
||||
s.run("layout.orientation", &json!({"value": "landscape"})).unwrap();
|
||||
let x = &s.doc.last_section;
|
||||
assert!(x.margin_left >= 0.0 && x.margin_right >= 0.0, "{x:?}");
|
||||
let mut sides = [x.margin_left, x.margin_right];
|
||||
sides.sort_by(f32::total_cmp);
|
||||
assert_eq!(sides, [40.0, 60.0], "the exact margins' sizes go to the sides");
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ pub(super) fn outline_step(s: &mut Session, promote: bool) -> CmdResult {
|
||||
// Outline view: the headings hidden under a collapsed heading move a level with it.
|
||||
let carried = crate::cmd::outline::hidden_subheadings(s);
|
||||
let (a, b) = s.sel.ordered();
|
||||
let paths = s.doc.paths_between(&a, &b);
|
||||
let paths = if s.cell_range().is_some_and(|range| !range.stream) { crate::cmd::selected_paths(s) } else { s.doc.paths_between(&a, &b) };
|
||||
// The heading before the selection, for promoted body text.
|
||||
let before = s
|
||||
.doc
|
||||
|
||||
@@ -187,12 +187,170 @@ pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"id": id}))
|
||||
}
|
||||
|
||||
/// Deserialize `T` from `v`, rejecting unknown fields on `T` and any nested structs (#9203, #9291).
|
||||
fn deserialize_strict<T: serde::de::DeserializeOwned>(section: &str, v: &Value) -> Result<T, CmdError> {
|
||||
use serde::de::{DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};
|
||||
|
||||
struct StrictDe<'a>(&'a Value);
|
||||
struct StrictSeq<'a>(std::slice::Iter<'a, Value>);
|
||||
struct StrictMap<'a>(serde_json::map::Iter<'a>, Option<&'a Value>);
|
||||
struct StrictEnum<'a>(&'a str, &'a Value);
|
||||
|
||||
// Internally tagged enums buffer their fields before decoding them, bypassing StrictMap.
|
||||
fn validate_text_fill(fill: &Value) -> Result<(), serde_json::Error> {
|
||||
let tag = fill.get("type").or_else(|| fill.get(0));
|
||||
// Serde's numeric variant indices follow the TextFill declaration order.
|
||||
let fields: &[_] = match (tag.and_then(Value::as_str), tag.and_then(Value::as_u64)) {
|
||||
(Some("none"), _) | (_, Some(0)) => &["type"],
|
||||
(Some("solid"), _) | (_, Some(1)) => &["type", "color", "transparency"],
|
||||
(Some("gradient"), _) | (_, Some(2)) => &["type", "stops", "angle"],
|
||||
_ => return Ok(()), // The regular decoder reports missing or unknown tags.
|
||||
};
|
||||
let stops = if let Some(map) = fill.as_object() {
|
||||
if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) {
|
||||
return Err(serde::de::Error::custom(format!("`textEffects.fill`: unknown field `{key}`")));
|
||||
}
|
||||
map.get("stops")
|
||||
} else if fields.contains(&"stops") {
|
||||
fill.get(1)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(stops) = stops.and_then(Value::as_array) {
|
||||
for stop in stops {
|
||||
<wordcraft_doc::wordart::GradStop as serde::Deserialize>::deserialize(StrictDe(stop))
|
||||
.map_err(|e| serde::de::Error::custom(format!("`textEffects.fill.stops`: {e}")))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<'de> SeqAccess<'de> for StrictSeq<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error> {
|
||||
self.0.next().map(|v| seed.deserialize(StrictDe(v))).transpose()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> MapAccess<'de> for StrictMap<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> {
|
||||
let Some((k, v)) = self.0.next() else { return Ok(None) };
|
||||
self.1 = Some(v);
|
||||
seed.deserialize(k.as_str().into_deserializer()).map(Some)
|
||||
}
|
||||
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Self::Error> {
|
||||
let v = self.1.take().ok_or_else(|| serde::de::Error::custom("missing map value"))?;
|
||||
seed.deserialize(StrictDe(v))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> VariantAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
fn unit_variant(self) -> Result<(), Self::Error> {
|
||||
serde::Deserialize::deserialize(self.1)
|
||||
}
|
||||
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Self::Error> {
|
||||
seed.deserialize(StrictDe(self.1))
|
||||
}
|
||||
fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
serde::Deserializer::deserialize_tuple(StrictDe(self.1), len, visitor)
|
||||
}
|
||||
fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> {
|
||||
serde::Deserializer::deserialize_struct(StrictDe(self.1), "", fields, visitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> EnumAccess<'de> for StrictEnum<'_> {
|
||||
type Error = serde_json::Error;
|
||||
type Variant = Self;
|
||||
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> {
|
||||
let val = seed.deserialize(self.0.into_deserializer())?;
|
||||
Ok((val, self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserializer<'de> for StrictDe<'_> {
|
||||
type Error = serde_json::Error;
|
||||
|
||||
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
match self.0 {
|
||||
Value::Null => visitor.visit_unit(),
|
||||
Value::Bool(b) => visitor.visit_bool(*b),
|
||||
Value::Number(n) => n.deserialize_any(visitor),
|
||||
Value::String(s) => visitor.visit_str(s),
|
||||
Value::Array(arr) => visitor.visit_seq(StrictSeq(arr.iter())),
|
||||
Value::Object(map) => visitor.visit_map(StrictMap(map.iter(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
if self.0.is_null() { visitor.visit_none() } else { visitor.visit_some(self) }
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> {
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V: Visitor<'de>>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
match self.0 {
|
||||
Value::String(s) => visitor.visit_enum(s.as_str().into_deserializer()),
|
||||
Value::Object(map) if map.len() == 1 => {
|
||||
if let Some((k, v)) = map.iter().next() {
|
||||
visitor.visit_enum(StrictEnum(k, v))
|
||||
} else {
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V: Visitor<'de>>(
|
||||
self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error> {
|
||||
if name == "TextEffects" {
|
||||
let fill = match self.0 {
|
||||
Value::Array(values) => fields.iter().position(|&field| field == "fill").and_then(|index| values.get(index)),
|
||||
_ => self.0.get("fill"),
|
||||
};
|
||||
if let Some(fill) = fill {
|
||||
validate_text_fill(fill)?;
|
||||
}
|
||||
}
|
||||
if let Value::Object(map) = self.0 {
|
||||
for key in map.keys() {
|
||||
if !fields.contains(&key.as_str()) {
|
||||
return Err(serde::de::Error::custom(format!("unknown field `{key}`")));
|
||||
}
|
||||
}
|
||||
return visitor.visit_map(StrictMap(map.iter(), None));
|
||||
}
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
|
||||
unit unit_struct seq tuple tuple_struct map identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
T::deserialize(StrictDe(v)).map_err(|e| CmdError::Params(format!("`{section}`: {e}")))
|
||||
}
|
||||
|
||||
/// Modify a style's character and paragraph formatting, display name or next-paragraph style.
|
||||
pub(super) fn modify_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let id = style_id(s, p::req_str(v, "style")?)?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let para: Option<ParaProps> =
|
||||
v.get("para").map(|c| serde_json::from_value(c.clone())).transpose().map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
let chr: Option<CharProps> = v.get("chr").map(|c| deserialize_strict("chr", c)).transpose()?;
|
||||
let para: Option<ParaProps> = v.get("para").map(|c| deserialize_strict("para", c)).transpose()?;
|
||||
let next = p::str(v, "next").map(str::to_string);
|
||||
let name = p::str(v, "name").map(str::to_string);
|
||||
let d = &s.doc.styles.default_chr;
|
||||
|
||||
@@ -20,7 +20,8 @@ use fields::caption;
|
||||
#[cfg(test)]
|
||||
use fields::output_fields_with;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, caption_preview, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in,
|
||||
update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
|
||||
@@ -27,12 +27,29 @@ pub const CHAPTER_SEPARATORS: [&str; 5] = ["-", ".", ":", "\u{2014}", "\u{2013}"
|
||||
/// a chapter number (`STYLEREF n \s` and a separator) and a `SEQ label \* format \s n` number
|
||||
/// (ECMA-376 §17.16.5.56, §17.16.5.59).
|
||||
pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let text = p::str(v, "text").unwrap_or("");
|
||||
s.doc.insert_block(story, &at, Block::Para(caption_paragraph(v, text)?))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story, path: at, off });
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Number a prospective caption at its insertion site without changing the document or selection.
|
||||
pub fn caption_preview(s: &Session, v: &Value) -> Result<String, CmdError> {
|
||||
let (story, at) = caption_site(s, v);
|
||||
let mut doc = s.doc.clone();
|
||||
doc.insert_block(story, &at, Block::Para(caption_paragraph(v, "")?))?;
|
||||
update_seq_in(&mut doc)?;
|
||||
Ok(doc.para(story, &at).map_or_else(String::new, Paragraph::plain_text))
|
||||
}
|
||||
|
||||
fn caption_paragraph(v: &Value, text: &str) -> Result<Paragraph, CmdError> {
|
||||
let label: String = p::str(v, "label").unwrap_or("Figure").chars().filter(|c| !matches!(c, '"' | '\\') && !c.is_control()).take(40).collect();
|
||||
let label = if label.trim().is_empty() { "Figure".to_string() } else { label.trim().to_string() };
|
||||
// SEQ identifiers are one word: Word joins a multi-word label with underscores.
|
||||
let ident = label.split_whitespace().collect::<Vec<_>>().join("_");
|
||||
let text = p::str(v, "text").unwrap_or("").to_string();
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let format = seq_format(p::str(v, "format").unwrap_or("ARABIC"));
|
||||
let chapter = p::u64(v, "chapter").filter(|l| (1..=9).contains(l));
|
||||
let sep = p::str(v, "separator").and_then(|x| CHAPTER_SEPARATORS.iter().find(|s| **s == x)).copied().unwrap_or("-");
|
||||
@@ -51,10 +68,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if !text.is_empty() {
|
||||
para.insert_text(para.len(), &format!(": {text}"), &CharProps::default())?;
|
||||
}
|
||||
Ok(para)
|
||||
}
|
||||
|
||||
fn caption_site(s: &Session, v: &Value) -> (StoryRef, Path) {
|
||||
// A selected picture, shape or chart: next to the paragraph holding it, in the same cell or
|
||||
// text box (#1230). Otherwise next to the caret's top-level block: a paragraph, or the whole
|
||||
// table it is in.
|
||||
let f = s.sel.focus.clone();
|
||||
let f = &s.sel.focus;
|
||||
let above = p::str(v, "position") == Some("above");
|
||||
let at = match crate::cmd::objects::object_selection(s) {
|
||||
Some((pos, _)) => {
|
||||
let k = pos.path.last();
|
||||
@@ -65,11 +87,7 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Path::top(if above { top } else { top.saturating_add(1) })
|
||||
}
|
||||
};
|
||||
s.doc.insert_block(f.story, &at, Block::Para(para))?;
|
||||
update_seq(s)?;
|
||||
let off = s.doc.para(f.story, &at).map_or(0, |p| p.len());
|
||||
s.sel = Selection::caret(Pos { story: f.story, path: at, off });
|
||||
sel_result(s)
|
||||
(f.story, at)
|
||||
}
|
||||
|
||||
/// Renumber the body's SEQ fields in document order, honouring `\* format`, `\s level` (restart
|
||||
@@ -78,11 +96,15 @@ pub(super) fn caption(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// the last level-n heading's number, or its count when the heading isn't numbered) and the
|
||||
/// text or number of the nearest paragraph of a style.
|
||||
pub fn update_seq(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_seq_in(&mut s.doc)
|
||||
}
|
||||
|
||||
fn update_seq_in(doc: &mut wordcraft_doc::Document) -> Result<(), CmdError> {
|
||||
// Numbers first: a STYLEREF to a heading that holds a SEQ field shows its new number.
|
||||
let numbers = seq_results(&s.doc);
|
||||
apply_results(&mut s.doc, numbers)?;
|
||||
let refs = styleref_results(&s.doc);
|
||||
apply_results(&mut s.doc, refs)
|
||||
let numbers = seq_results(doc);
|
||||
apply_results(doc, numbers)?;
|
||||
let refs = styleref_results(doc);
|
||||
apply_results(doc, refs)
|
||||
}
|
||||
|
||||
/// A field's fresh result: its story and paragraph, its object index there and the text.
|
||||
|
||||
@@ -264,8 +264,7 @@ fn resolve_loose_blocks(blocks: &mut wordcraft_doc::Blocks, accept: bool) -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph. Only apply it
|
||||
/// when paragraph removal or joining also moves the endpoint.
|
||||
/// Byte offset after resolving the runs in the endpoint's original paragraph.
|
||||
fn resolved_offset(s: &Session, end: &Pos, accept: bool) -> usize {
|
||||
let Some(para) = s.doc.para_at(end) else { return end.off };
|
||||
let removed: usize = para
|
||||
@@ -307,6 +306,8 @@ fn remap_after_middle_paragraph(s: &mut Session, story: StoryRef, path: &wordcra
|
||||
|
||||
fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let mut offsets = [&s.sel.anchor, &s.sel.focus].map(|end| resolved_offset(s, end, accept));
|
||||
s.sel.anchor.off = offsets[0];
|
||||
s.sel.focus.off = offsets[1];
|
||||
let stories: Vec<StoryRef> = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k))).collect();
|
||||
for st in stories {
|
||||
for path in s.doc.para_paths(st).into_iter().rev() {
|
||||
@@ -319,10 +320,11 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
|
||||
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
|
||||
if trailing && remove_trailing_para(s, st, &path)? {
|
||||
// Selection ends in the removed paragraph go to the end of the one before it;
|
||||
// clamping later would keep their offsets in that paragraph's text (#8500).
|
||||
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
|
||||
// keep that offset through any later remapping when earlier edits resolve.
|
||||
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(&mut offsets) {
|
||||
if end.story == st && end.path == path {
|
||||
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
|
||||
*offset = end.off;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,12 +123,12 @@ pub(super) fn insert(s: &mut Session, v: &Value) -> CmdResult {
|
||||
s.push_undo("AutoFormat", doc, sel);
|
||||
// Undo right after it makes the capitalised word an exception.
|
||||
let depth = s.undo_steps_so_far();
|
||||
if let Some(c) = s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
c.depth = depth;
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.commit_depth(depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
s.set_ime_edit_outcome(outcome);
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -87,22 +87,35 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
|
||||
}
|
||||
if f.off > 0 {
|
||||
let a = Pos { off: para.backspace_from(f.off), ..f.clone() };
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
let carried = deleted_char_props(s, &a, &f);
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome {
|
||||
classified: true,
|
||||
content_changed: effect.content_changed,
|
||||
state_changed: effect.state_changed,
|
||||
transformed: false,
|
||||
selection_changed: false,
|
||||
});
|
||||
let (content_changed, state_changed, transformed) = if let Some(start) =
|
||||
s.autocap.as_ref().and_then(|c| c.pronoun_before_separator(&a, &f, s.undo_steps_so_far()))
|
||||
&& matches!(para.text.get(start.off..f.off), Some("I " | "I," | "I." | "I;" | "I:" | "I!" | "I?"))
|
||||
{
|
||||
// This restores a letter in place. Ordinary typing over a selection removes its link.
|
||||
let props = para.props_of_char(start.off);
|
||||
let linked_letter = props.link.as_ref().map(|_| props.clone());
|
||||
s.sel = Selection { anchor: start.clone(), focus: f.clone() };
|
||||
let pending = std::mem::replace(&mut s.pending, linked_letter);
|
||||
let effect = crate::cmd::type_text_effect(s, "i");
|
||||
s.pending = pending;
|
||||
let effect = effect?;
|
||||
if let Some(c) = &mut s.autocap {
|
||||
c.note_backspace(&start, &f);
|
||||
}
|
||||
(effect.content_changed, effect.state_changed, true)
|
||||
} else {
|
||||
if let Some(c) = s.autocap.as_mut() {
|
||||
c.note_backspace(&a, &f);
|
||||
}
|
||||
s.sel = Selection { anchor: a.clone(), focus: f };
|
||||
let effect = delete_selection_effect(s)?;
|
||||
(effect.content_changed, effect.state_changed, false)
|
||||
};
|
||||
s.set_ime_edit_outcome(crate::ImeEditOutcome { classified: true, content_changed, state_changed, transformed, selection_changed: false });
|
||||
// As in Word, text typed next takes the deleted character's formatting until the caret
|
||||
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
|
||||
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
if content_changed && s.sel.is_collapsed() && s.sel.focus == a {
|
||||
s.pending_at = carried.as_ref().map(|_| a.clone());
|
||||
s.pending = carried;
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
if let Some((doc, sel)) = plain {
|
||||
// Removes the marks, then AutoCorrects the word as without them.
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
let (done_doc, done_sel) = (std::mem::replace(&mut s.doc, doc), std::mem::replace(&mut s.sel, sel));
|
||||
let new = split_para(s, &at)?;
|
||||
let c = s.doc.para_at(&new).map(|p| p.mark.clone()).unwrap_or_default();
|
||||
@@ -165,7 +165,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
|
||||
return Ok(());
|
||||
}
|
||||
crate::cmd::tools::autocorrect_word(s, true)?;
|
||||
s.autocap.take_if(|c| c.depth == u64::MAX);
|
||||
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
|
||||
at = s.sel.focus.clone();
|
||||
}
|
||||
let new = split_para(s, &at)?;
|
||||
|
||||
@@ -268,6 +268,15 @@ fn plain_word(w: &str) -> bool {
|
||||
!w.trim().is_empty() && w.chars().count() <= MAX_FROM && !w.contains(|c: char| c.is_whitespace() || c == '\u{FFFC}')
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct PronounCap {
|
||||
depth: u64,
|
||||
story: wordcraft_doc::StoryRef,
|
||||
path: wordcraft_doc::Path,
|
||||
start: usize,
|
||||
backspaced: bool,
|
||||
}
|
||||
|
||||
/// The newest automatic capitalisation (a sentence capital, a TWo INitial CApitals fix), kept so
|
||||
/// that undoing it, or backspacing it and typing the word again, makes an exception (#1857).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -283,11 +292,64 @@ pub struct AutoCap {
|
||||
pub(super) prev: String,
|
||||
/// The TWo INitial CApitals word as typed ("TWo").
|
||||
pub(super) two_caps: Option<String>,
|
||||
/// The English replacement of lowercase i with uppercase I, kept alongside an earlier sentence
|
||||
/// capital so an automatic `I` does not wipe the pending first-letter exception.
|
||||
pub(super) pronoun: Option<PronounCap>,
|
||||
/// The user backspaced into the word after the change.
|
||||
pub(super) backspaced: bool,
|
||||
}
|
||||
|
||||
impl AutoCap {
|
||||
pub(crate) fn commit_depth(&mut self, depth: u64) {
|
||||
if self.depth == u64::MAX {
|
||||
self.depth = depth;
|
||||
}
|
||||
if let Some(p) = self.pronoun.as_mut().filter(|p| p.depth == u64::MAX) {
|
||||
p.depth = depth;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_uncommitted(slot: &mut Option<Self>) {
|
||||
if let Some(c) = slot.as_mut() {
|
||||
if c.pronoun.as_ref().is_some_and(|p| p.depth == u64::MAX) {
|
||||
c.pronoun = None;
|
||||
}
|
||||
if c.depth == u64::MAX {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn record_pronoun(slot: &mut Option<Self>, story: wordcraft_doc::StoryRef, path: wordcraft_doc::Path, start: usize) {
|
||||
let pronoun = PronounCap { depth: u64::MAX, story, path: path.clone(), start, backspaced: false };
|
||||
if let Some(c) = slot.as_mut().filter(|c| !c.prev.is_empty() || c.two_caps.is_some()) {
|
||||
c.pronoun = Some(pronoun);
|
||||
} else {
|
||||
*slot =
|
||||
Some(Self { depth: u64::MAX, story, path, start, prev: String::new(), two_caps: None, pronoun: Some(pronoun), backspaced: false });
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take_backspaced_pronoun(slot: &mut Option<Self>, english: bool, word: &str, f: &Pos, start: usize) -> bool {
|
||||
let Some(c) = slot.as_mut() else { return false };
|
||||
let Some(p) = c.pronoun.take() else { return false };
|
||||
if c.prev.is_empty() && c.two_caps.is_none() {
|
||||
*slot = None;
|
||||
}
|
||||
english && word == "i" && p.backspaced && p.story == f.story && p.path == f.path && p.start == start
|
||||
}
|
||||
|
||||
/// The start of a just-corrected I when Backspace removes the separator after it.
|
||||
pub(crate) fn pronoun_before_separator(&self, a: &Pos, f: &Pos, undo_steps: u64) -> Option<Pos> {
|
||||
let p = self.pronoun.as_ref()?;
|
||||
(!p.backspaced
|
||||
&& p.story == f.story
|
||||
&& p.path == f.path
|
||||
&& p.start.checked_add(1) == Some(a.off)
|
||||
&& p.depth.checked_add(1) == Some(undo_steps))
|
||||
.then(|| Pos { off: p.start, ..f.clone() })
|
||||
}
|
||||
|
||||
pub(crate) fn add_exceptions(self, ac: &mut AutoCorrectPrefs) {
|
||||
if ac.auto_add_first_letter && !self.prev.is_empty() {
|
||||
ac.add_exception(self.prev);
|
||||
@@ -304,6 +366,14 @@ impl AutoCap {
|
||||
if f.story == self.story && f.path == self.path && a.off <= self.start && f.off > self.start {
|
||||
self.backspaced = true;
|
||||
}
|
||||
if let Some(p) = &mut self.pronoun
|
||||
&& f.story == p.story
|
||||
&& f.path == p.path
|
||||
&& a.off <= p.start
|
||||
&& f.off > p.start
|
||||
{
|
||||
p.backspaced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,41 @@ fn resolving_a_middle_paragraph_keeps_the_caret_with_its_text() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_all_keeps_selection_with_surviving_multibyte_text_in_the_same_paragraph() {
|
||||
for (cmd, initial) in [("review.acceptAll", "雪漢字Q"), ("review.rejectAll", "漢字Q")] {
|
||||
let mut original = Session::new(Document::from_text(initial));
|
||||
let removed = "雪".len();
|
||||
let first_kept = "漢".len();
|
||||
original.run("review.trackChanges", &json!({"value": true})).unwrap();
|
||||
if cmd == "review.acceptAll" {
|
||||
original.sel = Selection { anchor: Pos::body(0, 0), focus: Pos::body(0, removed) };
|
||||
original.run("text.delete", &json!({})).unwrap();
|
||||
} else {
|
||||
original.sel = Selection::caret(Pos::body(0, 0));
|
||||
original.run("text.insert", &json!({"text": "雪"})).unwrap();
|
||||
}
|
||||
assert_eq!(original.doc.plain_text(StoryRef::Body), "雪漢字Q");
|
||||
|
||||
for (before, after, typed) in [
|
||||
(Selection::caret(Pos::body(0, removed)), Selection::caret(Pos::body(0, 0)), "!漢字Q"),
|
||||
(
|
||||
Selection { anchor: Pos::body(0, removed + first_kept), focus: Pos::body(0, removed) },
|
||||
Selection { anchor: Pos::body(0, first_kept), focus: Pos::body(0, 0) },
|
||||
"!字Q",
|
||||
),
|
||||
] {
|
||||
let mut s = Session::new(original.doc.clone());
|
||||
s.sel = before;
|
||||
s.run(cmd, &json!({"stopTracking": true})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "漢字Q", "{cmd}");
|
||||
assert_eq!(s.sel, after, "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "!"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), typed, "{cmd}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepting_a_middle_paragraph_join_keeps_the_backward_selection() {
|
||||
let mut s = Session::new(Document::from_text("A\néDROP\nX🙂B\nC"));
|
||||
@@ -163,19 +198,20 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
|
||||
|
||||
#[test]
|
||||
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
|
||||
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
|
||||
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
|
||||
// same offsets of that paragraph's text (#8500).
|
||||
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
|
||||
for (orig, revised, cmd) in cases {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
|
||||
let keep = "A\nKeep this";
|
||||
// Both endpoints of the removed paragraph go to the preceding paragraph's end (#8500),
|
||||
// even if removing another paragraph subsequently shifts that paragraph up (#8913).
|
||||
for (changed, last) in [("A\nKeep this\nNEW", 2), ("A\nEarlier\nKeep this\nNEW", 3)] {
|
||||
for (orig, revised, cmd) in [(keep, changed, "review.rejectAll"), (changed, keep, "review.acceptAll")] {
|
||||
let mut s = Session::new(Document::from_text(orig));
|
||||
s.run("review.compare", &json!({"text": revised})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(last, 0), "focus": Pos::body(last, 3)})).unwrap();
|
||||
s.run(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), keep, "{cmd}, last block {last}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}, last block {last}");
|
||||
s.run("text.insert", &json!({"text": "Z"})).unwrap();
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}, last block {last}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
&& letters.chars().nth(1).is_some_and(char::is_uppercase)
|
||||
&& letters.chars().next().is_some_and(char::is_uppercase))
|
||||
.then(|| letters.clone()),
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
let fixed: String = reps.concat();
|
||||
@@ -84,7 +85,9 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
// A whole-word replacement, else "wait..." → "wait…". Proofing decides what is English the
|
||||
// same way (#835); every English (en-GB, en-CA…) counts (#1281).
|
||||
let english = s.doc.para_at(&f).is_none_or(|_| wordcraft_proof::ProofLang::from_tag(lang.as_deref()).is_english());
|
||||
let found = if ac.replace_text { ac.replacement_in(&word, english) } else { None };
|
||||
// A rejected pronoun is kept at this occurrence only, including at the start of a sentence.
|
||||
let keep_i = AutoCap::take_backspaced_pronoun(&mut s.autocap, english, &word, &f, start);
|
||||
let found = if ac.replace_text && !keep_i { ac.replacement_in(&word, english) } else { None };
|
||||
let (from, rep) = match found {
|
||||
Some(r) => (start, Some(r)),
|
||||
None if ac.replace_text && word.len() > 3 && word.ends_with("...") => (start + word.len() - 3, Some("…".to_string())),
|
||||
@@ -106,6 +109,9 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
para.insert_text(from, &rep, &props)?;
|
||||
caret = (f.off + rep.len()).saturating_sub(end - from);
|
||||
s.sel = Selection::caret(Pos { off: caret, ..f.clone() });
|
||||
if english && word == "i" && rep == "I" {
|
||||
AutoCap::record_pronoun(&mut s.autocap, f.story, f.path.clone(), start);
|
||||
}
|
||||
}
|
||||
let end = caret.saturating_sub(trigger);
|
||||
let Some(word) = s.doc.para_at(&f).and_then(|p| p.text.get(start..end)).map(str::to_string) else { return Ok(()) };
|
||||
@@ -147,7 +153,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
} else {
|
||||
last
|
||||
};
|
||||
let mut sentence = sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let mut sentence = !keep_i && sentence_on && starts_sentence(before_word, &exceptions) && should_capitalize(first, next);
|
||||
let prev = if sentence { prev_token(before_word) } else { String::new() };
|
||||
// Typing the word again after backspacing an automatic capital: the user doesn't want it
|
||||
// (Word's "Automatically add words to list"); an exception, so no capital this time either.
|
||||
@@ -173,7 +179,16 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
|
||||
match s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
|
||||
Some(c) => c.prev = prev,
|
||||
None => {
|
||||
s.autocap = Some(AutoCap { depth: u64::MAX, story: f.story, path: f.path, start, prev, two_caps: None, backspaced: false })
|
||||
s.autocap = Some(AutoCap {
|
||||
depth: u64::MAX,
|
||||
story: f.story,
|
||||
path: f.path,
|
||||
start,
|
||||
prev,
|
||||
two_caps: None,
|
||||
pronoun: None,
|
||||
backspaced: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! `/work`), exactly: on Windows what exists is resolved to its real case first.
|
||||
//! - Writing replaces or removes a directory entry, so for write access the entry itself (its
|
||||
//! folder's links followed, its own name as given) must lie inside the root as well: a link
|
||||
//! folder's links followed, its own name as it stands) must lie inside the root as well: a link
|
||||
//! outside the root that leads into it is not a way to write outside (#3735).
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
@@ -222,14 +222,24 @@ fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
|
||||
/// The directory entry `path` names: its folder resolved as [`resolve`] resolves it, then its own
|
||||
/// name as given, so a link there is the entry itself, not what it leads to. That entry is what
|
||||
/// replacing or removing the file changes.
|
||||
/// replacing or removing the file changes. What exists and isn't a link gets its real case, which
|
||||
/// is how the root is spelled when another spelling of the root is named.
|
||||
fn resolve_entry(path: &str) -> Result<PathBuf, String> {
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?;
|
||||
let (Some(folder), Some(name)) = (absolute.parent(), absolute.file_name()) else {
|
||||
return Err(format!("automation path rejected: not a file name: {path}"));
|
||||
};
|
||||
let mut entry = resolve_absolute(path, folder)?;
|
||||
entry.push(name);
|
||||
let resolved_folder = resolve_absolute(path, folder)?;
|
||||
let entry = resolved_folder.join(name);
|
||||
// Only accept `canonicalize` (for on-disk case) when it stays in `resolved_folder` under the
|
||||
// same name, so a symlink swapped in after `symlink_metadata` cannot redirect outside -> inside (#9292).
|
||||
if std::fs::symlink_metadata(&entry).is_ok_and(|m| !m.file_type().is_symlink())
|
||||
&& let Ok(canon) = std::fs::canonicalize(&entry)
|
||||
&& canon.parent() == Some(resolved_folder.as_path())
|
||||
&& canon.file_name().is_some_and(|c| c.to_string_lossy().eq_ignore_ascii_case(&name.to_string_lossy()))
|
||||
{
|
||||
return Ok(canon);
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
@@ -270,30 +280,19 @@ fn resolve_absolute(path: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
/// Is `path` (resolved) `root` or inside it, component by component? Exactly, on Windows too: what
|
||||
/// exists has its real case from [`resolve`], and a folder that doesn't exist yet may be a different
|
||||
/// one from the root where a parent folder is case sensitive.
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
root.components().all(|r| path.next() == Some(r))
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return false;
|
||||
}
|
||||
match (a.as_os_str().to_str(), b.as_os_str().to_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
|
||||
let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered =
|
||||
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
@@ -387,6 +386,7 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A root and a path reached through links are compared after the links are followed.
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
@@ -434,20 +434,78 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that differs in case is another name until the file system says otherwise.
|
||||
#[test]
|
||||
fn names_are_compared_exactly() {
|
||||
let root = Path::new("/work/In");
|
||||
assert!(inside(Path::new("/work/In/new/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/IN/a.docx"), root));
|
||||
assert!(!inside(Path::new("/WORK/In/a.docx"), root));
|
||||
assert!(!inside(Path::new("/work/in\u{212A}/a.docx"), Path::new("/work/ink")), "the Kelvin sign folds to k");
|
||||
if cfg!(windows) {
|
||||
let root = Path::new(r"C:\work\In");
|
||||
assert!(inside(Path::new(r"c:\work\In\a.docx"), root), "a drive letter is one drive in either case");
|
||||
assert!(!inside(Path::new(r"C:\work\IN\a.docx"), root));
|
||||
}
|
||||
}
|
||||
|
||||
/// In a case-sensitive folder, `IN` beside the root `in` is another folder, there or not yet.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
fn a_case_sensitive_folder_keeps_a_differently_cased_name_out() {
|
||||
let base = std::env::temp_dir().join(format!("wc-file-access-case-sensitive-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let set = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output();
|
||||
if !set.as_ref().is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: a case-sensitive folder can't be made here: {set:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir(base.join("in")).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("in"))).unwrap().unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/new.docx")), Access::Write), Ok(()));
|
||||
let e = roots.check(&s(base.join("IN/new.docx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
std::fs::create_dir(base.join("IN")).unwrap();
|
||||
std::fs::write(base.join("IN/secret.docx"), "x").unwrap();
|
||||
let e = roots.check(&s(base.join("IN/secret.docx")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// On Windows a path finds its real case on disk, and device names are refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_finds_the_real_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/A.SVG"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(&s(base.join("In/Sub/New.docx")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT/New.docx")), Access::Write), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT")), Access::Write), Ok(()), "the root itself, in another spelling");
|
||||
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
|
||||
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A symlink beside the write root that leads into it is not inside the root: writing would replace the link.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sibling_symlink_into_the_write_root_is_rejected() {
|
||||
let (base, roots) = folders("sibling-link");
|
||||
let link = base.join("evil");
|
||||
std::os::unix::fs::symlink(base.join("out"), &link).unwrap();
|
||||
let e = roots.check(&s(link), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Scopes nest, and a scope applies only on the thread that set it.
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
@@ -469,12 +527,13 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// What is a device name, with superscript digits and a name before a colon, and what isn't.
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL "] {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.docx", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x"] {
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.docx", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,10 @@ impl Session {
|
||||
/// A navigated style change is for the Accept or Reject that follows: a command that edits
|
||||
/// or moves the selection forgets it.
|
||||
fn forget_review_style(&mut self, id: &str, mutates: bool) {
|
||||
if (mutates && !matches!(id, "review.accept" | "review.reject")) || id.starts_with("caret.") || id.starts_with("select.") {
|
||||
if (mutates && !matches!(id, "review.accept" | "review.reject" | "review.acceptAndNext" | "review.rejectAndNext"))
|
||||
|| id.starts_with("caret.")
|
||||
|| id.starts_with("select.")
|
||||
{
|
||||
self.review_style = None;
|
||||
}
|
||||
}
|
||||
|
||||
+184
-29
@@ -312,6 +312,9 @@ fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_thei
|
||||
assert!(wordcraft_proof::user_dictionary().contains(&"zxqengconfined".to_string()), "kept in memory");
|
||||
wordcraft_proof::remove_word("zxqengconfined");
|
||||
assert!(!outside.exists(), "nothing written outside the write root");
|
||||
std::fs::write(&outside, "outsideword\n").unwrap();
|
||||
assert!(confined(&mut s, "file.options", json!({"customDictionary": outside})).is_err());
|
||||
assert_eq!(s.prefs.custom_dictionary, None);
|
||||
for key in ["dictionariesFolder", "userTemplatesFolder"] {
|
||||
assert!(confined(&mut s, "file.options", json!({key: base.join("outside").to_string_lossy()})).is_err(), "{key}");
|
||||
}
|
||||
@@ -407,33 +410,6 @@ fn custom_dictionary_freestanding_file_option() {
|
||||
let rel_err = s.run("file.options", &json!({"customDictionary": "relative/custom.dic"})).unwrap_err();
|
||||
assert!(format!("{rel_err:?}").contains("isn't a full path"));
|
||||
|
||||
// Accept ~/ path expansion when HOME points to a directory.
|
||||
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
|
||||
let home_dir = std::path::PathBuf::from(home);
|
||||
let test_name = format!(".wordcraft-test-tilde-{}.dic", std::process::id());
|
||||
let tilde_file = home_dir.join(&test_name);
|
||||
struct CleanFile(std::path::PathBuf);
|
||||
impl Drop for CleanFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
if let Ok(mut f) = opts.open(&tilde_file) {
|
||||
use std::io::Write;
|
||||
let _ = f.write_all(b"tildeword\n");
|
||||
let _cleaner = CleanFile(tilde_file.clone());
|
||||
let tilde_res = s.run("file.options", &json!({"customDictionary": format!("~/{test_name}")}));
|
||||
assert!(tilde_res.is_ok(), "tilde expansion succeeds: {:?}", tilde_res.err());
|
||||
assert_eq!(s.prefs.custom_dictionary.as_deref(), Some(tilde_file.to_string_lossy().as_ref()));
|
||||
assert!(wordcraft_proof::is_correct("tildeword"));
|
||||
s.run("file.options", &json!({"customDictionary": "auto"})).unwrap();
|
||||
wordcraft_proof::remove_word("tildeword");
|
||||
wordcraft_proof::remove_word("defaultword");
|
||||
}
|
||||
}
|
||||
|
||||
let huge_dic = dir.path().join("huge.dic");
|
||||
std::fs::write(&huge_dic, vec![b'a'; (crate::custom_dict::MAX_CUSTOM_FILE_BYTES + 1024) as usize]).unwrap();
|
||||
assert!(s.run("file.options", &json!({"customDictionary": huge_dic.to_string_lossy()})).is_err());
|
||||
@@ -4532,6 +4508,14 @@ fn tracked_style_definition_changes_are_recorded_and_resolved() {
|
||||
run(&mut s, "review.acceptAll", json!({}));
|
||||
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.bold, Some(true), "accepting keeps the change");
|
||||
assert!(s.doc.revisions.is_empty());
|
||||
|
||||
for (command, italic) in [("review.rejectAndNext", None), ("review.acceptAndNext", Some(true))] {
|
||||
run(&mut s, "styles.modify", json!({"style": "Heading1", "chr": {"italic": true}}));
|
||||
run(&mut s, "review.nextChange", json!({}));
|
||||
run(&mut s, command, json!({}));
|
||||
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.italic, italic, "{command} resolves the navigated style definition");
|
||||
assert_eq!(run(&mut s, "review.changes", json!({})), json!([]), "{command} leaves no style change behind");
|
||||
}
|
||||
}
|
||||
|
||||
/// #2697 review: Update Style to Match Selection also rewrites the selected paragraph. Its body
|
||||
@@ -8455,6 +8439,156 @@ fn styles_apply_multi_paragraph_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9203: `styles.modify` rejects unknown keys in `para` and `chr` (such as snake_case names)
|
||||
/// instead of silently dropping them, while applying camelCase `ParaProps` fields.
|
||||
#[test]
|
||||
fn styles_modify_rejects_unknown_para_and_chr_fields() {
|
||||
let mut s = s();
|
||||
let err = s
|
||||
.run("styles.modify", &json!({"style": "Heading1", "para": {"space_before": 123, "page_break_before": true}, "chr": {"size": 33}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
|
||||
let h1 = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_ne!(h1.chr.size, Some(33.0), "rejected para block must not partially apply chr");
|
||||
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"unknownKey": true}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
|
||||
|
||||
// #9291: unknown keys inside nested structs (such as Borders / Border) are rejected too.
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"Top": {"width": 1.0}}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error for nested Borders key, got {err:?}");
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"top": {"bogus": 1.0}}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error for nested Border key, got {err:?}");
|
||||
|
||||
s.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "para": {"spaceBefore": 123.0, "pageBreakBefore": true, "borders": {"top": {"width": 1.5, "style": "single"}}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let h1 = s.doc.styles.get("Heading1").unwrap();
|
||||
assert_eq!(h1.para.space_before, Some(123.0));
|
||||
assert_eq!(h1.para.page_break_before, Some(true));
|
||||
assert!(h1.para.borders.as_ref().and_then(|b| b.top).is_some_and(|t| (t.width - 1.5).abs() < 0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_tagged_text_fill_fields_before_changing_the_style() {
|
||||
use wordcraft_doc::wordart::TextFill;
|
||||
|
||||
let mut s = s();
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
let gradient_stops = json!([{"pos": 0, "color": "112233"}, {"pos": 100, "color": "445566", "transparency": 25}]);
|
||||
for (fill, field) in [
|
||||
(json!({"type": "solid", "color": "FF0000", "bogus": 1}), "bogus"),
|
||||
(json!({"type": "none", "color": "FF0000"}), "color"),
|
||||
(json!({"type": "gradient", "stops": gradient_stops, "color": "FF0000"}), "color"),
|
||||
(json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}), "bogus"),
|
||||
] {
|
||||
let err = s
|
||||
.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": {"fill": fill}}}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains(field)), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before), "rejected fill must leave the style unchanged");
|
||||
}
|
||||
|
||||
let fill = |s: &Session| s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap();
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "solid", "color": "FF0000"}}}})).unwrap();
|
||||
assert_eq!(fill(&s), TextFill::Solid { color: wordcraft_doc::Rgb(255, 0, 0), transparency: 0.0 });
|
||||
s.run(
|
||||
"styles.modify",
|
||||
&json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "gradient", "angle": 45, "stops": gradient_stops}}}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(fill(&s), TextFill::Gradient { stops, angle } if angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "none"}}}})).unwrap();
|
||||
assert_eq!(fill(&s), TextFill::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_text_fills_in_positional_arguments() {
|
||||
use serde_json::Value;
|
||||
use wordcraft_doc::wordart::TextFill;
|
||||
|
||||
let chr_with = |text_effects: Value, positional: bool| {
|
||||
if positional {
|
||||
// CharProps puts textEffects after the first 30 optional fields.
|
||||
let mut fields = vec![Value::Null; 30];
|
||||
fields.push(text_effects);
|
||||
Value::Array(fields)
|
||||
} else {
|
||||
json!({"textEffects": text_effects})
|
||||
}
|
||||
};
|
||||
let mut s = s();
|
||||
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
|
||||
for (positional_chr, positional_effects) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let effects = |fill: Value| if positional_effects { json!([fill]) } else { json!({"fill": fill}) };
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
for fill in [
|
||||
json!({"type": "solid", "color": "FF0000", "bogus": 1}),
|
||||
json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
|
||||
json!(["gradient", [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
|
||||
] {
|
||||
let chr = chr_with(effects(fill), positional_chr);
|
||||
let params = json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": chr});
|
||||
let err = s.run("styles.modify", ¶ms).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
for fill in [json!({"type": "gradient", "stops": stops, "angle": 45}), json!(["gradient", stops, 45])] {
|
||||
let chr = chr_with(effects(fill), positional_chr);
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": chr})).unwrap();
|
||||
let fill = s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.as_ref().unwrap();
|
||||
assert!(matches!(fill, TextFill::Gradient { stops, angle } if *angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
|
||||
}
|
||||
}
|
||||
|
||||
let before = s.doc.styles.get("Heading1").unwrap().clone();
|
||||
let old = chr_with(json!([{"type": "solid", "color": "FF0000", "bogus": 1}]), true);
|
||||
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"fmtChange": {"rev": 0, "old": old}}})).unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_modify_checks_numeric_text_fill_tags() {
|
||||
let mut refused = s();
|
||||
let before = refused.doc.styles.get("Heading1").unwrap().clone();
|
||||
for fill in [
|
||||
json!({"type": 0, "bogus": 1}),
|
||||
json!({"type": 1, "color": "FF0000", "bogus": 1}),
|
||||
json!({"type": 2, "stops": [{"pos": 0, "color": "112233"}], "bogus": 1}),
|
||||
json!({"type": 2, "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
|
||||
json!([2, [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
|
||||
] {
|
||||
let err = refused
|
||||
.run("styles.modify", &json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": [fill]}}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
|
||||
assert_eq!(refused.doc.styles.get("Heading1"), Some(&before));
|
||||
}
|
||||
|
||||
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
|
||||
for (fill, named) in [
|
||||
(json!({"type": 0}), json!({"type": "none"})),
|
||||
(json!([0]), json!({"type": "none"})),
|
||||
(json!({"type": 1, "color": "FF0000"}), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
|
||||
(json!([1, "FF0000", 0]), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
|
||||
(json!({"type": 2, "stops": stops, "angle": 45}), json!({"type": "gradient", "stops": stops, "angle": 45})),
|
||||
(json!([2, stops, 45]), json!({"type": "gradient", "stops": stops, "angle": 45})),
|
||||
] {
|
||||
let set_fill = |fill| {
|
||||
let mut s = s();
|
||||
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": fill}}})).unwrap();
|
||||
s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap()
|
||||
};
|
||||
assert_eq!(set_fill(fill), set_fill(named));
|
||||
}
|
||||
}
|
||||
|
||||
/// #865: `styles.modify` takes a colour the way `format.color` does (`RRGGBB`, `#RRGGBB`, `auto`),
|
||||
/// still reads the serialized forms, and rejects a bad colour without touching the style.
|
||||
#[test]
|
||||
@@ -12458,6 +12592,7 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
// A language without proofing tools: no marks. `zxx` (no linguistic content) never has
|
||||
// them; a real language such as fr-FR does wherever its system Hunspell dictionary is installed.
|
||||
run(&mut s, "review.language", json!({"lang": "zxx"}));
|
||||
assert_eq!(run(&mut s, "format.state", json!({}))["lang"], "zxx");
|
||||
assert_eq!(run(&mut s, "review.issues", json!({})), json!([]));
|
||||
}
|
||||
|
||||
@@ -15059,7 +15194,7 @@ fn export_png_refuses_a_path_that_is_not_png() {
|
||||
#[test]
|
||||
fn ime_body_epoch_marks_body_replacements_not_edits() {
|
||||
let mut s = s();
|
||||
let id = s.document_id();
|
||||
let document_id = s.document_id();
|
||||
run(&mut s, "text.insert", json!({"text": "one"}));
|
||||
let first = s.ime_body_epoch();
|
||||
run(&mut s, "text.insert", json!({"text": " two"}));
|
||||
@@ -15068,7 +15203,7 @@ fn ime_body_epoch_marks_body_replacements_not_edits() {
|
||||
run(&mut s, "document.setText", json!({"text": "same text"}));
|
||||
let replaced = s.ime_body_epoch();
|
||||
assert!(replaced > first, "setText replaces the body under the same document id");
|
||||
assert_eq!(s.document_id(), id, "the document id itself is unchanged");
|
||||
assert_eq!(s.document_id(), document_id, "the document id itself is unchanged");
|
||||
|
||||
// The same text again still replaces the body: a composition must not survive on content
|
||||
// equality.
|
||||
@@ -16035,6 +16170,26 @@ fn replace_all_with_track_changes_keeps_caret_when_original_story_has_no_match()
|
||||
);
|
||||
}
|
||||
|
||||
/// #9186: With Track Changes on, Replace All must keep the caret in its original story even when
|
||||
/// both that story and the main text have matches.
|
||||
#[test]
|
||||
fn replace_all_with_track_changes_keeps_caret_in_original_story_when_both_match() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body: [NAME]."}));
|
||||
let header_id = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
let header_story = StoryRef::Part(header_id);
|
||||
t.sel = crate::session::Selection::caret(Pos::new(header_story, wordcraft_doc::Path::top(0), 0));
|
||||
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 2, "{r}");
|
||||
assert_eq!(t.sel.focus.story, header_story, "caret must stay in the header story");
|
||||
assert!(t.in_header_footer());
|
||||
assert!(t.doc.plain_text(StoryRef::Body).contains("Jane"));
|
||||
assert!(t.doc.plain_text(header_story).contains("Jane"));
|
||||
}
|
||||
|
||||
/// #9064: Replace All skips stories nothing shows any more (a removed header, a footnote whose
|
||||
/// reference was deleted without tracking) and does not count them.
|
||||
#[test]
|
||||
|
||||
@@ -7,24 +7,31 @@ use crate::Session;
|
||||
use crate::cmd::insert::base64_encode;
|
||||
|
||||
#[test]
|
||||
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
|
||||
fn format_state_reports_the_east_asian_theme_face_and_per_run_fallbacks() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::props::ThemeFont;
|
||||
use wordcraft_doc::{Document, Path, StoryRef};
|
||||
|
||||
let mut doc = Document::from_text("漢字");
|
||||
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
|
||||
doc.para_mut(StoryRef::Body, &Path::top(0))
|
||||
.unwrap()
|
||||
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
|
||||
.unwrap();
|
||||
let first = "漢".len();
|
||||
let second = "漢字".len();
|
||||
let mut doc = Document::from_text("漢字文");
|
||||
let defaults = &mut Arc::make_mut(&mut doc.styles).default_chr;
|
||||
defaults.font = Some("Example Latin".into());
|
||||
defaults.font_ea = Some("Times New Roman".into());
|
||||
let para = doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
para.format(0, second, &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
|
||||
para.format(first, second, &|props| props.font = Some("Other Latin".into())).unwrap();
|
||||
let mut fallback = Session::new(doc.clone());
|
||||
fallback.run("select.all", &json!({})).unwrap();
|
||||
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
|
||||
for (start, end, family) in [(0, first, "Example Latin"), (first, second, "Other Latin")] {
|
||||
fallback.run("select.range", &json!({"anchor": Pos::body(0, start), "focus": Pos::body(0, end)})).unwrap();
|
||||
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], family);
|
||||
}
|
||||
fallback.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
|
||||
assert!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the unresolved slot uses each run's own font");
|
||||
|
||||
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
|
||||
let mut s = Session::new(doc);
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
|
||||
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
|
||||
s.run("select.all", &json!({})).unwrap();
|
||||
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
|
||||
|
||||
@@ -3171,6 +3171,80 @@ fn undoing_a_replacement_adds_no_exception() {
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So teh and the ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspacing_an_automatic_i_keeps_the_retyped_word_lowercase() {
|
||||
let mut s = typed("so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i");
|
||||
typ(&mut s, " want this and i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i want this and I ");
|
||||
|
||||
let mut s = typed("so i ");
|
||||
typ(&mut s, "\u{8}\u{8}i want this and i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i want this and I ");
|
||||
|
||||
let s = typed("i \u{8}\u{8}i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "i ");
|
||||
|
||||
let s = typed("so I \u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_i_keeps_pending_first_letter_exception_from_earlier_sentence_capital() {
|
||||
let mut s = typed("hello there. so i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So I ");
|
||||
// Backspacing back to "hello there. " and retyping "so " still learns "there.".
|
||||
typ(&mut s, "\u{8}\u{8}\u{8}\u{8}\u{8}so ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
|
||||
assert_eq!(first_letter_list(&s), ["there."]);
|
||||
|
||||
// Restoring lowercase "i" first still leaves the earlier sentence-capital record intact.
|
||||
let mut s = typed("hello there. so i ");
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So i");
|
||||
typ(&mut s, " \u{8}\u{8}\u{8}\u{8}\u{8}so ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
|
||||
assert_eq!(first_letter_list(&s), ["there."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_a_lowercase_i_preserves_the_deleted_separators_formatting_for_typing() {
|
||||
let mut s = typed("so ");
|
||||
run(&mut s, "format.bold", json!({"value": true}));
|
||||
typ(&mut s, "i");
|
||||
run(&mut s, "format.bold", json!({"value": false}));
|
||||
typ(&mut s, " ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I ");
|
||||
assert!(bold_at(&s, 3) && !bold_at(&s, 4));
|
||||
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So i");
|
||||
assert!(bold_at(&s, 3));
|
||||
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
|
||||
typ(&mut s, "x");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So ix");
|
||||
assert!(!bold_at(&s, 4), "the deleted separator was plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_a_lowercase_i_keeps_its_hyperlink() {
|
||||
let mut s = typed("so ");
|
||||
run(&mut s, "insert.link", json!({"url": "https://example.org/", "text": "ab"}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 4}}));
|
||||
typ(&mut s, " i ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a I b");
|
||||
assert_eq!(links(&s), [("a I b".into(), false)]);
|
||||
|
||||
typ(&mut s, "\u{8}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a ib");
|
||||
assert_eq!(links(&s), [("a ib".into(), false)]);
|
||||
typ(&mut s, "x");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "So a ixb");
|
||||
assert_eq!(links(&s), [("a ib".into(), false)], "the next letter uses the unlinked separator formatting");
|
||||
}
|
||||
|
||||
/// Checked in Word for Mac: the same rule as First Letter.
|
||||
#[test]
|
||||
fn undoing_an_initial_caps_fix_adds_an_initial_caps_exception() {
|
||||
@@ -3425,6 +3499,53 @@ fn backspace_deletes_selected_columns_and_delete_clears_them() {
|
||||
assert_eq!(table_cells(&s), [["a1", "", "c1"], ["a2", "", "c2"], ["a3", "", "c3"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_and_demote_only_change_list_levels_in_selected_cells() {
|
||||
for (command, changed_level) in [("para.promote", 0), ("para.demote", 2)] {
|
||||
let mut s = table_between(0, 1);
|
||||
let num = Arc::make_mut(&mut s.doc.numbering).try_add_list(wordcraft_doc::ListKind::Numbered).unwrap();
|
||||
let story = StoryRef::Body;
|
||||
for path in s.doc.para_paths(story) {
|
||||
s.doc.para_mut(story, &path).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 1 });
|
||||
}
|
||||
|
||||
run(&mut s, "table.selectColumn", json!({}));
|
||||
let range = s.cell_range().unwrap().clone();
|
||||
assert_eq!((range.rows, range.cols), ((0, 2), (1, 1)));
|
||||
let selected = s.sel.clone();
|
||||
run(&mut s, command, json!({}));
|
||||
assert_eq!(s.sel, selected);
|
||||
for path in s.doc.para_paths(story) {
|
||||
let expected = if path.cell().is_some_and(|(_, _, col)| col == 1) { changed_level } else { 1 };
|
||||
let actual = s.doc.para(story, &path).unwrap().props.numbering;
|
||||
assert_eq!(actual, Some(wordcraft_doc::props::NumRef { num, level: expected }), "{command}: {path:?}");
|
||||
}
|
||||
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
for path in s.doc.para_paths(story) {
|
||||
assert_eq!(
|
||||
s.doc.para(story, &path).unwrap().props.numbering,
|
||||
Some(wordcraft_doc::props::NumRef { num, level: 1 }),
|
||||
"undo {command}: {path:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_keeps_the_heading_at_the_end_of_a_text_selection_in_scope() {
|
||||
let mut s = typed("First\nSecond\nThird");
|
||||
for index in 0..3 {
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(index, 0)}));
|
||||
run(&mut s, "para.style", json!({"style": "Heading2"}));
|
||||
}
|
||||
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [2, 2, 2]);
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(1, 0)}));
|
||||
assert!(s.cell_range().is_none());
|
||||
run(&mut s, "para.promote", json!({}));
|
||||
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [1, 1, 2]);
|
||||
}
|
||||
|
||||
/// The first top-level table's cells, row by row, one entry per block: a paragraph's text, or
|
||||
/// `<table>` for a nested table.
|
||||
fn cell_blocks(s: &Session) -> Vec<Vec<Vec<String>>> {
|
||||
|
||||
@@ -483,3 +483,17 @@ fn named_instances_and_collection_members_are_capped() {
|
||||
// (under 0.1 s on a loaded machine) only backs up "read once", with room for a busy CI.
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_calibri_without_carlito_reports_the_drawn_fallback() {
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
db.faces.write().unwrap().retain(|face| !face.family.eq_ignore_ascii_case("Carlito"));
|
||||
assert!(!db.has_family("Carlito"));
|
||||
|
||||
let missing = crate::word::missing_metric_fonts_in(&db);
|
||||
let used = missing.iter().find(|(family, _)| *family == "Calibri").map_or("", |(_, used)| used.as_str());
|
||||
assert!(!used.is_empty(), "Calibri should be reported without Carlito");
|
||||
assert_ne!(used, "Carlito");
|
||||
assert!(db.has_family(used), "the notice names the face actually drawn");
|
||||
}
|
||||
|
||||
@@ -76,10 +76,10 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
|
||||
}
|
||||
}
|
||||
const SERIF: &[&str] = &["Caladea", "Times New Roman", "Liberation Serif", "Georgia", "Noto Serif", "DejaVu Serif", "Source Serif 4"];
|
||||
const MONO: &[&str] = &["Courier New", "Liberation Mono", "Menlo", "Consolas", "DejaVu Sans Mono", "JetBrains Mono"];
|
||||
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"];
|
||||
const MONO: &[&str] = &["Courier New", "Liberation Mono", "Cousine", "Menlo", "Consolas", "DejaVu Sans Mono", "JetBrains Mono"];
|
||||
const ARIAL: &[&str] = &["Liberation Sans", "Arimo", "Helvetica", "Helvetica Neue", "Source Sans 3"];
|
||||
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Arimo", "Helvetica", "Helvetica Neue", "Source Sans 3"];
|
||||
const TIMES: &[&str] = &["Liberation Serif", "Tinos", "Times", "Source Serif 4"];
|
||||
// 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.
|
||||
@@ -494,6 +494,37 @@ fn substitute(db: &FontDb, family: &str) -> Option<&'static str> {
|
||||
.or_else(|| installed.first().copied())
|
||||
}
|
||||
|
||||
/// Word's core families, each with the open fonts that share its metrics. Without the family or
|
||||
/// a twin, text set in it wraps and paginates differently from Word (Times New Roman drawn in a
|
||||
/// wider serif fits fewer lines to a page).
|
||||
const CORE_METRIC_FONTS: &[(&str, &[&str])] = &[
|
||||
("Times New Roman", &["Liberation Serif", "Tinos"]),
|
||||
("Arial", &["Liberation Sans", "Arimo"]),
|
||||
("Courier New", &["Liberation Mono", "Cousine"]),
|
||||
("Calibri", &["Carlito"]),
|
||||
("Cambria", &["Caladea"]),
|
||||
];
|
||||
|
||||
/// Word's core families not drawn with themselves or a metric twin, paired with the primary
|
||||
/// resolved family. Glyphs the primary family cannot draw may still use glyph fallback.
|
||||
pub fn missing_metric_fonts() -> Vec<(&'static str, String)> {
|
||||
missing_metric_fonts_in(FontDb::global())
|
||||
}
|
||||
|
||||
pub(crate) fn missing_metric_fonts_in(db: &FontDb) -> Vec<(&'static str, String)> {
|
||||
CORE_METRIC_FONTS
|
||||
.iter()
|
||||
.filter_map(|(word, twins)| {
|
||||
let resolved = resolve_with_db(db, word, false, false);
|
||||
if has_metric_resolution(db.has_family(word), twins, &resolved.face.family) { None } else { Some((*word, resolved.face.family.clone())) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn has_metric_resolution(installed_word_font: bool, twins: &[&str], resolved_family: &str) -> bool {
|
||||
installed_word_font || twins.iter().any(|twin| resolved_family.eq_ignore_ascii_case(twin))
|
||||
}
|
||||
|
||||
fn style_name(bold: bool, italic: bool) -> &'static str {
|
||||
match (bold, italic) {
|
||||
(false, false) => "Regular",
|
||||
@@ -705,9 +736,7 @@ pub fn resolve(family: &str, bold: bool, italic: bool) -> Resolved {
|
||||
return *r;
|
||||
}
|
||||
}
|
||||
let (fam, substituted) = resolve_family(db, family);
|
||||
let face = db.face(&fam, style_name(bold, italic));
|
||||
let r = Resolved { synth_bold: bold && face.weight < 600.0, synth_italic: italic && !face.italic, substituted, face: FaceRef::of(&face) };
|
||||
let r = resolve_with_db(db, family, bold, italic);
|
||||
if cacheable {
|
||||
let mut c = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if c.0 == generation {
|
||||
@@ -728,6 +757,12 @@ pub fn resolve(family: &str, bold: bool, italic: bool) -> Resolved {
|
||||
r
|
||||
}
|
||||
|
||||
fn resolve_with_db(db: &FontDb, family: &str, bold: bool, italic: bool) -> Resolved {
|
||||
let (fam, substituted) = resolve_family(db, family);
|
||||
let face = db.face(&fam, style_name(bold, italic));
|
||||
Resolved { synth_bold: bold && face.weight < 600.0, synth_italic: italic && !face.italic, substituted, face: FaceRef::of(&face) }
|
||||
}
|
||||
|
||||
/// A line's (ascent, descent) from hhea values, both positive: the line gap goes above the ascent.
|
||||
fn hhea_line(ascender: i16, descender: i16, line_gap: i16) -> (f64, f64) {
|
||||
(f64::from(ascender) + f64::from(line_gap.max(0)), f64::from(descender).abs())
|
||||
@@ -1094,6 +1129,48 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_font_notice_uses_the_actual_installed_face() {
|
||||
const SERIF: &[u8] = include_bytes!("../../../assets/fonts/SourceSerif4-Regular.ttf");
|
||||
let database = |name: Option<&str>| {
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
db.set_system_fallback(false);
|
||||
if let Some(name) = name {
|
||||
assert_eq!(db.add_document_fonts(vec![(SERIF.to_vec(), name.to_owned())]), 1);
|
||||
}
|
||||
db
|
||||
};
|
||||
|
||||
let original = database(Some("Times New Roman"));
|
||||
assert!(missing_metric_fonts_in(&original).iter().all(|(family, _)| *family != "Times New Roman"));
|
||||
assert_eq!(resolve_with_db(&original, "Times New Roman", false, false).face.family, "Times New Roman");
|
||||
|
||||
let twin = database(Some("Liberation Serif"));
|
||||
assert!(missing_metric_fonts_in(&twin).iter().all(|(family, _)| *family != "Times New Roman"));
|
||||
assert_eq!(resolve_with_db(&twin, "Times New Roman", false, false).face.family, "Liberation Serif");
|
||||
|
||||
let fallback = database(None);
|
||||
assert_eq!(
|
||||
missing_metric_fonts_in(&fallback).iter().find(|(family, _)| *family == "Times New Roman"),
|
||||
Some(&("Times New Roman", "Source Serif 4".to_owned()))
|
||||
);
|
||||
assert_eq!(resolve_with_db(&fallback, "Times New Roman", false, false).face.family, "Source Serif 4");
|
||||
|
||||
let no_carlito = database(Some("DejaVu Sans"));
|
||||
assert!(!no_carlito.has_family("Carlito"));
|
||||
assert_eq!(resolve_with_db(&no_carlito, "Calibri", false, false).face.family, "DejaVu Sans");
|
||||
assert_eq!(
|
||||
missing_metric_fonts_in(&no_carlito).iter().find(|(family, _)| *family == "Calibri"),
|
||||
Some(&("Calibri", "DejaVu Sans".to_owned()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_but_uninstalled_carlito_does_not_hide_the_chosen_fallback() {
|
||||
assert!(!has_metric_resolution(false, &["Carlito"], "DejaVu Sans"));
|
||||
assert!(has_metric_resolution(false, &["Carlito"], "Carlito"));
|
||||
}
|
||||
|
||||
/// Semicolon-separated fallback lists resolve to the first installed family, or to a
|
||||
/// candidate's substitute when no listed family is installed.
|
||||
#[test]
|
||||
|
||||
@@ -123,10 +123,16 @@ fn blocks_text(blocks: &[FBlock], out: &mut Vec<String>, lists: &mut ListCounter
|
||||
if c.covered || depth > 8 {
|
||||
cells.push(String::new());
|
||||
} else {
|
||||
let mut v = Vec::new();
|
||||
blocks_text(&c.blocks, &mut v, &mut ListCounter::default(), depth + 1);
|
||||
// Flatten breaks and tabs inside a field without changing its spacing.
|
||||
cells.push(v.join(" ").replace("\r\n", " ").replace(['\t', '\r', '\n', '\u{000B}', '\u{000E}'], " "));
|
||||
let mut parts = Vec::new();
|
||||
blocks_text(&c.blocks, &mut parts, &mut ListCounter::default(), depth + 1);
|
||||
parts.retain(|part| !part.is_empty());
|
||||
// Flatten structural separators while preserving spaces typed in the cell.
|
||||
cells.push(
|
||||
parts
|
||||
.join(" ")
|
||||
.replace("\r\n", " ")
|
||||
.replace(['\t', '\r', '\n', '\u{000B}', '\u{000E}', '\u{0085}', '\u{2028}', '\u{2029}'], " "),
|
||||
);
|
||||
}
|
||||
for _ in 1..c.colspan.clamp(1, 63) {
|
||||
cells.push(String::new());
|
||||
@@ -217,6 +223,24 @@ mod tests {
|
||||
assert_eq!(export(&doc), " A\u{00A0}B C D E F G\u{2009}H \tRight\r\n\tLast".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_table_export_flattens_record_separators_without_adding_spaces_for_empty_paragraphs() {
|
||||
let paragraph = |text| para_block(Paragraph::with_text(text, CharProps::default()));
|
||||
let mut nested = Table::new(1, 2, 40.0);
|
||||
nested.rows[0].cells[0].blocks = vec![paragraph("p")];
|
||||
nested.rows[0].cells[1].blocks = vec![paragraph("q")];
|
||||
let mut table = Table::new(2, 3, 200.0);
|
||||
table.rows[0].cells[0].blocks = vec![paragraph("A"), paragraph(""), paragraph("B"), paragraph("")];
|
||||
table.rows[0].cells[1].blocks = vec![paragraph("X"), std::sync::Arc::new(Block::Table(nested)), paragraph("")];
|
||||
table.rows[0].cells[2].blocks = vec![paragraph(" C\u{00A0}D E\u{0085}F\u{2028}G\u{2029}H\tI\nJ\u{000E}K ")];
|
||||
table.rows[1].cells[1].blocks = vec![paragraph("L"), paragraph(" "), paragraph("R")];
|
||||
table.rows[1].cells[2].blocks = vec![paragraph("End")];
|
||||
let mut doc = Document::new();
|
||||
doc.body = vec![std::sync::Arc::new(Block::Table(table))];
|
||||
|
||||
assert_eq!(export(&doc), "A B\tX p q\t C\u{00A0}D E F G H I J K \r\n\tL R\tEnd".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_table_export_colspan_covered_and_newline_cleaning() {
|
||||
let mut t = crate::model::FTable::default();
|
||||
|
||||
@@ -809,7 +809,7 @@ impl Joint {
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, AreaKind::Object)];
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, AreaKind::Joint)];
|
||||
// Just below the first row as the line breaker tests it: the breaker tests every row at
|
||||
// its estimate (`row_est`), not at the line's height, so the first row never meets this
|
||||
// area and every later row, starting lower, does and moves below it. The probe's own first
|
||||
@@ -817,7 +817,7 @@ impl Joint {
|
||||
// line), so its height can't be used here.
|
||||
let below = self.top + gap + probe.row_est + 0.01;
|
||||
if self.bottom() > below {
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, AreaKind::Object));
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, AreaKind::Joint));
|
||||
}
|
||||
(gap, areas)
|
||||
}
|
||||
|
||||
@@ -100,10 +100,10 @@ pub fn field_name(instr: &str) -> String {
|
||||
instr.split_whitespace().next().unwrap_or("").trim_start_matches('=').to_ascii_uppercase()
|
||||
}
|
||||
|
||||
/// REF's hyperlink switch links its cached result without updating that result.
|
||||
/// REF and PAGEREF use the hyperlink switch to link their displayed text to the bookmark.
|
||||
pub(crate) fn reference_link(instr: &str) -> Option<String> {
|
||||
let (name, args) = instr.trim_start().split_once(char::is_whitespace)?;
|
||||
if !name.eq_ignore_ascii_case("REF") {
|
||||
if !name.eq_ignore_ascii_case("REF") && !name.eq_ignore_ascii_case("PAGEREF") {
|
||||
return None;
|
||||
}
|
||||
let args = args.trim_start();
|
||||
|
||||
@@ -85,8 +85,8 @@ pub(crate) fn float_rect(frame: Option<PageFrame>, col: (f32, f32), y0: f32, w:
|
||||
match float.v_rel {
|
||||
Anchor::Page => Some((0.0, s.page_h)),
|
||||
Anchor::Margin => Some(margin_y(f)),
|
||||
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top)),
|
||||
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom, s.margin_bottom)),
|
||||
Anchor::TopMargin | Anchor::InsideMargin => Some((0.0, s.margin_top.abs())),
|
||||
Anchor::BottomMargin | Anchor::OutsideMargin => Some((s.page_h - s.margin_bottom.abs(), s.margin_bottom.abs())),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
@@ -125,6 +125,8 @@ pub(crate) enum AreaKind {
|
||||
Tight,
|
||||
/// A floating table.
|
||||
Table,
|
||||
/// A paragraph continuing after a hidden paragraph mark (`Joint::fit`).
|
||||
Joint,
|
||||
}
|
||||
|
||||
/// Wrap areas a page starts with (#2048): by page index, the floating objects (block, object
|
||||
@@ -242,6 +244,7 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
|
||||
side: *side,
|
||||
table: *kind == AreaKind::Table,
|
||||
tight: *kind == AreaKind::Tight,
|
||||
joint: *kind == AreaKind::Joint,
|
||||
})
|
||||
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
|
||||
// room, with that space laid out again below them (#7143). Any ending at or above it
|
||||
|
||||
@@ -665,7 +665,8 @@ impl<'a> Flow<'a> {
|
||||
// Not in the full-height fallback pass, which must keep the original layout.
|
||||
let column = pb.uncapped_bottom() - pb.top;
|
||||
let balancing = pb.balance.is_some_and(|(page, h)| page + 1 == pb.pages.len() && h + 0.01 < column);
|
||||
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || !balancing || pb.web {
|
||||
// A paragraph closing a section never shares its column with the next section's first block (#9206).
|
||||
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || self.p.section.is_some() || !balancing || pb.web {
|
||||
return fit.l1;
|
||||
}
|
||||
let (Some(first), Some(last)) = (self.pl.lines.get(l0), self.pl.lines.last()) else { return fit.l1 };
|
||||
@@ -1325,16 +1326,21 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
// Its border room, unless it joins the paragraph before (or after) in one box.
|
||||
let own = Edges::own(&pl, 0, pl.lines.len());
|
||||
let top = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block), None) { 0.0 } else { own.top };
|
||||
// Contextual spacing and automatic spacing between list items drop this paragraph's space before (#9208).
|
||||
let prev_para = ctx.doc.body.get(block).and_then(|b| match &**b {
|
||||
Block::Para(prev) => Some(prev),
|
||||
_ => None,
|
||||
});
|
||||
let dropped_before = prev_para.is_some_and(|prev| {
|
||||
let prp = ctx.doc.styles.resolve_para(&prev.props);
|
||||
(pl.rp.style == prp.style && pl.rp.contextual_spacing) || (pl.rp.before_auto && ctx.has_label(prev) && ctx.has_label(p))
|
||||
});
|
||||
let space_before = if dropped_before { 0.0 } else { pl.rp.space_before };
|
||||
// The paragraph closing the section, when the next section starts a new page, keeps
|
||||
// with nothing on this page (Word ignores its Keep with next).
|
||||
if pl.rp.keep_next && depth < 8 && !(new_page && p.section.is_some()) {
|
||||
let bottom = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block + 2), None) { 0.0 } else { own.bottom };
|
||||
pl.rp.space_before
|
||||
+ top
|
||||
+ pl.height
|
||||
+ bottom
|
||||
+ pl.rp.space_after
|
||||
+ next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
|
||||
space_before + top + pl.height + bottom + pl.rp.space_after + next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
|
||||
} else {
|
||||
// The room this one needs to start on the page with the kept paragraph before
|
||||
// it (#966).
|
||||
@@ -1342,7 +1348,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
(Some(first), Some(last)) => last.top + last.height - first.top,
|
||||
_ => 0.0,
|
||||
};
|
||||
pl.rp.space_before
|
||||
space_before
|
||||
+ top
|
||||
+ if pl.rp.keep_lines {
|
||||
pl.height
|
||||
@@ -1368,6 +1374,38 @@ mod tests {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_geom::Rect;
|
||||
|
||||
#[test]
|
||||
fn kept_paragraphs_reserve_no_room_for_suppressed_spacing() {
|
||||
crate::test_fonts();
|
||||
let room = |doc: &Document| {
|
||||
let mut reserved = None;
|
||||
crate::pass::with_flow_page(doc, |ctx, pb| {
|
||||
reserved = Some(next_first_line(ctx, 0, pb.col_w(), 0, false, &mut ctx.counters.clone()));
|
||||
});
|
||||
reserved.expect("the flow page was measured")
|
||||
};
|
||||
for automatic_list in [false, true] {
|
||||
let mut base = Document::from_text("Kept paragraph\nFollowing paragraph");
|
||||
if automatic_list {
|
||||
let num = Arc::make_mut(&mut base.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
for block in 0..2 {
|
||||
base.para_mut(StoryRef::Body, &Path::top(block)).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 0 });
|
||||
}
|
||||
}
|
||||
let q = base.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
q.props.space_before = Some(0.0);
|
||||
let mut spaced = base.clone();
|
||||
let q = spaced.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
|
||||
q.props.space_before = Some(48.0);
|
||||
if automatic_list {
|
||||
q.props.space_before_auto = Some(true);
|
||||
} else {
|
||||
q.props.contextual_spacing = Some(true);
|
||||
}
|
||||
assert_eq!(room(&spaced), room(&base), "suppressed spacing takes no room (list: {automatic_list})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -189,6 +189,34 @@ pub(crate) fn placed_cost_by(it: &Placed, limit: usize, cost: impl Fn(&Placed) -
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a header laid out with the rendered body area grows past `body_top` and retrying
|
||||
/// with the declared margins (`margin_area: None`) produces a shorter layout. Both
|
||||
/// [`header_table_areas`] and [`headers_footers`] use this so body table avoidance matches the
|
||||
/// header actually drawn.
|
||||
fn lay_header_box<T>(
|
||||
ctx: &mut Ctx,
|
||||
frame: PageFrame<'_>,
|
||||
header_y: f32,
|
||||
body_top: f32,
|
||||
measured: bool,
|
||||
mut lay: impl FnMut(&mut Ctx, PageFrame<'_>) -> (f32, T),
|
||||
) -> T {
|
||||
// List counters and equation numbers before the header, so a second layout counts from the
|
||||
// same place and only the layout kept advances them.
|
||||
let before = (ctx.counters.clone(), ctx.eq_count);
|
||||
let (laid_h, laid) = lay(ctx, frame);
|
||||
if measured && header_y + laid_h > body_top + 0.01 {
|
||||
let rendered = (std::mem::replace(&mut ctx.counters, before.0), ctx.eq_count);
|
||||
ctx.eq_count = before.1;
|
||||
let (measured_h, measured) = lay(ctx, PageFrame { margin_area: None, ..frame });
|
||||
if measured_h < laid_h - 0.01 {
|
||||
return measured;
|
||||
}
|
||||
(ctx.counters, ctx.eq_count) = rendered;
|
||||
}
|
||||
laid
|
||||
}
|
||||
|
||||
/// Header tables can displace a non-overlapping body table. Page-positioned drawings keep
|
||||
/// their own wrapping rules, so only table areas are retained from the header layout.
|
||||
pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
@@ -207,9 +235,10 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
return Vec::new();
|
||||
}
|
||||
let set = hf.heads.set(page.section);
|
||||
let even_page = !(sect.title_page && first) && ctx.doc.settings.even_odd_headers && page.number.is_multiple_of(2);
|
||||
let id = if sect.title_page && first {
|
||||
set.first
|
||||
} else if ctx.doc.settings.even_odd_headers && page.number.is_multiple_of(2) {
|
||||
} else if even_page {
|
||||
set.even.or(set.default)
|
||||
} else {
|
||||
set.default
|
||||
@@ -217,6 +246,8 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
let Some(id) = id else { return Vec::new() };
|
||||
let Some(part) = ctx.doc.parts.get(&id) else { return Vec::new() };
|
||||
let blocks = part.blocks.clone();
|
||||
// As in `headers_footers`: an even-page header with its own part was never measured for the body top.
|
||||
let header_measured = !even_page || set.even.is_none();
|
||||
let x = sect.margin_left + sect.gutter;
|
||||
let frame =
|
||||
PageFrame { sect, margin_area: Some((page.body.y, page.body.bottom())), origin: (x, sect.header), number: page.number, mirror: ctx.mirror };
|
||||
@@ -229,8 +260,11 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
|
||||
let track = std::mem::replace(&mut ctx.track_totals, false);
|
||||
ctx.fields.page_format = sect.page_num_format;
|
||||
ctx.fields.page = page.number;
|
||||
let mut areas = again(ctx, 0, |ctx| {
|
||||
with_pct_base(ctx, base, |ctx| layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame)))).table_areas
|
||||
let mut areas = lay_header_box(ctx, frame, sect.header, page.body.y, header_measured, |ctx, frame| {
|
||||
let res = again(ctx, 0, |ctx| {
|
||||
with_pct_base(ctx, base, |ctx| layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame))))
|
||||
});
|
||||
(res.height, res.table_areas)
|
||||
});
|
||||
ctx.counters = counters;
|
||||
ctx.boxes = boxes;
|
||||
@@ -485,23 +519,15 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
|
||||
with_pct_base(ctx, base, |c| layout_box(c, BoxInput::other(StoryRef::Part(id), &blocks, w, 0, Some(frame))))
|
||||
})
|
||||
};
|
||||
// List counters and equation numbers before the header, so a second layout counts
|
||||
// from the same place and only the layout kept advances them.
|
||||
let before = (ctx.counters.clone(), ctx.eq_count);
|
||||
let (mut laid, mut behind, mut front) = lay_header(ctx, frame);
|
||||
// The body top was measured with the declared margins (`body_top_for`). If the rendered
|
||||
// area moves a wrapping Margin-anchored object into the header's text and the header
|
||||
// grows past that body top, keep the measured layout: its text can't run into the body.
|
||||
if sect.header + laid.height > page.body.y + 0.01 {
|
||||
let rendered = (std::mem::replace(&mut ctx.counters, before.0), ctx.eq_count);
|
||||
ctx.eq_count = before.1;
|
||||
let measured = lay_header(ctx, PageFrame { margin_area: None, ..frame });
|
||||
if measured.0.height < laid.height - 0.01 {
|
||||
(laid, behind, front) = measured;
|
||||
} else {
|
||||
(ctx.counters, ctx.eq_count) = rendered;
|
||||
}
|
||||
}
|
||||
// The body top was measured with the declared margins (`body_top_for`), only for the
|
||||
// default and first-page headers of non-turned sections (`section_tops`). Even-page
|
||||
// headers and fixed-margin sections were never measured for `page.body.y`, so skip
|
||||
// the retry (#9226).
|
||||
let header_measured = !sect.text_direction.is_turned() && (page.hf_slot != HfSlot::Even || hf.heads.set(page.section).even.is_none());
|
||||
let (laid, behind, front) = lay_header_box(ctx, frame, sect.header, page.body.y, header_measured, |ctx, frame| {
|
||||
let res = lay_header(ctx, frame);
|
||||
(res.0.height, res)
|
||||
});
|
||||
let mut items = laid.items;
|
||||
for it in &mut items {
|
||||
it.translate(x, sect.header);
|
||||
|
||||
+43
-20
@@ -12,7 +12,7 @@ use crate::{DocLayout, Page, Placed};
|
||||
|
||||
/// Caret geometry on a page: a bar from (`x`, `top`) to (`x + width`, `top + height`). It is
|
||||
/// upright (`width` 0) except in turned text (a table cell's text direction), where it lies
|
||||
/// across the page (`height` 0), and `turn` is the direction its line reads in.
|
||||
/// across the page (`height` 0).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Caret {
|
||||
pub page: usize,
|
||||
@@ -20,7 +20,6 @@ pub struct Caret {
|
||||
pub top: f32,
|
||||
pub height: f32,
|
||||
pub width: f32,
|
||||
pub turn: TextDirection,
|
||||
}
|
||||
|
||||
/// An equation as [`DocLayout::equation_box`] finds it, in page coordinates: its left edge
|
||||
@@ -759,7 +758,7 @@ impl DocLayout {
|
||||
let base = top + (l.baseline - l.top);
|
||||
let ctop = (base - asc).max(top);
|
||||
let r = crate::turn_rect(*turn, *x, *y, Rect::new(cx, ctop, 0.0, (base + desc - ctop).max(4.0)));
|
||||
return Some(Caret { page: pi, x: r.x, top: r.y, height: r.h, width: r.w, turn: *turn });
|
||||
return Some(Caret { page: pi, x: r.x, top: r.y, height: r.h, width: r.w });
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -767,15 +766,18 @@ impl DocLayout {
|
||||
/// The style run text typed at `pos` would take (the character's before it, or at the start
|
||||
/// of a paragraph the first character's) and the baseline it sits on, on the page: `pos`'s
|
||||
/// line's, raised or lowered by the run's shift (superscript, `w:position`). An input method's
|
||||
/// composition is drawn with them, as Word draws it in the text's own font and size. In turned
|
||||
/// text the baseline is meaningless (the lines aren't horizontal); use the run only.
|
||||
/// composition is drawn with them, as Word draws it in the text's own font and size. `None` in
|
||||
/// turned text, whose lines aren't horizontal.
|
||||
pub fn typing_style(&self, pos: &Pos, page_hint: usize) -> Option<(StyleRun, f32)> {
|
||||
for (_, it) in self.pieces(pos.story, &pos.path, page_hint) {
|
||||
let Placed::Lines { para, l0, l1, y, .. } = it else { continue };
|
||||
let Placed::Lines { para, l0, l1, y, turn, .. } = it else { continue };
|
||||
let li = para.line_of(pos.off);
|
||||
if li < *l0 || li >= *l1 {
|
||||
continue;
|
||||
}
|
||||
if *turn != TextDirection::Horizontal {
|
||||
return None;
|
||||
}
|
||||
let first = para.lines.get(*l0)?;
|
||||
let line = para.lines.get(li)?;
|
||||
let at = |off: usize| para.clusters.iter().find(|c| c.start <= off && off < c.end).and_then(|c| para.styles.get(c.style as usize));
|
||||
@@ -796,23 +798,44 @@ impl DocLayout {
|
||||
/// In turned text, the position on the next (`next`) or previous line in reading order, at
|
||||
/// `goal` along the line (its own frame; `None` keeps the caret's). Returns it with that
|
||||
/// along-line coordinate. Only lines of the same flow count (the paragraphs of one story
|
||||
/// level or of one table cell, not another cell's), so `None` at the first/last line of the
|
||||
/// caret's flow on the page.
|
||||
/// level or of one table cell, not another cell's). In the body the step crosses page
|
||||
/// boundaries, so `None` only at the first/last line of the flow; in any other story (laid
|
||||
/// out again on every page) it stops at the first/last line on the page.
|
||||
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
// Only the body flows from page to page: a header, a footer or a text box in one is laid
|
||||
// out again on every page, so the adjacent page holds the caret's own lines again.
|
||||
let crosses_pages = pos.story == StoryRef::Body;
|
||||
let page_lines = |page_idx: usize| -> Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> {
|
||||
let Some(page) = self.pages.get(page_idx) else { return Vec::new() };
|
||||
items_of(page, pos.story)
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { story, path, para, l0, l1, turn, .. }
|
||||
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
|
||||
{
|
||||
Some((path, para, *l0, *l1))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
|
||||
.collect()
|
||||
};
|
||||
let c = self.caret_on(pos, page_hint)?;
|
||||
let lines: Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> = items_of(self.pages.get(c.page)?, pos.story)
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { story, path, para, l0, l1, turn, .. }
|
||||
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
|
||||
{
|
||||
Some((path, para, *l0, *l1))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
|
||||
.collect();
|
||||
let lines = page_lines(c.page);
|
||||
let here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
|
||||
let (path, para, li) = lines.get(if next { here + 1 } else { here.checked_sub(1)? })?;
|
||||
let adjacent;
|
||||
let (path, para, li) = if next {
|
||||
if let Some(t) = lines.get(here + 1) {
|
||||
t
|
||||
} else {
|
||||
adjacent = if crosses_pages { page_lines(c.page + 1) } else { Vec::new() };
|
||||
adjacent.first()?
|
||||
}
|
||||
} else if let Some(prev) = here.checked_sub(1).and_then(|i| lines.get(i)) {
|
||||
prev
|
||||
} else {
|
||||
adjacent = if crosses_pages { page_lines(c.page.checked_sub(1)?) } else { Vec::new() };
|
||||
adjacent.last()?
|
||||
};
|
||||
let gx = match goal {
|
||||
Some(g) => g,
|
||||
None => lines[here].1.x_of(lines[here].2, pos.off)?,
|
||||
|
||||
@@ -386,7 +386,7 @@ impl PageBuilder<'_> {
|
||||
self.number = self.restart_at.take().unwrap_or_else(|| self.number.saturating_add(1));
|
||||
let (w, h) = if self.web { (s.page_w, f32::MAX / 4.0) } else { (s.page_w, s.page_h) };
|
||||
let bottom = self.body_bottom(body_top);
|
||||
self.leading_floor = (s.page_h - s.margin_bottom).min(self.foot_top);
|
||||
self.leading_floor = (s.page_h - s.margin_bottom.abs()).min(self.foot_top);
|
||||
let body = Rect::new(s.margin_left + s.gutter, body_top, s.text_width(), (bottom - body_top).max(36.0));
|
||||
let mut decor = Vec::new();
|
||||
if !self.web {
|
||||
@@ -473,8 +473,12 @@ impl PageBuilder<'_> {
|
||||
self.bottom >= self.leading_floor - 0.01
|
||||
}
|
||||
/// The bottom of the body on a page started with its body at `body_top`: a footer taller than
|
||||
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room.
|
||||
/// the bottom margin pushes it up (Word: no gap), leaving it at least a little room. A
|
||||
/// negative bottom margin is exact: the body ends at its size and the footer overlaps it.
|
||||
fn body_bottom(&self, body_top: f32) -> f32 {
|
||||
if self.sect.margin_bottom < 0.0 {
|
||||
return self.sect.page_h + self.sect.margin_bottom;
|
||||
}
|
||||
// ODF keeps the footer's spacing above a footer too tall for the bottom margin.
|
||||
let gap = if self.sect.footer_gap.is_finite() { self.sect.footer_gap.clamp(0.0, 1584.0) } else { 0.0 };
|
||||
(self.sect.page_h - self.sect.margin_bottom).min((self.foot_top - gap).max(body_top + 36.0))
|
||||
@@ -569,8 +573,12 @@ pub(crate) fn item_bottom(y: f32, para: &ParaLayout, l0: usize, l1: usize) -> Op
|
||||
Some(y + l.top + l.height - f.top)
|
||||
}
|
||||
|
||||
/// Where body text starts: the top margin, or below the header if it's taller.
|
||||
/// Where body text starts: the top margin, or below the header if it's taller. A negative top
|
||||
/// margin is exact (ECMA-376 §17.6.11): the text starts at its size and the header overlaps it.
|
||||
pub(crate) fn body_top_for(ctx: &mut Ctx, sect: &SectionProps, header: Option<u32>) -> f32 {
|
||||
if sect.margin_top < 0.0 {
|
||||
return -sect.margin_top;
|
||||
}
|
||||
let Some(id) = header else { return sect.margin_top };
|
||||
let Some(part) = ctx.doc.parts.get(&id) else { return sect.margin_top };
|
||||
let blocks = part.blocks.clone();
|
||||
@@ -681,7 +689,7 @@ pub(crate) fn margin_y(f: &PageFrame) -> (f32, f32) {
|
||||
let s = f.sect;
|
||||
match f.margin_area {
|
||||
Some((top, bottom)) => (top, (bottom - top).max(18.0)),
|
||||
None => (s.margin_top, s.text_height()),
|
||||
None => (s.margin_top.abs(), s.text_height()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +176,9 @@ pub struct Exclusion {
|
||||
/// Tight and Through wrapping: before Word 2013 layout text goes in a narrower gap beside
|
||||
/// it (#6316).
|
||||
pub tight: bool,
|
||||
/// A paragraph continuing after a hidden paragraph mark (`Joint::fit`): keeps the 20pt minimum
|
||||
/// span rather than the 18pt floating-object minimum (#9160).
|
||||
pub joint: bool,
|
||||
}
|
||||
|
||||
impl Exclusion {
|
||||
|
||||
@@ -600,6 +600,7 @@ impl<'e> Breaker<'e> {
|
||||
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
|
||||
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
|
||||
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
|
||||
let picture_leading = if pictures_alone { font_natural } else { run_leading };
|
||||
// Keep the picture floor independent of list-label metrics.
|
||||
let natural = asc + desc;
|
||||
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
|
||||
@@ -609,7 +610,7 @@ impl<'e> Breaker<'e> {
|
||||
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
|
||||
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
|
||||
(LineSpacing::Multiple(m), None) => {
|
||||
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
|
||||
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * picture_leading), false)
|
||||
}
|
||||
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
|
||||
(LineSpacing::Exactly(v), _) => (v, false),
|
||||
@@ -1211,7 +1212,7 @@ const MIN_SPAN_CONTOUR_OLD: f32 = 9.0;
|
||||
|
||||
/// The narrowest span text goes into beside `e`, with Word 2013 layout or later (`current`).
|
||||
fn min_span(e: &Exclusion, current: bool) -> f32 {
|
||||
match (e.table, e.tight) {
|
||||
match (e.table || e.joint, e.tight) {
|
||||
(true, _) => MIN_SPAN,
|
||||
(false, true) if !current => MIN_SPAN_CONTOUR_OLD,
|
||||
_ => MIN_SPAN_OBJECT,
|
||||
@@ -1326,7 +1327,18 @@ mod tests {
|
||||
|
||||
/// An exclusion from the row's left edge to `right`, 100pt tall.
|
||||
fn area(right: f32, table: bool, tight: bool) -> Exclusion {
|
||||
Exclusion { top: 0.0, bottom: 100.0, left: 0.0, right, top_bottom: false, contour: None, side: WrapText::BothSides, table, tight }
|
||||
Exclusion {
|
||||
top: 0.0,
|
||||
bottom: 100.0,
|
||||
left: 0.0,
|
||||
right,
|
||||
top_bottom: false,
|
||||
contour: None,
|
||||
side: WrapText::BothSides,
|
||||
table,
|
||||
tight,
|
||||
joint: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a line at the top of a 100pt row finds a span `gap` points wide beside `e`.
|
||||
@@ -1344,6 +1356,8 @@ mod tests {
|
||||
assert!(fits(area(50.0, true, false), 20.0, current) && !fits(area(50.0, true, false), 19.9, current));
|
||||
}
|
||||
assert!(fits(area(50.0, false, true), 18.0, true) && !fits(area(50.0, false, true), 17.9, true));
|
||||
assert!(fits(Exclusion { joint: true, ..area(50.0, false, false) }, 20.0, true));
|
||||
assert!(!fits(Exclusion { joint: true, ..area(50.0, false, false) }, 19.9, true));
|
||||
assert!(fits(area(50.0, false, true), 9.0, false) && !fits(area(50.0, false, true), 8.9, false));
|
||||
// A span between a picture and a table needs the table's 20.
|
||||
let both = |gap: f32| {
|
||||
|
||||
@@ -291,7 +291,7 @@ fn section_tops(ctx: &mut Ctx, hf: &HfLinks, (si, sect): (usize, &SectionProps),
|
||||
let (heads, feet) = (hf.heads.set(si), hf.feet.set(si));
|
||||
let hb = |i: Option<u32>| hf.defining_width(false, si, i);
|
||||
let fb = |i: Option<u32>| hf.defining_width(true, si, i);
|
||||
let body = if fixed { sect.margin_top } else { with_pct_base(ctx, hb(heads.default), |c| body_top_for(c, sect, heads.default)) };
|
||||
let body = if fixed { sect.margin_top.abs() } else { with_pct_base(ctx, hb(heads.default), |c| body_top_for(c, sect, heads.default)) };
|
||||
let first = if fixed || !sect.title_page { body } else { with_pct_base(ctx, hb(heads.first), |c| body_top_for(c, sect, heads.first)) };
|
||||
let foot = if fixed { f32::MAX } else { with_pct_base(ctx, fb(feet.default), |c| foot_top_for(c, sect, feet.default)) };
|
||||
let first_foot = if fixed || !sect.title_page { foot } else { with_pct_base(ctx, fb(feet.first), |c| foot_top_for(c, sect, feet.first)) };
|
||||
@@ -625,7 +625,7 @@ pub(crate) fn layout_pass(
|
||||
section_endnotes(&mut ctx, &mut pb, &mut endnotes, (sect, si, block));
|
||||
}
|
||||
if pb.pages.is_empty() {
|
||||
pb.new_page(0, sect_ref.margin_top);
|
||||
pb.new_page(0, sect_ref.margin_top.abs());
|
||||
}
|
||||
// The rest of the endnotes after the last paragraph.
|
||||
let rest: Vec<u32> = endnotes.into_iter().map(|(id, _)| id).collect();
|
||||
|
||||
+147
-36
@@ -40,6 +40,11 @@ pub struct MergeEdges {
|
||||
pub top: Vec<Placed>,
|
||||
/// When the row is the last on a page: the closing bottom border of a merge running on.
|
||||
pub end: Vec<Placed>,
|
||||
/// `(x, w)` of each vertical merge in this row that continues onto the following row.
|
||||
pub spans: Vec<(f32, f32)>,
|
||||
/// `(x, w)` of each vertical merge that ends in this row: it too continues past the first part
|
||||
/// of the row when the row is split.
|
||||
pub ends: Vec<(f32, f32)>,
|
||||
}
|
||||
|
||||
/// A cell of a [`RowLayout`].
|
||||
@@ -915,13 +920,33 @@ fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember the fill (or none) each restart cell gives its merge's continuation.
|
||||
fn note_restart_fills(merge_fill: &mut std::collections::HashMap<usize, Rgb>, cells: &[CellBox]) {
|
||||
for c in cells.iter().filter(|c| c.vmerge == VMerge::Restart) {
|
||||
/// Remember the fill and background picture (or none) each restart cell gives its merge's continuation.
|
||||
fn note_restarts<'a>(
|
||||
merge_fill: &mut std::collections::HashMap<usize, Rgb>,
|
||||
merge_picture: &mut std::collections::HashMap<usize, &'a wordcraft_doc::props::CellPicture>,
|
||||
table: &'a Table,
|
||||
ri: usize,
|
||||
cells: &[CellBox],
|
||||
) {
|
||||
for (ci, c) in cells.iter().enumerate().filter(|(_, c)| c.vmerge == VMerge::Restart) {
|
||||
match c.fill {
|
||||
Some(f) => merge_fill.insert(c.g, f),
|
||||
None => merge_fill.remove(&c.g),
|
||||
};
|
||||
match table.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()) {
|
||||
Some(pic) => merge_picture.insert(c.g, pic),
|
||||
None => merge_picture.remove(&c.g),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a cell's clipped background picture to `items` if it produces any placed images.
|
||||
fn push_cell_picture(items: &mut Vec<Placed>, pic: Option<&wordcraft_doc::props::CellPicture>, rect: Rect, story: StoryRef, path: &[u32]) {
|
||||
if let Some(pic) = pic {
|
||||
let images = cell_picture(pic, rect, story, path);
|
||||
if !images.is_empty() {
|
||||
items.push(Placed::Clip { rect, spin: wordcraft_geom::Spin::default(), items: images });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -941,6 +966,17 @@ struct TableRows<'a> {
|
||||
only: Option<(usize, f32)>,
|
||||
}
|
||||
|
||||
/// Total height of a vertical merge from row `ri` (starting at `rh`) through its continuing rows.
|
||||
fn cont_height(cont: &[Vec<usize>], heights: &[f32], ri: usize, g: usize, rh: f32) -> f32 {
|
||||
let mut total = rh;
|
||||
let mut k = ri + 1;
|
||||
while cont.get(k).is_some_and(|v| v.contains(&g)) {
|
||||
total += heights.get(k).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
|
||||
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
|
||||
/// the cell's text.
|
||||
@@ -965,10 +1001,11 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
// Second pass: place cells with their row height, fills and borders.
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
let mut merge_fill: std::collections::HashMap<usize, Rgb> = std::collections::HashMap::new();
|
||||
let mut merge_picture: std::collections::HashMap<usize, &wordcraft_doc::props::CellPicture> = std::collections::HashMap::new();
|
||||
for (ri, cells) in rows.into_iter().enumerate() {
|
||||
if only.is_some_and(|(row, _)| row != ri) {
|
||||
// The restart fills of earlier rows still shade the continuation of a merge.
|
||||
note_restart_fills(&mut merge_fill, &cells);
|
||||
// The restart fills and background pictures of earlier rows still apply to the continuation of a merge.
|
||||
note_restarts(&mut merge_fill, &mut merge_picture, t, ri, &cells);
|
||||
continue;
|
||||
}
|
||||
let rh = heights.get(ri).copied().unwrap_or(0.0);
|
||||
@@ -979,14 +1016,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
for (ci, c) in cells.into_iter().enumerate() {
|
||||
let first = items.len();
|
||||
// A restart cell spans several rows: its height is their sum.
|
||||
let mut span_h = rh;
|
||||
if c.vmerge == VMerge::Restart {
|
||||
let mut k = ri + 1;
|
||||
while cont.get(k).is_some_and(|v| v.contains(&c.g)) {
|
||||
span_h += heights.get(k).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
let span_h = if c.vmerge == VMerge::Restart { cont_height(&cont, &heights, ri, c.g, rh) } else { rh };
|
||||
let rect = Rect::new(c.x, 0.0, c.w, span_h);
|
||||
if c.vmerge != VMerge::Continue
|
||||
&& let Some(f) = c.fill
|
||||
@@ -994,13 +1024,14 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
items.push(Placed::Fill { rect, color: f });
|
||||
}
|
||||
// Its background picture, over the shading and under the text, cut off at its edges.
|
||||
if c.vmerge != VMerge::Continue
|
||||
&& let Some(pic) = t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref())
|
||||
{
|
||||
let images = cell_picture(pic, rect, story, path);
|
||||
if !images.is_empty() {
|
||||
items.push(Placed::Clip { rect, spin: wordcraft_geom::Spin::default(), items: images });
|
||||
}
|
||||
if c.vmerge != VMerge::Continue {
|
||||
push_cell_picture(
|
||||
&mut items,
|
||||
t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()),
|
||||
rect,
|
||||
story,
|
||||
path,
|
||||
);
|
||||
}
|
||||
// Behind-text frames count towards vertical alignment even without inline content.
|
||||
// They do not increase the row's flow height.
|
||||
@@ -1076,28 +1107,36 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
|
||||
items.push(Placed::Rule { x0: hx0, y0, x1: hx1, y1: y0, border: e });
|
||||
}
|
||||
let last_of_merge = c.vmerge == VMerge::None || !cont.get(ri + 1).is_some_and(|v| v.contains(&c.g));
|
||||
if last_of_merge && let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
items.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
}
|
||||
if c.vmerge == VMerge::Restart {
|
||||
match c.fill {
|
||||
Some(f) => merge_fill.insert(c.g, f),
|
||||
None => merge_fill.remove(&c.g),
|
||||
};
|
||||
match t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()) {
|
||||
Some(pic) => merge_picture.insert(c.g, pic),
|
||||
None => merge_picture.remove(&c.g),
|
||||
};
|
||||
}
|
||||
if !last_of_merge && let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
merge.end.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
if !last_of_merge {
|
||||
merge.spans.push((c.x, c.w));
|
||||
if let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
merge.end.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
}
|
||||
} else {
|
||||
if c.vmerge == VMerge::Continue {
|
||||
merge.ends.push((c.x, c.w));
|
||||
}
|
||||
if let Some(e) = b.bottom.filter(Border::is_visible) {
|
||||
items.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
|
||||
}
|
||||
}
|
||||
if c.vmerge == VMerge::Continue {
|
||||
let mut left = rh;
|
||||
let mut k = ri + 1;
|
||||
while cont.get(k).is_some_and(|v| v.contains(&c.g)) {
|
||||
left += heights.get(k).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
let left = cont_height(&cont, &heights, ri, c.g, rh);
|
||||
let cont_rect = Rect::new(c.x, 0.0, c.w, left);
|
||||
if let Some(color) = merge_fill.get(&c.g) {
|
||||
merge.top.push(Placed::Fill { rect: Rect::new(c.x, 0.0, c.w, left), color: *color });
|
||||
merge.top.push(Placed::Fill { rect: cont_rect, color: *color });
|
||||
}
|
||||
push_cell_picture(&mut merge.top, merge_picture.get(&c.g).copied(), cont_rect, story, path);
|
||||
if let Some(e) = b.top.filter(Border::is_visible) {
|
||||
merge.top.push(Placed::Rule { x0: hx0, y0, x1: hx1, y1: y0, border: e });
|
||||
}
|
||||
@@ -1434,7 +1473,13 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
bottom: row.bottom,
|
||||
edge: 0.0,
|
||||
cells: Vec::new(),
|
||||
merge: MergeEdges { top: row.merge.top.clone(), end: at_y(&row.merge.end, cut) },
|
||||
// Every merge in the row runs on from this part, those ending in the row too.
|
||||
merge: MergeEdges {
|
||||
top: row.merge.top.clone(),
|
||||
end: at_y(&row.merge.end, cut),
|
||||
spans: [row.merge.spans.as_slice(), &row.merge.ends].concat(),
|
||||
ends: Vec::new(),
|
||||
},
|
||||
},
|
||||
RowLayout {
|
||||
height,
|
||||
@@ -1442,7 +1487,12 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
bottom: row.bottom,
|
||||
edge: row.edge,
|
||||
cells: parts,
|
||||
merge: MergeEdges { top: shorter(&row.merge.top, row.height - height), end: at_y(&row.merge.end, height) },
|
||||
merge: MergeEdges {
|
||||
top: shorter(&row.merge.top, row.height - height),
|
||||
end: at_y(&row.merge.end, height),
|
||||
spans: row.merge.spans.clone(),
|
||||
ends: row.merge.ends.clone(),
|
||||
},
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -1463,12 +1513,19 @@ fn at_y(items: &[Placed], y: f32) -> Vec<Placed> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The fills of a merge's top edge for a continuation `by` points shorter than its row.
|
||||
/// Shorten a merge's continuation backgrounds by the height removed from its first row.
|
||||
fn shorter(items: &[Placed], by: f32) -> Vec<Placed> {
|
||||
let shorten = |rect: &Rect| Rect::new(rect.x, rect.y, rect.w, rect.h - by);
|
||||
items
|
||||
.iter()
|
||||
.map(|it| match it {
|
||||
Placed::Fill { rect, color } => Placed::Fill { rect: Rect::new(rect.x, rect.y, rect.w, (rect.h - by).max(0.0)), color: *color },
|
||||
Placed::Fill { rect, color } => Placed::Fill { rect: shorten(rect), color: *color },
|
||||
Placed::Clip { rect, spin, items } => {
|
||||
let rect = shorten(rect);
|
||||
// Keep the original picture geometry, including any tile that crosses the new bottom.
|
||||
let items = items.iter().filter(|it| !matches!(it, Placed::Image { rect: image, .. } if !rect.intersects(image))).cloned().collect();
|
||||
Placed::Clip { rect, spin: *spin, items }
|
||||
}
|
||||
other => other.clone(),
|
||||
})
|
||||
.collect()
|
||||
@@ -2068,6 +2125,60 @@ fn autofit(grid: &mut [f32], content: &[(f32, f32)], t: &Table, avail: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod merged_min_height_tests {
|
||||
use super::*;
|
||||
|
||||
// The vertical merge used by turned-text layout in #6529, with three rows
|
||||
// in the right-hand column and a fourth row outside the merge.
|
||||
fn three_row_merge() -> Table {
|
||||
let mut table = Table::new(4, 2, 100.0);
|
||||
for (row, (merge, height)) in
|
||||
table.rows.iter_mut().zip([(VMerge::Restart, 24.0), (VMerge::Continue, 32.0), (VMerge::Continue, 40.0), (VMerge::None, 64.0)])
|
||||
{
|
||||
row.cells[1].props.vmerge = merge;
|
||||
row.props.height_rule = HeightRule::AtLeast;
|
||||
row.props.height = Some(height);
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_min_height_sums_all_three_rows() {
|
||||
assert_eq!(merged_min_height(&three_row_merge(), 0, 1), Some(96.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_min_height_requires_a_restart_followed_by_a_continuation() {
|
||||
let mut table = three_row_merge();
|
||||
assert_eq!(merged_min_height(&table, 1, 1), None, "a continuation is not a restart");
|
||||
table.rows[1].cells[1].props.vmerge = VMerge::None;
|
||||
assert_eq!(merged_min_height(&table, 0, 1), None, "a continuation below a gap does not count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_min_height_requires_valid_at_least_heights_throughout() {
|
||||
let mut table = three_row_merge();
|
||||
for i in 0..3 {
|
||||
let original = table.rows[i].props.clone();
|
||||
for (rule, height) in [
|
||||
(HeightRule::Auto, Some(32.0)),
|
||||
(HeightRule::Exact, Some(32.0)),
|
||||
(HeightRule::AtLeast, None),
|
||||
(HeightRule::AtLeast, Some(0.0)),
|
||||
(HeightRule::AtLeast, Some(-1.0)),
|
||||
(HeightRule::AtLeast, Some(f32::INFINITY)),
|
||||
(HeightRule::AtLeast, Some(f32::NAN)),
|
||||
] {
|
||||
table.rows[i].props.height_rule = rule;
|
||||
table.rows[i].props.height = height;
|
||||
assert_eq!(merged_min_height(&table, 0, 1), None, "row {i}: {rule:?}, {height:?}");
|
||||
}
|
||||
table.rows[i].props = original;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod width_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -253,6 +253,8 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
// Where the items of this table's rows on the page and column start; none before a row is placed.
|
||||
let page_from = std::cell::Cell::new(None::<usize>);
|
||||
let pending_end: std::cell::RefCell<Vec<Placed>> = std::cell::RefCell::new(Vec::new());
|
||||
let pending_spans: std::cell::RefCell<Vec<(f32, f32)>> = std::cell::RefCell::new(Vec::new());
|
||||
let in_spans = |spans: &[(f32, f32)], rect: &Rect| spans.iter().any(|&(sx, sw)| (rect.x - sx).abs() < 0.01 && (rect.w - sw).abs() < 0.01);
|
||||
let place = |pb: &mut PageBuilder, row: &table::RowLayout, body: bool| {
|
||||
let (x, y) = (pb.col_x() + tl.x, pb.y);
|
||||
let limit = pb.bottom.max(y + row.height);
|
||||
@@ -270,19 +272,28 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
it
|
||||
})
|
||||
.collect();
|
||||
*pending_spans.borrow_mut() = row.merge.spans.iter().map(|&(mx, mw)| (x + mx, mw)).collect();
|
||||
}
|
||||
if let Some(pg) = pb.page() {
|
||||
if starts_page {
|
||||
page_from.set(Some(pg.items.len()));
|
||||
}
|
||||
// The continuing fill goes under the row's items (their borders), its top rules over them.
|
||||
// Continuing shading and pictures go under the row's content and borders.
|
||||
// The merge's opening border still goes above the row.
|
||||
let top = if starts_page { row.merge.top.as_slice() } else { &[] };
|
||||
let (fills, rules) = (top.iter().filter(|i| matches!(i, Placed::Fill { .. })), top.iter().filter(|i| !matches!(i, Placed::Fill { .. })));
|
||||
for it in fills.chain(&row.items).chain(rules) {
|
||||
let is_background = |it: &&Placed| matches!(it, Placed::Fill { .. } | Placed::Clip { .. });
|
||||
let backgrounds = top.iter().filter(is_background);
|
||||
let rules = top.iter().filter(|it| !is_background(it));
|
||||
for it in backgrounds.chain(&row.items).chain(rules) {
|
||||
let mut it = it.clone();
|
||||
let is_merge = match &it {
|
||||
Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } => in_spans(&row.merge.spans, rect),
|
||||
_ => false,
|
||||
};
|
||||
it.translate(x, y);
|
||||
// The area ends at this page's bottom, #8872.
|
||||
if let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = &mut it
|
||||
// The merged cell's area ends at this page's bottom, #8872 / #9191.
|
||||
if is_merge
|
||||
&& let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = &mut it
|
||||
&& rect.bottom() > limit
|
||||
{
|
||||
rect.h = (limit - rect.y).max(0.0);
|
||||
@@ -296,11 +307,13 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
// The page ends here: close the merges running on to the next one.
|
||||
let close_merges = |pb: &mut PageBuilder| {
|
||||
let end = std::mem::take(&mut *pending_end.borrow_mut());
|
||||
let spans = std::mem::take(&mut *pending_spans.borrow_mut());
|
||||
let bottom = pb.y;
|
||||
if let Some(pg) = pb.page() {
|
||||
// The merged cells' areas end with the last row on the page.
|
||||
// Only the merged cells' areas end with the last row on the page (#9191).
|
||||
for it in pg.items.iter_mut().skip(page_from.get().unwrap_or(usize::MAX)) {
|
||||
if let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = it
|
||||
&& in_spans(&spans, rect)
|
||||
&& rect.y < bottom
|
||||
&& rect.bottom() > bottom
|
||||
{
|
||||
@@ -448,7 +461,7 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
|
||||
// The text a table anchored to it stands in: where the next paragraph starts.
|
||||
let v_area = match f.v_rel {
|
||||
Anchor::Page => (0.0, s.page_h),
|
||||
Anchor::Margin => (s.margin_top, s.text_height()),
|
||||
Anchor::Margin => (s.margin_top.abs(), s.text_height()),
|
||||
_ => (pb.y, 0.0),
|
||||
};
|
||||
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
|
||||
|
||||
+402
-8
@@ -3463,6 +3463,39 @@ fn a_vertical_merge_across_a_page_break_stays_inside_the_page() {
|
||||
assert!(spanning, "the merge still spans the rows left on the page");
|
||||
}
|
||||
|
||||
/// The same when the merge's last row is the one split: on each page its area ends with the
|
||||
/// part of that row there, whether the merge starts on that page or runs on from an earlier one.
|
||||
#[test]
|
||||
fn a_vertical_merge_whose_last_row_splits_ends_with_each_part() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::{Rgb, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(20, 2, 468.0);
|
||||
for (i, row) in t.rows.iter_mut().enumerate() {
|
||||
row.cells[0].props.vmerge = match i {
|
||||
10 => VMerge::Restart,
|
||||
11..=13 => VMerge::Continue,
|
||||
_ => VMerge::None,
|
||||
};
|
||||
}
|
||||
t.rows[10].cells[0].props.shading = Some(Rgb(200, 0, 0));
|
||||
t.rows[13].cells[1].blocks = (0..80).map(|_| wordcraft_doc::para_block(Paragraph::with_text("line", Default::default()))).collect();
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let l = lay(&d);
|
||||
let mut shaded_pages = 0;
|
||||
for page in &l.pages {
|
||||
// Where the rows on this page end, by the unmerged column.
|
||||
let rows_end =
|
||||
page.items.iter().filter_map(|i| if let Placed::Cell { rect, cell: 1, .. } = i { Some(rect.bottom()) } else { None }).fold(0.0, f32::max);
|
||||
let fills: Vec<Rect> = page.items.iter().filter_map(|i| if let Placed::Fill { rect, .. } = i { Some(*rect) } else { None }).collect();
|
||||
shaded_pages += usize::from(!fills.is_empty());
|
||||
for rect in fills {
|
||||
assert!(rect.bottom() <= rows_end + 0.01, "{rect:?} runs past the rows on its page, which end at {rows_end}");
|
||||
}
|
||||
}
|
||||
assert!(shaded_pages >= 3, "the last row splits over more than one page break: {shaded_pages}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertical_merge_aligns_its_text_with_the_first_page() {
|
||||
crate::test_fonts();
|
||||
@@ -10449,11 +10482,14 @@ fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
|
||||
// run's own height to it, not (m - 1) x the line's (Word for Mac and Windows: 10pt Times New
|
||||
// Roman with 10pt Courier New, 18.09pt at 1.5 spacing where 1.5 x the 12.34pt line gives 18.51).
|
||||
let font = |(f, size): (&str, f32)| wordcraft_doc::CharProps { font: Some(f.into()), size: Some(size), ..Default::default() };
|
||||
let height = |fonts: &[(&str, f32)], m: f32| {
|
||||
let height = |fonts: &[(&str, f32)], m: f32, with_picture: bool| {
|
||||
let mut p = wordcraft_doc::Paragraph::with_text("run ", font(fonts[0]));
|
||||
for &f in &fonts[1..] {
|
||||
p.append(wordcraft_doc::Paragraph::with_text("run ", font(f)));
|
||||
}
|
||||
if with_picture {
|
||||
p.insert_object(p.len(), picture(30.0, 40.0, Default::default()), &font(fonts[0])).unwrap();
|
||||
}
|
||||
p.props = ParaProps { line_spacing: Some(wordcraft_doc::props::LineSpacing::Multiple(m)), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
@@ -10462,12 +10498,19 @@ fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
|
||||
};
|
||||
// The larger sans has the taller ascent, the serif the deeper descent.
|
||||
let (sans, serif) = (("Inter", 12.0), ("Source Serif 4", 10.5));
|
||||
let tallest = height(&[sans], 1.0).max(height(&[serif], 1.0));
|
||||
let mixed = height(&[sans, serif], 1.0);
|
||||
let tallest = height(&[sans], 1.0, false).max(height(&[serif], 1.0, false));
|
||||
let mixed = height(&[sans, serif], 1.0, false);
|
||||
assert!(mixed > tallest + 0.1, "the fonts don't make a taller line together: {mixed} vs {tallest}");
|
||||
for m in [1.5, 2.0] {
|
||||
let got = height(&[sans, serif], m);
|
||||
assert!((got - (mixed + (m - 1.0) * tallest)).abs() < 0.01, "{m}: {got}, line {mixed}, tallest run {tallest}");
|
||||
let with_picture = height(&[sans, serif], 1.0, true);
|
||||
assert!(with_picture > mixed, "the tall picture raises the line height");
|
||||
for (with_picture, single_height) in [(false, mixed), (true, with_picture)] {
|
||||
for m in [1.5, 2.0] {
|
||||
let got = height(&[sans, serif], m, with_picture);
|
||||
assert!(
|
||||
(got - (single_height + (m - 1.0) * tallest)).abs() < 0.01,
|
||||
"{m}, picture {with_picture}: {got}, line {single_height}, tallest run {tallest}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13332,6 +13375,66 @@ fn balanced_columns_keep_a_continued_tail_with_the_space_after_it() {
|
||||
assert!((q.2 - (tail_top + 28.0 + 28.0)).abs() < 0.5, "Q under P5's space after: Q {q:?}, P {pieces:?}");
|
||||
}
|
||||
|
||||
/// #9206: a paragraph that closes a balanced section with `keep_next` must not reserve column
|
||||
/// room in `kept_tail_end` for the next section's first paragraph.
|
||||
#[test]
|
||||
fn balanced_columns_do_not_keep_a_section_closing_tail_with_the_next_section() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
let lb = wordcraft_doc::para::LINE_BREAK;
|
||||
let filler = 135;
|
||||
let make_doc = |keep_next: bool| {
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
|
||||
text.push("P1".into());
|
||||
text.push("Q".into());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
for block in &mut d.body {
|
||||
if let Block::Para(para) = Arc::make_mut(block) {
|
||||
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
let mut s = SectionProps::default();
|
||||
s.columns.count = 3;
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
|
||||
let rest: String = (2..=12).map(|i| format!("{lb}P{i}")).collect();
|
||||
p.insert_text(2, &rest, &Default::default()).unwrap();
|
||||
p.props.keep_next = Some(keep_next);
|
||||
p.section = Some(Box::new(s));
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
d
|
||||
};
|
||||
|
||||
let without = lay(&make_doc(false));
|
||||
let with_keep = lay(&make_doc(true));
|
||||
assert_eq!(pieces_of(&with_keep, filler), pieces_of(&without, filler), "keep_next on section-closing tail must not unbalance columns");
|
||||
assert_eq!(para_boxes(&with_keep)[filler + 1], para_boxes(&without)[filler + 1], "Q below the balanced section must stay at the same y");
|
||||
}
|
||||
|
||||
/// #9208: when the next paragraph's `space_before` is dropped by contextual spacing, `kept_tail_end`
|
||||
/// must not count it on top of `gap_after`.
|
||||
#[test]
|
||||
fn balanced_columns_keep_a_continued_tail_without_dropped_space_before() {
|
||||
crate::test_fonts();
|
||||
let (base_doc, filler) = continued_tail_doc(14.0);
|
||||
let base_layout = lay(&base_doc);
|
||||
let base_pieces = pieces_of(&base_layout, filler);
|
||||
let base_q = para_boxes(&base_layout)[filler + 1];
|
||||
|
||||
let (mut ctx_doc, _) = continued_tail_doc(14.0);
|
||||
let q = ctx_doc.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
q.props.space_before = Some(28.0);
|
||||
q.props.contextual_spacing = Some(true);
|
||||
let ctx_layout = lay(&ctx_doc);
|
||||
let ctx_pieces = pieces_of(&ctx_layout, filler);
|
||||
let ctx_q = para_boxes(&ctx_layout)[filler + 1];
|
||||
|
||||
assert_eq!(ctx_pieces, base_pieces, "dropped space_before must not change tail placement");
|
||||
assert_eq!(ctx_q, base_q, "dropped space_before must not change Q placement");
|
||||
}
|
||||
|
||||
/// #6829: the lines going over with the next paragraph keep their row together. Text on the far
|
||||
/// side of a floating object is part of the same row (`settled_end`), and the end
|
||||
/// `kept_tail_end` picks must not split it: the whole row goes over with the next paragraph.
|
||||
@@ -13663,8 +13766,8 @@ fn unproofed_languages_and_no_proof_runs_are_not_marked() {
|
||||
let text = "Nous écrivons beaucoup aujourd'hui.";
|
||||
let mut d = Document::from_text(text);
|
||||
assert!(issues(&d) > 0, "French words are English misspellings in an English document");
|
||||
Arc::make_mut(&mut d.styles).default_chr.lang = Some("fr-FR".into());
|
||||
assert_eq!(issues(&d), 0, "no French dictionary: no marks");
|
||||
Arc::make_mut(&mut d.styles).default_chr.lang = Some("zxx".into());
|
||||
assert_eq!(issues(&d), 0, "no linguistic content (`zxx`): no marks");
|
||||
Arc::make_mut(&mut d.styles).default_chr.lang = Some("pl-PL".into());
|
||||
let mut pl = Document::from_text("Płynie żeka.");
|
||||
Arc::make_mut(&mut pl.styles).default_chr.lang = Some("pl-PL".into());
|
||||
@@ -19608,6 +19711,89 @@ fn header_margin_wrap_retry_counts_labels_once() {
|
||||
assert_eq!(retried, labels(Wrap::BehindText), "the retried header counts like the one laid out once");
|
||||
}
|
||||
|
||||
/// #9226: an even-page header is never measured for `page.body.y`, so it keeps its rendered
|
||||
/// margin-area layout instead of retrying with the declared margins.
|
||||
#[test]
|
||||
fn even_page_header_does_not_retry_with_declared_margins() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
let even_shape_y = |wrap: Wrap| {
|
||||
let mut doc = Document::from_text(&"Body\n".repeat(120));
|
||||
doc.settings.even_odd_headers = true;
|
||||
let s = &mut doc.last_section;
|
||||
s.margin_top = 20.0;
|
||||
s.margin_bottom = 20.0;
|
||||
s.header = 36.0;
|
||||
s.footer = 36.0;
|
||||
let (pw, ph) = (s.page_w, s.page_h);
|
||||
// Short default header/footer so `page.body.y == 36.0 + 10.0 = 46.0` (smaller than the even header).
|
||||
let def_h = doc.add_part(
|
||||
wordcraft_doc::PartKind::Header,
|
||||
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Odd", Default::default()))],
|
||||
);
|
||||
let def_f = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
let mut hp = boundary_header_para();
|
||||
let float = Float { wrap, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
|
||||
let even_h = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
|
||||
let s = &mut doc.last_section;
|
||||
s.headers.default = Some(def_h);
|
||||
s.headers.even = Some(even_h);
|
||||
s.footers.default = Some(def_f);
|
||||
let laid = lay(&doc);
|
||||
assert!(laid.pages.len() >= 2);
|
||||
shapes(&laid.pages[1].header)[0].y
|
||||
};
|
||||
assert!((even_shape_y(Wrap::Square) - even_shape_y(Wrap::BehindText)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_table_areas_match_retried_header_margin_fallback() {
|
||||
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
|
||||
use wordcraft_doc::props::{HeightRule, TableFloat};
|
||||
|
||||
let mut doc = Document::from_text("Body");
|
||||
let s = &mut doc.last_section;
|
||||
s.margin_top = 20.0;
|
||||
s.margin_bottom = 20.0;
|
||||
s.header = 36.0;
|
||||
s.footer = 36.0;
|
||||
let (pw, ph) = (s.page_w, s.page_h);
|
||||
|
||||
// Header has a wrapping Margin-bottom picture that triggers the retry with declared margins,
|
||||
// plus a Margin-bottom floating table.
|
||||
let mut hp = boundary_header_para();
|
||||
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
|
||||
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
|
||||
let mut header_table = Table::new(1, 1, 80.0);
|
||||
header_table.rows[0].props.height = Some(20.0);
|
||||
header_table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
header_table.props.float =
|
||||
Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), x: 300.0, ..Default::default() });
|
||||
let header = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp), Arc::new(Block::Table(header_table))]);
|
||||
doc.last_section.headers.default = Some(header);
|
||||
|
||||
let footer = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
|
||||
doc.last_section.footers.default = Some(footer);
|
||||
|
||||
// Place a body floating table at the rendered-area bottom position (ph - 86 - 20). Because the
|
||||
// drawn header falls back to declared margins (ph - 20 - 20), the two tables do not overlap
|
||||
// and the body table must stay at ph - 106.0.
|
||||
let mut body_table = Table::new(1, 1, 80.0);
|
||||
body_table.rows[0].props.height = Some(20.0);
|
||||
body_table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
let rendered_y = ph - 86.0 - 20.0;
|
||||
body_table.props.float = Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Page, x: 300.0, y: rendered_y, ..Default::default() });
|
||||
doc.body.insert(0, Arc::new(Block::Table(body_table)));
|
||||
|
||||
let laid = lay(&doc);
|
||||
let page = &laid.pages[0];
|
||||
let cell_y = |items: &[Placed]| items.iter().find_map(|it| if let Placed::Cell { rect, .. } = it { Some(rect.y) } else { None }).unwrap();
|
||||
let header_tbl_y = cell_y(&page.header);
|
||||
let body_tbl_y = cell_y(&page.items);
|
||||
assert!((header_tbl_y - (ph - 20.0 - 20.0)).abs() < 0.01, "header table at declared margin: {header_tbl_y}");
|
||||
assert!((body_tbl_y - rendered_y).abs() < 0.01, "body table should not avoid ghost rendered-area header table: {body_tbl_y} vs {rendered_y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_boundary_obstacle() {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
@@ -19785,6 +19971,89 @@ fn header_margin_table_area() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9383: the final part of a split continuation row keeps its own background extent.
|
||||
#[test]
|
||||
fn a_split_merge_continuation_picture_ends_at_the_following_row() {
|
||||
use display::Draw;
|
||||
use wordcraft_doc::props::{CellPicture, HeightRule, LineSpacing, PictureRepeat, Rgb, VMerge};
|
||||
|
||||
let paragraph = |text: &str| {
|
||||
let mut p = Paragraph::with_text(text, Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
wordcraft_doc::para_block(p)
|
||||
};
|
||||
let shade = Rgb(220, 185, 70);
|
||||
let tile = [30.0, 7.0];
|
||||
for split in [false, true] {
|
||||
let mut d = pagination_fixture_document("");
|
||||
d.last_section.page_h = 320.0;
|
||||
d.last_section.margin_top = 40.0;
|
||||
d.last_section.margin_bottom = 40.0;
|
||||
let media = d.add_media(vec![0u8; 8], "png");
|
||||
let mut table = Table::new(3, 2, 200.0);
|
||||
let start = &mut table.rows[0].cells[0];
|
||||
start.props.vmerge = VMerge::Restart;
|
||||
start.props.shading = Some(shade);
|
||||
start.props.picture = Some(Box::new(CellPicture { media: media.clone(), size: tile, repeat: PictureRepeat::Tile, align: [0.0, 0.0] }));
|
||||
start.blocks = vec![paragraph("Merged")];
|
||||
table.rows[0].cells[1].blocks = vec![paragraph("Start")];
|
||||
table.rows[1].cells[0].props.vmerge = VMerge::Continue;
|
||||
table.rows[1].cells[1].blocks = (0..if split { 26 } else { 3 }).map(|_| paragraph("Continued")).collect();
|
||||
table.rows[2].cells[0].blocks = vec![paragraph("Following")];
|
||||
if !split {
|
||||
// The short continuation moves on whole, so it still opens its second page.
|
||||
table.rows[0].props.height = Some(220.0);
|
||||
table.rows[0].props.height_rule = HeightRule::Exact;
|
||||
table.rows[1].props.cant_split = true;
|
||||
}
|
||||
d.body = vec![Arc::new(Block::Table(table)), paragraph("Aftertable")];
|
||||
|
||||
let layout = lay(&d);
|
||||
let parts: Vec<_> = (0..layout.pages.len()).filter_map(|i| cell_rect(&layout, i, 1, 0).map(|rect| (i, rect))).collect();
|
||||
assert_eq!(parts.len(), if split { 2 } else { 1 }, "split={split}: {parts:?}");
|
||||
let &(last, continuation) = parts.last().unwrap();
|
||||
assert!(last > 0, "the final fragment opens a later page");
|
||||
let following = cell_rect(&layout, last, 2, 0).expect("the next row shares the final page");
|
||||
let draws = display::page_display(&d, &layout.pages[last], &display::DisplayOptions::default());
|
||||
let (clip, tiles) = draws
|
||||
.iter()
|
||||
.find_map(|draw| match draw {
|
||||
Draw::Clip { rect, items } if items.iter().any(|item| matches!(item, Draw::Image { media: key, .. } if *key == media)) => {
|
||||
Some((rect, items))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("continued background picture");
|
||||
assert!((clip.y - continuation.y).abs() < 0.01 && (clip.h - continuation.h).abs() < 0.01, "split={split}: {clip:?} vs {continuation:?}");
|
||||
assert!(clip.bottom() <= following.y + 0.01, "the picture ends before the following row");
|
||||
assert!(
|
||||
draws.iter().any(|draw| matches!(draw, Draw::Fill { rect, color, .. }
|
||||
if *color == shade && *rect == *clip)),
|
||||
"solid shading has the same extent"
|
||||
);
|
||||
|
||||
let images: Vec<_> = tiles
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
Draw::Image { rect, media: key, .. } if *key == media => Some(rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(images.iter().all(|image| clip.intersects(image) && image.w == tile[0] && image.h == tile[1]));
|
||||
assert!(images.iter().any(|image| (image.y - clip.y).abs() < 0.01), "the first tile stays at the top");
|
||||
assert!(images.iter().any(|image| image.bottom() >= clip.bottom() - 0.01), "the last tile reaches the clipped edge");
|
||||
for following_text in ["Following", "Aftertable"] {
|
||||
assert!(
|
||||
draws.iter().any(|draw| matches!(draw, Draw::Glyphs { text, glyphs, .. }
|
||||
if text == following_text && !glyphs.is_empty() && glyphs.iter().all(|g| g.2 > clip.bottom()))),
|
||||
"{following_text} is drawn below the background"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod shape_alpha;
|
||||
|
||||
/// A row with a background picture split over two pages: each part draws its own piece of the
|
||||
@@ -19815,6 +20084,131 @@ fn a_split_cells_background_picture_is_drawn_on_both_parts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9192 and #9362: a vertically merged cell draws its clipped background picture behind
|
||||
/// the text and borders on the first page and on continuation pages.
|
||||
#[test]
|
||||
fn a_merged_cells_background_picture_is_drawn_on_both_pages() {
|
||||
use display::Draw;
|
||||
use wordcraft_doc::props::{Border, Borders, CellPicture, PictureRepeat, Rgb, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = wordcraft_doc::Table::new(50, 2, 100.0);
|
||||
let media = d.add_media(vec![0u8; 8], "png");
|
||||
let shade = Rgb(240, 230, 150);
|
||||
let border_color = Rgb(20, 40, 150);
|
||||
let border = Some(Border { color: Some(border_color), ..Border::single(6.0) });
|
||||
t.props.borders = Some(Borders { left: border, inside_v: border, ..Default::default() });
|
||||
let restart = &mut t.rows[0].cells[0];
|
||||
restart.props.vmerge = VMerge::Restart;
|
||||
restart.props.shading = Some(shade);
|
||||
restart.props.picture = Some(Box::new(CellPicture { media, size: [30.0, 6.0], repeat: PictureRepeat::Tile, align: [0.0, 0.0] }));
|
||||
restart.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
if r > 0 {
|
||||
row.cells[0].props.vmerge = VMerge::Continue;
|
||||
}
|
||||
row.cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("Row {r}"), Default::default()))];
|
||||
}
|
||||
d.body = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(t)), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
|
||||
let l = lay(&d);
|
||||
assert!(l.pages.len() >= 2, "the merged table spans at least two pages");
|
||||
for (n, page) in l.pages.iter().take(2).enumerate() {
|
||||
let clips: Vec<Rect> = page.items.iter().filter_map(|it| if let Placed::Clip { rect, .. } = it { Some(*rect) } else { None }).collect();
|
||||
assert_eq!(clips.len(), 1, "page {n}: expected continued merged-cell picture clip, got {clips:?}");
|
||||
let picture_rect = clips[0];
|
||||
assert!(picture_rect.h > 0.0 && picture_rect.bottom() <= page.h + 0.01, "page {n}: {picture_rect:?}");
|
||||
let draws = display::page_display(&d, page, &display::DisplayOptions::default());
|
||||
let fill = draws
|
||||
.iter()
|
||||
.position(|item| matches!(item, Draw::Fill { color, rect, .. } if *color == shade && *rect == picture_rect))
|
||||
.expect("merged-cell shading");
|
||||
let picture = draws
|
||||
.iter()
|
||||
.position(|item| {
|
||||
matches!(item, Draw::Clip { rect, items }
|
||||
if *rect == picture_rect && items.iter().any(|item| matches!(item, Draw::Image { .. })))
|
||||
})
|
||||
.expect("clipped background picture");
|
||||
assert!(fill < picture, "page {n}: shading goes behind the picture");
|
||||
|
||||
for x in [picture_rect.x, picture_rect.right()] {
|
||||
let side = draws
|
||||
.iter()
|
||||
.position(|item| {
|
||||
matches!(item, Draw::Line { color, width, x0, y0, x1, y1, .. }
|
||||
if *color == border_color && *width >= 6.0 && (*x0 - x).abs() < 0.01 && (*x1 - x).abs() < 0.01
|
||||
&& (*y0 - picture_rect.y).abs() < 0.01 && *y1 > *y0)
|
||||
})
|
||||
.unwrap_or_else(|| panic!("page {n}: first-row border at x={x}"));
|
||||
assert!(picture < side, "page {n}: the picture must be behind the first-row side border at x={x}");
|
||||
}
|
||||
|
||||
let text = draws.iter().position(|item| matches!(item, Draw::Glyphs { text, .. } if !text.trim().is_empty())).expect("first row text");
|
||||
assert!(picture < text, "page {n}: the picture goes behind the text");
|
||||
}
|
||||
}
|
||||
|
||||
/// #9191: page-end trimming in `table_flow` must cut only continuing merged-cell areas, not
|
||||
/// unrelated `Clip` items (such as a floating drawing canvas anchored in a row).
|
||||
#[test]
|
||||
fn page_end_trimming_does_not_cut_a_floating_canvas_clip_in_a_table_row() {
|
||||
use wordcraft_doc::para::{Anchor, CanvasStyle, Float, GroupChild, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::{Rgb, VMerge};
|
||||
let mut d = Document::new();
|
||||
let mut t = wordcraft_doc::Table::new(50, 2, 200.0);
|
||||
t.rows[0].cells[0].props.vmerge = VMerge::Restart;
|
||||
t.rows[0].cells[0].props.shading = Some(Rgb(10, 20, 30));
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
if r > 0 {
|
||||
row.cells[0].props.vmerge = VMerge::Continue;
|
||||
}
|
||||
row.cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("Row {r}"), Default::default()))];
|
||||
}
|
||||
d.body = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(t)), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
|
||||
let probe = lay(&d);
|
||||
assert!(probe.pages.len() >= 2);
|
||||
let last_row = probe.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Cell { row, .. } => Some(*row),
|
||||
_ => None,
|
||||
})
|
||||
.max()
|
||||
.expect("page 0 has table rows");
|
||||
|
||||
let member = InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w: 40.0,
|
||||
h: 30.0,
|
||||
fill: Some(Fill::solid(Rgb(40, 50, 60))),
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Float::default(),
|
||||
story: None,
|
||||
effects: Default::default(),
|
||||
freeform: None,
|
||||
extra: Default::default(),
|
||||
};
|
||||
let canvas = InlineObject::Group {
|
||||
w: 80.0,
|
||||
h: 120.0,
|
||||
float: Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: 40.0, ..Default::default() },
|
||||
ch_w: 80.0,
|
||||
ch_h: 120.0,
|
||||
children: vec![GroupChild { x: 10.0, y: 10.0, obj: member }],
|
||||
canvas: Some(CanvasStyle { fill: Some(Fill::solid(Rgb(0xF0, 0xF4, 0xFF))), stroke: None, stroke_width: 0.0 }),
|
||||
};
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(&format!("Row {last_row}"), Default::default());
|
||||
p.insert_object(0, canvas, &Default::default()).unwrap();
|
||||
if let wordcraft_doc::Block::Table(tbl) = std::sync::Arc::make_mut(&mut d.body[0]) {
|
||||
tbl.rows[last_row].cells[1].blocks = vec![wordcraft_doc::para_block(p)];
|
||||
}
|
||||
|
||||
let l = lay(&d);
|
||||
let clips: Vec<Rect> = l.pages[0].items.iter().filter_map(|it| if let Placed::Clip { rect, .. } = it { Some(*rect) } else { None }).collect();
|
||||
assert!(clips.iter().any(|r| (r.h - 120.0).abs() < 0.01), "floating canvas clip must keep its full 120 pt height: {clips:?}");
|
||||
}
|
||||
|
||||
/// A table moved to a new page by a page break before its first paragraph shows the number of
|
||||
/// the page it lands on in that cell's PAGE field, not the page it was laid out for.
|
||||
#[test]
|
||||
|
||||
@@ -1168,6 +1168,43 @@ fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() {
|
||||
assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]);
|
||||
}
|
||||
|
||||
/// Word's exact margins: a negative top (bottom) margin starts (ends) the body at its size from
|
||||
/// the page edge even when the header (footer) is taller, and the two overlap (ECMA-376
|
||||
/// §17.6.11, `w:pgMar` below zero; DOC `dyaTop` / `dyaBottom`), so the same text fits on fewer
|
||||
/// pages. Positive margins stay "at least": a taller header or footer pushes the body.
|
||||
#[test]
|
||||
fn negative_margins_are_exact_and_let_the_header_and_footer_overlap_the_body() {
|
||||
crate::test_fonts();
|
||||
let make = |top: f32, bottom: f32| {
|
||||
let mut d = Document::from_text(&"Body line\n".repeat(100));
|
||||
d.last_section.page_w = 595.3;
|
||||
d.last_section.page_h = 841.9;
|
||||
d.last_section.margin_top = top;
|
||||
d.last_section.margin_bottom = bottom;
|
||||
d.last_section.header = 36.0;
|
||||
d.last_section.footer = 36.0;
|
||||
let head = d.add_part(PartKind::Header, paras("Header line", 6));
|
||||
let foot = d.add_part(PartKind::Footer, paras("Footer line", 6));
|
||||
d.last_section.headers.default = Some(head);
|
||||
d.last_section.footers.default = Some(foot);
|
||||
let l = lay(&d);
|
||||
let body = extent(&l.pages[0].items, StoryRef::Body).unwrap();
|
||||
let header = extent(&l.pages[0].header, StoryRef::Part(head)).unwrap();
|
||||
let footer = extent(&l.pages[0].footer, StoryRef::Part(foot)).unwrap();
|
||||
(l.pages.len(), body, header, footer)
|
||||
};
|
||||
let (pages, body, header, footer) = make(-60.0, -60.0);
|
||||
assert!(header.1 > 60.0 && footer.0 < 841.9 - 60.0, "the bands reach past the margins: {header:?} {footer:?}");
|
||||
assert!((body.0 - 60.0).abs() < 0.5, "the body starts at the exact top margin, over the header: {body:?}");
|
||||
assert!(
|
||||
body.1 <= 841.9 - 60.0 + 0.01 && body.1 > footer.0,
|
||||
"the body runs down to the exact bottom margin, over the footer: {body:?} {footer:?}"
|
||||
);
|
||||
let (at_least_pages, at_least_body, at_least_header, at_least_footer) = make(60.0, 60.0);
|
||||
assert!(at_least_body.0 >= at_least_header.1 - 0.01 && at_least_body.1 <= at_least_footer.0 + 0.01, "{at_least_body:?}");
|
||||
assert!(pages < at_least_pages, "exact margins: {pages} pages, at least: {at_least_pages}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_keeps_a_multiple_spaced_picture_line_while_the_picture_fits() {
|
||||
// A paragraph holding only a picture, at 1.15 spacing, as the page's last line stays on the
|
||||
|
||||
@@ -214,3 +214,88 @@ fn turned_line_stays_in_its_table_cell() {
|
||||
assert!(l.turned_line(&at(cell, 0, 1), None, false, 0).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// #9151: in a multi-page vertical section, stepping past the last column of page 0 enters the
|
||||
/// first column of page 1, and stepping back from page 1's first column returns to page 0.
|
||||
#[test]
|
||||
fn turned_line_crosses_page_boundary() {
|
||||
crate::test_fonts();
|
||||
let text = (0..60).map(|i| format!("col{i:02}")).collect::<Vec<_>>().join("\n");
|
||||
let mut d = Document::from_text(&text);
|
||||
d.last_section.text_direction = TextDirection::Down;
|
||||
let l = lay(&d);
|
||||
assert!(l.pages.len() >= 2, "expected multiple pages, got {}", l.pages.len());
|
||||
|
||||
let page0_last_para = l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
crate::Placed::Lines { path, .. } => Some(path.last()),
|
||||
_ => None,
|
||||
})
|
||||
.next_back()
|
||||
.expect("page 0 has turned lines");
|
||||
let page1_first_para = l.pages[1]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
crate::Placed::Lines { path, .. } => Some(path.last()),
|
||||
_ => None,
|
||||
})
|
||||
.next()
|
||||
.expect("page 1 has turned lines");
|
||||
assert_eq!(page1_first_para, page0_last_para + 1);
|
||||
|
||||
let last_on_p0 = Pos::body(page0_last_para, 2);
|
||||
let (next, g) = l.turned_line(&last_on_p0, None, true, 0).expect("steps onto page 1");
|
||||
assert_eq!((&next.path, next.off), (&Path::top(page1_first_para), 2));
|
||||
|
||||
let (back, _) = l.turned_line(&next, Some(g), false, 1).expect("steps back onto page 0");
|
||||
assert_eq!((back.path, back.off), (Path::top(page0_last_para), 2));
|
||||
}
|
||||
|
||||
/// #9151: a header is laid out again on every page, so a vertical text box in it holds the same
|
||||
/// columns on each; stepping past its last or first column stays in the box instead of entering
|
||||
/// the copy on the adjacent page.
|
||||
#[test]
|
||||
fn turned_line_does_not_cross_pages_in_a_header_text_box() {
|
||||
use wordcraft_doc::props::TextVert;
|
||||
use wordcraft_doc::{PartKind, TextBody, para_block};
|
||||
crate::test_fonts();
|
||||
let text = (0..200).map(|i| format!("line{i:03}")).collect::<Vec<_>>().join("\n");
|
||||
let mut d = Document::from_text(&text);
|
||||
let boxed = d.add_part(
|
||||
PartKind::TextBox,
|
||||
vec![para_block(Paragraph::with_text("ab", Default::default())), para_block(Paragraph::with_text("cd", Default::default()))],
|
||||
);
|
||||
if let Some(p) = d.parts.get_mut(&boxed) {
|
||||
p.body = TextBody { vert: TextVert::Vert, ..Default::default() };
|
||||
}
|
||||
let shape = InlineObject::Shape {
|
||||
kind: wordcraft_doc::para::ShapeKind::TextBox,
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: Default::default(),
|
||||
story: Some(boxed),
|
||||
effects: Default::default(),
|
||||
freeform: None,
|
||||
extra: Default::default(),
|
||||
};
|
||||
let mut p = Paragraph::with_text("Header", Default::default());
|
||||
p.insert_object(6, shape, &Default::default()).unwrap();
|
||||
let header = d.add_part(PartKind::Header, vec![para_block(p)]);
|
||||
d.last_section.headers.default = Some(header);
|
||||
let l = lay(&d);
|
||||
assert!(l.pages.len() >= 4, "expected several pages, got {}", l.pages.len());
|
||||
let at = |para: usize, off: usize| Pos { story: StoryRef::Part(boxed), path: Path::top(para), off };
|
||||
// Within the box, the columns still step.
|
||||
assert_eq!(l.turned_line(&at(0, 1), None, true, 1).map(|(p, _)| p.path), Some(Path::top(1)));
|
||||
// Past its edges, there is no further column, on any page.
|
||||
for page in 1..3 {
|
||||
assert!(l.turned_line(&at(1, 1), None, true, page).is_none(), "next from the last column on page {page}");
|
||||
assert!(l.turned_line(&at(0, 1), None, false, page).is_none(), "previous from the first column on page {page}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub(crate) fn unturned_sect(s: &SectionProps, body_top: f32) -> SectionProps {
|
||||
v.page_w = s.page_h;
|
||||
v.page_h = s.page_w;
|
||||
v.gutter = 0.0;
|
||||
let (top, right, bottom, left) = (body_top, s.margin_right, s.margin_bottom, s.margin_left + s.gutter);
|
||||
let (top, right, bottom, left) = (body_top, s.margin_right, s.margin_bottom.abs(), s.margin_left + s.gutter);
|
||||
// The unturned frame's (u, v) lands at (W - v, u) for `Down` and (v, H - u) for `Up`: its
|
||||
// top edge is the real right edge (left for `Up`), its left edge the real top (bottom).
|
||||
match s.text_direction {
|
||||
|
||||
+25
-13
@@ -351,8 +351,8 @@ impl Exporter<'_> {
|
||||
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
|
||||
let draws = shown.draws(it, &dopts);
|
||||
match it {
|
||||
Placed::Lines { story, path, para, .. } => {
|
||||
let idx = self.entry(*story, path, para);
|
||||
Placed::Lines { story, path, para, l0, l1, .. } => {
|
||||
let idx = self.entry(*story, path, para, *l0..*l1);
|
||||
for d in &draws {
|
||||
self.line_item(s, d, idx, *story, path);
|
||||
}
|
||||
@@ -412,21 +412,33 @@ impl Exporter<'_> {
|
||||
p.text_without(&dropped)
|
||||
}
|
||||
|
||||
/// The structure entry for a paragraph on this page (created on first sight, in reading order).
|
||||
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout) -> usize {
|
||||
if let Some(i) = self.tag_index.get(&(story, path.clone())) {
|
||||
return *i;
|
||||
}
|
||||
let kind: TagKind = match self.doc.para(story, path).map(|p| self.doc.styles.resolve_para(&p.props).outline_level) {
|
||||
Some(Some(l)) if l < 6 => {
|
||||
/// The structure entry for a paragraph on this page. A heading starts at its first visible line.
|
||||
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout, lines: std::ops::Range<usize>) -> usize {
|
||||
let key = (story, path.clone());
|
||||
let existing = self.tag_index.get(&key).copied();
|
||||
let heading: Option<TagKind> = match self.doc.para(story, path).map(|p| self.doc.styles.resolve_para(&p.props).outline_level) {
|
||||
Some(Some(l)) if l < 6 && lines.contains(&nav::first_heading_line(pl)) => {
|
||||
let title = self.doc.para(story, path).map(|p| self.title_text(p, pl).trim().chars().take(200).collect::<String>());
|
||||
Tag::Hn(NonZeroU16::new(u16::from(l) + 1).unwrap_or(NonZeroU16::MIN), title).into()
|
||||
Some(Tag::Hn(NonZeroU16::new(u16::from(l) + 1).unwrap_or(NonZeroU16::MIN), title).into())
|
||||
}
|
||||
_ => Tag::P.into(),
|
||||
_ => None,
|
||||
};
|
||||
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
|
||||
if let Some(i) = existing {
|
||||
// A break-only piece in an earlier column can already have opened an entry: empty, or
|
||||
// holding only the list number the layout still draws before a column break.
|
||||
if let Some(kind) = heading
|
||||
&& !matches!(self.tags[i].kind, TagKind::Hn(..))
|
||||
{
|
||||
self.tags[i].kind = kind;
|
||||
if self.tags[i].children.is_empty() {
|
||||
self.tags[i].at = self.at;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
self.tags.push(TagEntry { kind: heading.unwrap_or_else(|| Tag::P.into()), children: Vec::new(), source: Some(key.clone()), at: self.at });
|
||||
let i = self.tags.len() - 1;
|
||||
self.tag_index.insert((story, path.clone()), i);
|
||||
self.tag_index.insert(key, i);
|
||||
i
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
use wordcraft_doc::numbering::NumberingIndex;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
use super::{
|
||||
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, LinkTag, Outline, OutlineNode, Placed, Point, StoryRef, Target,
|
||||
XyzDestination, krilla, write,
|
||||
};
|
||||
|
||||
/// A leading page or column break can be placed separately from the heading.
|
||||
pub(super) fn first_heading_line(para: &wordcraft_layout::para::ParaLayout) -> usize {
|
||||
para.lines
|
||||
.iter()
|
||||
.take_while(|line| {
|
||||
matches!(line.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
|
||||
&& para
|
||||
.clusters
|
||||
.get(line.c0..line.c1)
|
||||
.is_some_and(|cs| cs.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::ColumnBreak | ClKind::Marker)))
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
impl Exporter<'_> {
|
||||
/// Where a bookmark is: (output page, x, y) — the page and line its start lands on, which
|
||||
/// in a paragraph split across pages need not be the paragraph's first page.
|
||||
@@ -80,6 +97,7 @@ impl Exporter<'_> {
|
||||
/// The outline from body headings (outline levels 1–9) on the exported pages.
|
||||
pub(crate) fn outline(&self, pages: &[usize]) -> Option<Outline> {
|
||||
let mut flat: Vec<(u8, String, usize, f32, f32)> = Vec::new();
|
||||
let numbering = NumberingIndex::new(&self.doc.numbering);
|
||||
for pi in pages {
|
||||
let Some((out, fit)) = self.out_index.get(pi) else { continue };
|
||||
let Some(page) = self.lay.pages.get(*pi) else { continue };
|
||||
@@ -87,27 +105,33 @@ impl Exporter<'_> {
|
||||
let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, x, y, .. } = it else { continue };
|
||||
let Some(p) = self.doc.para(StoryRef::Body, path) else { continue };
|
||||
let Some(level) = self.doc.styles.resolve_para(&p.props).outline_level else { continue };
|
||||
// A leading page break can be placed on the previous page without the heading.
|
||||
let first = para
|
||||
.lines
|
||||
.iter()
|
||||
.take_while(|line| {
|
||||
line.end == LineEnd::PageBreak
|
||||
&& para
|
||||
.clusters
|
||||
.get(line.c0..line.c1)
|
||||
.is_some_and(|cs| cs.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker)))
|
||||
})
|
||||
.count();
|
||||
let first = first_heading_line(para);
|
||||
if !(*l0..*l1).contains(&first) {
|
||||
continue;
|
||||
}
|
||||
let Some(line) = para.lines.get(first) else { continue };
|
||||
let Some(piece) = para.lines.get(*l0) else { continue };
|
||||
let title: String = self.title_text(p, para).split_whitespace().collect::<Vec<_>>().join(" ").chars().take(200).collect();
|
||||
if title.is_empty() {
|
||||
let text = self.title_text(p, para);
|
||||
if text.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Layout already counted the label in document order, including headings on omitted pages.
|
||||
let number = para.label.as_ref().filter(|_| {
|
||||
p.props
|
||||
.numbering
|
||||
.or(para.rp.numbering)
|
||||
.and_then(|n| numbering.level(n.num, n.level.min(8)))
|
||||
.is_some_and(|level| !matches!(level.format, NumFormat::Bullet | NumFormat::None))
|
||||
});
|
||||
let title: String = number
|
||||
.map_or("", |label| label.text.as_str())
|
||||
.split_whitespace()
|
||||
.chain(text.split_whitespace())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.chars()
|
||||
.take(200)
|
||||
.collect();
|
||||
let (x, y) = fit.point(*x, *y + line.top - piece.top);
|
||||
flat.push((level.min(8), title, *out, x, y));
|
||||
}
|
||||
|
||||
+92
-12
@@ -2047,6 +2047,41 @@ fn ref_fields_export_cached_links() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_keeps_numbered_heading_labels() {
|
||||
use hayro_syntax::object::{Dict, String as PdfString};
|
||||
use wordcraft_doc::numbering::Level;
|
||||
|
||||
let mut d = Document::new();
|
||||
let numbering = Arc::make_mut(&mut d.numbering);
|
||||
let sections = numbering
|
||||
.try_add_levels(None, vec![Level { text: "%1".into(), ..Default::default() }, Level { text: "%1.%2".into(), ..Default::default() }])
|
||||
.unwrap();
|
||||
let bullets = numbering.add_list(ListKind::Bullet);
|
||||
let mut overview = Paragraph::with_text("Overview", CharProps::default()).styled("Heading1");
|
||||
overview.props.numbering = Some(NumRef { num: sections, level: 0 });
|
||||
Arc::make_mut(&mut d.styles).get_mut("Heading2").unwrap().para.numbering = Some(NumRef { num: sections, level: 1 });
|
||||
let details = Paragraph::with_text("Details", CharProps::default()).styled("Heading2");
|
||||
let blank = Paragraph::new().styled("Heading2");
|
||||
let summary = Paragraph::with_text("Summary", CharProps::default()).styled("Heading1");
|
||||
let mut notes = Paragraph::with_text("Notes", CharProps::default()).styled("Heading1");
|
||||
notes.props.numbering = Some(NumRef { num: bullets, level: 0 });
|
||||
d.body = [overview, details, blank, summary, notes].into_iter().map(para_block).collect();
|
||||
|
||||
let pdf = hayro_syntax::Pdf::new(export(&d, &PdfOptions::default()).unwrap()).unwrap();
|
||||
let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
|
||||
let outline = catalog.get::<Dict<'_>>(b"Outlines").unwrap();
|
||||
let title = |node: &Dict<'_>| pdf_text_string(node.get::<PdfString<'_>>(b"Title").unwrap().as_bytes());
|
||||
let overview = outline.get::<Dict<'_>>(b"First").unwrap();
|
||||
let details = overview.get::<Dict<'_>>(b"First").unwrap();
|
||||
assert_eq!(title(&overview), "1 Overview");
|
||||
assert_eq!(title(&details), "1.1 Details");
|
||||
assert!(details.get::<Dict<'_>>(b"Next").is_none(), "blank headings keep no outline entry");
|
||||
let summary = overview.get::<Dict<'_>>(b"Next").unwrap();
|
||||
assert_eq!(title(&summary), "Summary");
|
||||
assert_eq!(title(&summary.get::<Dict<'_>>(b"Next").unwrap()), "Notes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_after_leading_breaks() {
|
||||
use hayro_syntax::object::{Array, Dict};
|
||||
@@ -2070,8 +2105,9 @@ fn outline_after_leading_breaks() {
|
||||
assert!(target > 0, "the heading follows a page break");
|
||||
for pages in [None, Some(vec![target]), Some(vec![target, 0]), Some(vec![0])] {
|
||||
let expected = pages.as_ref().map_or(Some(target), |p| p.iter().position(|i| *i == target));
|
||||
let bytes = export(&d, &PdfOptions { pages, ..Default::default() }).unwrap();
|
||||
let bytes = export(&d, &PdfOptions { pages, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
assert_eq!(heading_one_tags(&pdf), usize::from(expected.is_some()), "heading tags follow the visible heading past leading breaks");
|
||||
let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
|
||||
let outlines = catalog.get::<Dict<'_>>(b"Outlines");
|
||||
let Some(expected) = expected else {
|
||||
@@ -2086,6 +2122,37 @@ fn outline_after_leading_breaks() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_heading_after_column_break_keeps_heading_tag() {
|
||||
let mut d = Document::from_text("");
|
||||
d.last_section.columns = wordcraft_doc::section::Columns { count: 2, space: 36.0, separator: false, widths: Vec::new() };
|
||||
let list = Arc::make_mut(&mut d.numbering).add_list(ListKind::Numbered);
|
||||
let mut heading = Paragraph::with_text("\u{e}Second column heading", CharProps::default()).styled("Heading1");
|
||||
heading.props.numbering = Some(NumRef { num: list, level: 0 });
|
||||
d.body = vec![para_block(Paragraph::with_text("First column", CharProps::default())), para_block(heading)];
|
||||
let bytes = export(&d, &PdfOptions { tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
assert_eq!(heading_one_tags(&pdf), 1, "the heading is tagged where its text starts, though its number is drawn before the column break");
|
||||
}
|
||||
|
||||
fn heading_one_tags(pdf: &hayro_syntax::Pdf) -> usize {
|
||||
use hayro_syntax::object::{Dict, Name, Object};
|
||||
|
||||
fn count(node: Object<'_>) -> usize {
|
||||
match node {
|
||||
Object::Array(array) => array.iter::<Object>().map(count).sum(),
|
||||
Object::Dict(dict) => {
|
||||
let heading = dict.get::<Name>(b"S").is_some_and(|role| role.as_ref() == b"H1");
|
||||
usize::from(heading) + dict.get::<Object>(b"K").map_or(0, count)
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
let catalog = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
|
||||
catalog.get::<Dict>(b"StructTreeRoot").and_then(|tree| tree.get::<Object>(b"K")).map_or(0, count)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_keeps_visible_objects() {
|
||||
use hayro_syntax::object::{Array, Dict};
|
||||
@@ -3590,21 +3657,31 @@ fn figure_tags_keep_story_paths_and_reordered_pages() {
|
||||
/// as Word's export does, where the document stores "9" for both.
|
||||
#[test]
|
||||
fn exported_page_references_show_the_page_or_words_error() {
|
||||
use hayro_syntax::object::{Array, Dict};
|
||||
|
||||
let field =
|
||||
|instr: &str| InlineObject::Field { instr: instr.into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() };
|
||||
let mut d = Document::from_text("See \nMissing \nTarget");
|
||||
for (i, instr) in [(0, "PAGEREF Target"), (1, "PAGEREF NoSuchMark")] {
|
||||
let mut d = Document::from_text("See \nUnlinked \nMissing \nTarget");
|
||||
for (i, instr) in [(0, r"PAGEREF Target \h"), (1, "PAGEREF Target"), (2, r"PAGEREF NoSuchMark \h")] {
|
||||
let p = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(i)).unwrap();
|
||||
let n = p.len();
|
||||
p.insert_object(n, field(instr), &CharProps::default()).unwrap();
|
||||
}
|
||||
let target = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap();
|
||||
let target = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(3)).unwrap();
|
||||
target.props.page_break_before = Some(true);
|
||||
target.insert_object(0, InlineObject::BookmarkStart { name: "Target".into() }, &CharProps::default()).unwrap();
|
||||
let text = extract_text(&export(&d, &PdfOptions::default()).unwrap());
|
||||
let bytes = export(&d, &PdfOptions::default()).unwrap();
|
||||
let text = extract_text(&bytes);
|
||||
let first = squash(&text[0]);
|
||||
assert!(first.contains("See 2"), "{first}");
|
||||
assert!(first.contains("Unlinked 2"), "{first}");
|
||||
assert!(first.contains("Missing Error! Bookmark not defined."), "{first}");
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
let annotations = pdf.pages()[0].raw().get::<Array>(b"Annots").expect("the linked page reference produces an annotation");
|
||||
let destinations: Vec<_> = annotations.iter::<Dict>().filter_map(|a| a.get::<Array>(b"Dest")).collect();
|
||||
assert_eq!(destinations.len(), 1, "only the linked, existing bookmark has a destination");
|
||||
let linked_page = destinations[0].raw_iter().next().unwrap().as_obj_ref().map(Into::into);
|
||||
assert_eq!(linked_page, pdf.pages()[1].raw().obj_id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4096,9 +4173,9 @@ fn table_cell_links_with_same_target_stay_in_their_own_cells() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph's continuation must follow the footer and header between its pages.
|
||||
/// A split heading has one heading tag, with its continuation read after the intervening footer and header.
|
||||
#[test]
|
||||
fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
fn spanning_heading_has_one_heading_tag_and_keeps_link_order() {
|
||||
use hayro_syntax::object::{Array, Dict, Name, Object};
|
||||
|
||||
let mut d = Document::new();
|
||||
@@ -4109,7 +4186,9 @@ fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
let footer = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(linked("Footer", "footer"))]);
|
||||
d.last_section.headers.default = Some(header);
|
||||
d.last_section.footers.default = Some(footer);
|
||||
d.body = vec![para_block(linked("First page\u{c}Second page", "body"))];
|
||||
let mut heading = linked("First page\u{c}Second page", "body");
|
||||
heading.props.outline_level = Some(0);
|
||||
d.body = vec![para_block(heading)];
|
||||
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
@@ -4123,14 +4202,14 @@ fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
expected.push(format!("{:?}", annots[i].obj_id().unwrap()));
|
||||
}
|
||||
}
|
||||
fn collect(o: Object<'_>, out: &mut Vec<String>) {
|
||||
fn collect(o: Object<'_>, links: &mut Vec<String>) {
|
||||
match o {
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, out)),
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, links)),
|
||||
Object::Dict(d) => {
|
||||
if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") {
|
||||
out.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
|
||||
links.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
|
||||
} else if let Some(k) = d.get::<Object>(b"K") {
|
||||
collect(k, out);
|
||||
collect(k, links);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -4140,5 +4219,6 @@ fn spanning_paragraph_links_follow_page_reading_order() {
|
||||
let tree = root.get::<Dict>(b"StructTreeRoot").unwrap();
|
||||
let mut actual = Vec::new();
|
||||
collect(tree.get::<Object>(b"K").unwrap(), &mut actual);
|
||||
assert_eq!(heading_one_tags(&pdf), 1, "the second page continues the heading text without a duplicate heading tag");
|
||||
assert_eq!(actual, expected, "links must follow page reading order across a split paragraph");
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ craft = { workspace = true, features = [
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-html = { workspace = true }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -77,7 +77,7 @@ craft-ui-test-kit = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "18499ec3a61f6d7a7d8a70951fa9765e5cf9853c", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -271,12 +271,8 @@ impl WordApp {
|
||||
let roots = self.pass_roots.take();
|
||||
wordcraft_engine::file_access::confine(roots.as_ref(), || self.run_fired(&ctx, &out));
|
||||
self.canvas.take_focus_after_pass(&ctx);
|
||||
// The zoom is context-wide but the display scale is per window: read it from the active
|
||||
// document window. The windowless root has no window, so it reports none (#8853).
|
||||
let active = self.active_viewport();
|
||||
let native_now = ctx.input_for(active, |i| i.viewport().native_pixels_per_point).or_else(|| ctx.native_pixels_per_point());
|
||||
self.native_scale = theme::usable_scale(native_now.unwrap_or(1.0));
|
||||
if let Some(native) = native_now
|
||||
self.native_scale = theme::usable_scale(ctx.native_pixels_per_point().unwrap_or(1.0));
|
||||
if let Some(native) = ctx.native_pixels_per_point()
|
||||
&& let Some(old) = self.legacy_interface_size.take()
|
||||
{
|
||||
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
|
||||
|
||||
@@ -149,6 +149,20 @@ const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
|
||||
[Cut, Copy, Paste, Undo, Redo]
|
||||
};
|
||||
|
||||
/// Customize Keyboard's path fallback for commands defined by the framework. Its category
|
||||
/// filters are function pointers, so keep only the built-in registry's linked tab names.
|
||||
pub(crate) fn linked_command_tab(id: &str) -> Option<&'static str> {
|
||||
static TABS: std::sync::LazyLock<[(&'static str, Option<&'static str>); LINKED_EDIT.len()]> = std::sync::LazyLock::new(|| {
|
||||
let registry = wordcraft_engine::cmd::registry();
|
||||
LINKED_EDIT.map(|command| {
|
||||
let id = command.id();
|
||||
let tab = registry.get(id).and_then(|spec| location_path(spec.location)).and_then(|path| path.first().copied());
|
||||
(id, tab)
|
||||
})
|
||||
});
|
||||
TABS.iter().find(|(linked, _)| *linked == id).and_then(|(_, tab)| *tab)
|
||||
}
|
||||
|
||||
/// The English parts of a registry `location` (`Home › Font`, split as `i18n::location` does); `None` for no place.
|
||||
pub(crate) fn location_path(location: &str) -> Option<Vec<&str>> {
|
||||
let path: Vec<&str> = location.split(" › ").filter(|part| !part.is_empty()).collect();
|
||||
|
||||
@@ -157,7 +157,17 @@ impl WordApp {
|
||||
self.execute_command(id, params, false)
|
||||
}
|
||||
|
||||
/// Resolving a comment saves the text typed in its open edit first. If that write is
|
||||
/// refused, the comment stays unresolved and the draft is kept.
|
||||
fn save_comment_edit_before(&mut self, id: &str) -> Result<(), String> {
|
||||
if id == "review.resolveComment" {
|
||||
panes::commit_open_comment_edit(self)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn execute_command(&mut self, id: &str, params: Value, bitmap_if_empty: bool) -> Result<Value, String> {
|
||||
self.save_comment_edit_before(id)?;
|
||||
self.clear_command_targets(id);
|
||||
if let Some(error) = self.document_required_error(id) {
|
||||
return Err(error);
|
||||
@@ -165,6 +175,11 @@ impl WordApp {
|
||||
if let Some(r) = self.ui_command(id, ¶ms) {
|
||||
return r;
|
||||
}
|
||||
// Resolve takes a whole thread, found from a reply's id or the caret, and its fields turn read-only: every
|
||||
// draft is written first, for scripts and agents too (#9196). A refused draft stays.
|
||||
if id == "review.resolveComment" {
|
||||
let _ = panes::flush_comment_drafts(self);
|
||||
}
|
||||
if id == "file.close" {
|
||||
return self.close_document(¶ms);
|
||||
}
|
||||
|
||||
@@ -639,12 +639,19 @@ fn mark_area(page: usize, r: &wordcraft_geom::Rect, kind: MarkKind) -> MarkArea
|
||||
}
|
||||
|
||||
/// The selection, Find › Reading Highlight and Read Aloud marks, in page points.
|
||||
fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcraft_geom::Rect)]) -> Vec<MarkArea> {
|
||||
pub(crate) fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcraft_geom::Rect)]) -> Vec<MarkArea> {
|
||||
let mut areas: Vec<MarkArea> = selected.iter().map(|(page, r)| mark_area(*page, r, MarkKind::Selection)).collect();
|
||||
// Find's places are the document's, not the preview's.
|
||||
if preview_sel(app).is_none() {
|
||||
let hint = app.session.page_hint;
|
||||
let found: Vec<(Pos, Pos)> = app.session.find_highlights().iter().take(5000).cloned().collect();
|
||||
// Highlight Navigation pane search results across all tabs while the pane is open (#9229).
|
||||
let found: Vec<(Pos, Pos)> = if app.session.find.highlight {
|
||||
app.session.find_highlights().iter().take(5000).cloned().collect()
|
||||
} else if app.session.view.nav_pane && !app.session.find.results.is_empty() {
|
||||
app.session.find.results.iter().take(5000).cloned().collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for (a, b) in &found {
|
||||
for (page, r) in layout.selection_rects(&app.session.doc, a, b, hint) {
|
||||
areas.push(mark_area(page, &r, MarkKind::Found));
|
||||
|
||||
@@ -81,6 +81,9 @@ fn open_edit_on_double_click(app: &mut WordApp, ui: &Ui) {
|
||||
return;
|
||||
}
|
||||
let Some(c) = app.session.doc.comments.get(&id) else { return };
|
||||
if c.resolved {
|
||||
return;
|
||||
}
|
||||
let text = app.session.doc.plain_text(StoryRef::Part(c.part));
|
||||
app.canvas.comments.edit(thread_id(id), 0, text);
|
||||
}
|
||||
@@ -102,6 +105,9 @@ fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
|
||||
}
|
||||
CommentEdit::Edit { thread, index, text, .. } => {
|
||||
let Some(id) = app_id(thread).and_then(|t| message_id(app, t, index)) else { return };
|
||||
if app.session.doc.comments.get(&id).is_some_and(|c| c.resolved) {
|
||||
return;
|
||||
}
|
||||
// An empty comment is deleted, as Word does.
|
||||
let _ = if text.trim().is_empty() {
|
||||
app.run("review.deleteComment", json!({"id": id}))
|
||||
|
||||
@@ -13,7 +13,6 @@ use craft::ui::primitives::{FaceRun, PaintShape, StrokeWidth, TextRun};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2};
|
||||
use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_layout::DocLayout;
|
||||
|
||||
use super::cursor::{caret_color_at, preedit_cursor_chars};
|
||||
@@ -40,13 +39,8 @@ struct Placement {
|
||||
/// The selection is collapsed, so a caret is drawn.
|
||||
collapsed: bool,
|
||||
/// The face, size and baseline on screen text typed at the caret takes, which a composition is drawn in. `None`
|
||||
/// in an equation and without a style run. In turned text the baseline is unused.
|
||||
/// in an equation, in turned text and without a style run.
|
||||
typing: Option<TypingFace>,
|
||||
/// The direction the caret's line reads in; turned text has a composition running down or up the page.
|
||||
turn: TextDirection,
|
||||
/// Turned text: the caret's top on screen, where the composition starts, and the line's width across the page.
|
||||
y0: f32,
|
||||
across: f32,
|
||||
}
|
||||
|
||||
/// The face text typed at the caret asks for, its size and its baseline on screen (`DocLayout::typing_style`).
|
||||
@@ -82,9 +76,6 @@ fn place(app: &WordApp, doc: &DocLayout, pages: &[PlacedPage]) -> Option<Placeme
|
||||
in_equation: true,
|
||||
collapsed: true,
|
||||
typing: None,
|
||||
turn: TextDirection::Horizontal,
|
||||
y0,
|
||||
across: 0.0,
|
||||
});
|
||||
}
|
||||
let sel = preview_sel(app).unwrap_or(&app.session.sel);
|
||||
@@ -114,17 +105,15 @@ fn place(app: &WordApp, doc: &DocLayout, pages: &[PlacedPage]) -> Option<Placeme
|
||||
} else {
|
||||
[pos2(x.round() + 0.5, y0), pos2(x.round() + 0.5, y1)]
|
||||
};
|
||||
// Word draws a composition in the font and size of the text it goes into, along the line (turned text: down or up
|
||||
// the page).
|
||||
let turned = c.width > 0.0;
|
||||
let typing = doc
|
||||
.typing_style(&sel.focus, app.session.page_hint)
|
||||
.filter(|(run, base)| run.size.is_finite() && run.size > 0.0 && (turned || base.is_finite()))
|
||||
.map(|(run, base)| TypingFace {
|
||||
face: run.requested_face,
|
||||
size: run.size * scale,
|
||||
baseline: if turned { 0.0 } else { pr.rect.min.y + base * scale },
|
||||
});
|
||||
// Word draws a composition in the font and size of the text it goes into; not in turned text, whose lines aren't
|
||||
// horizontal.
|
||||
let typing = if c.width > 0.0 {
|
||||
None
|
||||
} else {
|
||||
doc.typing_style(&sel.focus, app.session.page_hint)
|
||||
.filter(|(run, base)| run.size.is_finite() && run.size > 0.0 && base.is_finite())
|
||||
.map(|(run, base)| TypingFace { face: run.requested_face, size: run.size * scale, baseline: pr.rect.min.y + base * scale })
|
||||
};
|
||||
Some(Placement {
|
||||
bar,
|
||||
page: c.page,
|
||||
@@ -135,9 +124,6 @@ fn place(app: &WordApp, doc: &DocLayout, pages: &[PlacedPage]) -> Option<Placeme
|
||||
in_equation: false,
|
||||
collapsed: sel.is_collapsed(),
|
||||
typing,
|
||||
turn: c.turn,
|
||||
y0,
|
||||
across: c.width * scale,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -218,9 +204,6 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
cursor,
|
||||
color: ink(app),
|
||||
typing: pl.typing,
|
||||
turn: pl.turn,
|
||||
y0: pl.y0,
|
||||
across: pl.across,
|
||||
});
|
||||
} else {
|
||||
let look = step(app, request(pl.bar, shown));
|
||||
@@ -241,8 +224,8 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
// them an empty rect that clips their strokes away.
|
||||
let out = CaretMarks::new(tl!("Text cursor").to_string(), bars, composition).show_at(ui, pass.rect);
|
||||
// The candidate window sits at the input method's cursor inside the composition, as production placed it.
|
||||
if let Some(r) = out.composition_caret {
|
||||
report = if pl.turn.is_turned() { r } else { Rect::from_min_max(pos2(r.min.x, report.min.y), pos2(r.min.x + 1.0, report.max.y)) };
|
||||
if let Some(x) = out.composition_caret {
|
||||
report = Rect::from_min_max(pos2(x, report.min.y), pos2(x + 1.0, report.max.y));
|
||||
}
|
||||
}
|
||||
// Reported after the marks, which lay the composition out: this pass's final caret for the input method.
|
||||
@@ -262,11 +245,6 @@ struct Composition {
|
||||
color: Color32,
|
||||
/// The face, size and baseline it is drawn in; without them, the interface font from the caret's bottom.
|
||||
typing: Option<TypingFace>,
|
||||
/// The line's direction; turned, the composition's characters stack upright down or up from `y0`, in a column
|
||||
/// `across` wide starting at `left`.
|
||||
turn: TextDirection,
|
||||
y0: f32,
|
||||
across: f32,
|
||||
}
|
||||
|
||||
/// The style of the caret marks: the composition's ink.
|
||||
@@ -287,9 +265,8 @@ pub(crate) struct CaretMarks {
|
||||
common: Common,
|
||||
bars: Vec<(Bar, Color32)>,
|
||||
composition: Option<Composition>,
|
||||
/// Where the paint put the caret inside the composition (a bar in screen points; turned text: the rect the
|
||||
/// composition fills), measured from the laid-out text.
|
||||
composition_caret: Option<Rect>,
|
||||
/// Where the paint put the caret inside the composition (screen x), measured from the laid-out text.
|
||||
composition_caret: Option<f32>,
|
||||
}
|
||||
|
||||
impl CaretMarks {
|
||||
@@ -302,7 +279,7 @@ impl CaretMarks {
|
||||
/// What the marks report: the caret's place inside the composition they drew, for the candidate window.
|
||||
pub(crate) struct CaretMarksOutput {
|
||||
response: Response,
|
||||
composition_caret: Option<Rect>,
|
||||
composition_caret: Option<f32>,
|
||||
}
|
||||
|
||||
impl Outcome for CaretMarksOutput {
|
||||
@@ -353,12 +330,6 @@ impl Component for CaretMarks {
|
||||
}
|
||||
let Some(c) = &self.composition else { return };
|
||||
let color = DataColor::new(c.color);
|
||||
if c.turn.is_turned()
|
||||
&& let Some(t) = &c.typing
|
||||
{
|
||||
self.composition_caret = Some(paint_turned(&draw, c, t, color));
|
||||
return;
|
||||
}
|
||||
let (layout, top, bottom) = match &c.typing {
|
||||
// In the text's own face and size, its first baseline on the line's, as typed text would sit. Characters the
|
||||
// face lacks (CJK in a Latin font) come from the interface fonts; a size past the font atlas is capped.
|
||||
@@ -379,7 +350,7 @@ impl Component for CaretMarks {
|
||||
draw.stroke(&PaintShape::Path(underline), StrokeWidth::Thin, color);
|
||||
let x = (c.left + layout.char_x(c.cursor)).round() + 0.5;
|
||||
draw.stroke(&PaintShape::Path(vec![pos2(x, top), pos2(x, bottom)]), StrokeWidth::Medium, color);
|
||||
self.composition_caret = Some(Rect::from_min_max(pos2(x, top), pos2(x, bottom)));
|
||||
self.composition_caret = Some(x);
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
@@ -390,27 +361,3 @@ impl Component for CaretMarks {
|
||||
CaretMarksOutput { response: cx.response.clone(), composition_caret: self.composition_caret }
|
||||
}
|
||||
}
|
||||
|
||||
/// A composition in turned text: its characters upright, each in a cell of the run's size, stacked from the caret down
|
||||
/// the page (`Down`) or up it (`Up`) in a column across the line, with the underline along the column's left edge and
|
||||
/// the input method's cursor across it. Returns the rect the composition fills, which the candidate window avoids.
|
||||
fn paint_turned(draw: &craft::ui::primitives::Draw<'_>, c: &Composition, t: &TypingFace, color: DataColor) -> Rect {
|
||||
let key = face_key(t.face);
|
||||
let sign = if c.turn == TextDirection::Up { -1.0 } else { 1.0 };
|
||||
// The cell's edge `i` characters from the start.
|
||||
let edge = |i: usize| c.y0 + sign * t.size * i as f32;
|
||||
let n = c.text.chars().count();
|
||||
for (i, ch) in c.text.chars().enumerate() {
|
||||
let mut buf = [0; 4];
|
||||
let s: &str = ch.encode_utf8(&mut buf);
|
||||
// Centred in the column as an em-wide ideograph; the baseline sits at 0.86 em in the cell, where its body lies.
|
||||
let top = edge(i).min(edge(i + 1));
|
||||
let at = pos2(c.left + (c.across - t.size) / 2.0, top + 0.86 * t.size);
|
||||
draw.face_run(at, &FaceRun::new(s, &key, t.size, color), || face_bytes(t.face));
|
||||
}
|
||||
let end = edge(n);
|
||||
draw.stroke(&PaintShape::Path(vec![pos2(c.left, c.y0), pos2(c.left, end)]), StrokeWidth::Thin, color);
|
||||
let at = edge(c.cursor.min(n)).round() + 0.5;
|
||||
draw.stroke(&PaintShape::Path(vec![pos2(c.left, at), pos2(c.left + c.across, at)]), StrokeWidth::Medium, color);
|
||||
Rect::from_two_pos(pos2(c.left, c.y0), pos2(c.left + c.across, end))
|
||||
}
|
||||
|
||||
@@ -27,6 +27,13 @@ pub(super) fn context_suggestions(app: &mut WordApp) {
|
||||
app.canvas.context_synonyms = app.session.run("review.thesaurus", &json!({})).ok().and_then(|v| v.get("synonyms").cloned());
|
||||
}
|
||||
|
||||
/// Hands the keyboard back to the page from a menu action, in this same pass, and asks for a
|
||||
/// repaint so the page redraws with the focused caret (#6715).
|
||||
fn refocus_canvas(app: &mut WordApp, ui: &Ui) {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
/// The heading of a proofing issue's context menu, in the interface language like the rest of
|
||||
/// the menu: a spelling issue's own message is in the text's language (craft-proof's, "Faute
|
||||
/// d'orthographe possible" for French text), so it says Possible spelling mistake instead.
|
||||
@@ -80,7 +87,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
|
||||
let pick = menu.pick(ui, &rows);
|
||||
if let Some(act) = pick.picked {
|
||||
super::equation_frame::run_equation_act(app, &act);
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
refocus_canvas(app, ui);
|
||||
}
|
||||
} else {
|
||||
// The companion bar and the rows both need the app; they run one after the other, never nested.
|
||||
@@ -121,15 +128,17 @@ pub(crate) fn paste_menu_item(app: &mut WordApp, ui: &mut Ui) {
|
||||
}
|
||||
if row.show(ui).ran {
|
||||
let _ = app.run("edit.paste", json!({}));
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
refocus_canvas(app, ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// A row labelled `label` that runs command `id` with `params`; its chord, enabled state and
|
||||
/// action come from the command, its wording from the menu (one command id serves several rows).
|
||||
fn item(ui: &mut Ui, label: &str, id: &str, params: Value) {
|
||||
fn item(app: &mut WordApp, ui: &mut Ui, label: &str, id: &str, params: Value) {
|
||||
// `MenuItem::command`, not `new(..).command(..)`: only the row's own binding shows the command's chord.
|
||||
let _ = MenuItem::command(CommandRef::with_params(id, params)).label(tl!(label).to_string()).show(ui);
|
||||
if MenuItem::command(CommandRef::with_params(id, params)).label(tl!(label).to_string()).show(ui).ran && !id.starts_with("ui.") {
|
||||
refocus_canvas(app, ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn rule(ui: &mut Ui) {
|
||||
@@ -151,22 +160,23 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
|
||||
for sgt in sugg {
|
||||
if MenuItem::new(sgt.clone()).show(ui).ran {
|
||||
let _ = app.run("review.applySuggestion", json!({"text": sgt}));
|
||||
refocus_canvas(app, ui);
|
||||
}
|
||||
}
|
||||
if issue.get("kind").and_then(|k| k.as_str()) == Some("spelling") {
|
||||
item(ui, "Ignore All", "review.ignoreAll", json!({}));
|
||||
item(ui, "Add to Dictionary", "review.addToDictionary", json!({}));
|
||||
item(app, ui, "Ignore All", "review.ignoreAll", json!({}));
|
||||
item(app, ui, "Add to Dictionary", "review.addToDictionary", json!({}));
|
||||
}
|
||||
rule(ui);
|
||||
}
|
||||
item(ui, "Cut", "edit.cut", json!({}));
|
||||
item(ui, "Copy", "edit.copy", json!({}));
|
||||
item(app, ui, "Cut", "edit.cut", json!({}));
|
||||
item(app, ui, "Copy", "edit.copy", json!({}));
|
||||
// How to paste, chosen before pasting (#2583): the ribbon's Paste menu, item for item. Paste
|
||||
// keeps the clipboard's formatting (Word's Keep Source Formatting).
|
||||
paste_menu_item(app, ui);
|
||||
item(ui, "Keep Text Only", "edit.pasteText", json!({}));
|
||||
item(ui, "Merge Formatting", "edit.pasteMerge", json!({}));
|
||||
item(ui, "Paste Special…", "edit.pasteSpecial", json!({}));
|
||||
item(app, ui, "Keep Text Only", "edit.pasteText", json!({}));
|
||||
item(app, ui, "Merge Formatting", "edit.pasteMerge", json!({}));
|
||||
item(app, ui, "Paste Special…", "edit.pasteSpecial", json!({}));
|
||||
rule(ui);
|
||||
if let Some(syn) = app.canvas.context_synonyms.clone().and_then(|v| v.as_array().cloned()).filter(|a| !a.is_empty()) {
|
||||
let _ = Menu::submenu_row(ui, tl!("Synonyms").to_string(), |ui, _cx| {
|
||||
@@ -176,29 +186,30 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
|
||||
if let Some((a, b)) = wordcraft_engine::cmd::review::thesaurus_word(&app.session) {
|
||||
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
|
||||
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
|
||||
refocus_canvas(app, ui);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
item(ui, "Font…", "ui.dialog", json!({"name": "font"}));
|
||||
item(ui, "Paragraph…", "ui.dialog", json!({"name": "paragraph"}));
|
||||
item(ui, "Link…", "ui.dialog", json!({"name": "link"}));
|
||||
item(ui, "New Comment", "review.newComment", json!({}));
|
||||
item(app, ui, "Font…", "ui.dialog", json!({"name": "font"}));
|
||||
item(app, ui, "Paragraph…", "ui.dialog", json!({"name": "paragraph"}));
|
||||
item(app, ui, "Link…", "ui.dialog", json!({"name": "link"}));
|
||||
item(app, ui, "New Comment", "review.newComment", json!({}));
|
||||
if !wordcraft_engine::cmd::fields::selected(&app.session).is_empty() {
|
||||
rule(ui);
|
||||
item(ui, "Update Field", "references.updateFields", json!({}));
|
||||
item(ui, "Edit Field…", "fields.setCode", json!({}));
|
||||
item(ui, "Toggle Field Codes", "fields.toggleCode", json!({}));
|
||||
item(app, ui, "Update Field", "references.updateFields", json!({}));
|
||||
item(app, ui, "Edit Field…", "fields.setCode", json!({}));
|
||||
item(app, ui, "Toggle Field Codes", "fields.toggleCode", json!({}));
|
||||
} else if wordcraft_engine::cmd::references::caret_in_toc(&app.session) {
|
||||
// The TOC field sits in the table's heading; its entries are plain paragraphs.
|
||||
rule(ui);
|
||||
item(ui, "Update Field", "references.updateToc", json!({}));
|
||||
item(ui, "Remove Table of Contents", "references.removeToc", json!({}));
|
||||
item(app, ui, "Update Field", "references.updateToc", json!({}));
|
||||
item(app, ui, "Remove Table of Contents", "references.removeToc", json!({}));
|
||||
}
|
||||
let selected_object = wordcraft_engine::cmd::objects::selected(&app.session).is_some();
|
||||
if selected_object || app.session.sel.focus.path.cell().is_some() {
|
||||
item(ui, "View Alt Text…", "view.altTextPane", json!({"value": true}));
|
||||
item(app, ui, "View Alt Text…", "view.altTextPane", json!({"value": true}));
|
||||
}
|
||||
// A selected picture, shape, text box or chart: its own items, then Wrap Text (#513).
|
||||
let picture = crate::ribbon::has_picture_selected(&app.session);
|
||||
@@ -207,61 +218,61 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
|
||||
rule(ui);
|
||||
}
|
||||
if picture {
|
||||
item(ui, "Change Picture…", "ui.changePicture", json!({}));
|
||||
item(ui, "Reset Picture", "picture.reset", json!({}));
|
||||
item(ui, "Size and Crop…", "ui.tab", json!({"tab": "Picture Format"}));
|
||||
item(ui, "Crop", "ui.crop", json!({}));
|
||||
item(app, ui, "Change Picture…", "ui.changePicture", json!({}));
|
||||
item(app, ui, "Reset Picture", "picture.reset", json!({}));
|
||||
item(app, ui, "Size and Crop…", "ui.tab", json!({"tab": "Picture Format"}));
|
||||
item(app, ui, "Crop", "ui.crop", json!({}));
|
||||
}
|
||||
if picture || object {
|
||||
// A numbered caption under (or over) the picture, shape, text box or chart (#1230).
|
||||
item(ui, "Insert Caption…", "references.caption", json!({}));
|
||||
item(app, ui, "Insert Caption…", "references.caption", json!({}));
|
||||
}
|
||||
if object {
|
||||
let _ = Menu::submenu_row(ui, tl!("Wrap Text").to_string(), |ui, _cx| crate::ribbon::wrap_text_items(ui, app));
|
||||
}
|
||||
if craft::ui::runtime::commands::resolve(ui.ctx(), CommandRef::new("shape.fill")).enabled {
|
||||
item(ui, "Format Shape…", "view.formatShapePane", json!({"value": true}));
|
||||
item(app, ui, "Format Shape…", "view.formatShapePane", json!({"value": true}));
|
||||
}
|
||||
if app.session.sel.focus.path.cell().is_some() {
|
||||
// The table's items follow what is selected, as in Word (2019, Windows).
|
||||
let pick = table_pick(&app.session);
|
||||
rule(ui);
|
||||
let _ = Menu::submenu_row(ui, tl!("Insert").to_string(), |ui, _cx| {
|
||||
item(ui, "Insert Columns to the Left", "table.insertColumnLeft", json!({}));
|
||||
item(ui, "Insert Columns to the Right", "table.insertColumnRight", json!({}));
|
||||
item(ui, "Insert Rows Above", "table.insertRowAbove", json!({}));
|
||||
item(ui, "Insert Rows Below", "table.insertRowBelow", json!({}));
|
||||
item(app, ui, "Insert Columns to the Left", "table.insertColumnLeft", json!({}));
|
||||
item(app, ui, "Insert Columns to the Right", "table.insertColumnRight", json!({}));
|
||||
item(app, ui, "Insert Rows Above", "table.insertRowAbove", json!({}));
|
||||
item(app, ui, "Insert Rows Below", "table.insertRowBelow", json!({}));
|
||||
});
|
||||
// Every Delete is there whatever is selected, as on Word's Delete button: with the caret
|
||||
// in a cell, Delete Table is how the table goes (#1198).
|
||||
let _ = Menu::submenu_row(ui, tl!("Delete").to_string(), |ui, _cx| {
|
||||
item(ui, "Delete Cells", "table.deleteCells", json!({}));
|
||||
item(ui, "Delete Columns", "table.deleteColumn", json!({}));
|
||||
item(ui, "Delete Rows", "table.deleteRow", json!({}));
|
||||
item(ui, "Delete Table", "table.deleteTable", json!({}));
|
||||
item(app, ui, "Delete Cells", "table.deleteCells", json!({}));
|
||||
item(app, ui, "Delete Columns", "table.deleteColumn", json!({}));
|
||||
item(app, ui, "Delete Rows", "table.deleteRow", json!({}));
|
||||
item(app, ui, "Delete Table", "table.deleteTable", json!({}));
|
||||
});
|
||||
if pick == TablePick::Cell {
|
||||
item(ui, "Split Cells", "table.split", json!({}));
|
||||
item(app, ui, "Split Cells", "table.split", json!({}));
|
||||
}
|
||||
if matches!(pick, TablePick::Cells | TablePick::Rows | TablePick::Columns) {
|
||||
item(ui, "Merge Cells", "table.merge", json!({}));
|
||||
item(app, ui, "Merge Cells", "table.merge", json!({}));
|
||||
}
|
||||
if matches!(pick, TablePick::Rows | TablePick::Columns | TablePick::Table) {
|
||||
item(ui, "Distribute Rows", "table.distributeRows", json!({}));
|
||||
item(ui, "Distribute Columns", "table.distributeColumns", json!({}));
|
||||
item(app, ui, "Distribute Rows", "table.distributeRows", json!({}));
|
||||
item(app, ui, "Distribute Columns", "table.distributeColumns", json!({}));
|
||||
}
|
||||
if pick == TablePick::Table {
|
||||
let _ = Menu::submenu_row(ui, tl!("AutoFit").to_string(), |ui, _cx| {
|
||||
item(ui, "AutoFit Contents", "table.autofit", json!({"mode": "contents"}));
|
||||
item(ui, "AutoFit Window", "table.autofit", json!({"mode": "window"}));
|
||||
item(ui, "Fixed Column Width", "table.autofit", json!({"mode": "fixed"}));
|
||||
item(app, ui, "AutoFit Contents", "table.autofit", json!({"mode": "contents"}));
|
||||
item(app, ui, "AutoFit Window", "table.autofit", json!({"mode": "window"}));
|
||||
item(app, ui, "Fixed Column Width", "table.autofit", json!({"mode": "fixed"}));
|
||||
});
|
||||
}
|
||||
item(ui, "Text Direction", "table.textDirection", json!({}));
|
||||
item(app, ui, "Text Direction", "table.textDirection", json!({}));
|
||||
if pick == TablePick::Table {
|
||||
item(ui, "Insert Caption…", "references.caption", json!({}));
|
||||
item(app, ui, "Insert Caption…", "references.caption", json!({}));
|
||||
}
|
||||
item(ui, "Table Properties…", "table.properties", json!({}));
|
||||
item(app, ui, "Table Properties…", "table.properties", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ impl Component for EquationFrameControl<'_> {
|
||||
line: cx.color(t.color.overlay.line),
|
||||
accent: cx.color(t.color.accent.solid),
|
||||
soft: cx.color(t.color.accent.soft),
|
||||
shade: cx.color(t.color.accent.solid.with_alpha(40)),
|
||||
shade: cx.color(t.color.state.text_selection),
|
||||
handle_fill: cx.color(t.color.overlay.handle_fill),
|
||||
handle_stroke: cx.color(t.color.overlay.handle_stroke),
|
||||
}
|
||||
|
||||
@@ -69,12 +69,7 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
|
||||
// A section whose columns `column_drag` refuses shows its gaps without grips.
|
||||
let gaps_draggable = cg.as_ref().is_none_or(|cg| super::column_ruler::draggable(&cg.sect));
|
||||
|
||||
let mut margins = Margins::uniform(0.0);
|
||||
margins.top = f64::from(sect.margin_top);
|
||||
margins.bottom = f64::from(sect.margin_bottom);
|
||||
margins.left = f64::from(sect.margin_left);
|
||||
margins.right = f64::from(sect.margin_right);
|
||||
let edges = PageEdges::new(margins);
|
||||
let edges = page_edges(§);
|
||||
let mirrored = app.session.doc.settings.mirror_margins && page.number.is_multiple_of(2);
|
||||
let unit = DocUnit::new(unit_kind(app.session.units()), 96.0);
|
||||
let kind = ruler_align(app.canvas.tab_kind).unwrap_or_default();
|
||||
@@ -260,8 +255,21 @@ fn indent_params(shown: &RulerValues, v: &RulerValues, col_x: f32, w: f32) -> Op
|
||||
(!p.is_empty()).then_some(Value::Object(p))
|
||||
}
|
||||
|
||||
/// The page's margins as the ruler shows and clamps them. An exact (negative) top or bottom margin (#7107) counts at
|
||||
/// its size, where the layout puts the body's edge: it is shown there, and a drag of the opposite edge keeps an inch
|
||||
/// of text beside it, as `layout.margins` checks it. Only a moved edge is sent back ([`margin_params`]), so the exact
|
||||
/// margin stays exact unless it is the one dragged.
|
||||
pub(super) fn page_edges(sect: &wordcraft_doc::section::SectionProps) -> PageEdges {
|
||||
let mut margins = Margins::uniform(0.0);
|
||||
margins.top = f64::from(sect.margin_top.abs());
|
||||
margins.bottom = f64::from(sect.margin_bottom.abs());
|
||||
margins.left = f64::from(sect.margin_left);
|
||||
margins.right = f64::from(sect.margin_right);
|
||||
PageEdges::new(margins)
|
||||
}
|
||||
|
||||
/// `layout.margins` params for the margins `v` moved from `shown`.
|
||||
fn margin_params(shown: &PageEdges, v: &PageEdges) -> Option<Value> {
|
||||
pub(super) fn margin_params(shown: &PageEdges, v: &PageEdges) -> Option<Value> {
|
||||
let (a, b) = (&shown.margins, &v.margins);
|
||||
let mut p = Map::new();
|
||||
for (key, was, now) in [("left", a.left, b.left), ("right", a.right, b.right), ("top", a.top, b.top), ("bottom", a.bottom, b.bottom)] {
|
||||
|
||||
@@ -3288,93 +3288,6 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
|
||||
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
|
||||
}
|
||||
|
||||
/// Mouse-wheel notches scroll by WordCraft's document line distance (`NOTCH_PX`, 56 pt) rather than the framework's
|
||||
/// 16 pt default, and rapid flick notches accelerate when animations are enabled (#8840).
|
||||
#[test]
|
||||
fn mouse_wheel_notch_scrolls_document_line_distance_and_accelerates_on_flick() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "lorem ipsum dolor sit amet consectetur ".repeat(2000)})).unwrap();
|
||||
a.run("caret.docStart", json!({})).unwrap();
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 4);
|
||||
let center = h.state().canvas.view_rect().expect("the canvas laid out").center();
|
||||
let wheel = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
|
||||
// With animations off, one notch jumps the full document line distance in a single frame.
|
||||
let start_y = h.state().canvas.view.offset.1;
|
||||
h.event(egui::Event::PointerMoved(center));
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
let one_notch = h.state().canvas.view.offset.1 - start_y;
|
||||
assert!(
|
||||
(one_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"one mouse-wheel notch should scroll ~{} pt, got {one_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
// With animations on, a single notch eases to the same distance, and a rapid flick accelerates past it.
|
||||
h.state_mut().ui.animations = crate::theme::Animations::On;
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 4);
|
||||
let eased_start = h.state().canvas.view.offset.1;
|
||||
h.event(wheel());
|
||||
steps(&mut h, 30);
|
||||
let eased_notch = h.state().canvas.view.offset.1 - eased_start;
|
||||
assert!(
|
||||
(eased_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"an eased notch should settle at ~{} pt, got {eased_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 30);
|
||||
let flick_start = h.state().canvas.view.offset.1;
|
||||
for _ in 0..5 {
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
}
|
||||
steps(&mut h, 40);
|
||||
let flicked = h.state().canvas.view.offset.1 - flick_start;
|
||||
assert!(flicked > 5.0 * eased_notch, "a rapid 5-notch flick ({flicked}) should accelerate past 5 single notches ({})", 5.0 * eased_notch);
|
||||
}
|
||||
|
||||
/// In vertical text the composition runs down the line, upright and at the text's size, and the candidate window
|
||||
/// reports the column it fills, not a horizontal strip (#8980).
|
||||
#[test]
|
||||
fn a_composition_in_vertical_text_runs_down_the_line() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.run("document.setText", json!({"text": "Hello"})).unwrap();
|
||||
app.run("layout.textDirection", json!({"value": "tbRl"})).unwrap();
|
||||
app.run("caret.docEnd", json!({})).unwrap();
|
||||
let mut h = composing_harness(app);
|
||||
kana_test_glyphs(&h.ctx);
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほん".into(), active_range_chars: None }));
|
||||
for _ in 0..4 {
|
||||
h.app_frame();
|
||||
}
|
||||
let kana: Vec<_> = ["に", "ほ", "ん"].iter().filter_map(|k| drawn_composition(&h, k)).collect();
|
||||
assert_eq!(kana.len(), 3, "each kana is drawn on its own");
|
||||
let at = |i: usize| kana[i].pos;
|
||||
assert!(at(0).y < at(1).y && at(1).y < at(2).y, "the kana stack down the page");
|
||||
assert!((at(0).x - at(2).x).abs() < 1.0, "in one column");
|
||||
let ime = h.output().platform_output.ime.clone().expect("the canvas places the candidate window").cursor_rect;
|
||||
assert!(ime.height() > ime.width(), "the candidate window sits by the column: {ime:?}");
|
||||
}
|
||||
|
||||
/// The pictures drawn in the last pass that are at least 300 texels wide (a page's, not an icon's or the font
|
||||
/// atlas's glyphs): how many device pixels each is drawn across and down, and how many texels it shows.
|
||||
fn drawn_pictures(
|
||||
@@ -3468,3 +3381,173 @@ fn a_page_at_rest_is_drawn_one_texel_per_device_pixel() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mouse-wheel notches scroll by WordCraft's document line distance (`NOTCH_PX`, 56 pt) rather than the framework's
|
||||
/// 16 pt default, and rapid flick notches accelerate when animations are enabled (#8840).
|
||||
#[test]
|
||||
fn mouse_wheel_notch_scrolls_document_line_distance_and_accelerates_on_flick() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "lorem ipsum dolor sit amet consectetur ".repeat(2000)})).unwrap();
|
||||
a.run("caret.docStart", json!({})).unwrap();
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 4);
|
||||
let center = h.state().canvas.view_rect().expect("the canvas laid out").center();
|
||||
let wheel = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
|
||||
// With animations off, one notch jumps the full document line distance in a single frame.
|
||||
let start_y = h.state().canvas.view.offset.1;
|
||||
h.event(egui::Event::PointerMoved(center));
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
let one_notch = h.state().canvas.view.offset.1 - start_y;
|
||||
assert!(
|
||||
(one_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"one mouse-wheel notch should scroll ~{} pt, got {one_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
// With animations on, a single notch eases to the same distance, and a rapid flick accelerates past it.
|
||||
h.state_mut().ui.animations = crate::theme::Animations::On;
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 4);
|
||||
let eased_start = h.state().canvas.view.offset.1;
|
||||
h.event(wheel());
|
||||
steps(&mut h, 30);
|
||||
let eased_notch = h.state().canvas.view.offset.1 - eased_start;
|
||||
assert!(
|
||||
(eased_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"an eased notch should settle at ~{} pt, got {eased_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 30);
|
||||
let flick_start = h.state().canvas.view.offset.1;
|
||||
for _ in 0..5 {
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
}
|
||||
steps(&mut h, 40);
|
||||
let flicked = h.state().canvas.view.offset.1 - flick_start;
|
||||
assert!(flicked > 5.0 * eased_notch, "a rapid 5-notch flick ({flicked}) should accelerate past 5 single notches ({})", 5.0 * eased_notch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_spelling_suggestion_opens_with_shift_f10_and_keeps_focus() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("teh")), Default::default());
|
||||
a.session.sel = wordcraft_engine::Selection::caret(Pos::body(0, 1));
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
assert!(h.state().canvas.focused(&h.ctx), "canvas starts focused");
|
||||
// Shift+F10 opens the context menu with spelling suggestions.
|
||||
h.event(egui::Event::Key { key: egui::Key::F10, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::SHIFT });
|
||||
steps(&mut h, 3);
|
||||
assert!(h.state().canvas.context_menu_open, "Shift+F10 opens the context menu");
|
||||
let suggestion = h
|
||||
.state()
|
||||
.canvas
|
||||
.context_issue
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("suggestions"))
|
||||
.and_then(|v| v.as_array())
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("spelling suggestion for 'teh'")
|
||||
.to_string();
|
||||
let btn = h.get_by_label(&suggestion).rect().center();
|
||||
h.event(egui::Event::PointerMoved(btn));
|
||||
steps(&mut h, 2);
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: btn, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
|
||||
h.app_frame();
|
||||
}
|
||||
// The very next pass is the one that has to keep the keyboard: the page was drawn before the
|
||||
// menu, so it only takes focus back then, and a character typed before that used to be lost.
|
||||
h.event(egui::Event::Text("x".into()));
|
||||
h.app_frame();
|
||||
assert!(!h.state().canvas.context_menu_open, "applying a suggestion closes the context menu");
|
||||
assert_eq!(
|
||||
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body),
|
||||
format!("{suggestion}x"),
|
||||
"a character typed in the frame after the click lands in the document"
|
||||
);
|
||||
assert!(h.state().canvas.focused(&h.ctx), "canvas keeps focus after applying a spelling suggestion so the caret remains visible");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_spelling_suggestion_returns_focus_when_opened_unfocused() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("teh")), Default::default());
|
||||
a.session.sel = wordcraft_engine::Selection::caret(Pos::body(0, 1));
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 6);
|
||||
let size_box =
|
||||
h.get_all_by_role(Role::TextInput).find(|n| n.value().is_some_and(|v| v.trim().parse::<f64>().is_ok())).expect("the font size box").rect();
|
||||
h.event(egui::Event::PointerMoved(size_box.center()));
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: size_box.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
|
||||
h.app_frame();
|
||||
}
|
||||
h.app_frame();
|
||||
assert!(!h.state().canvas.focused(&h.ctx), "canvas starts unfocused before opening the menu");
|
||||
h.state_mut().canvas.context_request = Some(super::context_menu::ContextAsk::AtCaret);
|
||||
steps(&mut h, 3);
|
||||
assert!(h.state().canvas.context_menu_open, "context menu opens");
|
||||
let suggestion = h
|
||||
.state()
|
||||
.canvas
|
||||
.context_issue
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("suggestions"))
|
||||
.and_then(|v| v.as_array())
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("spelling suggestion for 'teh'")
|
||||
.to_string();
|
||||
let btn = h.get_by_label(&suggestion).rect().center();
|
||||
h.event(egui::Event::PointerMoved(btn));
|
||||
steps(&mut h, 2);
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: btn, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
|
||||
h.app_frame();
|
||||
}
|
||||
h.event(egui::Event::Text("x".into()));
|
||||
h.app_frame();
|
||||
assert!(!h.state().canvas.context_menu_open, "applying a suggestion closes the context menu");
|
||||
assert_eq!(
|
||||
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body),
|
||||
format!("{suggestion}x"),
|
||||
"a character typed in the frame after the click lands in the document"
|
||||
);
|
||||
assert!(h.state().canvas.focused(&h.ctx), "canvas takes focus after applying a spelling suggestion even when opened unfocused");
|
||||
}
|
||||
|
||||
@@ -150,6 +150,42 @@ fn dragging_the_bottom_margin_on_the_ruler_keeps_the_view_and_follows_the_pointe
|
||||
assert_eq!(h.state().session.undo_depth(), depth + 1, "one undo step for the drag");
|
||||
}
|
||||
|
||||
/// #7107: an exact (negative) top or bottom margin counts at its size on the vertical ruler, so a
|
||||
/// drag of the opposite edge keeps an inch of text beside it and `layout.margins` accepts it, and
|
||||
/// the exact margin, not dragged, stays exact.
|
||||
#[test]
|
||||
fn ruler_margin_drags_clamp_against_an_exact_opposite_margin() {
|
||||
use crate::canvas::rulers::{margin_params, page_edges};
|
||||
use craft::pages::ui::{MarginEdge, MarginRules, dragged_margin};
|
||||
|
||||
let s = wordcraft_doc::section::SectionProps {
|
||||
page_w: 612.0,
|
||||
page_h: 792.0,
|
||||
margin_left: 72.0,
|
||||
margin_right: 72.0,
|
||||
margin_top: -72.0,
|
||||
margin_bottom: -72.0,
|
||||
gutter: 0.0,
|
||||
..Default::default()
|
||||
};
|
||||
let rules = MarginRules::new((612.0, 792.0), page_edges(&s));
|
||||
assert_eq!(dragged_margin(MarginEdge::Bottom, 72.0, &rules).points, 792.0 - 72.0 - 72.0);
|
||||
assert_eq!(dragged_margin(MarginEdge::Top, 720.0, &rules).points, 792.0 - 72.0 - 72.0);
|
||||
|
||||
// Through the command: the clamped value fits beside the exact top margin, which stays exact.
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.session.doc.last_section.margin_top = -72.0;
|
||||
let sect = wordcraft_engine::cmd::page::sect(&app.session);
|
||||
let shown = page_edges(§);
|
||||
let moved = shown.with(dragged_margin(MarginEdge::Bottom, 72.0, &MarginRules::new((f64::from(sect.page_w), f64::from(sect.page_h)), shown)));
|
||||
let p = margin_params(&shown, &moved).expect("the bottom margin moved");
|
||||
assert!(p.get("top").is_none(), "the exact top margin is not sent: {p}");
|
||||
app.run("layout.margins", p).unwrap();
|
||||
let after = wordcraft_engine::cmd::page::sect(&app.session);
|
||||
assert_eq!(after.margin_top, -72.0);
|
||||
assert!(after.page_h - after.margin_top.abs() - after.margin_bottom >= 72.0 - 0.01);
|
||||
}
|
||||
|
||||
/// #1878: in Multiple Pages both rulers belong to the caret's page: the margin splitters of the
|
||||
/// horizontal ruler lie over that page's width and the vertical ruler's over its height, and
|
||||
/// they follow the caret to another page of the row and to the next row.
|
||||
@@ -354,6 +390,24 @@ fn draft_text(app: &WordApp) -> Option<String> {
|
||||
app.canvas.comments.editing.as_ref().map(|(_, _, text)| text.clone())
|
||||
}
|
||||
|
||||
/// Whether this frame painted `text` inside `rect`: the balloon's own text. Not an accessible name, which holds the
|
||||
/// same words while nothing is drawn: the card's name is built from the stored comment (so it reads "Original" even
|
||||
/// while the card shows a draft), the picture Size dialog's "Original size" and Compare's "Original document" hold the
|
||||
/// word too (#9218). A text its clip hides (a card scrolled out of the balloon column) is not painted either.
|
||||
fn paints_inside(h: &H, rect: Rect, text: &str) -> bool {
|
||||
fn walk(shape: &egui::Shape, visible: Rect, text: &str) -> bool {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => t.galley.text().contains(text) && visible.contains_rect(shape.visual_bounding_rect()),
|
||||
egui::Shape::Vec(children) => children.iter().any(|child| walk(child, visible, text)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
h.output().shapes.iter().any(|clipped| {
|
||||
let visible = rect.intersect(clipped.clip_rect);
|
||||
visible.is_positive() && walk(&clipped.shape, visible, text)
|
||||
})
|
||||
}
|
||||
|
||||
/// #1348: a comment edit typed, then refused (the document became read-only).
|
||||
fn refused_draft() -> (H, u32) {
|
||||
let (mut h, id) = comment_harness();
|
||||
@@ -433,22 +487,50 @@ fn escape_reverts_a_comment_draft() {
|
||||
// initial build frame, which populates `balloon_rects` before `click_balloon` clicks). The window stays wide enough
|
||||
// for the click on the page's centre to land on the page, not on a balloon.
|
||||
let (mut h, id) = comment_harness_in(egui::vec2(1440.0, 900.0), 0);
|
||||
let card = |h: &H| h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_balloon(&mut h, id);
|
||||
type_in(&mut h, "Discarded ");
|
||||
assert!(draft_text(h.state()).is_some_and(|d| d.contains("Discarded")), "the draft was recorded before Escape");
|
||||
assert!(edit_field(&h).and_then(|n| n.value()).is_some_and(|v| v.contains("Discarded")), "the Edit field showed the typed draft before Escape");
|
||||
assert!(paints_inside(&h, card(&h), "Discarded"), "and the balloon paints it before Escape");
|
||||
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
|
||||
h.app_frame();
|
||||
assert_eq!(draft_text(h.state()), None, "the draft is gone");
|
||||
assert_eq!(comment_text(h.state(), id), "Original", "nothing was written");
|
||||
assert!(edit_field(&h).is_none(), "Escape closes the inline Edit field");
|
||||
assert!(h.query_by_label_contains("Original").is_some(), "the balloon shows the comment's original text again");
|
||||
assert!(h.query_by_label_contains("Discarded").is_none(), "no discarded draft remains shown in the balloon");
|
||||
// The card's painted text, not the window's accessible names: the card's own name comes from the comment, and the
|
||||
// picture Size dialog's "Original size" and Compare's "Original document" hold the word too, so a name would
|
||||
// satisfy this even if the balloon painted nothing (#9218).
|
||||
assert!(paints_inside(&h, card(&h), "Original"), "the balloon paints the comment's original text again");
|
||||
assert!(!paints_inside(&h, card(&h), "Discarded"), "no discarded draft remains painted in the balloon");
|
||||
leave_field(&mut h);
|
||||
assert_eq!(h.state().canvas.selected_balloon(), None, "the click on the page left the balloon");
|
||||
assert_eq!(comment_text(h.state(), id), "Original", "and nothing is written later");
|
||||
}
|
||||
|
||||
/// #9218: the balloon's check reads the text its card paints, not the window's accessible names. A card scrolled out of
|
||||
/// the balloon column keeps the name it takes from the stored comment while it paints none of it, so a name search
|
||||
/// would pass with nothing drawn.
|
||||
#[test]
|
||||
fn the_balloon_check_reads_painted_text_not_its_name() {
|
||||
let (mut h, id) = comment_harness_in(egui::vec2(1440.0, 900.0), 0);
|
||||
let card = |h: &H| h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
assert!(paints_inside(&h, card(&h), "Original"), "a card in view paints the comment's text");
|
||||
// Scroll the card up out of the balloon column.
|
||||
h.event(egui::Event::PointerMoved(card(&h).center()));
|
||||
h.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -200.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: Default::default(),
|
||||
});
|
||||
h.app_frame();
|
||||
let card = card(&h);
|
||||
assert!(h.query_all_by_label_contains("Original").any(|n| card.contains_rect(n.rect())), "the card's name still holds the comment's text");
|
||||
assert!(!paints_inside(&h, card, "Original"), "though the card paints none of it: the balloon check reads paint, so it fails");
|
||||
}
|
||||
|
||||
/// #3268: clicking a balloon's Reply button, typing a reply and clicking away posts it as a
|
||||
/// reply comment under the original, not a draft that silently disappears.
|
||||
#[test]
|
||||
@@ -1044,3 +1126,35 @@ fn context_menu_paste_inserts_system_clipboard_text() {
|
||||
steps(&mut h, 3);
|
||||
assert_eq!(h.state().session.doc.body[0].as_para().unwrap().plain_text(), "Hello pasted text");
|
||||
}
|
||||
|
||||
/// #9190: resolving a comment while its balloon is being edited keeps what was typed.
|
||||
#[test]
|
||||
fn resolving_a_comment_mid_edit_keeps_the_typed_text() {
|
||||
let (mut h, id) = comment_harness();
|
||||
click_balloon(&mut h, id);
|
||||
type_in(&mut h, "Typed ");
|
||||
let resolve = h.get_by_label("Resolve").rect().center();
|
||||
click_at(&mut h, resolve);
|
||||
assert!(h.state().session.doc.comments[&id].resolved);
|
||||
assert_eq!(draft_text(h.state()), None, "resolving ends the edit");
|
||||
h.app_frame();
|
||||
assert!(edit_field(&h).is_none(), "the resolved balloon shows no edit field");
|
||||
leave_field(&mut h);
|
||||
let text = comment_text(h.state(), id);
|
||||
assert!(text.contains("Typed "), "{text:?}");
|
||||
}
|
||||
|
||||
/// #9190: double-clicking a resolved comment balloon must not open it for editing.
|
||||
#[test]
|
||||
fn double_clicking_a_resolved_comment_balloon_does_not_open_edit() {
|
||||
let (mut h, id) = comment_harness();
|
||||
h.state_mut().run("review.resolveComment", json!({"id": id})).unwrap();
|
||||
steps(&mut h, 3);
|
||||
assert!(h.state().session.doc.comments[&id].resolved);
|
||||
|
||||
select_balloon_card(&mut h, id);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
double_click_at(&mut h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert!(h.state().canvas.comments.editing.is_none(), "a resolved balloon must not enter edit mode");
|
||||
assert!(edit_field(&h).is_none(), "no inline edit field should open for a resolved balloon");
|
||||
}
|
||||
|
||||
@@ -9,11 +9,10 @@ use craft::theme::ControlSize;
|
||||
use craft::theme::variant::Variant;
|
||||
use craft::ui::bars::{Bar, BarKind};
|
||||
use craft::ui::buttons::{Button, ButtonOutput, IconButton, ToggleButton};
|
||||
use craft::ui::contract::{AfterInk, Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::display::{Divider, Text};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::runtime::env::with_env;
|
||||
use craft::ui::value_drag::{Slider, SliderScale};
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
@@ -46,16 +45,7 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
if let Ok(mut a) = app.try_borrow_mut() {
|
||||
// The readouts are secondary text, as v0.19.1 drew them (#8811): craft's ghost button takes the muted ink
|
||||
// where it passes text contrast.
|
||||
let rect = with_env(
|
||||
ui,
|
||||
|o| {
|
||||
o.values.set(AfterInk::Muted);
|
||||
},
|
||||
|ui| readouts(&mut a, ui),
|
||||
);
|
||||
page.set(Some(rect));
|
||||
page.set(Some(readouts(&mut a, ui)));
|
||||
}
|
||||
});
|
||||
if let (Some(page), Some(group), Ok(mut a)) = (page.get(), group.get(), app.try_borrow_mut()) {
|
||||
|
||||
@@ -301,6 +301,11 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, layout: &DocLayout, body: &Pa
|
||||
}
|
||||
let out = ContentControls::new(tl!("Content controls").to_string(), &framed, &check_rects, button.as_ref().map(|(last, _)| *last))
|
||||
.show_at(ui, body.rect);
|
||||
// The pointer parts preserve the caret. Give the page focus before a popup opens so closing it
|
||||
// returns to the page even when another field had the keyboard before the click.
|
||||
if (out.toggled.is_some() || out.opened) && !app.canvas.focused(ui.ctx()) {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
if let Some(at) = out.toggled.and_then(|i| check_at.get(i)) {
|
||||
let at = serde_json::to_value(at).unwrap_or_default();
|
||||
let _ = app.run("developer.toggleCheckBox", json!({"at": at}));
|
||||
@@ -486,15 +491,19 @@ mod tests {
|
||||
assert!(h.state().session.undo_depth() > depth, "the stroke ran table.draw");
|
||||
}
|
||||
|
||||
/// #7862: a press on the list button leaves the keyboard with the page, so the list gives it
|
||||
/// back to the page when it closes, by Escape or by a pick.
|
||||
/// #7862 and #8407: closing the list returns focus to the page even when a ribbon field held it
|
||||
/// before the list opened. Clicking the list button still leaves the caret in place.
|
||||
#[test]
|
||||
fn closing_the_list_gives_the_keyboard_back_to_the_page() {
|
||||
fn closing_the_list_returns_focus_to_the_page_from_a_ribbon_field() {
|
||||
let mut h = dropdown_harness();
|
||||
focus_page(&mut h);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Font Size").focus();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Font Size").is_focused(), "the ribbon field has the keyboard");
|
||||
let caret = h.state().session.sel.focus.clone();
|
||||
let button = h.get_by_label("Choose item").rect().center();
|
||||
click_at(&mut h, button);
|
||||
assert!(popup_open(h.state()), "the list is open");
|
||||
assert_eq!(h.state().session.sel.focus, caret, "the list button leaves the caret in place");
|
||||
h.key_press(egui::Key::Escape);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(!popup_open(h.state()), "Escape closes the list");
|
||||
|
||||
@@ -4,6 +4,8 @@ use serde_json::{Value, json};
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
use craft::automation::control::{ControlRequest, Reply};
|
||||
use craft::behavior::Selection;
|
||||
use craft::review::ThreadId;
|
||||
|
||||
use super::handle;
|
||||
use crate::{Services, WordApp};
|
||||
@@ -87,6 +89,34 @@ fn methods_address_an_open_document_by_id() {
|
||||
assert_eq!(r["result"]["blocks"][0]["text"], "First more", "{r}");
|
||||
}
|
||||
|
||||
/// A control command resolving a parked thread writes that document's comment and reply drafts first (#9335).
|
||||
#[test]
|
||||
fn resolving_an_addressed_comment_saves_its_parked_drafts() {
|
||||
let mut a = app();
|
||||
let (first, second) = two_documents(&mut a);
|
||||
assert_eq!(exec(&mut a, "view.switchWindows", json!({"id": first}))["ok"], true);
|
||||
let comment = exec(&mut a, "review.newComment", json!({"text": "Original comment"}));
|
||||
let id = comment["result"]["id"].as_u64().expect("a comment was added");
|
||||
let thread = ThreadId(id);
|
||||
a.canvas.comments.editing = Some((thread, 0, "Edited comment".into()));
|
||||
a.canvas.comments.selected = Selection::single(thread);
|
||||
a.canvas.comments.reply = "New reply".into();
|
||||
assert_eq!(exec(&mut a, "view.switchWindows", json!({"id": second}))["ok"], true);
|
||||
assert!(a.document_has_comment_drafts(first));
|
||||
|
||||
let r = send(&mut a, "engine.execute", json!({"command": "review.resolveComment", "params": {"id": id}, "doc": first}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!(a.session.document_id(), second);
|
||||
assert_eq!(body(&a).trim(), "Second");
|
||||
let r = send(&mut a, "engine.execute", json!({"command": "review.comments", "doc": first}));
|
||||
let comments = r["result"].as_array().expect("the parked document's comments");
|
||||
assert_eq!(comments[0]["text"], "Edited comment");
|
||||
assert_eq!(comments[1]["text"], "New reply");
|
||||
assert_eq!(comments[1]["parent"], id);
|
||||
assert!(comments.iter().all(|c| c["resolved"] == true));
|
||||
assert!(!a.document_has_comment_drafts(first));
|
||||
}
|
||||
|
||||
/// W1: `file.close` addressed to a document in the background refuses its unsaved changes
|
||||
/// unless forced (only a boolean true), as it does for the window's document (#1268), and closes
|
||||
/// only that document.
|
||||
|
||||
@@ -232,7 +232,13 @@ fn handle_in(app: &mut WordApp, doc: u64, method: &str, p: &Value) -> Reply {
|
||||
return err(e);
|
||||
}
|
||||
}
|
||||
let r = app.session.with_document(doc, |s| s.run(id, ¶ms));
|
||||
let parked = app.parked.get_mut(&doc).filter(|_| id == "review.resolveComment");
|
||||
let r = app.session.with_document(doc, |s| {
|
||||
if let Some(parked) = parked {
|
||||
crate::panes::flush_parked_comment_drafts(s, &mut parked.comments);
|
||||
}
|
||||
s.run(id, ¶ms)
|
||||
});
|
||||
// UI requests the command made carry `document`, so the window can tell they aren't
|
||||
// about the document it shows. A command that changes nothing opens the dialog it asks for, as in
|
||||
// `after_command`.
|
||||
|
||||
@@ -52,19 +52,16 @@ fn assignable(binding: &Binding) -> bool {
|
||||
|
||||
/// The ribbon tab a command lives on, in English (the first part of its path).
|
||||
fn tab(def: &CommandDef) -> &str {
|
||||
if let Some(tab) = def.paths.first().and_then(|path| path.first()) {
|
||||
return tab;
|
||||
}
|
||||
// The runtime owns these definitions and their bindings. Use the engine's ribbon location
|
||||
// for classification when the linked definition has no path of its own.
|
||||
match def.command.id.as_str() {
|
||||
"edit.cut" | "edit.copy" | "edit.paste" => wordcraft_engine::cmd::edit::LINKED_CLIPBOARD_LOCATION.split(" › ").next().unwrap_or_default(),
|
||||
_ => "",
|
||||
}
|
||||
def.paths
|
||||
.first()
|
||||
.and_then(|path| path.first())
|
||||
.map(String::as_str)
|
||||
.or_else(|| crate::app::command_board::linked_command_tab(&def.command.id))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
|
||||
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
|
||||
const EXTRA_CONTEXT_TABS: [&str; 4] = ["Header & Footer", "Outlining", "Reading", "Read Mode"];
|
||||
|
||||
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
|
||||
tab(def) == TABS[N]
|
||||
@@ -325,6 +322,11 @@ mod tests {
|
||||
assert_eq!(listing(&on(&["Help", "Support"])), ["Help", "All Commands"], "every ribbon tab has its entry");
|
||||
assert_eq!(listing(&on(&["Table Design", "Styles"])), ["Contextual Tabs", "All Commands"]);
|
||||
assert_eq!(listing(&on(&[])), ["Other", "All Commands"]);
|
||||
// Explicit paths still take precedence for linked commands, and unrelated pathless
|
||||
// commands never inherit a location from the edit set.
|
||||
let copy = CommandDef::new(CommandRef::new("edit.copy"), "Copy", Scope::app()).with_path(vec!["Insert".into()]);
|
||||
assert_eq!(listing(©), ["Insert", "All Commands"]);
|
||||
assert_eq!(listing(&CommandDef::new(CommandRef::new("format.bold"), "Bold", Scope::app())), ["Other", "All Commands"]);
|
||||
assert_eq!(areas.last().map(|a| a.id), Some("All Commands"), "All Commands comes last");
|
||||
}
|
||||
|
||||
@@ -354,13 +356,17 @@ mod tests {
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let areas = super::areas();
|
||||
|
||||
for (id, tab, group) in [("insert.video", "Insert", "Media"), ("draw.inkToMath", "Draw", "Convert")] {
|
||||
for (id, tab, group, category) in [
|
||||
("insert.video", "Insert", "Media", "Insert"),
|
||||
("draw.inkToMath", "Draw", "Convert", "Draw"),
|
||||
("view.readLayout", "Read Mode", "View", "Contextual Tabs"),
|
||||
] {
|
||||
let command = CommandRef::new(id);
|
||||
assert!(a.session.registry.get(id).is_none(), "{id} is still unimplemented");
|
||||
let def = catalog.defs().iter().find(|def| def.command == command).unwrap_or_else(|| panic!("{id} in catalog"));
|
||||
assert_eq!(def.paths, [vec![tab.to_owned(), group.to_owned()]], "{id} keeps its full ribbon path");
|
||||
let categories: Vec<_> = areas.iter().filter(|area| (area.rows)(def)).map(|area| area.id).collect();
|
||||
assert_eq!(categories, [tab, "All Commands"], "{id} is filed under its ribbon tab");
|
||||
assert_eq!(categories, [category, "All Commands"], "{id} is filed under its ribbon category");
|
||||
assert!(def.defaults.is_empty(), "{id} has no default chord");
|
||||
let state = a.command_states.get(&command);
|
||||
assert!(state.is_some_and(|state| !state.is_enabled()), "{id} publishes an explicit disabled state");
|
||||
@@ -379,15 +385,21 @@ mod tests {
|
||||
#[test]
|
||||
fn linked_clipboard_commands_are_listed_once_under_home() {
|
||||
let mut a = app();
|
||||
a.ui.language = "en".into();
|
||||
let app_catalog = a.catalog().expect("app catalog");
|
||||
let mut h = crate::test_harness::builder().build_eframe(|_| a);
|
||||
super::open(&mut a, KEY, &json!({}), None).expect("dialog opens");
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
h.run_steps(2);
|
||||
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board installs a keymap");
|
||||
let areas = super::areas();
|
||||
|
||||
for (id, category, shortcut) in
|
||||
[("edit.cut", "Home", "Mod+X"), ("edit.copy", "Home", "Mod+C"), ("edit.paste", "Home", "Mod+V"), ("edit.undo", "Other", "Mod+Z")]
|
||||
{
|
||||
for (id, category, shortcut) in [
|
||||
("edit.cut", "Home", "Mod+X"),
|
||||
("edit.copy", "Home", "Mod+C"),
|
||||
("edit.paste", "Home", "Mod+V"),
|
||||
("edit.undo", "Other", "Mod+Z"),
|
||||
("edit.redo", "Other", "Mod+Y"),
|
||||
] {
|
||||
let command = CommandRef::new(id);
|
||||
assert!(app_catalog.defs().iter().all(|def| def.command != command), "{id} is owned by the linked set");
|
||||
let mut rows = keymap.catalog().iter().filter(|def| def.command == command);
|
||||
@@ -398,5 +410,17 @@ mod tests {
|
||||
let shortcut = Binding::parse(shortcut).unwrap();
|
||||
assert!(keymap.bindings(&command).iter().any(|binding| binding.trigger == shortcut.trigger), "{id} retains its shortcut");
|
||||
}
|
||||
let ctx = h.ctx.clone();
|
||||
let dlg = dialog_id(KEY);
|
||||
let set = |h: &mut egui_kittest::Harness<'_, WordApp>, field: &str, value: &str| {
|
||||
h.state_mut().dialog_host.set_json_field(&ctx, dlg, field, json!(value)).expect("dialog field");
|
||||
h.run_steps(2);
|
||||
};
|
||||
let copies = |h: &egui_kittest::Harness<'_, WordApp>| h.query_all(By::new().role(Role::ListItem).label("Copy")).count();
|
||||
set(&mut h, "search", "Copy");
|
||||
set(&mut h, "area", "Home");
|
||||
assert_eq!(copies(&h), 1, "Home shows exactly one Copy row in the dialog");
|
||||
set(&mut h, "area", "Other");
|
||||
assert_eq!(copies(&h), 0, "Other does not show Copy");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use craft::ui::text::TextField;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::Block;
|
||||
use wordcraft_engine::Selection;
|
||||
|
||||
use super::labels::{BUILT_IN_LABELS, NUMBER_FORMATS, SEPARATORS, own_labels};
|
||||
use crate::WordApp;
|
||||
@@ -39,6 +40,17 @@ pub struct CaptionForm {
|
||||
/// Heading level that starts a chapter (1–9).
|
||||
pub chapter_level: u8,
|
||||
pub separator: String,
|
||||
#[serde(skip)]
|
||||
preview: Option<CaptionPreview>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct CaptionPreview {
|
||||
document: u64,
|
||||
revision: u64,
|
||||
selection: Selection,
|
||||
number_options: Value,
|
||||
prefix: String,
|
||||
}
|
||||
|
||||
impl CaptionForm {
|
||||
@@ -65,11 +77,15 @@ impl CaptionForm {
|
||||
chapter: false,
|
||||
chapter_level: 1,
|
||||
separator: "-".into(),
|
||||
preview: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The number as it will show (`Figure 1-A`).
|
||||
pub fn preview(&self) -> String {
|
||||
if let Some(preview) = &self.preview {
|
||||
return preview.prefix.clone();
|
||||
}
|
||||
let n = match self.format.as_str() {
|
||||
"alphabetic" => "a",
|
||||
"ALPHABETIC" => "A",
|
||||
@@ -82,11 +98,9 @@ impl CaptionForm {
|
||||
format!("{label}{chapter}{n}")
|
||||
}
|
||||
|
||||
/// `references.caption` parameters.
|
||||
pub fn params(&self) -> Value {
|
||||
fn number_options(&self) -> Value {
|
||||
let mut v = json!({
|
||||
"label": self.label,
|
||||
"text": self.text.trim(),
|
||||
"position": self.position,
|
||||
"excludeLabel": self.exclude_label,
|
||||
"format": self.format,
|
||||
@@ -97,6 +111,13 @@ impl CaptionForm {
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// `references.caption` parameters.
|
||||
pub fn params(&self) -> Value {
|
||||
let mut options = self.number_options();
|
||||
options["text"] = json!(self.text.trim());
|
||||
options
|
||||
}
|
||||
}
|
||||
|
||||
impl WordForm for CaptionForm {
|
||||
@@ -112,6 +133,20 @@ impl WordForm for CaptionForm {
|
||||
vec![("references.caption".to_string(), self.params())]
|
||||
}
|
||||
|
||||
fn prepare(&mut self, app: &WordApp) {
|
||||
let session = &app.session;
|
||||
let options = self.number_options();
|
||||
let document = session.document_id();
|
||||
let revision = session.rev();
|
||||
if self.preview.as_ref().is_some_and(|cached| {
|
||||
cached.document == document && cached.revision == revision && cached.selection == session.sel && cached.number_options == options
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
let prefix = wordcraft_engine::cmd::references::caption_preview(session, &options).unwrap_or_default();
|
||||
self.preview = Some(CaptionPreview { document, revision, selection: session.sel.clone(), number_options: options, prefix });
|
||||
}
|
||||
|
||||
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, asks: &mut Vec<Asks>) -> bool {
|
||||
let caption = Label::from(tl!("Caption:").to_string());
|
||||
if let Some(text) = Field::new(caption.clone())
|
||||
@@ -137,8 +172,10 @@ impl WordForm for CaptionForm {
|
||||
.show(ui, |ui, _| Select::new(label_title.clone(), Bind::given(Mixed::Same(self.label.clone())), &labels).show(ui).value().cloned())
|
||||
.inner
|
||||
.flatten()
|
||||
&& label != self.label
|
||||
{
|
||||
self.label = label;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let position_title = Label::from(tl!("Position:").to_string());
|
||||
let positions = [
|
||||
@@ -151,12 +188,17 @@ impl WordForm for CaptionForm {
|
||||
})
|
||||
.inner
|
||||
.flatten()
|
||||
&& position != self.position
|
||||
{
|
||||
self.position = position;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let exclude = Label::from(tl!("Leave the label out of the caption").to_string());
|
||||
if let Some(on) = Checkbox::new(Bind::given(self.exclude_label)).label(exclude).show(ui).value().copied() {
|
||||
if let Some(on) = Checkbox::new(Bind::given(self.exclude_label)).label(exclude).show(ui).value().copied()
|
||||
&& on != self.exclude_label
|
||||
{
|
||||
self.exclude_label = on;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if Button::new(Label::from(tl!("New Label…").to_string())).show(ui).clicked() {
|
||||
asks.push(Asks::Open("newLabel".to_string(), Value::Null));
|
||||
@@ -284,6 +326,10 @@ impl WordForm for NumberingForm {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn prepare(&mut self, app: &WordApp) {
|
||||
self.0.prepare(app);
|
||||
}
|
||||
|
||||
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
|
||||
let f = &mut self.0;
|
||||
let format_title = Label::from(tl!("Format:").to_string());
|
||||
|
||||
@@ -65,6 +65,63 @@ fn caption_dialog_numbers_with_chapters() {
|
||||
assert_eq!(a.prefs().caption_labels, vec!["Plate".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caption_preview_matches_the_inserted_sequence_after_changing_label() {
|
||||
let mut a = app("Results\nA chart\nAnother chart");
|
||||
a.ui.caption_labels.push("Plate".into());
|
||||
a.run("select.text", json!({"text": "Results"})).unwrap();
|
||||
a.run("styles.apply", json!({"style": "Heading 1"})).unwrap();
|
||||
a.run("select.text", json!({"text": "A chart"})).unwrap();
|
||||
a.run("references.caption", json!({"label": "Plate", "text": "First chart", "chapter": 1, "separator": ".", "format": "ALPHABETIC"})).unwrap();
|
||||
a.run("select.text", json!({"text": "Another chart"})).unwrap();
|
||||
|
||||
let mut f = CaptionForm::read(&a);
|
||||
f.label = "Figure".into();
|
||||
f.format = "ALPHABETIC".into();
|
||||
f.chapter = true;
|
||||
f.separator = ".".into();
|
||||
f.prepare(&a);
|
||||
assert_eq!(f.preview(), "Figure 1.A");
|
||||
|
||||
f.label = "Plate".into();
|
||||
f.text = "Second chart".into();
|
||||
let before = a.session.doc.plain_text(StoryRef::Body);
|
||||
let selection = a.session.sel.clone();
|
||||
f.prepare(&a);
|
||||
let prefix = f.preview();
|
||||
assert_eq!(prefix, "Plate 1.B");
|
||||
assert_eq!(a.session.doc.plain_text(StoryRef::Body), before);
|
||||
assert_eq!(a.session.sel, selection);
|
||||
a.run("references.caption", f.params()).unwrap();
|
||||
assert!(a.session.doc.plain_text(StoryRef::Body).contains(&format!("{prefix}: Second chart")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbering_form_prepare_computes_real_next_caption_example() {
|
||||
use super::caption::NumberingForm;
|
||||
|
||||
let mut a = app("Results\nA chart\nAnother chart");
|
||||
a.ui.caption_labels.push("Plate".into());
|
||||
a.run("select.text", json!({"text": "Results"})).unwrap();
|
||||
a.run("styles.apply", json!({"style": "Heading 1"})).unwrap();
|
||||
a.run("select.text", json!({"text": "A chart"})).unwrap();
|
||||
a.run("references.caption", json!({"label": "Plate", "text": "First chart", "chapter": 1, "separator": ".", "format": "ALPHABETIC"})).unwrap();
|
||||
a.run("select.text", json!({"text": "Another chart"})).unwrap();
|
||||
|
||||
let mut f = CaptionForm::read(&a);
|
||||
f.label = "Plate".into();
|
||||
f.format = "ALPHABETIC".into();
|
||||
f.chapter = true;
|
||||
f.separator = ".".into();
|
||||
f.prepare(&a);
|
||||
assert_eq!(f.preview(), "Plate 1.B");
|
||||
|
||||
// Opening Numbering… round-trips CaptionForm through JSON, skipping `preview`.
|
||||
let mut numbering: NumberingForm = serde_json::from_value(json!(NumberingForm(f))).unwrap();
|
||||
numbering.prepare(&a);
|
||||
assert_eq!(numbering.0.preview(), "Plate 1.B");
|
||||
}
|
||||
|
||||
/// #3120: Insert Caption picks the label used last, and saves it with the preferences.
|
||||
#[test]
|
||||
fn caption_dialog_remembers_the_last_label() {
|
||||
|
||||
@@ -25,6 +25,10 @@ pub(crate) struct PaperLabels {
|
||||
/// `layout.size` keeps the section's orientation; `layout.orientation` then turns the page and
|
||||
/// its margins to what the dialog shows. A size equal to the opened one (either way round,
|
||||
/// within 0.01 pt) doesn't run `layout.size`.
|
||||
/// An exact (negative) top or bottom the dialog still shows as the section has it, on a page
|
||||
/// not turned, is left out of `layout.margins`, which keeps a side left out (a negative given
|
||||
/// counts as zero): changing another side keeps it exact, as the ruler does. The fit checks
|
||||
/// count an exact margin at its size.
|
||||
pub(super) fn page_layout_commands(
|
||||
app: &WordApp,
|
||||
(paper, was): ((f32, f32), (f32, f32)),
|
||||
@@ -33,6 +37,20 @@ pub(super) fn page_layout_commands(
|
||||
) -> Result<Vec<(String, Value)>, &'static str> {
|
||||
use wordcraft_engine::cmd::page::{MARGINS_DONT_FIT, margins_fit, sect};
|
||||
let cur = sect(&app.session);
|
||||
let kept = |shown: f32, now: f32| landscape == cur.landscape && now < 0.0 && shown == now;
|
||||
let (keep_top, keep_bottom) = (kept(m.0, cur.margin_top), kept(m.1, cur.margin_bottom));
|
||||
let sizes = |(t, b, l, r): (f32, f32, f32, f32)| (t.abs(), b.abs(), l.abs(), r.abs());
|
||||
// `layout.margins` with the sides it sets: all but the exact ones kept.
|
||||
let set_margins = |(t, b, l, r): (f32, f32, f32, f32)| {
|
||||
let mut v = json!({"top": t, "bottom": b, "left": l, "right": r});
|
||||
for (keep, k) in [(keep_top, "top"), (keep_bottom, "bottom")] {
|
||||
if keep && let Some(o) = v.as_object_mut() {
|
||||
o.remove(k);
|
||||
}
|
||||
}
|
||||
("layout.margins".to_string(), v)
|
||||
};
|
||||
let m = sizes(m);
|
||||
if !margins_fit(paper, m, cur.gutter) {
|
||||
return Err(MARGINS_DONT_FIT);
|
||||
}
|
||||
@@ -41,8 +59,8 @@ pub(super) fn page_layout_commands(
|
||||
let new_size = (w0 - w1).abs() >= 0.01 || (h0 - h1).abs() >= 0.01;
|
||||
let size = ("layout.size".to_string(), json!({"width": paper.0, "height": paper.1}));
|
||||
let orientation = ("layout.orientation".to_string(), json!({"value": if landscape { "landscape" } else { "portrait" }}));
|
||||
let margins = ("layout.margins".to_string(), json!({"top": m.0, "bottom": m.1, "left": m.2, "right": m.3}));
|
||||
let old_margins = (cur.margin_top, cur.margin_bottom, cur.margin_left, cur.margin_right);
|
||||
let margins = set_margins(m);
|
||||
let old_margins = sizes((cur.margin_top, cur.margin_bottom, cur.margin_left, cur.margin_right));
|
||||
Ok(if !new_size || margins_fit(turned(cur.landscape, paper), old_margins, cur.gutter) {
|
||||
let mut v = if new_size { vec![size] } else { Vec::new() };
|
||||
v.extend([orientation, margins]);
|
||||
@@ -50,7 +68,7 @@ pub(super) fn page_layout_commands(
|
||||
} else if margins_fit(turned(landscape, (cur.page_w, cur.page_h)), m, cur.gutter) {
|
||||
vec![orientation, margins, size]
|
||||
} else {
|
||||
vec![orientation, ("layout.margins".to_string(), json!({"top": 0.0, "bottom": 0.0, "left": 0.0, "right": 0.0})), size, margins]
|
||||
vec![orientation, set_margins((0.0, 0.0, 0.0, 0.0)), size, margins]
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1173,6 +1173,48 @@ fn page_setup_refuses_margins_that_dont_fit_and_applies_smaller_ones_first() {
|
||||
assert_eq!((s.page_w.round(), s.page_h.round(), s.margin_left.round(), s.margin_top.round()), (100.0, 500.0, 18.0, 18.0));
|
||||
}
|
||||
|
||||
/// #7108: an exact (negative) top or bottom margin Page Setup's OK didn't change stays exact
|
||||
/// when another side changes, as with the ruler and `layout.margins`; one changed in the
|
||||
/// dialog takes the value shown.
|
||||
#[test]
|
||||
fn page_setup_keeps_an_exact_margin_it_didnt_change() {
|
||||
let mut h = app_harness(app_with("Page"));
|
||||
h.run_steps(2);
|
||||
let sect = |h: &egui_kittest::Harness<'_, WordApp>| wordcraft_engine::cmd::page::sect(&h.state().session);
|
||||
{
|
||||
let x = &mut h.state_mut().session.doc.last_section;
|
||||
(x.margin_top, x.margin_bottom) = (-60.0, -40.0);
|
||||
}
|
||||
page_setup(&mut h, |f| f.margins.left = 80.0);
|
||||
assert!(!is_open(h.state(), "pageSetup"));
|
||||
let x = sect(&h);
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (-60.0, -40.0, 80.0), "the exact margins kept");
|
||||
page_setup(&mut h, |f| f.margins.top = 50.0);
|
||||
let x = sect(&h);
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (50.0, -40.0, 80.0), "the changed one set, the other kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_setup_turning_page_keeps_exact_margin_size_on_new_side() {
|
||||
let mut h = app_harness(app_with("Page"));
|
||||
h.run_steps(2);
|
||||
let sect = |h: &egui_kittest::Harness<'_, WordApp>| wordcraft_engine::cmd::page::sect(&h.state().session);
|
||||
{
|
||||
let x = &mut h.state_mut().session.doc.last_section;
|
||||
(x.margin_top, x.margin_bottom, x.margin_left, x.margin_right) = (-60.0, -40.0, 72.0, 54.0);
|
||||
}
|
||||
// Turning portrait -> landscape in the dialog rotates the shown margins (top -> right, bottom -> left).
|
||||
page_setup(&mut h, |f| {
|
||||
set_landscape(f, true);
|
||||
let (t, b, l, r) = (f.margins.top, f.margins.bottom, f.margins.left, f.margins.right);
|
||||
(f.margins.top, f.margins.bottom, f.margins.left, f.margins.right) = (l, r, b, t);
|
||||
});
|
||||
assert!(!is_open(h.state(), "pageSetup"));
|
||||
let x = sect(&h);
|
||||
assert!(x.landscape);
|
||||
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), (72.0, 54.0, 40.0, 60.0));
|
||||
}
|
||||
|
||||
/// #1433: one OK in Page Setup is one undo step, whichever order its commands run in (the
|
||||
/// size first; the margins first; margins of 0 in between), and Undo restores the section.
|
||||
#[test]
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) struct Parked {
|
||||
read_from: Option<std::path::PathBuf>,
|
||||
/// The comment panel's selection and the comment and reply text typed in this document and not
|
||||
/// yet written to it.
|
||||
comments: craft::review::ui::CommentsPanelState,
|
||||
pub(crate) comments: craft::review::ui::CommentsPanelState,
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
|
||||
@@ -20,7 +20,9 @@ mod side;
|
||||
mod state;
|
||||
|
||||
use comments::comments;
|
||||
pub(crate) use comments::{commit_comment, commit_reply, flush_comment_drafts, has_comment_drafts, state_has_drafts};
|
||||
pub(crate) use comments::{
|
||||
commit_comment, commit_open_comment_edit, commit_reply, flush_comment_drafts, flush_parked_comment_drafts, has_comment_drafts, state_has_drafts,
|
||||
};
|
||||
use host::Content;
|
||||
#[cfg(test)]
|
||||
pub(crate) use host::apply;
|
||||
|
||||
@@ -11,7 +11,8 @@ use craft::ui::sections::GroupBox;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::{Document, StoryRef};
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
use super::WordApp;
|
||||
|
||||
@@ -79,29 +80,30 @@ fn drafts(app: &mut WordApp) -> &mut CommentsPanelState {
|
||||
|
||||
/// The comment thread a message of `id` belongs to, as the panel state names it.
|
||||
fn thread_of(app: &WordApp, id: u32) -> ThreadId {
|
||||
ThreadId(u64::from(thread_root(app, id)))
|
||||
ThreadId(u64::from(thread_root(&app.session.doc, id)))
|
||||
}
|
||||
|
||||
/// The place of comment `id` in its thread: 0 for the comment, then its replies in id order.
|
||||
fn message_index(app: &WordApp, id: u32) -> usize {
|
||||
let root = thread_root(app, id);
|
||||
let doc = &app.session.doc;
|
||||
let root = thread_root(doc, id);
|
||||
if root == id {
|
||||
return 0;
|
||||
}
|
||||
replies(app, root).iter().position(|r| *r == id).map_or(0, |at| at + 1)
|
||||
replies(doc, root).iter().position(|r| *r == id).map_or(0, |at| at + 1)
|
||||
}
|
||||
|
||||
/// The comment at message `index` of the thread rooted at `root`.
|
||||
fn message_id(app: &WordApp, root: u32, index: usize) -> Option<u32> {
|
||||
fn message_id(doc: &Document, root: u32, index: usize) -> Option<u32> {
|
||||
match index {
|
||||
0 => Some(root),
|
||||
_ => replies(app, root).get(index - 1).copied(),
|
||||
_ => replies(doc, root).get(index - 1).copied(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the replies to `root`, in id order.
|
||||
fn replies(app: &WordApp, root: u32) -> Vec<u32> {
|
||||
let mut replies: Vec<u32> = app.session.doc.comments.iter().filter(|(_, c)| c.parent == Some(root)).map(|(id, _)| *id).collect();
|
||||
fn replies(doc: &Document, root: u32) -> Vec<u32> {
|
||||
let mut replies: Vec<u32> = doc.comments.iter().filter(|(_, c)| c.parent == Some(root)).map(|(id, _)| *id).collect();
|
||||
replies.sort_unstable();
|
||||
replies
|
||||
}
|
||||
@@ -175,19 +177,36 @@ fn comment_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32, resolve
|
||||
/// is dropped once written (or when there is nothing to write); a refused edit keeps it.
|
||||
pub(crate) fn commit_comment(app: &mut WordApp, id: u32) -> Result<(), String> {
|
||||
let Some(text) = draft_of(app, id) else { return Ok(()) };
|
||||
if let Some(part) = app.session.doc.comments.get(&id).map(|c| c.part)
|
||||
&& text != app.session.doc.plain_text(StoryRef::Part(part))
|
||||
{
|
||||
app.run("review.editComment", json!({"id": id, "text": text}))?;
|
||||
if app.session.doc.comments.get(&id).is_some_and(|c| c.resolved) {
|
||||
drafts(app).editing = None;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(params) = edit_params(&app.session.doc, id, &text) {
|
||||
app.run("review.editComment", params)?;
|
||||
}
|
||||
drafts(app).editing = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the open comment edit, if any, before `review.resolveComment` runs: a resolved comment takes no edits, so
|
||||
/// a draft still open then would be lost (#9190). A refused edit keeps its draft.
|
||||
pub(crate) fn commit_open_comment_edit(app: &mut WordApp) -> Result<(), String> {
|
||||
let Some((thread, index, _)) = drafts(app).editing.clone() else { return Ok(()) };
|
||||
match u32::try_from(thread.0).ok().and_then(|root| message_id(&app.session.doc, root, index)) {
|
||||
Some(id) => commit_comment(app, id),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_params(doc: &Document, id: u32, text: &str) -> Option<Value> {
|
||||
let part = doc.comments.get(&id)?.part;
|
||||
(text != doc.plain_text(StoryRef::Part(part))).then(|| json!({"id": id, "text": text}))
|
||||
}
|
||||
|
||||
/// The comment a reply to `id` answers: replies to a reply join its thread.
|
||||
fn thread_root(app: &WordApp, id: u32) -> u32 {
|
||||
match app.session.doc.comments.get(&id).and_then(|c| c.parent) {
|
||||
Some(p) if app.session.doc.comments.contains_key(&p) => p,
|
||||
fn thread_root(doc: &Document, id: u32) -> u32 {
|
||||
match doc.comments.get(&id).and_then(|c| c.parent) {
|
||||
Some(p) if doc.comments.contains_key(&p) => p,
|
||||
_ => id,
|
||||
}
|
||||
}
|
||||
@@ -245,26 +264,28 @@ fn reply_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) -> bool {
|
||||
/// draft is dropped once posted; a refused reply keeps it.
|
||||
pub(crate) fn commit_reply(app: &mut WordApp, id: u32) -> Result<(), String> {
|
||||
let thread = thread_of(app, id);
|
||||
let d = drafts(app);
|
||||
let d = &app.canvas.comments;
|
||||
if !d.selected.lead.as_ref().is_some_and(|t| t.0 == thread.0) {
|
||||
return Ok(());
|
||||
}
|
||||
let text = d.reply.clone();
|
||||
if !text.trim().is_empty() && app.session.doc.comments.contains_key(&id) {
|
||||
let root = thread_root(app, id);
|
||||
app.run("review.reply", json!({"id": root, "text": text.trim_end()}))?;
|
||||
if let Some(params) = reply_params(&app.session.doc, id, &d.reply) {
|
||||
app.run("review.reply", params)?;
|
||||
}
|
||||
drafts(app).reply.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reply_params(doc: &Document, id: u32, text: &str) -> Option<Value> {
|
||||
(!text.trim().is_empty() && doc.comments.contains_key(&id)).then(|| json!({"id": thread_root(doc, id), "text": text.trim_end()}))
|
||||
}
|
||||
|
||||
/// Write every pending comment and reply draft to the document, so a save has them and a close,
|
||||
/// New or Open sees them as unsaved changes (#1348). Every draft is tried; the first refusal is
|
||||
/// returned (and is on the status line), and refused drafts stay.
|
||||
pub(crate) fn flush_comment_drafts(app: &mut WordApp) -> Result<(), String> {
|
||||
let mut first = Ok(());
|
||||
if let Some((thread, index, _)) = drafts(app).editing.clone() {
|
||||
let id = u32::try_from(thread.0).ok().and_then(|root| message_id(app, root, index));
|
||||
let id = u32::try_from(thread.0).ok().and_then(|root| message_id(&app.session.doc, root, index));
|
||||
let r = match id {
|
||||
Some(id) => commit_comment(app, id),
|
||||
// The comment is gone: its draft has nowhere to go.
|
||||
@@ -286,3 +307,21 @@ pub(crate) fn flush_comment_drafts(app: &mut WordApp) -> Result<(), String> {
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
/// Write a parked document's drafts while its session is temporarily addressed by the control
|
||||
/// channel. Like a resolve in the window, try both drafts and keep any the document refuses.
|
||||
pub(crate) fn flush_parked_comment_drafts(session: &mut Session, state: &mut CommentsPanelState) {
|
||||
if let Some((thread, index, text)) = &state.editing {
|
||||
let params =
|
||||
u32::try_from(thread.0).ok().and_then(|root| message_id(&session.doc, root, *index)).and_then(|id| edit_params(&session.doc, id, text));
|
||||
if params.is_none_or(|params| session.run("review.editComment", ¶ms).is_ok()) {
|
||||
state.editing = None;
|
||||
}
|
||||
}
|
||||
if let Some(id) = state.selected.lead.as_ref().and_then(|t| u32::try_from(t.0).ok()) {
|
||||
let params = reply_params(&session.doc, id, &state.reply);
|
||||
if params.is_none_or(|params| session.run("review.reply", ¶ms).is_ok()) {
|
||||
state.reply.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,6 +466,73 @@ mod comment_wrapping {
|
||||
assert_eq!(read(&h, ids[0]), "First comment. Edited.");
|
||||
assert!(!crate::panes::has_comment_drafts(h.state()));
|
||||
}
|
||||
|
||||
/// #9196: resolving a comment while its pane field still holds an uncommitted draft commits
|
||||
/// that draft first rather than hiding and dropping it.
|
||||
#[test]
|
||||
fn resolving_a_comment_while_editing_it_commits_the_pending_draft() {
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::StoryRef;
|
||||
|
||||
const FIRST: &str = "First comment.";
|
||||
const SECOND: &str = "Second comment.";
|
||||
let mut h = pane(&[FIRST.to_owned(), SECOND.to_owned()]);
|
||||
let ids: Vec<u32> = h.state().session.doc.comments.keys().copied().collect();
|
||||
let read = |h: &H, id| {
|
||||
let doc = &h.state().session.doc;
|
||||
doc.plain_text(StoryRef::Part(doc.comments[&id].part))
|
||||
};
|
||||
|
||||
let field = field_lines(&h, "Comment", FIRST).0.center();
|
||||
click_at(&mut h, field);
|
||||
press_key(&mut h, egui::Key::End);
|
||||
type_text(&mut h, " Typed.");
|
||||
assert!(crate::panes::has_comment_drafts(h.state()));
|
||||
|
||||
h.state_mut().run("review.resolveComment", json!({"id": ids[0]})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
assert!(h.state().session.doc.comments[&ids[0]].resolved);
|
||||
assert_eq!(read(&h, ids[0]), "First comment. Typed.");
|
||||
assert!(!crate::panes::has_comment_drafts(h.state()));
|
||||
|
||||
let page = h.state().canvas.page_rects().next().map(|(_, r)| r.center()).expect("a page is shown");
|
||||
click_at(&mut h, page);
|
||||
let second = field_lines(&h, "Comment", SECOND).0.center();
|
||||
click_at(&mut h, second);
|
||||
press_key(&mut h, egui::Key::End);
|
||||
type_text(&mut h, " Edited.");
|
||||
click_at(&mut h, page);
|
||||
assert_eq!(read(&h, ids[0]), "First comment. Typed.");
|
||||
assert_eq!(read(&h, ids[1]), "Second comment. Edited.");
|
||||
}
|
||||
|
||||
/// #9196: Resolve takes the whole thread, so text typed into a reply is written too, also when a script resolves
|
||||
/// the comment at the caret without naming an id.
|
||||
#[test]
|
||||
fn resolving_a_thread_without_an_id_commits_a_reply_draft() {
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::StoryRef;
|
||||
|
||||
let mut h = pane(&["First comment.".to_owned()]);
|
||||
let root = *h.state().session.doc.comments.keys().next().expect("a comment");
|
||||
h.state_mut().run("review.reply", json!({"id": root, "text": "A reply."})).unwrap();
|
||||
h.state_mut().run("select.text", json!({"text": "Alpha"})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
|
||||
let field = field_lines(&h, "Comment", "A reply.").0.center();
|
||||
click_at(&mut h, field);
|
||||
press_key(&mut h, egui::Key::End);
|
||||
type_text(&mut h, " Typed.");
|
||||
assert!(crate::panes::has_comment_drafts(h.state()));
|
||||
|
||||
h.state_mut().execute("review.resolveComment", json!({})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let doc = &h.state().session.doc;
|
||||
assert!(doc.comments[&root].resolved);
|
||||
let reply = doc.comments.values().find(|c| c.parent == Some(root)).expect("the reply");
|
||||
assert_eq!(doc.plain_text(StoryRef::Part(reply.part)), "A reply. Typed.");
|
||||
assert!(!crate::panes::has_comment_drafts(h.state()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Numbered headings are listed with the number they show, and numbered body paragraphs in
|
||||
|
||||
@@ -54,11 +54,13 @@ impl ThumbSource<usize> for SheetSource<'_> {
|
||||
|
||||
fn render(&self, key: &usize, request: &ThumbRequest) -> ThumbRender {
|
||||
let Some(sheet) = self.sheets.get(*key) else { return ThumbRender::Blank };
|
||||
let side = request.side.max(1) as usize;
|
||||
// The 2 px border below is added on top of `side`, so the bordered image stays within the requested side.
|
||||
let side = (request.side as usize).saturating_sub(2).max(1);
|
||||
let scale = side as f32 / sheet.width.max(sheet.height).max(1.0);
|
||||
let w = ((sheet.width * scale).round() as usize).clamp(1, side);
|
||||
let h = ((sheet.height * scale).round() as usize).clamp(1, side);
|
||||
let mut image = ColorImage::filled([w, h], Color32::WHITE);
|
||||
// Reserve a 1 px border around the sheet so `outline_sheet` sits outside the printed content (#9189).
|
||||
let mut image = ColorImage::filled([w + 2, h + 2], Color32::WHITE);
|
||||
for slot in &sheet.slots {
|
||||
let Some(pg) = self.lay.pages.get(slot.page) else { continue };
|
||||
let k = (slot.width / pg.w).min(slot.height / pg.h);
|
||||
@@ -70,45 +72,52 @@ impl ThumbSource<usize> for SheetSource<'_> {
|
||||
let y0 = ((slot.y + (slot.height - pg.h * k) / 2.0) * scale).round() as i64;
|
||||
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &preview_options(self.app));
|
||||
let straight = page.to_straight();
|
||||
let row_len = (page.width as usize).max(1) * 4;
|
||||
for (row, line) in straight.chunks_exact(row_len).enumerate() {
|
||||
let y = y0 + row as i64;
|
||||
if y < 0 || y >= h as i64 {
|
||||
continue;
|
||||
}
|
||||
for (col, px) in line.as_chunks::<4>().0.iter().enumerate() {
|
||||
let x = x0 + col as i64;
|
||||
if x < 0 || x >= w as i64 {
|
||||
continue;
|
||||
}
|
||||
let Some(dst) = image.pixels.get_mut(y as usize * w + x as usize) else { continue };
|
||||
let a = u32::from(px[3]);
|
||||
let mix = |src: u8, under: u8| ((u32::from(src) * a + u32::from(under) * (255 - a) + 127) / 255) as u8;
|
||||
*dst = Color32::from_rgb(mix(px[0], dst.r()), mix(px[1], dst.g()), mix(px[2], dst.b()));
|
||||
}
|
||||
}
|
||||
composite_page(&mut image, &straight, (page.width as usize).max(1), x0, y0, w, h);
|
||||
}
|
||||
outline_sheet(&mut image);
|
||||
ThumbRender::Ready(image)
|
||||
}
|
||||
}
|
||||
|
||||
/// Composite straight RGBA page pixels into a `sheet_w` × `sheet_h` sheet with a 1 px outer border.
|
||||
fn composite_page(image: &mut ColorImage, straight: &[u8], page_w: usize, x0: i64, y0: i64, sheet_w: usize, sheet_h: usize) {
|
||||
let stride = image.size[0];
|
||||
let row_len = page_w * 4;
|
||||
for (row, line) in straight.chunks_exact(row_len).enumerate() {
|
||||
let y = y0 + row as i64;
|
||||
if y < 0 || y >= sheet_h as i64 {
|
||||
continue;
|
||||
}
|
||||
for (col, px) in line.as_chunks::<4>().0.iter().enumerate() {
|
||||
let x = x0 + col as i64;
|
||||
if x < 0 || x >= sheet_w as i64 {
|
||||
continue;
|
||||
}
|
||||
let Some(dst) = image.pixels.get_mut((y as usize + 1) * stride + (x as usize + 1)) else { continue };
|
||||
let a = u32::from(px[3]);
|
||||
let mix = |src: u8, under: u8| ((u32::from(src) * a + u32::from(under) * (255 - a) + 127) / 255) as u8;
|
||||
*dst = Color32::from_rgb(mix(px[0], dst.r()), mix(px[1], dst.g()), mix(px[2], dst.b()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-pixel grey edge on the sheet. The pane's well is as white as the paper, so without it the sheet's
|
||||
/// own shape is invisible and a portrait page looks like a landscape sheet with the page off to one side (#9111).
|
||||
const SHEET_EDGE: Color32 = Color32::from_gray(145);
|
||||
|
||||
fn outline_sheet(image: &mut ColorImage) {
|
||||
// lean: fixed grey, not a theme token: the sheet is paper, white in every theme; a token needs a craft-libs pane overlay.
|
||||
const EDGE: Color32 = Color32::from_gray(150);
|
||||
let [w, h] = image.size;
|
||||
if w == 0 || h == 0 {
|
||||
return;
|
||||
}
|
||||
for x in 0..w {
|
||||
image.pixels[x] = EDGE;
|
||||
image.pixels[(h - 1) * w + x] = EDGE;
|
||||
image.pixels[x] = SHEET_EDGE;
|
||||
image.pixels[(h - 1) * w + x] = SHEET_EDGE;
|
||||
}
|
||||
for y in 0..h {
|
||||
image.pixels[y * w] = EDGE;
|
||||
image.pixels[y * w + w - 1] = EDGE;
|
||||
image.pixels[y * w] = SHEET_EDGE;
|
||||
image.pixels[y * w + w - 1] = SHEET_EDGE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,3 +192,37 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, lay: &Arc<DocLayout>) {
|
||||
app.print.settings.preview = next;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sheet_edge_sits_outside_printed_content() {
|
||||
let (w, h) = (4, 4);
|
||||
let mut image = ColorImage::filled([w + 2, h + 2], Color32::WHITE);
|
||||
let red = [200u8, 10, 20, 255];
|
||||
let straight = red.repeat(w * h);
|
||||
composite_page(&mut image, &straight, w, 0, 0, w, h);
|
||||
outline_sheet(&mut image);
|
||||
|
||||
let expected_red = Color32::from_rgb(200, 10, 20);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
assert_eq!(image.pixels[(y + 1) * (w + 2) + (x + 1)], expected_red, "content pixel ({x}, {y}) overwritten");
|
||||
}
|
||||
}
|
||||
for x in 0..w + 2 {
|
||||
assert_ne!(image.pixels[x], expected_red);
|
||||
assert_ne!(image.pixels[(h + 1) * (w + 2) + x], expected_red);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_edge_meets_3_to_1_contrast_against_white() {
|
||||
let srgb = f64::from(SHEET_EDGE.r()) / 255.0;
|
||||
let lum = if srgb <= 0.04045 { srgb / 12.92 } else { ((srgb + 0.055) / 1.055).powf(2.4) };
|
||||
let contrast = 1.05 / (lum + 0.05);
|
||||
assert!(contrast >= 3.0, "sheet edge contrast {contrast:.2}:1 is below 3:1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use craft::behavior::{IconId, keyed};
|
||||
use craft::behavior::{EditEvent, IconId, keyed};
|
||||
use craft::menu::{CommandRef, RibbonGroup, RibbonRow};
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::theme::{Emphasis, Variant};
|
||||
@@ -22,6 +22,69 @@ use serde_json::Value;
|
||||
use super::{Ui, WordApp, json};
|
||||
use crate::colors::{Remember, Target};
|
||||
|
||||
/// A wheel run in the Font box, kept between passes until the picker commits or cancels it.
|
||||
#[derive(Clone)]
|
||||
struct FontWheelRun {
|
||||
/// The selection's font while the run goes on; another one ends what is kept.
|
||||
from: String,
|
||||
/// The family the run proposes, which the box must go on showing or the picker cancels the run.
|
||||
to: String,
|
||||
/// The pass that kept it, so a box that was not drawn since does not take it up again.
|
||||
pass: u64,
|
||||
}
|
||||
|
||||
/// Whether `edit` is a step in the box rather than an Enter commit or a list pick: the commit that ends a wheel run
|
||||
/// (`wheel_commit`), or a `Set` by Up or Down on the focused box.
|
||||
fn stepped_in_box(ctx: &egui::Context, edit: &craft::ui::contract::EditResponse<String>, wheel_commit: bool) -> bool {
|
||||
let arrow_set =
|
||||
matches!(edit.events.iter().rev().find(|e| matches!(e, EditEvent::Set { .. } | EditEvent::Commit { .. })), Some(EditEvent::Set { .. }))
|
||||
&& craft::ui::runtime::focus::has(ctx, edit.response.id)
|
||||
&& ctx.input(|i| {
|
||||
i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::ArrowUp | egui::Key::ArrowDown, pressed: true, .. }))
|
||||
});
|
||||
wheel_commit || arrow_set
|
||||
}
|
||||
|
||||
/// The Home tab's Font box over `current`, the selection's font.
|
||||
fn font_family_box(ui: &mut Ui, app: &mut WordApp, current: &str) {
|
||||
let key = egui::Id::unique("home.font.wheelRun");
|
||||
let pass = ui.ctx().cumulative_pass_nr();
|
||||
let run = ui.data(|d| d.get_temp::<FontWheelRun>(key)).filter(|run| run.from == current && pass <= run.pass.saturating_add(1));
|
||||
let mut family = run.as_ref().map_or(current, |run| run.to.as_str()).to_string();
|
||||
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
|
||||
painted_ibeam_over(ui, &out.edit.response);
|
||||
// The wheel proposes with a gesture, which commits in a later pass, usually one with no wheel input.
|
||||
let wheeled = ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. })));
|
||||
let mut running = run.is_some();
|
||||
let mut wheel_commit = false;
|
||||
for event in out.edit.events.iter() {
|
||||
match event {
|
||||
EditEvent::Begin { .. } | EditEvent::Update { .. } => running |= wheeled,
|
||||
EditEvent::Commit { .. } => {
|
||||
wheel_commit |= running;
|
||||
running = false;
|
||||
}
|
||||
_ => running = false,
|
||||
}
|
||||
}
|
||||
if let Some(f) = &out.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
// Enter or a pick from the list hands the keyboard back to the document, as Word does (#9233).
|
||||
// Up, Down and the wheel step the font while keeping focus in the box (#9247).
|
||||
let held = ui.ctx().memory(|m| m.focused());
|
||||
if !stepped_in_box(ui.ctx(), &out.edit, wheel_commit) && (held.is_none() || craft::ui::runtime::focus::has(ui.ctx(), out.edit.response.id)) {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
}
|
||||
if running {
|
||||
let st = wordcraft_engine::cmd::format::cached_state(&app.session);
|
||||
let from = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
ui.data_mut(|d| d.insert_temp(key, FontWheelRun { from, to: family, pass }));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<FontWheelRun>(key));
|
||||
}
|
||||
}
|
||||
|
||||
/// A ribbon group titled `title`, with the Dialog Launcher `launcher` when it has one.
|
||||
fn ribbon_group(key: &'static str, title: &str, icon: &'static str, launcher: Option<&str>) -> RibbonGroup<'static> {
|
||||
let group = RibbonGroup::new(key, tl!(title).to_string(), crate::icons::spec(icon));
|
||||
@@ -198,13 +261,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
icon_only(ui, |ui| {
|
||||
two_rows(ui, |ui, at| {
|
||||
if at == 0 {
|
||||
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
|
||||
painted_ibeam_over(ui, &out.edit.response);
|
||||
if let Some(f) = out.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
font_family_box(ui, app, st.get("font").and_then(Value::as_str).unwrap_or(""));
|
||||
// Given, not bound: a bound local rebuilt from the engine each frame cancels the typed draft (#8921).
|
||||
let size = st.get("size").and_then(Value::as_f64).map(format_font_size).unwrap_or_default();
|
||||
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::given(size), font_size_entries())
|
||||
@@ -217,9 +274,35 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
let _ = app.run("format.size", json!({"size": x}));
|
||||
}
|
||||
// Enter or a pick from the list hands the keyboard back to the document, as Word does (#9233). A commit
|
||||
// by clicking another control leaves focus on that control.
|
||||
// by clicking another control leaves focus on that control. Up, Down and the wheel step the size with a
|
||||
// `Set` too; the box keeps focus then, so repeated steps go on. Only a `Set` from a wheel over the box
|
||||
// or Up/Down on the focused box counts as a step, so a stray wheel event in the same frame as Enter
|
||||
// still returns focus to the document (#9248).
|
||||
let held = ui.ctx().memory(|m| m.focused());
|
||||
if out.edit.events.committed().is_some() && (held.is_none() || craft::ui::runtime::focus::has(ui.ctx(), out.edit.response.id)) {
|
||||
let is_set = out
|
||||
.edit
|
||||
.events
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|e| match e {
|
||||
EditEvent::Set { .. } => Some(true),
|
||||
EditEvent::Commit { .. } => Some(false),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
let stepped = is_set
|
||||
&& ((out.edit.response.hovered()
|
||||
&& ui.ctx().input(|i| i.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))))
|
||||
|| (craft::ui::runtime::focus::has(ui.ctx(), out.edit.response.id)
|
||||
&& ui.ctx().input(|i| {
|
||||
i.events
|
||||
.iter()
|
||||
.any(|e| matches!(e, egui::Event::Key { key: egui::Key::ArrowUp | egui::Key::ArrowDown, pressed: true, .. }))
|
||||
})));
|
||||
if out.edit.events.committed().is_some()
|
||||
&& !stepped
|
||||
&& (held.is_none() || craft::ui::runtime::focus::has(ui.ctx(), out.edit.response.id))
|
||||
{
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")]
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::undo_marks::apply_edits;
|
||||
|
||||
/// Fills the Picture Format tab's Adjust, Picture Styles, Accessibility (Alt Text), Arrange and Size groups.
|
||||
pub(super) fn picture_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
let primary_picture = super::has_picture_selected(&app.session);
|
||||
row.group(RibbonGroup::new("picture.adjust", tl!("Adjust"), IconId::new("wordcraft.more").into()), |ui| {
|
||||
let stacked = |label: &'static str, tip: &'static str| {
|
||||
Button::new(tl!(label)).icon(IconId::new("picture")).tooltip(tl!(tip)).arrangement(Arrangement::Stacked)
|
||||
@@ -67,11 +68,13 @@ pub(super) fn picture_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
});
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Button::command(CommandRef::new("ui.changePicture"))
|
||||
.label(tl!("Change"))
|
||||
.icon(IconId::new("picture"))
|
||||
.tooltip(tl!("Change Picture"))
|
||||
.show(ui);
|
||||
if primary_picture {
|
||||
Button::command(CommandRef::new("ui.changePicture"))
|
||||
.label(tl!("Change"))
|
||||
.icon(IconId::new("picture"))
|
||||
.tooltip(tl!("Change Picture"))
|
||||
.show(ui);
|
||||
}
|
||||
Button::command(CommandRef::new("picture.reset")).label(tl!("Reset")).icon(IconId::new("picture")).tooltip(tl!("Reset Picture")).show(ui);
|
||||
});
|
||||
});
|
||||
@@ -95,6 +98,11 @@ pub(super) fn picture_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
}
|
||||
});
|
||||
});
|
||||
if !primary_picture {
|
||||
// The primary shape has its own Shape Format tab. Only the existing multi-picture
|
||||
// commands are offered under Picture Format in this case.
|
||||
return;
|
||||
}
|
||||
alt_text_group(row);
|
||||
row.group(RibbonGroup::new("picture.arrange", tl!("Arrange"), IconId::new("wordcraft.more").into()), |ui| {
|
||||
Button::command(CommandRef::new("arrange.position")).icon(IconId::new("position")).arrangement(Arrangement::Stacked).show(ui);
|
||||
|
||||
@@ -123,9 +123,7 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
SplitButton::<u8>::command(
|
||||
CommandRef::new("review.accept"),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
MenuItem::command(CommandRef::with_params("review.accept", json!({"next": true})))
|
||||
.label(tl!("Accept and Move to Next").to_string())
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::new("review.acceptAndNext")).label(tl!("Accept and Move to Next").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("review.accept", json!({}))).label(tl!("Accept This Change").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::new("review.acceptAll")).label(tl!("Accept All Changes").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("review.acceptAll", json!({"stopTracking": true})))
|
||||
@@ -140,9 +138,7 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
SplitButton::<u8>::command(
|
||||
CommandRef::new("review.reject"),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
MenuItem::command(CommandRef::with_params("review.reject", json!({"next": true})))
|
||||
.label(tl!("Reject and Move to Next").to_string())
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::new("review.rejectAndNext")).label(tl!("Reject and Move to Next").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("review.reject", json!({}))).label(tl!("Reject Change").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::new("review.rejectAll")).label(tl!("Reject All Changes").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("review.rejectAll", json!({"stopTracking": true})))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use craft::behavior::{ColumnWidth, IconId};
|
||||
use craft::behavior::{ColumnWidth, EditEvent, EditEvents, IconId, Mixed};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
|
||||
use craft::theme::ControlSize;
|
||||
@@ -9,6 +9,7 @@ use craft::ui::display::Text;
|
||||
use craft::ui::layout::{GridFit, empty_cell};
|
||||
use craft::ui::layout_components::{Grid, Row, Stack};
|
||||
use craft::ui::menu::MenuItem;
|
||||
use craft::ui::runtime::focus;
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::text::NumberField;
|
||||
|
||||
@@ -113,21 +114,26 @@ pub(super) fn table_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Table Layout › Cell Size: the caret cell's row height and column width. They show the size on the
|
||||
/// page (a row without a set height shows the height its text gives it) and editing runs
|
||||
/// `table.rowHeight` / `table.columnWidth`; a drag is one undo step.
|
||||
/// Table Layout › Cell Size: edit the caret cell's row height and starting grid column width. An
|
||||
/// automatic row shows the height its text gives it. A drag is one undo step.
|
||||
fn cell_size_boxes(ui: &mut Ui, app: &mut WordApp) {
|
||||
let story = app.session.sel.focus.story;
|
||||
let Some((tp, r, c)) = app.session.sel.focus.path.cell() else { return };
|
||||
let Some(t) = app.session.doc.table(story, &tp) else { return };
|
||||
let row = t.rows.get(r).map(|x| x.props.clone()).unwrap_or_default();
|
||||
let stored_w = t.grid.get(t.grid_col(r, c)).copied();
|
||||
let laid = app.session.layout().pages.iter().flat_map(|pg| pg.items.iter()).find_map(|it| match it {
|
||||
wordcraft_layout::Placed::Cell { rect, table, row, cell, story: st, .. } if *table == tp && *row == r && *cell == c && *st == story => {
|
||||
Some(*rect)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let column_w = t.grid.get(t.grid_col(r, c)).copied();
|
||||
let w0 = column_w
|
||||
.or_else(|| {
|
||||
app.session.layout().pages.iter().flat_map(|pg| pg.items.iter()).find_map(|it| match it {
|
||||
wordcraft_layout::Placed::Cell { rect, table, row, cell, story: st, .. }
|
||||
if *table == tp && *row == r && *cell == c && *st == story =>
|
||||
{
|
||||
Some(rect.w)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.unwrap_or(0.0);
|
||||
// The row's own height: a vertically merged cell's box spans several rows, so take the
|
||||
// shortest box in this row.
|
||||
let row_h = app
|
||||
@@ -142,25 +148,41 @@ fn cell_size_boxes(ui: &mut Ui, app: &mut WordApp) {
|
||||
})
|
||||
.reduce(f32::min);
|
||||
let h0 = row.height.or(row_h).unwrap_or(0.0);
|
||||
let w0 = laid.map(|x| x.w).or(stored_w).unwrap_or(0.0);
|
||||
let exact = row.height_rule == wordcraft_doc::props::HeightRule::Exact;
|
||||
let (height_units, width_units) = (crate::options::lengths(app.session.units()), crate::options::lengths(app.session.units()));
|
||||
// As the old ribbon and Layout › Paragraph: a visible label beside each field, two decimals ("0.20"). The fields are
|
||||
// as tall as the small buttons, so their rows line up with Distribute Rows and Distribute Columns beside them.
|
||||
let caption = |label: &'static str| Text::new(tl!(label)).role(TypeRole::Caption);
|
||||
let edit_field = |ui: &mut Ui, app: &WordApp, field: NumberField<'_>| -> EditEvents<Option<f64>> {
|
||||
let out = field
|
||||
.range(CELL_SIZE_RANGE)
|
||||
.edit_target((&app.session.sel.anchor, &app.session.sel.focus))
|
||||
.fixed_decimals(2)
|
||||
.size(ControlSize::Md)
|
||||
.show(ui);
|
||||
// Keep typing in the field until commit, while a scrub updates the table during the drag.
|
||||
let typing = focus::focused_rec(ui.ctx()).is_some_and(|rec| rec.stop.id == out.edit.response.id && rec.stop.text);
|
||||
out.edit
|
||||
.events
|
||||
.into_iter()
|
||||
.filter(|event| match event {
|
||||
EditEvent::Update { .. } => !typing,
|
||||
EditEvent::Set { before: Mixed::Same(before), after, .. } => before != after,
|
||||
_ => true,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Grid::new(&[ColumnWidth::Content; 2]).gap(Gap::Tight).show(ui, |ui, _| {
|
||||
caption("Height:").show(ui);
|
||||
let field = NumberField::length(tl!("Height:").to_string(), Bind::given(Some(f64::from(h0))), height_units).range(CELL_SIZE_RANGE);
|
||||
let out = field.fixed_decimals(2).size(ControlSize::Md).show(ui);
|
||||
apply_edits(app, out.edit.events, |app, v| {
|
||||
let events = edit_field(ui, app, NumberField::length(tl!("Height:").to_string(), Bind::given(Some(f64::from(h0))), height_units));
|
||||
apply_edits(app, events, |app, v| {
|
||||
if let Some(h) = v {
|
||||
let _ = app.run("table.rowHeight", json!({"height": h, "rule": if exact { "exact" } else { "atLeast" }}));
|
||||
}
|
||||
});
|
||||
caption("Width:").show(ui);
|
||||
let field = NumberField::length(tl!("Width:").to_string(), Bind::given(Some(f64::from(w0))), width_units).range(CELL_SIZE_RANGE);
|
||||
let out = field.fixed_decimals(2).size(ControlSize::Md).show(ui);
|
||||
apply_edits(app, out.edit.events, |app, v| {
|
||||
let events = edit_field(ui, app, NumberField::length(tl!("Width:").to_string(), Bind::given(Some(f64::from(w0))), width_units));
|
||||
apply_edits(app, events, |app, v| {
|
||||
if let Some(w) = v {
|
||||
let _ = app.run("table.columnWidth", json!({"width": w}));
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn contextual_tabs(s: &wordcraft_engine::Session) -> Vec<&'static str> {
|
||||
tabs.push("Table Design");
|
||||
tabs.push("Table Layout");
|
||||
}
|
||||
if has_picture_selected(s) {
|
||||
if wordcraft_engine::cmd::objects::has_picture_format_target(s) {
|
||||
tabs.push("Picture Format");
|
||||
}
|
||||
if has_shape_selected(s) {
|
||||
|
||||
@@ -535,6 +535,30 @@ fn every_proofing_language_is_picked_from_the_language_menu() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picture_format_offers_multi_picture_commands_for_a_shape_first_selection() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.picture", json!({"data": png_data()})).unwrap();
|
||||
app.run("caret.docEnd", json!({})).unwrap();
|
||||
app.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
|
||||
app.run("caret.docStart", json!({})).unwrap();
|
||||
app.run("select.addObject", json!({"index": 1})).unwrap();
|
||||
assert!(!contextual_tabs(&app.session).contains(&"Picture Format"));
|
||||
app.run("select.addObject", json!({"index": 0})).unwrap();
|
||||
let tabs = contextual_tabs(&app.session);
|
||||
assert!(tabs.contains(&"Picture Format") && tabs.contains(&"Shape Format"));
|
||||
let mut h = tab_harness(app, "Picture Format");
|
||||
let border = h.get_by_role_and_label(Role::Button, "Border");
|
||||
assert!(!border.accesskit_node().is_disabled());
|
||||
assert!(h.query_by_role_and_label(Role::Button, "Change").is_none());
|
||||
assert!(h.query_by_label("Crop").is_none());
|
||||
h.get_by_role_and_label(Role::Button, "Border").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(h.query_by_label("Thin").is_some(), "the Picture Border menu can be opened");
|
||||
}
|
||||
|
||||
/// #2573, #1901: Picture Format › Size's width shows the interface unit and takes a size typed
|
||||
/// in pixels, keeping the picture's proportions, as one undo step; Esc throws a typed size away
|
||||
/// with no undo step.
|
||||
@@ -1072,6 +1096,140 @@ fn table_cell_size_fields_line_up_with_the_distribute_buttons() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_width_box_for_a_merged_cell_commits_its_starting_column() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("file.options", json!({"units": "points"})).unwrap();
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
|
||||
let table = |app: &WordApp| app.session.doc.body.iter().position(|block| block.as_table().is_some()).expect("inserted table");
|
||||
let index = table(&app);
|
||||
let grid = |app: &WordApp| app.session.doc.body[index].as_table().expect("inserted table").grid.clone();
|
||||
let cell = |col| json!({"story": "body", "path": [index, 0, col, 0], "off": 0});
|
||||
app.run("select.range", json!({"anchor": cell(0), "focus": cell(1)})).unwrap();
|
||||
app.run("table.merge", json!({})).unwrap();
|
||||
|
||||
let mut h = tab_harness(app, "Table Layout");
|
||||
let before = grid(h.state());
|
||||
let undo = h.state().session.undo_depth();
|
||||
let displayed = h.get_by_role_and_label(Role::SpinButton, "Width:").accesskit_node().numeric_value().expect("Width value");
|
||||
assert!((displayed - f64::from(before[0])).abs() < 0.01, "the field shows the column it will edit");
|
||||
h.get_by_role_and_label(Role::SpinButton, "Width:").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
let focused = h.ctx.memory(|m| m.focused()).expect("Width took keyboard focus");
|
||||
h.key_press(egui::Key::End);
|
||||
h.key_press(egui::Key::Delete);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert_eq!((grid(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "Delete at the end changes nothing");
|
||||
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
for digit in ["5", "0"] {
|
||||
h.event(egui::Event::Text(digit.into()));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert_eq!((grid(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "typing changes only the draft");
|
||||
assert_eq!(h.ctx.memory(|m| m.focused()), Some(focused), "Width keeps the keyboard while typing");
|
||||
}
|
||||
h.key_press(egui::Key::Enter);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let mut expected = before.clone();
|
||||
expected[0] = 50.0;
|
||||
assert_eq!((grid(h.state()), h.state().session.undo_depth()), (expected, undo + 1), "commit changes the starting column in one step");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(grid(h.state()), before, "undo restores the width");
|
||||
}
|
||||
|
||||
/// #9377: Height preserves automatic rows until the user commits a change, and scrubs live as one step.
|
||||
#[test]
|
||||
fn the_height_box_commits_typing_and_scrubs_live() {
|
||||
use egui::accesskit::Role;
|
||||
use wordcraft_doc::props::HeightRule;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("file.options", json!({"units": "points"})).unwrap();
|
||||
app.run("insert.table", json!({"rows": 3, "cols": 2})).unwrap();
|
||||
let index = app.session.doc.body.iter().position(|block| block.as_table().is_some()).expect("inserted table");
|
||||
let cell = |row| json!({"story": "body", "path": [index, row, 0, 0], "off": 0});
|
||||
let select = |app: &mut WordApp, row| {
|
||||
app.run("select.range", json!({"anchor": cell(row), "focus": cell(row)})).unwrap();
|
||||
};
|
||||
select(&mut app, 2);
|
||||
app.run("table.rowHeight", json!({"height": 40, "rule": "exact"})).unwrap();
|
||||
select(&mut app, 1);
|
||||
app.run("table.rowHeight", json!({"height": 30, "rule": "atLeast"})).unwrap();
|
||||
|
||||
let mut h = tab_harness(app, "Table Layout");
|
||||
let rows = |app: &WordApp| {
|
||||
app.session.doc.body[index].as_table().unwrap().rows.iter().map(|r| (r.props.height, r.props.height_rule)).collect::<Vec<_>>()
|
||||
};
|
||||
let before = rows(h.state());
|
||||
let undo = h.state().session.undo_depth();
|
||||
assert_eq!(before, [(None, HeightRule::Auto), (Some(30.0), HeightRule::AtLeast), (Some(40.0), HeightRule::Exact)]);
|
||||
|
||||
let at = h.get_by_role_and_label(Role::SpinButton, "Height:").rect().center();
|
||||
let pointer = |pos, pressed| egui::Event::PointerButton { pos, pressed, button: egui::PointerButton::Primary, modifiers: egui::Modifiers::NONE };
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.event(pointer(at, true));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
let mut last = 30.0;
|
||||
for distance in [12.0, 24.0] {
|
||||
h.event(egui::Event::PointerMoved(at + vec2(distance, 0.0)));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
let after = rows(h.state());
|
||||
let height = after[1].0.expect("scrubbed height");
|
||||
assert!(height > last, "each move changes the height before release");
|
||||
assert_eq!(after[1].1, HeightRule::AtLeast);
|
||||
assert_eq!([after[0], after[2]], [before[0], before[2]]);
|
||||
last = height;
|
||||
}
|
||||
h.event(pointer(at + vec2(24.0, 0.0), false));
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
assert_eq!(rows(h.state())[1], (Some(last), HeightRule::AtLeast));
|
||||
assert_eq!(h.state().session.undo_depth(), undo + 1, "one scrub, one undo step");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(rows(h.state()), before);
|
||||
|
||||
for (row, rule) in [(0, HeightRule::AtLeast), (1, HeightRule::AtLeast), (2, HeightRule::Exact)] {
|
||||
select(h.state_mut(), row);
|
||||
h.state_mut().run("table.selectRow", json!({})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.get_by_role_and_label(Role::SpinButton, "Height:").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.key_press(egui::Key::End);
|
||||
h.key_press(egui::Key::Delete);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "Delete at the end changes nothing");
|
||||
|
||||
let type_height = |h: &mut Harness| {
|
||||
let focused = h.ctx.memory(|m| m.focused()).expect("Height took keyboard focus");
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
crate::test_harness::frames(h, 2);
|
||||
for digit in ["5", "6"] {
|
||||
h.event(egui::Event::Text(digit.into()));
|
||||
crate::test_harness::frames(h, 2);
|
||||
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "typing stays in the draft");
|
||||
assert_eq!(h.ctx.memory(|m| m.focused()), Some(focused), "Height keeps the keyboard while typing");
|
||||
}
|
||||
};
|
||||
type_height(&mut h);
|
||||
h.key_press(egui::Key::Escape);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "Escape discards the draft");
|
||||
|
||||
h.get_by_role_and_label(Role::SpinButton, "Height:").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
type_height(&mut h);
|
||||
h.key_press(egui::Key::Enter);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let mut expected = before.clone();
|
||||
expected[row] = (Some(56.0), rule);
|
||||
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (expected, undo + 1), "only the selected row changes");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(rows(h.state()), before, "one Undo restores the original row height and rule");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4017: Home's small buttons, icon-only or labelled, are at least 24 points square: the least target size the
|
||||
/// accessibility standard asks for (WCAG 2.5.8).
|
||||
#[test]
|
||||
@@ -1661,3 +1819,134 @@ fn a_size_typed_in_the_font_size_box_formats_the_selection() {
|
||||
let page = h.state().canvas.shown.canvas.expect("the page is shown");
|
||||
assert!(craft::ui::runtime::focus::has(&ctx, page), "the page has the keyboard after Enter");
|
||||
}
|
||||
|
||||
/// #9233: Up and Down in the focused Font Size box step the size and leave the box focused, so a second press steps again.
|
||||
#[test]
|
||||
fn down_in_the_font_size_box_steps_the_size_again_and_keeps_focus() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample\n\nafter")), crate::Services::default());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("format.size", json!({"size": 12.0})).unwrap();
|
||||
let mut h = tab_harness(app, "Home");
|
||||
h.get_all_by_role(Role::TextInput).find(|n| n.value().is_some_and(|v| v.trim().parse::<f64>().is_ok())).expect("the font size box").focus();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
let size =
|
||||
|h: &egui_kittest::Harness<'_, WordApp>| wordcraft_engine::cmd::format::cached_state(&h.state().session).get("size").and_then(Value::as_f64);
|
||||
assert_eq!(size(&h), Some(12.0));
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let first = size(&h).expect("a size");
|
||||
assert_ne!(first, 12.0, "one Down steps the size");
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let second = size(&h).expect("a size");
|
||||
assert_ne!(second, first, "a second Down steps again");
|
||||
let ctx = h.ctx.clone();
|
||||
let page = h.state().canvas.shown.canvas.expect("the page is shown");
|
||||
assert!(!craft::ui::runtime::focus::has(&ctx, page), "the box keeps the keyboard while stepping");
|
||||
}
|
||||
|
||||
/// #9247: Up and Down in the focused Font box step the font and leave the box focused, so a second press steps again.
|
||||
#[test]
|
||||
fn down_in_the_font_box_steps_the_font_again_and_keeps_focus() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample\n\nafter")), crate::Services::default());
|
||||
app.font_catalog = Some(crate::test_harness::fixed_catalog());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let mut h = tab_harness(app, "Home");
|
||||
h.get_all(By::new().role(Role::ComboBox).label("Font"))
|
||||
.min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y))
|
||||
.expect("the ribbon font box")
|
||||
.focus();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
let font = |h: &egui_kittest::Harness<'_, WordApp>| {
|
||||
wordcraft_engine::cmd::format::cached_state(&h.state().session).get("font").and_then(Value::as_str).map(str::to_owned)
|
||||
};
|
||||
let initial = font(&h);
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let first = font(&h);
|
||||
assert_ne!(first, initial, "one Down steps the font");
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let second = font(&h);
|
||||
assert_ne!(second, first, "a second Down steps again");
|
||||
let ctx = h.ctx.clone();
|
||||
let page = h.state().canvas.shown.canvas.expect("the page is shown");
|
||||
assert!(!craft::ui::runtime::focus::has(&ctx, page), "the box keeps the keyboard while stepping");
|
||||
}
|
||||
|
||||
/// #9247: the wheel over the focused Font box steps the font once the wheel stops and leaves the box focused.
|
||||
#[test]
|
||||
fn the_wheel_in_the_font_box_steps_the_font_and_keeps_focus() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample\n\nafter")), crate::Services::default());
|
||||
app.font_catalog = Some(crate::test_harness::fixed_catalog());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let mut h = tab_harness(app, "Home");
|
||||
let node = h
|
||||
.get_all(By::new().role(Role::ComboBox).label("Font"))
|
||||
.min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y))
|
||||
.expect("the ribbon font box");
|
||||
node.focus();
|
||||
let at = node.rect().center();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
let font = |h: &egui_kittest::Harness<'_, WordApp>| {
|
||||
wordcraft_engine::cmd::format::cached_state(&h.state().session).get("font").and_then(Value::as_str).map(str::to_owned)
|
||||
};
|
||||
let notch = |h: &mut egui_kittest::Harness<'_, WordApp>| {
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
});
|
||||
// Long enough for the wheel gesture to end, which commits the step.
|
||||
crate::test_harness::frames(h, 8);
|
||||
};
|
||||
let initial = font(&h);
|
||||
notch(&mut h);
|
||||
let first = font(&h);
|
||||
assert_ne!(first, initial, "one notch steps the font");
|
||||
let ctx = h.ctx.clone();
|
||||
let page = h.state().canvas.shown.canvas.expect("the page is shown");
|
||||
assert!(!craft::ui::runtime::focus::has(&ctx, page), "the box keeps the keyboard while stepping");
|
||||
notch(&mut h);
|
||||
assert_ne!(font(&h), first, "a second notch steps again");
|
||||
assert!(!craft::ui::runtime::focus::has(&ctx, page), "the box keeps the keyboard after the second notch");
|
||||
}
|
||||
|
||||
/// #9248: a stray MouseWheel event in the same frame as Enter must not keep focus in the Font Size box.
|
||||
#[test]
|
||||
fn enter_in_the_font_size_box_returns_focus_even_with_a_stray_wheel_event() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample\n\nafter")), crate::Services::default());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let mut h = tab_harness(app, "Home");
|
||||
h.get_all_by_role(Role::TextInput).find(|n| n.value().is_some_and(|v| v.trim().parse::<f64>().is_ok())).expect("the font size box").focus();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.event(egui::Event::Text("15".into()));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: egui::vec2(0.0, 1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Trackpad,
|
||||
});
|
||||
h.key_press(egui::Key::Enter);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let st = wordcraft_engine::cmd::format::cached_state(&h.state().session);
|
||||
assert_eq!(st.get("size").and_then(Value::as_f64), Some(15.0));
|
||||
let ctx = h.ctx.clone();
|
||||
let page = h.state().canvas.shown.canvas.expect("the page is shown");
|
||||
assert!(craft::ui::runtime::focus::has(&ctx, page), "the page has the keyboard after Enter even with a stray wheel event");
|
||||
}
|
||||
|
||||
@@ -474,7 +474,8 @@ fn find_replace_and_go_to_keys_like_word() {
|
||||
/// #8945: clicking a Navigation pane tab shows that view (the tab strip's selection event, not its overflow pick).
|
||||
#[test]
|
||||
fn nav_pane_tabs_switch_on_click() {
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 500.0)).build_eframe(|_| app());
|
||||
// A page view that comes to rest draws once more at its exact size, so a switch settles in a few more frames.
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 500.0)).with_max_steps(8).build_eframe(|_| app());
|
||||
h.state_mut().session.view.nav_pane = true;
|
||||
for _ in 0..2 {
|
||||
h.step();
|
||||
@@ -485,3 +486,34 @@ fn nav_pane_tabs_switch_on_click() {
|
||||
assert_eq!(h.state().ui.nav_tab, key);
|
||||
}
|
||||
}
|
||||
|
||||
/// #9229: switching Navigation pane tabs keeps the active search highlights in the document.
|
||||
#[test]
|
||||
fn nav_pane_switching_tabs_keeps_search_highlights() {
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 500.0)).build_eframe(|_| app());
|
||||
h.state_mut().run("document.setText", json!({"text": "Kilns fire clay. Kilns cool."})).unwrap();
|
||||
h.state_mut().session.view.nav_pane = true;
|
||||
for _ in 0..2 {
|
||||
h.step();
|
||||
}
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").focus();
|
||||
h.step();
|
||||
h.event(egui::Event::Text("Kilns".into()));
|
||||
h.step();
|
||||
h.step();
|
||||
assert_eq!(h.state().ui.nav_tab, "results");
|
||||
assert_eq!(h.state().session.find.results.len(), 2);
|
||||
|
||||
let found_count = |h: &mut egui_kittest::Harness<WordApp>| {
|
||||
let lay = h.state_mut().session.layout();
|
||||
crate::canvas::mark_areas(h.state_mut(), &lay, &[]).iter().filter(|m| m.kind == craft::pages::ui::MarkKind::Found).count()
|
||||
};
|
||||
assert_eq!(found_count(&mut h), 2, "Results tab highlights both matches");
|
||||
|
||||
for (label, key) in [("Headings", "headings"), ("Pages", "pages"), ("Results", "results")] {
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Tab, label).click();
|
||||
h.run();
|
||||
assert_eq!(h.state().ui.nav_tab, key);
|
||||
assert_eq!(found_count(&mut h), 2, "tab `{label}` must keep both search highlights");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,10 +484,7 @@ fn unregistered_registry(graph: &PartGraph) -> bool {
|
||||
mutations.update({
|
||||
'delta16 destructuring assignment': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: Package) -> usize { let items; Package { entries: items, .. } = pkg; items.len() }'),
|
||||
'delta16 parenthesized destructuring assignment': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: Package) -> usize { let items; (Package { entries: items, .. }) = pkg; items.len() }'),
|
||||
'delta16 macro-produced closure pattern': ('lib.rs', lambda s:s+'''
|
||||
macro_rules! package_pattern { ($items:ident) => { Package { entries: $items, .. } }; }
|
||||
fn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Package| items.len())(pkg) }
|
||||
'''),
|
||||
'delta16 macro-produced closure pattern': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Package| items.len())(pkg) }'),
|
||||
'delta16 raw field read': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: &Package) -> usize { pkg.r#entries.len() }'),
|
||||
'delta16 raw registry method': ('ownership.rs', lambda s:s.replace('impl PackageRegistryContext {', 'impl PackageRegistryContext { fn unregistered_registry(&self) -> usize { self.r#contexts("x").len() }', 1)),
|
||||
'delta16 module callback body': ('lib.rs', lambda s:s+'\nconst UNREGISTERED_READ: fn(&Package) -> usize = |pkg| pkg.entries.len();'),
|
||||
@@ -528,7 +525,7 @@ fn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Packa
|
||||
'external module without supplied source': ('lib.rs', lambda s:s+'\nmod hidden;'),
|
||||
'Unicode combining collection field': ('lib.rs', lambda s:s+'\nstruct UnicodeCollection { fresh\u0301: Vec<u8> } fn hidden(p: &UnicodeCollection) -> usize { p.fresh\u0301.len() }'),
|
||||
'Unicode combining membership receiver': ('lib.rs', lambda s:s+'\nfn hidden(fresh\u0301: &[u8]) -> bool { fresh\u0301.contains(&1) }'),
|
||||
'Unicode combining parser identifier': ('lib.rs', lambda s:s+'\nfn parse_fresh\u0301() -> usize { 1 } fn hidden() -> usize { parse_fresh\u0301() }'),
|
||||
'Unicode combining parser identifier': ('lib.rs', lambda s:s+'\nfn hidden() -> usize { parse_fresh\u0301() }'),
|
||||
'undeclared representation consumer': ('observed.rs', lambda s:s+'\nfn read(pkg: &Package) -> usize { pkg.entries.len() }'),
|
||||
'representation membership bypass': ('observed.rs', lambda s:s.replace('!self.0.contains(key)', '!self.0.contains(key) || raw.contains(key)', 1)),
|
||||
})
|
||||
@@ -580,7 +577,7 @@ fn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Packa
|
||||
mutations['R18 qualified consuming macro arguments'] = ('lib.rs', lambda s: s+'\nfn unregistered_read(pkg: &Package) -> String { std::format!("{}", pkg.entries.len()) }')
|
||||
mutations['R18 standard namespace import shadow'] = ('lib.rs', lambda s: s+'\nuse external as std;')
|
||||
mutations['R18 derive outside type context'] = ('lib.rs', lambda s: s+'\n#[derive(Debug)] fn unregistered() {}')
|
||||
mutations['R18 serde field attribute outside policy'] = ('lib.rs', lambda s: s+'\n#[serde(skip)] fn unregistered() {}')
|
||||
mutations['R18 serde field attribute outside policy'] = ('lib.rs', lambda s: s.replace('pub struct Finding {\n', 'pub struct Finding {\n #[serde(skip)]\n', 1))
|
||||
mutations['R18 inline outside closed options'] = ('lib.rs', lambda s: s+'\n#[inline(sometimes)] fn unregistered() {}')
|
||||
getter_contract = 'observation_contract! { rules: "-"; collections: "access.prefix*1"; scope: "prefix presence control"; loss: "incomplete observed map"; fallback: "only presence is established"; package_loss: "independent"; }'
|
||||
mutations['R18 contracted retained get equality absence'] = ('lib.rs', lambda s: s+'\nimpl Observed<HashMap<String, String>> { fn unregistered_absence(&self, key: &String) -> bool { '+getter_contract+' Self::prefix(self).get(key) == None } }')
|
||||
@@ -831,6 +828,149 @@ POSITIVE_INVENTORY = (
|
||||
'declared-presence row',
|
||||
)
|
||||
|
||||
EXPECTED_REJECTIONS = {
|
||||
'undeclared consumer': "lib.rs::invented_check: bounded consumption has no observation contract: ['access.prefix*1', 'type.Observed*1', 'type.Vec*1']",
|
||||
'undeclared array consumer': "lib.rs::invented_array: bounded consumption has no observation contract: ['access.prefix*1', 'type.Observed*1', 'type.Vec*1']",
|
||||
'missing fallback': 'lib.rs: macro argument mismatch',
|
||||
'accessor bypass': 'lib.rs::invented_bypass: bypasses private observation representation',
|
||||
'exception leakage': 'lib.rs::invented_registry: undeclared package-registry exception',
|
||||
'new undeclared accessor': "lib.rs::check_custom_xml: declared collections differ from bounded accesses: declared=['access.into_complete_set*2', 'access.missing*1', 'field.content_types*3', 'field.contexts*2', 'field.entries*3', 'lookup.content_unavailable*1', 'parser.parse_attached_schemas*1', 'parser.parse_custom_xml_schemas*1', 'type.CompleteSet*1', 'type.HashSet*3', 'type.Observed*2', 'type.Vec*3'], used=['access.into_complete_set*2', 'access.missing*1', 'access.retain_budget*1', 'field.content_types*3', 'field.contexts*2', 'field.entries*3', 'lookup.content_unavailable*1', 'parser.parse_attached_schemas*1', 'parser.parse_custom_xml_schemas*1', 'type.CompleteSet*1', 'type.HashSet*3', 'type.Observed*2', 'type.Vec*3']",
|
||||
'raw membership bypass': 'lib.rs::check_custom_xml: raw membership raw bypasses CompleteSet or undeclared structural scope',
|
||||
'raw absence difference': 'lib.rs::invented_absence: raw absence difference bypasses CompleteSet',
|
||||
'destructured package read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'module registry alias and method pointer': 'lib.rs: module-scope package-registry aliases/queries are unsupported',
|
||||
'destructured parameter read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'destructured match read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'destructured for read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'immediately invoked destructured closure': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'let-bound destructured closure': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'const fn-pointer destructured closure': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'closure argument with nested pattern': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
|
||||
'returned closure with later parameter': 'lib.rs: unrecognized pattern: Package { ref entries , .. }',
|
||||
'static fn-pointer destructured closure': 'lib.rs: unrecognized pattern: crate :: package :: Package { entries : items , .. }',
|
||||
'array-element destructured closure': 'lib.rs: unrecognized pattern: Package { entries : _ , .. }',
|
||||
'async destructured closure': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'nested struct closure pattern': 'lib.rs: unrecognized pattern: Wrapper { inner : Package { entries : items , .. } }',
|
||||
'closure pattern after associated-type constraint': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'closure pattern with attributes and comments': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'destructured closure returning adjacent closure': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'adjacent inner destructured closure': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'closure with parenthesized or-pattern': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'closure with generic struct path': 'lib.rs: unrecognized pattern: Package :: < Vec < u8 > > { entries , .. }',
|
||||
'closure with qualified struct path': 'lib.rs: unrecognized pattern: < Container as Trait > :: Package { entries , .. }',
|
||||
'closure with Unicode identifier continuation': 'lib.rs: unrecognized pattern: Packagé { entries , .. }',
|
||||
'closure with nested block comment': 'lib.rs: unrecognized pattern: Package { entries , .. }',
|
||||
'module registry type alias': 'lib.rs: module-scope package-registry aliases/queries are unsupported',
|
||||
'module registry method pointer': 'lib.rs::<initializer QUERY>: undeclared package-registry exception',
|
||||
'delta16 destructuring assignment': 'lib.rs: unrecognized assignment target: Package { entries : items , .. }',
|
||||
'delta16 parenthesized destructuring assignment': 'lib.rs: unrecognized assignment target: (Package { entries : items , .. })',
|
||||
'delta16 macro-produced closure pattern': 'lib.rs: unrecognized pattern: package_pattern ! (items)',
|
||||
'delta16 raw field read': "lib.rs::unregistered_read: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'delta16 raw registry method': 'ownership.rs::unregistered_registry: undeclared package-registry exception',
|
||||
'delta16 module callback body': "lib.rs::<initializer UNREGISTERED_READ>: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'static callback body': "lib.rs::<initializer UNREGISTERED_READ>: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'raw private representation': 'lib.rs::invented: bypasses private observation representation',
|
||||
'raw accessor': "lib.rs::invented: bounded consumption has no observation contract: ['access.prefix*1']",
|
||||
'raw registry type alias': 'lib.rs: module-scope package-registry aliases/queries are unsupported',
|
||||
'raw registry function name': 'ownership.rs::unregistered_registry: undeclared package-registry exception',
|
||||
'registry in representation provider': 'observed.rs::hidden: undeclared package-registry exception',
|
||||
'unsupported union item': 'lib.rs: unrecognized item: union Unsupported { field : usize }',
|
||||
'unsupported trait body': 'lib.rs: unrecognized item: trait Hidden { fn read (pkg : & Package) -> usize { pkg . entries . len () } }',
|
||||
'unsupported foreign item': 'lib.rs: unrecognized item: unsafe extern "C" { fn hidden () ; }',
|
||||
'unsupported production module': 'lib.rs: unrecognized item: mod hidden { fn read (pkg : & super :: Package) -> usize { pkg . entries . len () } }',
|
||||
'unsupported attribute macro': 'lib.rs: unrecognized attribute: # [hidden]',
|
||||
'unsupported pattern macro in binding': 'lib.rs: unrecognized pattern: hidden ! (items)',
|
||||
'unsupported pattern macro in parameter': 'lib.rs: unrecognized pattern: hidden ! (items)',
|
||||
'unsupported pattern macro in match': 'lib.rs: unrecognized pattern: hidden ! (items)',
|
||||
'unsupported pattern macro in assignment': 'lib.rs: unrecognized assignment target: hidden ! (items)',
|
||||
'unsupported expression macro': 'lib.rs: unrecognized expression/pattern macro: hidden ! (pkg . entries)',
|
||||
'unsupported macro repetition': 'lib.rs: unsupported macro matcher',
|
||||
'unsupported async body': 'lib.rs: unrecognized expression: async { pkg . entries . len () }',
|
||||
'nested closure body': "lib.rs::read: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'impl callback initializer': "lib.rs::<initializer READ>: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'enum discriminant body': "lib.rs::<structural expression>: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'type-level constant body': "lib.rs::<structural expression>: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'macro-generated consumer': "lib.rs::AuditPlaceholder: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'macro-captured collection field': "lib.rs::read: bounded consumption has no observation contract: ['field.AuditPlaceholder*1']",
|
||||
'contract macro starts emitting code': 'lib.rs: unsupported item macro expansion: expected one of: `fn`, `extern`, `use`, `static`, `const`, `unsafe`, `mod`, `type`, `struct`, `enum`, `union`, `trait`, `auto`, `impl`, `default`, `macro`, identifier, `self`, `super`, `crate`, `::`',
|
||||
'contract text in literal is not a declaration': "lib.rs::invented: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'standard macro shadow hides consuming expansion': 'lib.rs: standard expression macro shadowing is outside the closed grammar',
|
||||
'standard macro import shadow': 'lib.rs: unrecognized macro-shadowing import: format',
|
||||
'standard macro alias shadow': 'lib.rs: unrecognized macro-shadowing import: hidden as matches',
|
||||
'glob import could hide standard macro shadow': 'lib.rs: unrecognized glob import: *',
|
||||
'attribute macro on item invocation': 'scan.rs: unrecognized attribute: # [hidden]',
|
||||
'attribute macro on definition': 'scan.rs: unrecognized attribute: # [hidden]',
|
||||
'external module without supplied source': 'lib.rs: external module hidden has no supplied audited source or explicit excluded table/test/policy source',
|
||||
'Unicode combining collection field': "lib.rs::hidden: bounded consumption has no observation contract: ['field.fresh́*1']",
|
||||
'Unicode combining membership receiver': 'lib.rs::hidden: raw membership fresh́ bypasses CompleteSet or undeclared structural scope',
|
||||
'Unicode combining parser identifier': "lib.rs::hidden: bounded consumption has no observation contract: ['parser.parse_fresh́*1']",
|
||||
'undeclared representation consumer': 'observed.rs::read: representation contract differs or is missing',
|
||||
'representation membership bypass': 'observed.rs::missing: representation contract differs or is missing',
|
||||
'R18 obsolete Option absence': 'lib.rs::check_rels: unsupported package Resolution operation; match One/Absent/Unknown/Ambiguous explicitly',
|
||||
'R18 raw iterator absence': 'package.rs::unregistered_absence: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
|
||||
'R18 contracted raw iterator absence': 'package.rs::unregistered_absence: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
|
||||
'R18 helper-mediated absence': 'lib.rs::unregistered_absence: unsupported package Resolution operation; match One/Absent/Unknown/Ambiguous explicitly',
|
||||
'R18 raw slice alias': 'package.rs::unregistered_absence: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
|
||||
'R18 fabricated absence': 'package.rs::invented: unauthorized literal Resolution::Absent construction; use discovered with package loss evidence',
|
||||
'R18 fabricated completeness': 'package.rs::canonical_entry: literal true is not package completeness evidence',
|
||||
'R18 Unknown-or-Absent': 'lib.rs::check_rels: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
|
||||
'R18 missing Unknown': 'lib.rs::check_rels: package Resolution match must explicitly cover One, Absent, Unknown and Ambiguous',
|
||||
'R18 direct state deletion': 'lib.rs::has_unique_rels_owner: entry-loss predicate differs from its named conservative/lookup contract',
|
||||
'R18 direct state negation': 'lib.rs::has_unique_rels_owner: entry-loss predicate differs from its named conservative/lookup contract',
|
||||
'R18 discovery complete deletion': 'lib.rs::ownership_discovery_complete: entry-loss predicate differs from its named conservative/lookup contract',
|
||||
'R18 discovery complete negation': 'lib.rs::ownership_discovery_complete: entry-loss predicate differs from its named conservative/lookup contract',
|
||||
'R18 reader assembly limit inversion': 'package.rs::load: entry-loss predicate differs from its named conservative/lookup contract',
|
||||
'R18 canonical external call': 'package.rs::invented: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
|
||||
'R18 helper alias/value canonical_entry/hidden_lookup': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.canonical_entry*1']",
|
||||
'R18 helper alias/value canonical_entry/package::canonical_entry': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.canonical_entry*1']",
|
||||
'R18 helper alias/value entry_by_name/hidden_lookup': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.entry_by_name*1']",
|
||||
'R18 helper alias/value entry_by_name/package::entry_by_name': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.entry_by_name*1']",
|
||||
'R18 helper alias/value content_unavailable/hidden_lookup': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.content_unavailable*1']",
|
||||
'R18 helper alias/value content_unavailable/package::content_unavailable': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.content_unavailable*1']",
|
||||
'R18 retained prefix !Self::prefix(self).contains(key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix Self::prefix(self).contains(key) == false': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix !Self::prefix(self).iter().any(|candidate| candidate == key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix matches!(Self::prefix(self).contains(key), false)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix match Self::prefix(self).contains(key) { false => true, true => false }': 'lib.rs::unregistered_absence: boolean membership match on retained prefix requires CompleteSet',
|
||||
'R18 retained prefix !<Self>::prefix(self).contains(key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix <Self>::prefix(self).contains(key) == false': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix !<Self>::prefix(self).iter().any(|candidate| candidate == key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix matches!(<Self>::prefix(self).contains(key), false)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix match <Self>::prefix(self).contains(key) { false => true, true => false }': 'lib.rs::unregistered_absence: boolean membership match on retained prefix requires CompleteSet',
|
||||
'R18 retained prefix !<Observed<HashSet<String>>>::prefix(self).contains(key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix <Observed<HashSet<String>>>::prefix(self).contains(key) == false': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix !<Observed<HashSet<String>>>::prefix(self).iter().any(|candidate| candidate == key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix matches!(<Observed<HashSet<String>>>::prefix(self).contains(key), false)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained prefix match <Observed<HashSet<String>>>::prefix(self).contains(key) { false => true, true => false }': 'lib.rs::unregistered_absence: boolean membership match on retained prefix requires CompleteSet',
|
||||
'R18 accessor function binding Self::prefix': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 accessor function binding HiddenDefinitions::prefix': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 aliased UFCS': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 local prefix with exact original contract': 'lib.rs::special_notes: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 retained map get absence': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
|
||||
'R18 unauthorized ContentTypes reader serde::Serialize': 'package.rs::ContentTypes: unauthorized reader derive serde::Serialize or changed representation/DTO field shape',
|
||||
'R18 unauthorized ContentTypes reader serde::Deserialize': 'package.rs::ContentTypes: unauthorized reader derive serde::Deserialize or changed representation/DTO field shape',
|
||||
'R18 unauthorized ContentTypes reader Debug': 'package.rs::ContentTypes: unauthorized reader derive Debug or changed representation/DTO field shape',
|
||||
'R18 renamed reader derive': 'package.rs::ContentTypes: unauthorized reader derive serde::Serialize or changed representation/DTO field shape',
|
||||
'R18 unauthorized reader on DTO': 'lib.rs::Finding: unauthorized reader derive serde::Deserialize or changed representation/DTO field shape',
|
||||
'R18 registry fields added to allowed DTO': 'lib.rs::Finding: unauthorized reader derive Debug or changed representation/DTO field shape',
|
||||
'R18 reader allowance cannot transfer into a function scope': 'lib.rs::<function unregistered_nested_reader>::Limits: unauthorized reader derive Debug or changed representation/DTO field shape',
|
||||
'R18 same-named DTO in another module': 'package.rs::Finding: unauthorized reader derive Debug or changed representation/DTO field shape',
|
||||
'R18 unsupported qualified env macro': 'lib.rs: unrecognized expression/pattern macro: std :: env ! ("X")',
|
||||
'seam/other-macro-path (R18 argument footprint)': "lib.rs::unregistered_read: bounded consumption has no observation contract: ['field.entries*2']",
|
||||
'R18 qualified consuming macro arguments': "lib.rs::unregistered_read: bounded consumption has no observation contract: ['field.entries*1']",
|
||||
'R18 standard namespace import shadow': 'lib.rs: unrecognized macro-shadowing import: external as std',
|
||||
'R18 derive outside type context': 'lib.rs: derive is permitted only on a recorded struct/enum, never a function, field or other attribute context',
|
||||
'R18 serde field attribute outside policy': 'lib.rs: unrecognized attribute: # [serde (skip)]',
|
||||
'R18 inline outside closed options': 'lib.rs: unrecognized inline attribute: # [inline (sometimes)]',
|
||||
'R18 contracted retained get equality absence': 'lib.rs::unregistered_absence: unmodeled membership boolean comparison requires CompleteSet',
|
||||
'R18 local Resolution matches else collapse': 'lib.rs::check_rels: absence polarity: package lookup if-let/matches else collapse is unsupported; use explicit Resolution arms',
|
||||
'R18 Resolution parameter collapse Resolution<String>': 'lib.rs::unregistered_resolution_absence: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
|
||||
'R18 Resolution parameter collapse HiddenResolution': 'lib.rs::unregistered_resolution_absence: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
|
||||
'R18 Resolution Self collapse': 'resolution.rs::unregistered_resolution_absence: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
|
||||
'R18 aliased bool cannot launder raw absence': 'package.rs::unregistered_return_alias: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
|
||||
'R18 opaque function cannot collapse package Resolution': 'lib.rs::check_rels: absence polarity: package Resolution must be matched or locally bound; unmodeled callable/argument flow is forbidden',
|
||||
}
|
||||
|
||||
def inventory_check(actual, expected, kind):
|
||||
counts = Counter(iter(actual))
|
||||
missing = sorted(set(expected)-counts.keys())
|
||||
@@ -847,6 +987,7 @@ def inventory_digest():
|
||||
def checked_mutations():
|
||||
mutations = mutation_cases()
|
||||
inventory_check(mutations, MUTATION_INVENTORY, 'mutation')
|
||||
inventory_check(EXPECTED_REJECTIONS, MUTATION_INVENTORY, 'expected rejection')
|
||||
if len(MUTATION_INVENTORY) != 140 or inventory_digest() != 'cb823adedb87fc9ba64516406abdf954635f7579ed2e695ae42599fcbd7f51d7':
|
||||
raise ValueError('pinned round-18 mutation inventory changed')
|
||||
return mutations
|
||||
@@ -863,6 +1004,9 @@ def reject_mutation(sources, label, case):
|
||||
message = str(error).splitlines()[0] if str(error) else ''
|
||||
if not message.strip():
|
||||
raise ValueError('mutation has no rejection message: '+label)
|
||||
expected = EXPECTED_REJECTIONS[label]
|
||||
if message != expected:
|
||||
raise ValueError(f'mutation rejected with unexpected diagnostic for {label}: got {message!r}, expected {expected!r}')
|
||||
return dict(label=label, message=message)
|
||||
raise ValueError('audit accepted mutation: '+label)
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
+14
-5
@@ -106,6 +106,11 @@ open another one and make it active; later commands and the saves work on the ac
|
||||
`view.switchWindows={"id": n}` makes one active. A failing command stops the run with `command N (id): …` and exit
|
||||
status 1, and nothing is saved. Every output is checked (known extension, folder exists) before the first is written. Paths inside command params (a picture to insert, say) are relative to the working folder, not the script's. Scripts are capped at 4 MiB.
|
||||
|
||||
With `--print`, successful commands write `id: <JSON>` records to stdout. Successful saves then
|
||||
write `wrote <path>` confirmations on the same stream, including when `--print` is absent. A script
|
||||
that consumes command results should parse the JSON only in the result records. Use the MCP server
|
||||
for framed JSON responses.
|
||||
|
||||
## Tracked changes by an agent
|
||||
|
||||
Tracked changes and comments are recorded under the session's user name ("WordCraft User" by
|
||||
@@ -153,8 +158,10 @@ config works across the suite) keep the agent to the folders you give it:
|
||||
its nearest existing folder's links are followed and the rest must be plain names, so `..` below a
|
||||
folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would
|
||||
create its target). The result is compared with the root by whole folder names: `/work2/x` is not
|
||||
inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\...`) are resolved like
|
||||
drive-letter ones, and device names (`CON`, `NUL`, `COM1`...) are refused.
|
||||
inside `/work`. On Windows names are compared exactly after what exists is resolved to its real
|
||||
case (so `OUT\x` reaches the root `out` on an ordinary volume, but not in a case-sensitive
|
||||
folder), UNC paths (`\\server\share\...`) are resolved like drive-letter ones, and device names
|
||||
(`CON`, `NUL`, `COM1`, `COM¹`..., also followed by an extension or a colon) are refused.
|
||||
- A refused path is an ordinary tool error the agent can read and correct, for example
|
||||
`automation path rejected: outside the write root /work/project/out: /etc/x.docx` or
|
||||
`automation filesystem access is not granted: write authority is absent: /work/project/out/x.docx`.
|
||||
@@ -262,9 +269,11 @@ The acceptance test `crates/mcp/src/tests.rs` writes a formatted document using
|
||||
`format.set {"props": CharProps}`, `para.set {"props": ParaProps}`,
|
||||
`styles.modify {"style": …, "chr"?: CharProps, "para"?: ParaProps}` and the `para` of
|
||||
`table.newStyle` / `table.modifyStyle` take these two objects. Every field is optional: a field
|
||||
left out keeps what the style chain gives. A field name the object doesn't know is ignored, not
|
||||
refused, so check the spelling. Lengths are points. A colour is a hex string `"RRGGBB"` or
|
||||
`"#RRGGBB"`, or `[r, g, b]` (three numbers 0–255); it reads back as `[r, g, b]` (#865).
|
||||
left out keeps what the style chain gives. `styles.modify` refuses unknown top-level keys in
|
||||
`chr` and `para` with a `Params` error (#9203); in `format.set`, `para.set` and `table.newStyle` /
|
||||
`table.modifyStyle`, a field name the object doesn't know is ignored, not refused, so check the
|
||||
spelling. Lengths are points. A colour is a hex string `"RRGGBB"` or `"#RRGGBB"`, or `[r, g, b]`
|
||||
(three numbers 0–255); it reads back as `[r, g, b]` (#865).
|
||||
|
||||
```json
|
||||
{"command": "styles.modify", "params": {"style": "Heading1",
|
||||
|
||||
@@ -20,12 +20,9 @@ finish-args:
|
||||
# The shared updater inspects and updates this installation via flatpak-spawn --host.
|
||||
- --talk-name=org.freedesktop.Flatpak
|
||||
- --filesystem=xdg-data/ArtCraft/versions:ro
|
||||
# Display: Wayland, plus X11 always. The clipboard (arboard) needs the Wayland data-control
|
||||
# protocol, which KWin does not offer to apps; it then falls back to the X11 clipboard, which
|
||||
# XWayland bridges. With fallback-x11 the sandbox has no X11 under Wayland and paste fails
|
||||
# (#8969, #8868). Remove --socket=x11 once the clipboard uses wl_data_device.
|
||||
# Display: Wayland first; X11 only when no Wayland compositor is running.
|
||||
- --socket=wayland
|
||||
- --socket=x11
|
||||
- --socket=fallback-x11
|
||||
# X11 shared memory (MIT-SHM). Without it the X11 fallback is slow or fails.
|
||||
- --share=ipc
|
||||
# GPU access for the wgpu renderer (Vulkan, or GL as a fallback).
|
||||
|
||||
@@ -21,12 +21,9 @@ finish-args:
|
||||
# The shared updater inspects and updates this installation via flatpak-spawn --host.
|
||||
- --talk-name=org.freedesktop.Flatpak
|
||||
- --filesystem=xdg-data/ArtCraft/versions:ro
|
||||
# Display: Wayland, plus X11 always. The clipboard (arboard) needs the Wayland data-control
|
||||
# protocol, which KWin does not offer to apps; it then falls back to the X11 clipboard, which
|
||||
# XWayland bridges. With fallback-x11 the sandbox has no X11 under Wayland and paste fails
|
||||
# (#8969, #8868). Remove --socket=x11 once the clipboard uses wl_data_device.
|
||||
# Display: Wayland first; X11 only when no Wayland compositor is running.
|
||||
- --socket=wayland
|
||||
- --socket=x11
|
||||
- --socket=fallback-x11
|
||||
# X11 shared memory (MIT-SHM). Without it the X11 fallback is slow or fails.
|
||||
- --share=ipc
|
||||
# GPU access for the wgpu renderer (Vulkan, or GL as a fallback).
|
||||
|
||||
Reference in New Issue
Block a user